You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@juneau.apache.org by ja...@apache.org on 2016/08/09 17:15:22 UTC
[01/44] incubator-juneau git commit: Rename CT_* testcases.
Repository: incubator-juneau
Updated Branches:
refs/heads/master f24316e95 -> df0f8689f
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/xml/XmlParserTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/xml/XmlParserTest.java b/org.apache.juneau/src/test/java/org/apache/juneau/xml/XmlParserTest.java
new file mode 100755
index 0000000..e6b5976
--- /dev/null
+++ b/org.apache.juneau/src/test/java/org/apache/juneau/xml/XmlParserTest.java
@@ -0,0 +1,95 @@
+/***************************************************************************************************************************
+ * 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.juneau.xml;
+
+import static org.apache.juneau.xml.XmlParserContext.*;
+import static org.junit.Assert.*;
+
+import org.apache.juneau.*;
+import org.apache.juneau.parser.*;
+import org.junit.*;
+
+public class XmlParserTest {
+
+ @Test
+ public void testGenericAttributes() throws Exception {
+ String xml = "<A b='1'><c>2</c></A>";
+ ObjectMap m = XmlParser.DEFAULT.parse(xml, ObjectMap.class);
+ assertEquals("{b:'1',c:'2'}", m.toString());
+ }
+
+ @Test
+ public void testGenericWithChildElements() throws Exception {
+ String xml;
+ ObjectMap m;
+
+ xml = "<A><B><C>c</C></B></A>";
+ m = XmlParser.DEFAULT.parse(xml, ObjectMap.class);
+ assertEquals("{B:{C:'c'}}", m.toString());
+
+ xml = "<A><B><C1>c1</C1><C2>c2</C2></B></A>";
+ m = XmlParser.DEFAULT.parse(xml, ObjectMap.class);
+ assertEquals("{B:{C1:'c1',C2:'c2'}}", m.toString());
+
+ xml = "<A><B><C><D1>d1</D1><D2>d2</D2></C></B></A>";
+ m = XmlParser.DEFAULT.parse(xml, ObjectMap.class);
+ assertEquals("{B:{C:{D1:'d1',D2:'d2'}}}", m.toString());
+
+ xml = "<A><B><C><D1 d1a='d1av'><E1>e1</E1></D1><D2 d2a='d2av'><E2>e2</E2></D2></C></B></A>";
+ m = XmlParser.DEFAULT.parse(xml, ObjectMap.class);
+ assertEquals("{B:{C:{D1:{d1a:'d1av',E1:'e1'},D2:{d2a:'d2av',E2:'e2'}}}}", m.toString());
+
+ xml = "<A><B b='b'><C>c</C></B></A>";
+ m = XmlParser.DEFAULT.parse(xml, ObjectMap.class);
+ assertEquals("{B:{b:'b',C:'c'}}", m.toString());
+
+ xml = "<A><B b='b'>c</B></A>";
+ m = XmlParser.DEFAULT.parse(xml, ObjectMap.class);
+ assertEquals("{B:{b:'b',contents:'c'}}", m.toString());
+
+ xml = "<A><B>b1</B><B>b2</B></A>";
+ m = XmlParser.DEFAULT.parse(xml, ObjectMap.class);
+ assertEquals("{B:['b1','b2']}", m.toString());
+
+ xml = "<A><B><C>c1</C><C>c2</C></B></A>";
+ m = XmlParser.DEFAULT.parse(xml, ObjectMap.class);
+ assertEquals("{B:{C:['c1','c2']}}", m.toString());
+
+ xml = "<A><B v='v1'>b1</B><B v='v2'>b2</B></A>";
+ m = XmlParser.DEFAULT.parse(xml, ObjectMap.class);
+ assertEquals("{B:[{v:'v1',contents:'b1'},{v:'v2',contents:'b2'}]}", m.toString());
+
+ xml = "<A><B><C v='v1'>c1</C><C v='v2'>c2</C></B></A>";
+ m = XmlParser.DEFAULT.parse(xml, ObjectMap.class);
+ assertEquals("{B:{C:[{v:'v1',contents:'c1'},{v:'v2',contents:'c2'}]}}", m.toString());
+
+ xml = "<A><B c='c1'><c>c2</c></B></A>";
+ m = XmlParser.DEFAULT.parse(xml, ObjectMap.class);
+ assertEquals("{B:{c:['c1','c2']}}", m.toString());
+ }
+
+ @Test
+ public void testPreserveRootElement() throws Exception {
+ String xml;
+ ObjectMap m;
+ ReaderParser p = new XmlParser().setProperty(XML_preserveRootElement, true);
+
+ xml = "<A><B><C>c</C></B></A>";
+ m = p.parse(xml, ObjectMap.class);
+ assertEquals("{A:{B:{C:'c'}}}", m.toString());
+
+ xml = "<A></A>";
+ m = p.parse(xml, ObjectMap.class);
+ assertEquals("{A:{}}", m.toString());
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/xml/XmlTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/xml/XmlTest.java b/org.apache.juneau/src/test/java/org/apache/juneau/xml/XmlTest.java
new file mode 100755
index 0000000..f482163
--- /dev/null
+++ b/org.apache.juneau/src/test/java/org/apache/juneau/xml/XmlTest.java
@@ -0,0 +1,1050 @@
+/***************************************************************************************************************************
+ * 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.juneau.xml;
+
+import static org.apache.juneau.TestUtils.*;
+import static org.apache.juneau.serializer.SerializerContext.*;
+import static org.apache.juneau.xml.XmlSerializerContext.*;
+import static org.apache.juneau.xml.annotation.XmlFormat.*;
+import static org.junit.Assert.*;
+
+import java.net.*;
+import java.util.*;
+
+import org.apache.juneau.*;
+import org.apache.juneau.annotation.*;
+import org.apache.juneau.json.*;
+import org.apache.juneau.xml.annotation.*;
+import org.apache.juneau.xml.xml1a.*;
+import org.apache.juneau.xml.xml1b.*;
+import org.apache.juneau.xml.xml1c.*;
+import org.junit.*;
+
+@SuppressWarnings({"serial"})
+public class XmlTest {
+
+ //====================================================================================================
+ // Simple comparison test with JSON serializer
+ //====================================================================================================
+ @Test
+ public void testComparisonWithJson() throws Exception {
+ String json1 = readFile(getClass().getResource("/xml/testComparisonWithJson.json").getPath());
+ String xml1 = readFile(getClass().getResource("/xml/testComparisonWithJson.xml").getPath());
+
+ ObjectMap m = (ObjectMap) XmlParser.DEFAULT.parse(xml1, Object.class);
+ String json2 = new JsonSerializer.SimpleReadable().setProperty(SERIALIZER_quoteChar, '"').setProperty(SERIALIZER_trimNullProperties, false).serialize(m);
+ assertEquals(json1, json2);
+
+ m = (ObjectMap) JsonParser.DEFAULT.parse(json1, Object.class);
+ String xml2 = new XmlSerializer.SimpleXmlJsonSq().setProperty(SERIALIZER_useIndentation, true).setProperty(SERIALIZER_trimNullProperties, false).serialize(m);
+ assertEquals(xml1, xml2);
+ }
+
+ //====================================================================================================
+ // Test namespacing
+ //====================================================================================================
+ @Test
+ public void testNamespaces() throws Exception {
+ String e = readFile(getClass().getResource("/xml/testNamespaces.xml").getPath());
+ ObjectMap m = (ObjectMap) JsonParser.DEFAULT.parse(readFile(getClass().getResource("/xml/testComparisonWithJson.json").getPath()), Object.class);
+ String r = new XmlSerializer.XmlJsonSq()
+ .setProperty(XML_addNamespaceUrisToRoot, true)
+ .setProperty(XML_defaultNamespaceUri, "http://www.ibm.com")
+ .setProperty(SERIALIZER_useIndentation, true)
+ .setProperty(SERIALIZER_trimNullProperties, false)
+ .serialize(m);
+ assertEquals(e, r);
+ }
+
+ //====================================================================================================
+ // Test bean name annotation
+ //====================================================================================================
+ @Test
+ public void testBeanNameAnnotation() throws Exception {
+ String e =
+ "<Person1 type='object'>\n"
+ + " <name>John Smith</name>\n"
+ + " <age type='number'>123</age>\n"
+ + "</Person1>\n";
+ String r = new XmlSerializer.SimpleXmlJsonSq().setProperty(SERIALIZER_useIndentation, true).serialize(new Person1("John Smith", 123));
+ assertEquals(e, r);
+ }
+
+ /** Class with explicitly specified properties */
+ @Bean(properties = { "name", "age" })
+ @Xml(name="Person1")
+ public static class Person1 {
+ public int age;
+ private String name;
+ protected Person1(String name, int age) {
+ this.name = name;
+ this.age = age;
+ }
+ public String getName() {
+ return name;
+ }
+ public void setName(String name) {
+ this.name = name;
+ }
+ }
+
+ //====================================================================================================
+ // Test trimNulls property.
+ //====================================================================================================
+ @Test
+ public void testTrimNulls() throws Exception {
+ String e =
+ "<Person1 type='object'>\n"
+ + " <age type='number'>123</age>\n"
+ + "</Person1>\n";
+ String r = new XmlSerializer.SimpleXmlJsonSq().setProperty(SERIALIZER_useIndentation, true).serialize(new Person1(null, 123));
+ assertEquals(e, r);
+ }
+
+ //====================================================================================================
+ // Element name.
+ //====================================================================================================
+ @Test
+ public void testElementName() throws Exception {
+ XmlSerializer s = XmlSerializer.DEFAULT_SIMPLE_SQ;
+ A t = new A();
+ String r = s.serialize(t);
+ assertEquals("<foo><f1>1</f1></foo>", r);
+ validateXml(t);
+ }
+
+ @Xml(name="foo")
+ public static class A {
+ public int f1 = 1;
+ }
+
+ //====================================================================================================
+ // Element name on superclass.
+ //====================================================================================================
+ @Test
+ public void testElementNameOnSuperclass() throws Exception {
+ XmlSerializer s = XmlSerializer.DEFAULT_SIMPLE_SQ;
+ B2 t = new B2();
+ String r = s.serialize(t);
+ assertEquals("<foo><f1>1</f1></foo>", r);
+ validateXml(t);
+ }
+
+ public static class B1 extends A {}
+ public static class B2 extends B1 {}
+
+ //====================================================================================================
+ // Element name on interface.
+ //====================================================================================================
+ @Test
+ public void testElementNameOnInterface() throws Exception {
+ XmlSerializer s = XmlSerializer.DEFAULT_SIMPLE_SQ;
+ C3 t = new C3();
+ String r = s.serialize(t);
+ assertEquals("<foo><f1>1</f1></foo>", r);
+ validateXml(t);
+ }
+
+ @Xml(name="foo")
+ public static interface C1 {}
+ public static class C2 implements C1 {}
+ public static class C3 extends C2 {
+ public int f1 = 1;
+ }
+
+ //====================================================================================================
+ // Element name with invalid XML characters.
+ //====================================================================================================
+ @Test
+ public void testElementNameWithInvalidChars() throws Exception {
+ XmlSerializer s = XmlSerializer.DEFAULT_SIMPLE_SQ;
+ XmlParser p = XmlParser.DEFAULT;
+ D t = new D();
+ String r = s.serialize(t);
+ assertEquals("<_x007E__x0021__x0040__x0023__x0024__x0025__x005E__x0026__x002A__x0028__x0029___x002B__x0060_-_x003D__x007B__x007D__x007C__x005B__x005D__x005C__x003A__x0022__x003B__x0027__x003C__x003E__x003F__x002C_._x000A__x000D__x0009__x0008_><f1>1</f1></_x007E__x0021__x0040__x0023__x0024__x0025__x005E__x0026__x002A__x0028__x0029___x002B__x0060_-_x003D__x007B__x007D__x007C__x005B__x005D__x005C__x003A__x0022__x003B__x0027__x003C__x003E__x003F__x002C_._x000A__x000D__x0009__x0008_>", r);
+ t = p.parse(r, D.class);
+ validateXml(t);
+ }
+
+ @Xml(name="~!@#$%^&*()_+`-={}|[]\\:\";'<>?,.\n\r\t\b")
+ public static class D {
+ public int f1 = 1;
+ }
+
+ //====================================================================================================
+ // Element name can only be specified on classes.
+ //====================================================================================================
+ @Test
+ public void testElementNameInInvalidLocations() throws Exception {
+ XmlSerializer s = XmlSerializer.DEFAULT_SIMPLE_SQ;
+ E t = new E();
+ try {
+ s.serialize(t);
+ fail("Exception not thrown");
+ } catch (Exception e) {
+ assertEquals("org.apache.juneau.xml.XmlTest$E: Annotation error on property 'f1'. Found @Xml.name annotation can only be specified on types.", e.getLocalizedMessage());
+ }
+ }
+
+ public static class E {
+ @Xml(name="foo")
+ public int f1 = 1;
+ }
+
+ //====================================================================================================
+ // Element name on collection.
+ //====================================================================================================
+ @Test
+ public void testElementNameOnCollection() throws Exception {
+ XmlSerializer s = XmlSerializer.DEFAULT_SIMPLE_SQ;
+ XmlParser p = XmlParser.DEFAULT;
+ F t = new F();
+ t.add("bar");
+ String r = s.serialize(t);
+ assertEquals("<foo><string>bar</string></foo>", r);
+ t = p.parse(r, F.class);
+ assertEquals("bar", t.get(0));
+ validateXml(t);
+ }
+
+ @Xml(name="foo")
+ public static class F extends LinkedList<String>{}
+
+ //====================================================================================================
+ // Field of type collection with element name.
+ // Element name should be ignored.
+ //====================================================================================================
+ @Test
+ public void testIgnoreCollectionFieldWithElementName() throws Exception {
+ XmlSerializer s = XmlSerializer.DEFAULT_SIMPLE_SQ;
+ XmlParser p = XmlParser.DEFAULT;
+ G t = new G();
+ t.f1.add("bar");
+ String r = s.serialize(t);
+ assertEquals("<bar><f1><string>bar</string></f1></bar>", r);
+ t = p.parse(r, G.class);
+ validateXml(t);
+ }
+
+ @Xml(name="bar")
+ public static class G {
+ public F f1 = new F();
+ }
+
+ //====================================================================================================
+ // Element name on not-a-bean.
+ //====================================================================================================
+ @Test
+ public void testElementNameOnNotABean() throws Exception {
+ XmlSerializer s = XmlSerializer.DEFAULT_SIMPLE_SQ;
+ H t = new H();
+ String r = s.serialize(t);
+ assertEquals("<foo>bar</foo>", r);
+ }
+
+ @Xml(name="foo")
+ public static class H {
+ @Override /* Object */
+ public String toString() {
+ return "bar";
+ }
+ }
+
+ //====================================================================================================
+ // Fields with element name on not-a-beans.
+ // Element name should be used on array field entries, but not regular field.
+ //====================================================================================================
+ @Test
+ public void testFieldsWithElementNameOnNotABeans() throws Exception {
+ XmlSerializer s = XmlSerializer.DEFAULT_SIMPLE_SQ;
+ I t = new I();
+ String r = s.serialize(t);
+ assertEquals("<object><f1>bar</f1><f2><foo>bar</foo><foo>bar</foo></f2></object>", r);
+ }
+
+ public static class I {
+ public H f1 = new H();
+ public H[] f2 = {
+ new H(),
+ new H()
+ };
+ }
+
+ //====================================================================================================
+ // Element name on beans of a collection.
+ //====================================================================================================
+ @Test
+ public void testElementNameOnBeansOfCollection() throws Exception {
+ XmlSerializer s = XmlSerializer.DEFAULT_SIMPLE_SQ;
+ Object o = new J1();
+ String r = s.serialize(o);
+ assertEquals("<foo><f1><bar><f2>2</f2></bar></f1></foo>", r);
+ }
+
+ @Xml(name="foo")
+ public static class J1 {
+ @BeanProperty(properties={"f2"}) public List<J2> f1 = new LinkedList<J2>() {{
+ add(new J2());
+ }};}
+
+ @Xml(name="bar")
+ public static class J2 {
+ public int f2 = 2;
+ public int f3 = 3;
+ }
+
+ //====================================================================================================
+ // @Xml.ns without matching nsUri.
+ //====================================================================================================
+ @Test
+ public void testXmlNsWithoutMatchingNsUri() throws Exception {
+ XmlSerializer s = XmlSerializer.DEFAULT_SIMPLE_SQ;
+ K t = new K();
+ try {
+ s.serialize(t);
+ fail("Exception not thrown");
+ } catch (Exception e) {
+ assertEquals("Found @Xml.prefix annotation with no matching URI. prefix='foo'", e.getLocalizedMessage());
+ }
+ }
+
+ @Xml(prefix="foo")
+ public static class K {
+ public int f1;
+ }
+
+ //====================================================================================================
+ // @Xml.format=ATTR.
+ //====================================================================================================
+ @Test
+ public void testXmlFormatAttr() throws Exception {
+ XmlSerializer s = XmlSerializer.DEFAULT_SIMPLE_SQ;
+ XmlParser p = XmlParser.DEFAULT;
+ L t = new L();
+ String r = s.serialize(t);
+ assertEquals("<object f2='2'><f1>1</f1><f3>3</f3></object>", r);
+ t.f1 = 4; t.f2 = 5; t.f3 = 6;
+ t = p.parse(s.serialize(t), L.class);
+ assertEquals(4, t.f1);
+ assertEquals(5, t.f2);
+ assertEquals(6, t.f3);
+ validateXml(t);
+ }
+
+ public static class L {
+ public int f1 = 1;
+ @Xml(format=ATTR)
+ public int f2 = 2;
+ public int f3 = 3;
+ }
+
+ //====================================================================================================
+ // @Xml.format=ATTR with namespaces.
+ //====================================================================================================
+ @Test
+ public void testXmlFormatAttrWithNs() throws Exception {
+ XmlSerializer s = new XmlSerializer.SimpleSq();
+ XmlParser p = XmlParser.DEFAULT;
+ M t = new M();
+ String r = null;
+ r = s.serialize(t);
+ assertEquals("<object f1='1' f2='2' f3='3'/>", r);
+ s.setProperty(XML_enableNamespaces, true).setProperty(XML_addNamespaceUrisToRoot, true).setProperty(XML_autoDetectNamespaces, true).setProperty(SERIALIZER_trimNullProperties, false);
+ t.f1 = 4; t.f2 = 5; t.f3 = 6;
+ r = s.serialize(t);
+ assertEquals("<object xmlns='http://www.ibm.com/2013/Juneau' xmlns:bar='http://bar' xmlns:foo='http://foo' xmlns:baz='http://baz' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' bar:f1='4' foo:f2='5' baz:f3='6'/>", r);
+ t = p.parse(r, M.class);
+ assertEquals(4, t.f1);
+ assertEquals(5, t.f2);
+ assertEquals(6, t.f3);
+ validateXml(t, s);
+ }
+
+ @Xml(prefix="bar", namespace="http://bar")
+ public static class M {
+ @Xml(format=ATTR)
+ public int f1 = 1;
+ @Xml(prefix="foo", format=ATTR, namespace="http://foo")
+ public int f2 = 2;
+ @Xml(prefix="baz", namespace="http://baz", format=ATTR)
+ public int f3 = 3;
+ }
+
+ //====================================================================================================
+ // _xXXXX_ notation.
+ //====================================================================================================
+ @Test
+ public void testXXXXNotation() throws Exception {
+ XmlSerializer s = XmlSerializer.DEFAULT_SIMPLE_SQ;
+ XmlParser p = XmlParser.DEFAULT;
+ String in, r;
+
+ in = "\u0001";
+ r = s.serialize(in);
+ assertEquals("<string>_x0001_</string>", r);
+ in = p.parse(r, String.class);
+ assertEquals("\u0001", in);
+
+ in = "_x0001_";
+ r = s.serialize(in);
+ assertEquals("<string>_x005F_x0001_</string>", r);
+ in = p.parse(r, String.class);
+ assertEquals("_x0001_", in);
+
+ in = "_x001_";
+ r = s.serialize(in);
+ assertEquals("<string>_x001_</string>", r);
+ in = p.parse(r, String.class);
+ assertEquals("_x001_", in);
+
+ in = "_x00001_";
+ r = s.serialize(in);
+ assertEquals("<string>_x00001_</string>", r);
+ in = p.parse(r, String.class);
+ assertEquals("_x00001_", in);
+
+ in = "_xx001_";
+ r = s.serialize(in);
+ assertEquals("<string>_xx001_</string>", r);
+ in = p.parse(r, String.class);
+ assertEquals("_xx001_", in);
+ }
+
+ //====================================================================================================
+ // @Bean.uri annotation formatted as element
+ //====================================================================================================
+ @Test
+ public void testBeanUriAnnotationFormattedAsElement() throws Exception {
+ XmlParser p = XmlParser.DEFAULT;
+ XmlSerializer s = XmlSerializer.DEFAULT_SIMPLE_SQ;
+
+ N t = new N("http://foo",123, "bar");
+ String r = s.serialize(t);
+ assertEquals("<object><url>http://foo</url><id>123</id><name>bar</name></object>", r);
+
+ t = p.parse(r, N.class);
+ assertEquals("http://foo", t.url.toString());
+ assertEquals(123, t.id);
+ assertEquals("bar", t.name);
+
+ validateXml(t, s);
+ }
+
+ public static class N {
+ @BeanProperty(beanUri=true) @Xml(format=ELEMENT) public URL url;
+ public int id;
+ public String name;
+ public N() {}
+ public N(String url, int id, String name) throws Exception {
+ this.url = new URL(url);
+ this.id = id;
+ this.name = name;
+ }
+ }
+
+ //====================================================================================================
+ // @Bean.uri as elements, overridden element names
+ //====================================================================================================
+ @Test
+ public void testOverriddenBeanUriAsElementNames() throws Exception {
+ XmlParser p = XmlParser.DEFAULT;
+ XmlSerializer s = XmlSerializer.DEFAULT_SIMPLE_SQ;
+
+ O t = new O("http://foo", 123, "bar");
+ String r = s.serialize(t);
+ assertEquals("<object><url2>http://foo</url2><id2>123</id2><name>bar</name></object>", r);
+
+ t = p.parse(r, O.class);
+ assertEquals("http://foo", t.url.toString());
+ assertEquals(123, t.id);
+ assertEquals("bar", t.name);
+
+ validateXml(t, s);
+ }
+
+ public static class O {
+ @BeanProperty(beanUri=true, name="url2") @Xml(format=ELEMENT) public URL url;
+ @BeanProperty(name="id2") public int id;
+ public String name;
+ public O() {}
+ public O(String url, int id, String name) throws Exception {
+ this.url = new URL(url);
+ this.id = id;
+ this.name = name;
+ }
+ }
+
+ //====================================================================================================
+ // @Bean.uri and @Bean.id annotations, overridden attribute names
+ //====================================================================================================
+ @Test
+ public void testOverriddenBeanUriAndIdAnnotations() throws Exception {
+ XmlParser p = XmlParser.DEFAULT;
+ XmlSerializer s = XmlSerializer.DEFAULT_SIMPLE_SQ;
+
+ P t = new P("http://foo", 123, "bar");
+ String r = s.serialize(t);
+ assertEquals("<object url2='http://foo' id2='123'><name>bar</name></object>", r);
+
+ t = p.parse(r, P.class);
+ assertEquals("http://foo", t.url.toString());
+ assertEquals(123, t.id);
+ assertEquals("bar", t.name);
+
+ validateXml(t, s);
+ }
+
+ public static class P {
+ @BeanProperty(beanUri=true, name="url2") public URL url;
+ @BeanProperty(name="id2") @Xml(format=ATTR) public int id;
+ public String name;
+ public P() {}
+ public P(String url, int id, String name) throws Exception {
+ this.url = new URL(url);
+ this.id = id;
+ this.name = name;
+ }
+ }
+
+ //====================================================================================================
+ // Namespace on class
+ //====================================================================================================
+ @Test
+ public void testNsOnClass() throws Exception {
+ XmlSerializer s = new XmlSerializer.SimpleSq().setProperty(XML_autoDetectNamespaces, false);
+ XmlParser p = XmlParser.DEFAULT;
+
+ T1 t = new T1();
+ String r = s.serialize(t);
+ assertEquals("<object><f1>1</f1><f2>2</f2><f3>3</f3><f4>4</f4></object>", r);
+ assertTrue(t.equals(p.parse(r, T1.class)));
+
+ s.setProperty(XML_enableNamespaces, true).setProperty(XML_addNamespaceUrisToRoot, false);
+ r = s.serialize(t);
+ assertEquals("<object><foo:f1>1</foo:f1><bar:f2>2</bar:f2><foo:f3>3</foo:f3><baz:f4>4</baz:f4></object>", r);
+
+ // Add namespace URIs to root, but don't auto-detect.
+ // Only xsi should be added to root.
+ s.setProperty(XML_addNamespaceUrisToRoot, true);
+ r = s.serialize(t);
+ assertEquals("<object xmlns='http://www.ibm.com/2013/Juneau' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><foo:f1>1</foo:f1><bar:f2>2</bar:f2><foo:f3>3</foo:f3><baz:f4>4</baz:f4></object>", r);
+
+ // Manually set namespaces
+ s.setProperty(XML_namespaces,
+ new Namespace[] {
+ NamespaceFactory.get("foo","http://foo"),
+ NamespaceFactory.get("bar","http://bar"),
+ NamespaceFactory.get("baz","http://baz")
+ }
+ );
+ r = s.serialize(t);
+ assertEquals("<object xmlns='http://www.ibm.com/2013/Juneau' xmlns:foo='http://foo' xmlns:bar='http://bar' xmlns:baz='http://baz' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><foo:f1>1</foo:f1><bar:f2>2</bar:f2><foo:f3>3</foo:f3><baz:f4>4</baz:f4></object>", r);
+ assertTrue(t.equals(p.parse(r, T1.class)));
+ validateXml(t, s);
+
+ // Auto-detect namespaces.
+ s = new XmlSerializer.SimpleSq().setProperty(XML_autoDetectNamespaces, true);
+ r = s.serialize(t);
+ assertEquals("<object><f1>1</f1><f2>2</f2><f3>3</f3><f4>4</f4></object>", r);
+ assertTrue(t.equals(p.parse(r, T1.class)));
+
+ s.setProperty(XML_addNamespaceUrisToRoot, true);
+ r = s.serialize(t);
+ assertEquals("<object><f1>1</f1><f2>2</f2><f3>3</f3><f4>4</f4></object>", r);
+ assertTrue(t.equals(p.parse(r, T1.class)));
+
+ s.setProperty(XML_enableNamespaces, true);
+ r = s.serialize(t);
+ assertEquals("<object xmlns='http://www.ibm.com/2013/Juneau' xmlns:foo='http://foo' xmlns:bar='http://bar' xmlns:baz='http://baz' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><foo:f1>1</foo:f1><bar:f2>2</bar:f2><foo:f3>3</foo:f3><baz:f4>4</baz:f4></object>", r);
+ assertTrue(t.equals(p.parse(r, T1.class)));
+ validateXml(t, s);
+ }
+
+ //====================================================================================================
+ // Namespace on class with element name.
+ //====================================================================================================
+ @Test
+ public void testNsOnClassWithElementName() throws Exception {
+ XmlSerializer s = new XmlSerializer.SimpleSq().setProperty(XML_autoDetectNamespaces, false);
+ XmlParser p = XmlParser.DEFAULT;
+
+ T2 t = new T2();
+ String r = s.serialize(t);
+ assertEquals("<T2><f1>1</f1><f2>2</f2><f3>3</f3><f4>4</f4></T2>", r);
+ assertTrue(t.equals(p.parse(r, T2.class)));
+
+ s.setProperty(XML_enableNamespaces, true).setProperty(XML_addNamespaceUrisToRoot, false);
+ r = s.serialize(t);
+ assertEquals("<foo:T2><foo:f1>1</foo:f1><bar:f2>2</bar:f2><foo:f3>3</foo:f3><baz:f4>4</baz:f4></foo:T2>", r);
+
+ // Add namespace URIs to root, but don't auto-detect.
+ // Only xsi should be added to root.
+ s.setProperty(XML_addNamespaceUrisToRoot, true);
+ r = s.serialize(t);
+ assertEquals("<foo:T2 xmlns='http://www.ibm.com/2013/Juneau' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><foo:f1>1</foo:f1><bar:f2>2</bar:f2><foo:f3>3</foo:f3><baz:f4>4</baz:f4></foo:T2>", r);
+
+ // Manually set namespaces
+ s.setProperty(XML_namespaces,
+ new Namespace[] {
+ NamespaceFactory.get("foo","http://foo"),
+ NamespaceFactory.get("bar","http://bar"),
+ NamespaceFactory.get("baz","http://baz")
+ }
+ );
+ r = s.serialize(t);
+ assertEquals("<foo:T2 xmlns='http://www.ibm.com/2013/Juneau' xmlns:foo='http://foo' xmlns:bar='http://bar' xmlns:baz='http://baz' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><foo:f1>1</foo:f1><bar:f2>2</bar:f2><foo:f3>3</foo:f3><baz:f4>4</baz:f4></foo:T2>", r);
+ assertTrue(t.equals(p.parse(r, T2.class)));
+ validateXml(t, s);
+
+ // Auto-detect namespaces.
+ s = new XmlSerializer.SimpleSq().setProperty(XML_autoDetectNamespaces, true);
+ r = s.serialize(t);
+ assertEquals("<T2><f1>1</f1><f2>2</f2><f3>3</f3><f4>4</f4></T2>", r);
+
+ s.setProperty(XML_addNamespaceUrisToRoot, true);
+ r = s.serialize(t);
+ assertEquals("<T2><f1>1</f1><f2>2</f2><f3>3</f3><f4>4</f4></T2>", r);
+
+ s.setProperty(XML_enableNamespaces, true);
+ r = s.serialize(t);
+ assertEquals("<foo:T2 xmlns='http://www.ibm.com/2013/Juneau' xmlns:foo='http://foo' xmlns:bar='http://bar' xmlns:baz='http://baz' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><foo:f1>1</foo:f1><bar:f2>2</bar:f2><foo:f3>3</foo:f3><baz:f4>4</baz:f4></foo:T2>", r);
+ assertTrue(t.equals(p.parse(r, T2.class)));
+ validateXml(t, s);
+ }
+
+
+ //====================================================================================================
+ // Namespace on package, no namespace on class.
+ //====================================================================================================
+ @Test
+ public void testNsOnPackageNoNsOnClass() throws Exception {
+ XmlSerializer s = new XmlSerializer.SimpleSq();
+ XmlParser p = XmlParser.DEFAULT;
+
+ T3 t = new T3();
+ String r = s.serialize(t);
+ assertEquals("<object><f1>1</f1><f2>2</f2><f3>3</f3><f4>4</f4></object>", r);
+ assertTrue(t.equals(p.parse(r, T3.class)));
+ validateXml(t, s);
+
+ s.setProperty(XML_enableNamespaces, true).setProperty(XML_addNamespaceUrisToRoot, false);
+ r = s.serialize(t);
+ assertEquals("<object><p1:f1>1</p1:f1><bar:f2>2</bar:f2><p1:f3>3</p1:f3><baz:f4>4</baz:f4></object>", r);
+
+ // Add namespace URIs to root, but don't auto-detect.
+ // Only xsi should be added to root.
+ s.setProperty(XML_addNamespaceUrisToRoot, true).setProperty(XML_autoDetectNamespaces, false);
+ r = s.serialize(t);
+ assertEquals("<object xmlns='http://www.ibm.com/2013/Juneau' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><p1:f1>1</p1:f1><bar:f2>2</bar:f2><p1:f3>3</p1:f3><baz:f4>4</baz:f4></object>", r);
+
+ // Manually set namespaces
+ s.setProperty(XML_autoDetectNamespaces, false);
+ s.setProperty(XML_namespaces,
+ new Namespace[] {
+ NamespaceFactory.get("p1","http://p1"),
+ NamespaceFactory.get("bar","http://bar"),
+ NamespaceFactory.get("baz","http://baz")
+ }
+ );
+ r = s.serialize(t);
+ assertEquals("<object xmlns='http://www.ibm.com/2013/Juneau' xmlns:p1='http://p1' xmlns:bar='http://bar' xmlns:baz='http://baz' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><p1:f1>1</p1:f1><bar:f2>2</bar:f2><p1:f3>3</p1:f3><baz:f4>4</baz:f4></object>", r);
+ assertTrue(t.equals(p.parse(r, T3.class)));
+ validateXml(t, s);
+
+ // Auto-detect namespaces.
+ s = new XmlSerializer.SimpleSq().setProperty(XML_autoDetectNamespaces, true);
+ r = s.serialize(t);
+ assertEquals("<object><f1>1</f1><f2>2</f2><f3>3</f3><f4>4</f4></object>", r);
+
+ s.setProperty(XML_addNamespaceUrisToRoot, true);
+ r = s.serialize(t);
+ assertEquals("<object><f1>1</f1><f2>2</f2><f3>3</f3><f4>4</f4></object>", r);
+
+ s.setProperty(XML_enableNamespaces, true);
+ r = s.serialize(t);
+ assertEquals("<object xmlns='http://www.ibm.com/2013/Juneau' xmlns:p1='http://p1' xmlns:bar='http://bar' xmlns:baz='http://baz' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><p1:f1>1</p1:f1><bar:f2>2</bar:f2><p1:f3>3</p1:f3><baz:f4>4</baz:f4></object>", r);
+ assertTrue(t.equals(p.parse(r, T3.class)));
+ validateXml(t, s);
+ }
+
+ //====================================================================================================
+ // Namespace on package, no namespace on class, element name on class.
+ //====================================================================================================
+ @Test
+ public void testNsOnPackageNoNsOnClassElementNameOnClass() throws Exception {
+ XmlSerializer s = new XmlSerializer.SimpleSq().setProperty(XML_autoDetectNamespaces, false);
+ XmlParser p = XmlParser.DEFAULT;
+
+ T4 t = new T4();
+ String r = s.serialize(t);
+ assertEquals("<T4><f1>1</f1><f2>2</f2><f3>3</f3><f4>4</f4></T4>", r);
+ assertTrue(t.equals(p.parse(r, T4.class)));
+
+ s.setProperty(XML_enableNamespaces, true).setProperty(XML_addNamespaceUrisToRoot, false);
+ r = s.serialize(t);
+ assertEquals("<p1:T4><p1:f1>1</p1:f1><bar:f2>2</bar:f2><p1:f3>3</p1:f3><baz:f4>4</baz:f4></p1:T4>", r);
+
+ // Add namespace URIs to root, but don't auto-detect.
+ // Only xsi should be added to root.
+ s.setProperty(XML_addNamespaceUrisToRoot, true);
+ r = s.serialize(t);
+ assertEquals("<p1:T4 xmlns='http://www.ibm.com/2013/Juneau' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><p1:f1>1</p1:f1><bar:f2>2</bar:f2><p1:f3>3</p1:f3><baz:f4>4</baz:f4></p1:T4>", r);
+
+ // Manually set namespaces
+ s.setProperty(XML_namespaces,
+ new Namespace[] {
+ NamespaceFactory.get("foo","http://foo"),
+ NamespaceFactory.get("bar","http://bar"),
+ NamespaceFactory.get("baz","http://baz"),
+ NamespaceFactory.get("p1","http://p1")
+ }
+ );
+ r = s.serialize(t);
+ assertEquals("<p1:T4 xmlns='http://www.ibm.com/2013/Juneau' xmlns:foo='http://foo' xmlns:bar='http://bar' xmlns:baz='http://baz' xmlns:p1='http://p1' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><p1:f1>1</p1:f1><bar:f2>2</bar:f2><p1:f3>3</p1:f3><baz:f4>4</baz:f4></p1:T4>", r);
+ assertTrue(t.equals(p.parse(r, T4.class)));
+ validateXml(t, s);
+
+ // Auto-detect namespaces.
+ s = new XmlSerializer.SimpleSq().setProperty(XML_autoDetectNamespaces, true);
+ r = s.serialize(t);
+ assertEquals("<T4><f1>1</f1><f2>2</f2><f3>3</f3><f4>4</f4></T4>", r);
+
+ s.setProperty(XML_addNamespaceUrisToRoot, true);
+ r = s.serialize(t);
+ assertEquals("<T4><f1>1</f1><f2>2</f2><f3>3</f3><f4>4</f4></T4>", r);
+
+ s.setProperty(XML_enableNamespaces, true);
+ r = s.serialize(t);
+ assertEquals("<p1:T4 xmlns='http://www.ibm.com/2013/Juneau' xmlns:p1='http://p1' xmlns:bar='http://bar' xmlns:baz='http://baz' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><p1:f1>1</p1:f1><bar:f2>2</bar:f2><p1:f3>3</p1:f3><baz:f4>4</baz:f4></p1:T4>", r);
+ assertTrue(t.equals(p.parse(r, T4.class)));
+ validateXml(t, s);
+ }
+
+ //====================================================================================================
+ // Namespace on package, namespace on class, element name on class.
+ //====================================================================================================
+ @Test
+ public void testNsOnPackageNsOnClassElementNameOnClass() throws Exception {
+ XmlSerializer s = new XmlSerializer.SimpleSq();
+ XmlParser p = XmlParser.DEFAULT;
+
+ T5 t = new T5();
+ String r = s.serialize(t);
+ assertEquals("<T5><f1>1</f1><f2>2</f2><f3>3</f3><f4>4</f4></T5>", r);
+ assertTrue(t.equals(p.parse(r, T5.class)));
+ validateXml(t, s);
+
+ s.setProperty(XML_enableNamespaces, true).setProperty(XML_addNamespaceUrisToRoot, false).setProperty(XML_autoDetectNamespaces, false);
+ r = s.serialize(t);
+ assertEquals("<foo:T5><foo:f1>1</foo:f1><bar:f2>2</bar:f2><foo:f3>3</foo:f3><baz:f4>4</baz:f4></foo:T5>", r);
+
+ // Add namespace URIs to root, but don't auto-detect.
+ // Only xsi should be added to root.
+ s.setProperty(XML_addNamespaceUrisToRoot, true);
+ r = s.serialize(t);
+ assertEquals("<foo:T5 xmlns='http://www.ibm.com/2013/Juneau' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><foo:f1>1</foo:f1><bar:f2>2</bar:f2><foo:f3>3</foo:f3><baz:f4>4</baz:f4></foo:T5>", r);
+
+ // Manually set namespaces
+ s.setProperty(XML_namespaces,
+ new Namespace[] {
+ NamespaceFactory.get("foo","http://foo"),
+ NamespaceFactory.get("bar","http://bar"),
+ NamespaceFactory.get("baz","http://baz")
+ }
+ );
+ r = s.serialize(t);
+ assertEquals("<foo:T5 xmlns='http://www.ibm.com/2013/Juneau' xmlns:foo='http://foo' xmlns:bar='http://bar' xmlns:baz='http://baz' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><foo:f1>1</foo:f1><bar:f2>2</bar:f2><foo:f3>3</foo:f3><baz:f4>4</baz:f4></foo:T5>", r);
+ assertTrue(t.equals(p.parse(r, T5.class)));
+ validateXml(t, s);
+
+ // Auto-detect namespaces.
+ s = new XmlSerializer.SimpleSq().setProperty(XML_autoDetectNamespaces, true);
+ r = s.serialize(t);
+ assertEquals("<T5><f1>1</f1><f2>2</f2><f3>3</f3><f4>4</f4></T5>", r);
+ validateXml(t, s);
+
+ s.setProperty(XML_addNamespaceUrisToRoot, true);
+ r = s.serialize(t);
+ assertEquals("<T5><f1>1</f1><f2>2</f2><f3>3</f3><f4>4</f4></T5>", r);
+ validateXml(t, s);
+
+ s.setProperty(XML_enableNamespaces, true);
+ r = s.serialize(t);
+ assertEquals("<foo:T5 xmlns='http://www.ibm.com/2013/Juneau' xmlns:foo='http://foo' xmlns:bar='http://bar' xmlns:baz='http://baz' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><foo:f1>1</foo:f1><bar:f2>2</bar:f2><foo:f3>3</foo:f3><baz:f4>4</baz:f4></foo:T5>", r);
+ assertTrue(t.equals(p.parse(r, T5.class)));
+ validateXml(t, s);
+ }
+
+ //====================================================================================================
+ // Namespace on package, namespace on class, no element name on class.
+ //====================================================================================================
+ @Test
+ public void testNsOnPackageNsOnClassNoElementNameOnClass() throws Exception {
+ XmlSerializer s = new XmlSerializer.SimpleSq().setProperty(XML_autoDetectNamespaces, false);
+ XmlParser p = XmlParser.DEFAULT;
+
+ T6 t = new T6();
+ String r = s.serialize(t);
+ assertEquals("<object><f1>1</f1><f2>2</f2><f3>3</f3><f4>4</f4></object>", r);
+ assertTrue(t.equals(p.parse(r, T6.class)));
+
+ s.setProperty(XML_enableNamespaces, true).setProperty(XML_addNamespaceUrisToRoot, false);
+ r = s.serialize(t);
+ assertEquals("<object><foo:f1>1</foo:f1><bar:f2>2</bar:f2><foo:f3>3</foo:f3><baz:f4>4</baz:f4></object>", r);
+
+ // Add namespace URIs to root, but don't auto-detect.
+ // Only xsi should be added to root.
+ s.setProperty(XML_addNamespaceUrisToRoot, true).setProperty(XML_autoDetectNamespaces, false);
+ r = s.serialize(t);
+ assertEquals("<object xmlns='http://www.ibm.com/2013/Juneau' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><foo:f1>1</foo:f1><bar:f2>2</bar:f2><foo:f3>3</foo:f3><baz:f4>4</baz:f4></object>", r);
+
+ // Manually set namespaces
+ s.setProperty(XML_namespaces,
+ new Namespace[] {
+ NamespaceFactory.get("foo","http://foo"),
+ NamespaceFactory.get("bar","http://bar"),
+ NamespaceFactory.get("baz","http://baz")
+ }
+ );
+ r = s.serialize(t);
+ assertEquals("<object xmlns='http://www.ibm.com/2013/Juneau' xmlns:foo='http://foo' xmlns:bar='http://bar' xmlns:baz='http://baz' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><foo:f1>1</foo:f1><bar:f2>2</bar:f2><foo:f3>3</foo:f3><baz:f4>4</baz:f4></object>", r);
+ assertTrue(t.equals(p.parse(r, T6.class)));
+ validateXml(t, s);
+
+ // Auto-detect namespaces.
+ s = new XmlSerializer.SimpleSq().setProperty(XML_autoDetectNamespaces, true);
+ r = s.serialize(t);
+ assertEquals("<object><f1>1</f1><f2>2</f2><f3>3</f3><f4>4</f4></object>", r);
+ validateXml(t, s);
+
+ s.setProperty(XML_addNamespaceUrisToRoot, true);
+ r = s.serialize(t);
+ assertEquals("<object><f1>1</f1><f2>2</f2><f3>3</f3><f4>4</f4></object>", r);
+ validateXml(t, s);
+
+ s.setProperty(XML_enableNamespaces, true);
+ r = s.serialize(t);
+ assertEquals("<object xmlns='http://www.ibm.com/2013/Juneau' xmlns:foo='http://foo' xmlns:bar='http://bar' xmlns:baz='http://baz' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><foo:f1>1</foo:f1><bar:f2>2</bar:f2><foo:f3>3</foo:f3><baz:f4>4</baz:f4></object>", r);
+ assertTrue(t.equals(p.parse(r, T6.class)));
+ validateXml(t, s);
+ }
+
+ //====================================================================================================
+ // Combination of namespaces and overridden bean property names.
+ //====================================================================================================
+ @Test
+ public void testComboOfNsAndOverriddenBeanPropertyNames() throws Exception {
+ XmlSerializer s = new XmlSerializer.SimpleSq().setProperty(XML_autoDetectNamespaces, false);
+ XmlParser p = XmlParser.DEFAULT;
+
+ T7 t = new T7();
+ String r = s.serialize(t);
+ assertEquals("<object><g1>1</g1><g2>2</g2><g3>3</g3><g4>4</g4></object>", r);
+ assertTrue(t.equals(p.parse(r, T7.class)));
+
+ s.setProperty(XML_enableNamespaces, true).setProperty(XML_addNamespaceUrisToRoot, false);
+ r = s.serialize(t);
+ assertEquals("<object><p1:g1>1</p1:g1><bar:g2>2</bar:g2><p1:g3>3</p1:g3><baz:g4>4</baz:g4></object>", r);
+
+ // Add namespace URIs to root, but don't auto-detect.
+ // Only xsi should be added to root.
+ s.setProperty(XML_addNamespaceUrisToRoot, true).setProperty(XML_autoDetectNamespaces, false);
+ r = s.serialize(t);
+ assertEquals("<object xmlns='http://www.ibm.com/2013/Juneau' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><p1:g1>1</p1:g1><bar:g2>2</bar:g2><p1:g3>3</p1:g3><baz:g4>4</baz:g4></object>", r);
+
+ // Manually set namespaces
+ s.setProperty(XML_namespaces,
+ new Namespace[] {
+ NamespaceFactory.get("foo","http://foo"),
+ NamespaceFactory.get("bar","http://bar"),
+ NamespaceFactory.get("baz","http://baz"),
+ NamespaceFactory.get("p1","http://p1")
+ }
+ );
+ r = s.serialize(t);
+ assertEquals("<object xmlns='http://www.ibm.com/2013/Juneau' xmlns:foo='http://foo' xmlns:bar='http://bar' xmlns:baz='http://baz' xmlns:p1='http://p1' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><p1:g1>1</p1:g1><bar:g2>2</bar:g2><p1:g3>3</p1:g3><baz:g4>4</baz:g4></object>", r);
+ assertTrue(t.equals(p.parse(r, T7.class)));
+
+ // Auto-detect namespaces.
+ s = new XmlSerializer.SimpleSq().setProperty(XML_autoDetectNamespaces, true);
+ r = s.serialize(t);
+ assertEquals("<object><g1>1</g1><g2>2</g2><g3>3</g3><g4>4</g4></object>", r);
+
+ s.setProperty(XML_enableNamespaces, false);
+ r = s.serialize(t);
+ assertEquals("<object><g1>1</g1><g2>2</g2><g3>3</g3><g4>4</g4></object>", r);
+
+ s.setProperty(XML_enableNamespaces, true);
+ r = s.serialize(t);
+ assertEquals("<object xmlns='http://www.ibm.com/2013/Juneau' xmlns:p1='http://p1' xmlns:bar='http://bar' xmlns:baz='http://baz' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><p1:g1>1</p1:g1><bar:g2>2</bar:g2><p1:g3>3</p1:g3><baz:g4>4</baz:g4></object>", r);
+ assertTrue(t.equals(p.parse(r, T7.class)));
+ validateXml(t, s);
+ }
+
+ //====================================================================================================
+ // @XmlNs annotation
+ //====================================================================================================
+ @Test
+ public void testXmlNsAnnotation() throws Exception {
+ XmlSerializer s = new XmlSerializer.SimpleSq().setProperty(XML_autoDetectNamespaces, false);
+ XmlParser p = XmlParser.DEFAULT;
+
+ T8 t = new T8();
+ String r = s.serialize(t);
+ assertEquals("<object><f1>1</f1><f2>2</f2><f3>3</f3><f4>4</f4></object>", r);
+ assertTrue(t.equals(p.parse(r, T8.class)));
+
+ s.setProperty(XML_enableNamespaces, true).setProperty(XML_addNamespaceUrisToRoot, false).setProperty(XML_autoDetectNamespaces, false);
+ r = s.serialize(t);
+ assertEquals("<object><p2:f1>1</p2:f1><p1:f2>2</p1:f2><c1:f3>3</c1:f3><f1:f4>4</f1:f4></object>", r);
+
+ // Add namespace URIs to root, but don't auto-detect.
+ // Only xsi should be added to root.
+ s.setProperty(XML_addNamespaceUrisToRoot, true);
+ r = s.serialize(t);
+ assertEquals("<object xmlns='http://www.ibm.com/2013/Juneau' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><p2:f1>1</p2:f1><p1:f2>2</p1:f2><c1:f3>3</c1:f3><f1:f4>4</f1:f4></object>", r);
+
+ // Manually set namespaces
+ s.setProperty(XML_namespaces,
+ new Namespace[] {
+ NamespaceFactory.get("foo","http://foo"),
+ NamespaceFactory.get("bar","http://bar"),
+ NamespaceFactory.get("baz","http://baz")
+ }
+ );
+ r = s.serialize(t);
+ assertEquals("<object xmlns='http://www.ibm.com/2013/Juneau' xmlns:foo='http://foo' xmlns:bar='http://bar' xmlns:baz='http://baz' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><p2:f1>1</p2:f1><p1:f2>2</p1:f2><c1:f3>3</c1:f3><f1:f4>4</f1:f4></object>", r);
+
+ // Auto-detect namespaces.
+ s = new XmlSerializer.SimpleSq().setProperty(XML_autoDetectNamespaces, true);
+ r = s.serialize(t);
+ assertEquals("<object><f1>1</f1><f2>2</f2><f3>3</f3><f4>4</f4></object>", r);
+ assertTrue(t.equals(p.parse(r, T8.class)));
+ validateXml(t, s);
+
+ s.setProperty(XML_addNamespaceUrisToRoot, true);
+ r = s.serialize(t);
+ assertEquals("<object><f1>1</f1><f2>2</f2><f3>3</f3><f4>4</f4></object>", r);
+ validateXml(t, s);
+
+ s.setProperty(XML_enableNamespaces, true);
+ r = s.serialize(t);
+ assertEquals("<object xmlns='http://www.ibm.com/2013/Juneau' xmlns:p2='http://p2' xmlns:p1='http://p1' xmlns:c1='http://c1' xmlns:f1='http://f1' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><p2:f1>1</p2:f1><p1:f2>2</p1:f2><c1:f3>3</c1:f3><f1:f4>4</f1:f4></object>", r);
+ assertTrue(t.equals(p.parse(r, T8.class)));
+ validateXml(t, s);
+ }
+
+ //====================================================================================================
+ // @Xml.ns on package, @Xml.nsUri not on package but in @XmlNs.
+ //====================================================================================================
+ @Test
+ public void testXmlNsOnPackageNsUriInXmlNs() throws Exception {
+ XmlSerializer s = new XmlSerializer.SimpleSq().setProperty(XML_autoDetectNamespaces, false);
+ XmlParser p = XmlParser.DEFAULT;
+
+ T9 t = new T9();
+ String r = s.serialize(t);
+ assertEquals("<object><f1>1</f1></object>", r);
+ assertTrue(t.equals(p.parse(r, T9.class)));
+
+ s.setProperty(XML_enableNamespaces, true).setProperty(XML_autoDetectNamespaces, false).setProperty(XML_addNamespaceUrisToRoot, false);
+ r = s.serialize(t);
+ assertEquals("<object><p1:f1>1</p1:f1></object>", r);
+
+ // Add namespace URIs to root, but don't auto-detect.
+ // Only xsi should be added to root.
+ s.setProperty(XML_addNamespaceUrisToRoot, true);
+ r = s.serialize(t);
+ assertEquals("<object xmlns='http://www.ibm.com/2013/Juneau' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><p1:f1>1</p1:f1></object>", r);
+
+ // Manually set namespaces
+ s.setProperty(XML_namespaces,
+ new Namespace[] {
+ NamespaceFactory.get("foo","http://foo"),
+ NamespaceFactory.get("bar","http://bar"),
+ NamespaceFactory.get("baz","http://baz")
+ }
+ );
+ r = s.serialize(t);
+ assertEquals("<object xmlns='http://www.ibm.com/2013/Juneau' xmlns:foo='http://foo' xmlns:bar='http://bar' xmlns:baz='http://baz' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><p1:f1>1</p1:f1></object>", r);
+
+ // Auto-detect namespaces.
+ s = new XmlSerializer.SimpleSq().setProperty(XML_autoDetectNamespaces, true);
+ r = s.serialize(t);
+ assertEquals("<object><f1>1</f1></object>", r);
+ assertTrue(t.equals(p.parse(r, T9.class)));
+ validateXml(t, s);
+
+ s.setProperty(XML_addNamespaceUrisToRoot, true);
+ r = s.serialize(t);
+ assertEquals("<object><f1>1</f1></object>", r);
+ validateXml(t, s);
+
+ s.setProperty(XML_enableNamespaces, true);
+ r = s.serialize(t);
+ assertEquals("<object xmlns='http://www.ibm.com/2013/Juneau' xmlns:p1='http://p1' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><p1:f1>1</p1:f1></object>", r);
+ assertTrue(t.equals(p.parse(r, T9.class)));
+ validateXml(t, s);
+ }
+
+ //====================================================================================================
+ // @Xml.format=ATTR
+ //====================================================================================================
+ @Test
+ public void testXmlAttrs() throws Exception {
+ XmlSerializer s = new XmlSerializer.SimpleSq();
+ XmlParser p = XmlParser.DEFAULT;
+ String r;
+
+ Q t = new Q();
+ t.f1 = new URL("http://xf1");
+ t.f2 = "xf2";
+ t.f3 = "xf3";
+ r = s.serialize(t);
+ assertEquals("<object f1='http://xf1' f2='xf2' x3='xf3'/>", r);
+ t = p.parse(r, Q.class);
+ assertEquals("http://xf1", t.f1.toString());
+ assertEquals("xf2", t.f2);
+ assertEquals("xf3", t.f3);
+
+ s.setProperty(XML_enableNamespaces, true).setProperty(XML_addNamespaceUrisToRoot, true).setProperty(XML_autoDetectNamespaces, true);
+ r = s.serialize(t);
+ assertEquals("<object xmlns='http://www.ibm.com/2013/Juneau' xmlns:ns='http://ns' xmlns:nsf1='http://nsf1' xmlns:nsf3='http://nsf3' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' nsf1:f1='http://xf1' ns:f2='xf2' nsf3:x3='xf3'/>", r);
+ validateXml(t, s);
+
+ t = p.parse(r, Q.class);
+ assertEquals("http://xf1", t.f1.toString());
+ assertEquals("xf2", t.f2);
+ assertEquals("xf3", t.f3);
+ }
+
+ @Xml(prefix="ns", namespace="http://ns")
+ public static class Q {
+
+ @Xml(format=ATTR, prefix="nsf1", namespace="http://nsf1")
+ public URL f1;
+
+ @Xml(format=ATTR)
+ public String f2;
+
+ @BeanProperty(name="x3")
+ @Xml(format=ATTR, prefix="nsf3", namespace="http://nsf3")
+ public String f3;
+
+ public Q() throws Exception {
+ f1 = new URL("http://f1");
+ f2 = "f2";
+ f3 = "f3";
+ }
+ }
+}
\ No newline at end of file
[26/44] incubator-juneau git commit: Rename CT_* testcases.
Posted by ja...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/ObjectMapTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/ObjectMapTest.java b/org.apache.juneau/src/test/java/org/apache/juneau/ObjectMapTest.java
new file mode 100755
index 0000000..a1e3bf2
--- /dev/null
+++ b/org.apache.juneau/src/test/java/org/apache/juneau/ObjectMapTest.java
@@ -0,0 +1,313 @@
+/***************************************************************************************************************************
+ * 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.juneau;
+
+import static org.apache.juneau.TestUtils.*;
+import static org.junit.Assert.*;
+
+import org.apache.juneau.utils.*;
+import org.junit.*;
+
+public class ObjectMapTest {
+
+ //====================================================================================================
+ // testBasic
+ //====================================================================================================
+ @Test
+ public void testBasic() throws Exception {
+ String in;
+
+ in = "{A:'asdf'}";
+ checkStep(1, in, new ObjectMap(in).getString("A"), "asdf");
+
+ in = "{A:{B:'asdf'}}";
+ checkStep(2, in, getDeepString(new ObjectMap(in), "A/B"), "asdf");
+ checkStep(3, in, new ObjectMap(in).getString("A"), "{B:'asdf'}");
+
+ in = "{A:{B:'asdf'+\"asdf\"}}";
+ checkStep(4, in, getDeepString(new ObjectMap(in), "A/B"), "asdfasdf");
+ checkStep(5, in, new ObjectMap(in).getString("A"), "{B:'asdfasdf'}");
+
+ in = "{A:{B:'asdf' + \n\t \"asdf\"}}";
+ checkStep(6, in, getDeepString(new ObjectMap(in), "A/B"), "asdfasdf");
+ checkStep(7, in, new ObjectMap(in).getString("A"), "{B:'asdfasdf'}");
+
+ in = "{A:{B:'asdf\"asdf', C:\"asdf'asdf\", D : \"asdf\\\"asdf\", E: 'asdf\\\'asdf', F:\"asdf\\\'asdf\", G:'asdf\\\"asdf'}}";
+ checkStep(8, in, getDeepString(new ObjectMap(in), "A/B"), "asdf\"asdf");
+ checkStep(9, in, getDeepString(new ObjectMap(in), "A/C"), "asdf'asdf");
+ checkStep(10, in, getDeepString(new ObjectMap(in), "A/D"), "asdf\"asdf");
+ checkStep(11, in, getDeepString(new ObjectMap(in), "A/E"), "asdf'asdf");
+ checkStep(12, in, getDeepString(new ObjectMap(in), "A/F"), "asdf'asdf");
+ checkStep(13, in, getDeepString(new ObjectMap(in), "A/G"), "asdf\"asdf");
+
+ in = "{A:123, B: 123}";
+ checkStep(16, in, new Integer(new ObjectMap(in).getInt("A")).toString(), "123");
+ checkStep(17, in, new Integer(new ObjectMap(in).getInt("B")).toString(), "123");
+
+ in = "{A:true, B: true, C:false, D: false}";
+ checkStep(18, in, new Boolean(new ObjectMap(in).getBoolean("A")).toString(), "true");
+ checkStep(19, in, new Boolean(new ObjectMap(in).getBoolean("B")).toString(), "true");
+ checkStep(20, in, new Boolean(new ObjectMap(in).getBoolean("C")).toString(), "false");
+ checkStep(21, in, new Boolean(new ObjectMap(in).getBoolean("D")).toString(), "false");
+
+ in = "{'AAA':{\"BBB\":\"CCC\",'DDD':false}}";
+ checkStep(31, in, getDeepString(new ObjectMap(in), "AAA/BBB"), "CCC");
+ checkStep(32, in, getDeepBoolean(new ObjectMap(in), "AAA/DDD").toString(), "false");
+
+ in = " \n\n\t { 'AAA' : { \"BBB\" : \"CCC\" , 'DDD' : false } } \n\t";
+ checkStep(33, in, getDeepString(new ObjectMap(in), "AAA/BBB"), "CCC");
+ checkStep(34, in, getDeepBoolean(new ObjectMap(in), "AAA/DDD").toString(), "false");
+
+ in = "/*x*/{A:'B','C':1,\"E\":[1,2,3],G:['g1','g2','g3']}";
+ checkStep(100, in, new ObjectMap(in).getString("A"), "B");
+ in = "{/*x*/A:'B','C':1,\"E\":[1,2,3],G:['g1','g2','g3']}";
+ checkStep(101, in, new ObjectMap(in).getString("A"), "B");
+ in = "{A/*x*/:'B','C':1,\"E\":[1,2,3],G:['g1','g2','g3']}";
+ checkStep(102, in, new ObjectMap(in).getString("A"), "B");
+ in = "{A:/*x*/'B','C':1,\"E\":[1,2,3],G:['g1','g2','g3']}";
+ checkStep(103, in, new ObjectMap(in).getString("A"), "B");
+ in = "{A:'/*x*/B','C':1,\"E\":[1,2,3],G:['g1','g2','g3']}";
+ checkStep(104, in, new ObjectMap(in).getString("A"), "/*x*/B");
+ in = "{A:'B/*x*/','C':1,\"E\":[1,2,3],G:['g1','g2','g3']}";
+ checkStep(105, in, new ObjectMap(in).getString("A"), "B/*x*/");
+ in = "{A:'B'/*x*/,'C':1,\"E\":[1,2,3],G:['g1','g2','g3']}";
+ checkStep(106, in, new ObjectMap(in).getString("A"), "B");
+ in = "{A:'B',/*x*/'C':1,\"E\":[1,2,3],G:['g1','g2','g3']}";
+ checkStep(107, in, new ObjectMap(in).getString("C"), "1");
+ in = "{A:'B','C':/*x*/1,\"E\":[1,2,3],G:['g1','g2','g3']}";
+ checkStep(108, in, new ObjectMap(in).getString("C"), "1");
+ in = "{A:'B','C':1/*x*/,\"E\":[1,2,3],G:['g1','g2','g3']}";
+ checkStep(109, in, new ObjectMap(in).getString("C"), "1");
+ in = "{A:'B','C':1,/*x*/\"E\":[1,2,3],G:['g1','g2','g3']}";
+ checkStep(110, in, new ObjectMap(in).getObjectList("E").getString(0), "1");
+ in = "{A:'B','C':1,\"/*x*/E\":[1,2,3],G:['g1','g2','g3']}";
+ checkStep(111, in, new ObjectMap(in).getObjectList("/*x*/E").getString(0), "1");
+ in = "{A:'B','C':1,\"E/*x*/\":[1,2,3],G:['g1','g2','g3']}";
+ checkStep(112, in, new ObjectMap(in).getObjectList("E/*x*/").getString(0), "1");
+ in = "{A:'B','C':1,\"E\"/*x*/:[1,2,3],G:['g1','g2','g3']}";
+ checkStep(113, in, new ObjectMap(in).getObjectList("E").getString(0), "1");
+ in = "{A:'B','C':1,\"E\":/*x*/[1,2,3],G:['g1','g2','g3']}";
+ checkStep(114, in, new ObjectMap(in).getObjectList("E").getString(0), "1");
+ in = "{A:'B','C':1,\"E\":[/*x*/1,2,3],G:['g1','g2','g3']}";
+ checkStep(115, in, new ObjectMap(in).getObjectList("E").getString(0), "1");
+ in = "{A:'B','C':1,\"E\":[1/*x*/,2,3],G:['g1','g2','g3']}";
+ checkStep(116, in, new ObjectMap(in).getObjectList("E").getString(0), "1");
+ in = "{A:'B','C':1,\"E\":[1,/*x*/2,3],G:['g1','g2','g3']}";
+ checkStep(117, in, new ObjectMap(in).getObjectList("E").getString(1), "2");
+ in = "{A:'B','C':1,\"E\":[1,2/*x*/,3],G:['g1','g2','g3']}";
+ checkStep(118, in, new ObjectMap(in).getObjectList("E").getString(1), "2");
+ in = "{A:'B','C':1,\"E\":[1,2,/*x*/3],G:['g1','g2','g3']}";
+ checkStep(119, in, new ObjectMap(in).getObjectList("E").getString(2), "3");
+ in = "{A:'B','C':1,\"E\":[1,2,3]/*x*/,G:['g1','g2','g3']}";
+ checkStep(120, in, new ObjectMap(in).getObjectList("E").getString(2), "3");
+ in = "{A:'B','C':1,\"E\":[1,2,3],/*x*/G:['g1','g2','g3']}";
+ checkStep(121, in, new ObjectMap(in).getObjectList("G").getString(0), "g1");
+ in = "{A:'B','C':1,\"E\":[1,2,3],G:[/*x*/'g1','g2','g3']}";
+ checkStep(122, in, new ObjectMap(in).getObjectList("G").getString(0), "g1");
+ in = "{A:'B','C':1,\"E\":[1,2,3],G:['/*x*/g1','g2','g3']}";
+ checkStep(123, in, new ObjectMap(in).getObjectList("G").getString(0), "/*x*/g1");
+ in = "{A:'B','C':1,\"E\":[1,2,3],G:['g1'/*x*/,'g2','g3']}";
+ checkStep(124, in, new ObjectMap(in).getObjectList("G").getString(0), "g1");
+ in = "{A:'B','C':1,\"E\":[1,2,3],G:['g1',/*x*/'g2','g3']}";
+ checkStep(125, in, new ObjectMap(in).getObjectList("G").getString(1), "g2");
+ in = "{A:'B','C':1,\"E\":[1,2,3],G:['g1','g2'/*x*/,'g3']}";
+ checkStep(126, in, new ObjectMap(in).getObjectList("G").getString(1), "g2");
+ in = "{A:'B','C':1,\"E\":[1,2,3],G:['g1','g2',/*x*/'g3']}";
+ checkStep(127, in, new ObjectMap(in).getObjectList("G").getString(2), "g3");
+ in = "{A:'B','C':1,\"E\":[1,2,3],G:['g1','g2','g3'/*x*/]}";
+ checkStep(128, in, new ObjectMap(in).getObjectList("G").getString(2), "g3");
+ in = "{A:'B','C':1,\"E\":[1,2,3],G:['g1','g2','g3']/*x*/}";
+ checkStep(129, in, new ObjectMap(in).getObjectList("G").getString(2), "g3");
+ in = "{A:'B','C':1,\"E\":[1,2,3],G:['g1','g2','g3']}/*x*/";
+ checkStep(130, in, new ObjectMap(in).getObjectList("G").getString(2), "g3");
+
+ in = "/*\tx\t*///\tx\t\n\t/*\tx\t*/{A:'B','C':1,\"E\":[1,2,3],G:['g1','g2','g3']}";
+ checkStep(201, in, new ObjectMap(in).getString("A"), "B");
+ in = "{/*\tx\t*///\tx\t\n\t/*\tx\t*/A:'B','C':1,\"E\":[1,2,3],G:['g1','g2','g3']}";
+ checkStep(202, in, new ObjectMap(in).getString("A"), "B");
+ in = "{A/*\tx\t*///\tx\t\n\t/*\tx\t*/:'B','C':1,\"E\":[1,2,3],G:['g1','g2','g3']}";
+ checkStep(203, in, new ObjectMap(in).getString("A"), "B");
+ in = "{A:/*\tx\t*///\tx\t\n\t/*\tx\t*/'B','C':1,\"E\":[1,2,3],G:['g1','g2','g3']}";
+ checkStep(204, in, new ObjectMap(in).getString("A"), "B");
+ in = "{A:'/*\tx\t*///\tx\t\n\t/*\tx\t*/B','C':1,\"E\":[1,2,3],G:['g1','g2','g3']}";
+ checkStep(205, in, new ObjectMap(in).getString("A"), "/*\tx\t*///\tx\t\n\t/*\tx\t*/B");
+ in = "{A:'B/*\tx\t*///\tx\t\n\t/*\tx\t*/','C':1,\"E\":[1,2,3],G:['g1','g2','g3']}";
+ checkStep(206, in, new ObjectMap(in).getString("A"), "B/*\tx\t*///\tx\t\n\t/*\tx\t*/");
+ in = "{A:'B'/*\tx\t*///\tx\t\n\t/*\tx\t*/,'C':1,\"E\":[1,2,3],G:['g1','g2','g3']}";
+ checkStep(207, in, new ObjectMap(in).getString("A"), "B");
+ in = "{A:'B',/*\tx\t*///\tx\t\n\t/*\tx\t*/'C':1,\"E\":[1,2,3],G:['g1','g2','g3']}";
+ checkStep(208, in, new ObjectMap(in).getString("C"), "1");
+ in = "{A:'B','C':/*\tx\t*///\tx\t\n\t/*\tx\t*/1,\"E\":[1,2,3],G:['g1','g2','g3']}";
+ checkStep(209, in, new ObjectMap(in).getString("C"), "1");
+ in = "{A:'B','C':1/*\tx\t*///\tx\t\n\t/*\tx\t*/,\"E\":[1,2,3],G:['g1','g2','g3']}";
+ checkStep(210, in, new ObjectMap(in).getString("C"), "1");
+ in = "{A:'B','C':1,/*\tx\t*///\tx\t\n\t/*\tx\t*/\"E\":[1,2,3],G:['g1','g2','g3']}";
+ checkStep(211, in, new ObjectMap(in).getObjectList("E").getString(0), "1");
+ in = "{A:'B','C':1,\"/*\tx\t*///\tx\t\n\t/*\tx\t*/E\":[1,2,3],G:['g1','g2','g3']}";
+ checkStep(212, in, new ObjectMap(in).getObjectList("/*\tx\t*///\tx\t\n\t/*\tx\t*/E").getString(0), "1");
+ in = "{A:'B','C':1,\"E/*\tx\t*///\tx\t\n\t/*\tx\t*/\":[1,2,3],G:['g1','g2','g3']}";
+ checkStep(213, in, new ObjectMap(in).getObjectList("E/*\tx\t*///\tx\t\n\t/*\tx\t*/").getString(0), "1");
+ in = "{A:'B','C':1,\"E\"/*\tx\t*///\tx\t\n\t/*\tx\t*/:[1,2,3],G:['g1','g2','g3']}";
+ checkStep(214, in, new ObjectMap(in).getObjectList("E").getString(0), "1");
+ in = "{A:'B','C':1,\"E\":/*\tx\t*///\tx\t\n\t/*\tx\t*/[1,2,3],G:['g1','g2','g3']}";
+ checkStep(215, in, new ObjectMap(in).getObjectList("E").getString(0), "1");
+ in = "{A:'B','C':1,\"E\":[/*\tx\t*///\tx\t\n\t/*\tx\t*/1,2,3],G:['g1','g2','g3']}";
+ checkStep(216, in, new ObjectMap(in).getObjectList("E").getString(0), "1");
+ in = "{A:'B','C':1,\"E\":[1/*\tx\t*///\tx\t\n\t/*\tx\t*/,2,3],G:['g1','g2','g3']}";
+ checkStep(217, in, new ObjectMap(in).getObjectList("E").getString(0), "1");
+ in = "{A:'B','C':1,\"E\":[1,/*\tx\t*///\tx\t\n\t/*\tx\t*/2,3],G:['g1','g2','g3']}";
+ checkStep(218, in, new ObjectMap(in).getObjectList("E").getString(1), "2");
+ in = "{A:'B','C':1,\"E\":[1,2/*\tx\t*///\tx\t\n\t/*\tx\t*/,3],G:['g1','g2','g3']}";
+ checkStep(219, in, new ObjectMap(in).getObjectList("E").getString(1), "2");
+ in = "{A:'B','C':1,\"E\":[1,2,/*\tx\t*///\tx\t\n\t/*\tx\t*/3],G:['g1','g2','g3']}";
+ checkStep(220, in, new ObjectMap(in).getObjectList("E").getString(2), "3");
+ in = "{A:'B','C':1,\"E\":[1,2,3]/*\tx\t*///\tx\t\n\t/*\tx\t*/,G:['g1','g2','g3']}";
+ checkStep(221, in, new ObjectMap(in).getObjectList("E").getString(2), "3");
+ in = "{A:'B','C':1,\"E\":[1,2,3],/*\tx\t*///\tx\t\n\t/*\tx\t*/G:['g1','g2','g3']}";
+ checkStep(222, in, new ObjectMap(in).getObjectList("G").getString(0), "g1");
+ in = "{A:'B','C':1,\"E\":[1,2,3],G:[/*\tx\t*///\tx\t\n\t/*\tx\t*/'g1','g2','g3']}";
+ checkStep(223, in, new ObjectMap(in).getObjectList("G").getString(0), "g1");
+ in = "{A:'B','C':1,\"E\":[1,2,3],G:['/*\tx\t*///\tx\t\n\t/*\tx\t*/g1','g2','g3']}";
+ checkStep(224, in, new ObjectMap(in).getObjectList("G").getString(0), "/*\tx\t*///\tx\t\n\t/*\tx\t*/g1");
+ in = "{A:'B','C':1,\"E\":[1,2,3],G:['g1'/*\tx\t*///\tx\t\n\t/*\tx\t*/,'g2','g3']}";
+ checkStep(225, in, new ObjectMap(in).getObjectList("G").getString(0), "g1");
+ in = "{A:'B','C':1,\"E\":[1,2,3],G:['g1',/*\tx\t*///\tx\t\n\t/*\tx\t*/'g2','g3']}";
+ checkStep(226, in, new ObjectMap(in).getObjectList("G").getString(1), "g2");
+ in = "{A:'B','C':1,\"E\":[1,2,3],G:['g1','g2'/*\tx\t*///\tx\t\n\t/*\tx\t*/,'g3']}";
+ checkStep(227, in, new ObjectMap(in).getObjectList("G").getString(1), "g2");
+ in = "{A:'B','C':1,\"E\":[1,2,3],G:['g1','g2',/*\tx\t*///\tx\t\n\t/*\tx\t*/'g3']}";
+ checkStep(228, in, new ObjectMap(in).getObjectList("G").getString(2), "g3");
+ in = "{A:'B','C':1,\"E\":[1,2,3],G:['g1','g2','g3'/*\tx\t*///\tx\t\n\t/*\tx\t*/]}";
+ checkStep(229, in, new ObjectMap(in).getObjectList("G").getString(2), "g3");
+ in = "{A:'B','C':1,\"E\":[1,2,3],G:['g1','g2','g3']/*\tx\t*///\tx\t\n\t/*\tx\t*/}";
+ checkStep(230, in, new ObjectMap(in).getObjectList("G").getString(2), "g3");
+ in = "{A:'B','C':1,\"E\":[1,2,3],G:['g1','g2','g3']}/*\tx\t*///\tx\t\n\t/*\tx\t*/";
+ checkStep(231, in, new ObjectMap(in).getObjectList("G").getString(2), "g3");
+
+ in = "{ /* x */ // x \n /* x */ A:'B','C':1,\"E\":[1,2,3],G:['g1','g2','g3']}";
+ checkStep(240, in, new ObjectMap(in).getString("A"), "B");
+
+ in = "{A:'B','C':1,\"E\":[1,2,3],G:['g1','g2','g3']}";
+ checkStep(301, in, new ObjectMap(in).getString("A", "default"), "B");
+ in = "{/*A:'B',*/'C':1,\"E\":[1,2,3],G:['g1','g2','g3']}";
+ checkStep(302, in, new ObjectMap(in).getString("A", "default"), "default");
+ in = "{A:'B',/*'C':1,*/\"E\":[1,2,3],G:['g1','g2','g3']}";
+ checkStep(303, in, new ObjectMap(in).getString("C", "default"), "default");
+ in = "{A:'B','C':1,/*\"E\":[1,2,3],*/G:['g1','g2','g3']}";
+ checkStep(304, in, new ObjectMap(in).getString("E", "default"), "default");
+ in = "{A:'B','C':1,\"E\":[/*1,*/2,3],G:['g1','g2','g3']}";
+ checkStep(305, in, new ObjectMap(in).getObjectList("E").getString(0), "2");
+ in = "{A:'B','C':1,\"E\":[1,/*2,*/3],G:['g1','g2','g3']}";
+ checkStep(306, in, new ObjectMap(in).getObjectList("E").getString(1), "3");
+ in = "{A:'B','C':1,\"E\":[1,2/*,3*/],G:['g1','g2','g3']}";
+ checkStep(307, in, new ObjectMap(in).getObjectList("E").getString(1), "2");
+ in = "{A:'B','C':1,\"E\":[1,2,3],G:[/*'g1',*/'g2','g3']}";
+ checkStep(308, in, new ObjectMap(in).getObjectList("G").getString(0), "g2");
+ in = "{A:'B','C':1,\"E\":[1,2,3],G:['g1'/*,'g2'*/,'g3']}";
+ checkStep(309, in, new ObjectMap(in).getObjectList("G").getString(1), "g3");
+ in = "{A:'B','C':1,\"E\":[1,2,3],G:['g1','g2'/*,'g3'*/]}";
+ checkStep(310, in, new ObjectMap(in).getObjectList("G").getString(1), "g2");
+ in = "{A:'B','C':1,\"E\":[1,2,3],G:['g1','g2','g3']}";
+ checkStep(310, in, new ObjectMap(in).getObjectList("G").getString(1), "g2");
+
+ // Check keys that contain array indexes
+ in = "{A:{B:[{C:'c0'},{C:'c1'},{C:'c2'}]}}";
+ checkStep(401, in, getDeepString(new ObjectMap(in), "A/B/0/C"), "c0");
+ checkStep(402, in, getDeepString(new ObjectMap(in), "A/B/1/C"), "c1");
+ checkStep(403, in, getDeepString(new ObjectMap(in), "A/B/2/C"), "c2");
+
+ // Check extended unicode characters.
+ in = "{'\U00024b62\U00024b62':'\U00024b62\U00024b62'}";
+ checkStep(1, in, new ObjectMap(in).getString("\U00024b62\U00024b62"), "\U00024b62\U00024b62");
+ }
+
+ private String getDeepString(ObjectMap m, String url) {
+ PojoRest r = new PojoRest(m);
+ return (String)r.get(url);
+ }
+
+ private Boolean getDeepBoolean(ObjectMap m, String url) {
+ PojoRest r = new PojoRest(m);
+ return (Boolean)r.get(url);
+ }
+
+ private void checkStep(int step, String input, String output, String expectedValue) {
+ if (!output.equals(expectedValue)) {
+ String msg = "Step #" + step + " failed: [" + input + "]->[" + output + "]...Expected value=[" + expectedValue + "]";
+ fail(msg);
+ }
+ }
+
+ //====================================================================================================
+ // testComparison
+ //====================================================================================================
+ @Test
+ public void testComparison() throws Exception {
+ ObjectMap m1 = new ObjectMap("{ firstName:'John', lastName:'Smith', age:123, isDeceased:false }");
+ ObjectMap m2 = new ObjectMap("{ age:123, isDeceased:false, lastName:'Smith', firstName:'John' }");
+
+ assertTrue(m1.equals(m2));
+ }
+
+ //====================================================================================================
+ // testParent
+ //====================================================================================================
+ @Test
+ public void testParent() throws Exception {
+ ObjectMap m1 = new ObjectMap("{a:1}");
+ ObjectMap m2 = new ObjectMap("{b:2}").setInner(m1);
+
+ assertEquals(new Integer(1), m2.getInt("a"));
+ }
+
+ //====================================================================================================
+ // testUpdatability
+ //====================================================================================================
+ @Test
+ public void testUpdatability() throws Exception {
+ ObjectMap m = new ObjectMap("{a:[{b:'c'}]}");
+ ObjectList l = m.getObjectList("a");
+ ObjectMap m2 = l.getObjectMap(0);
+ m2.put("b", "x");
+ assertObjectEquals("{a:[{b:'x'}]}", m);
+
+ m = new ObjectMap("{a:[{b:'c'}]}");
+ for (ObjectMap m3 : m.getObjectList("a").elements(ObjectMap.class))
+ m3.put("b", "y");
+
+ assertObjectEquals("{a:[{b:'y'}]}", m);
+ }
+
+ //====================================================================================================
+ // testAtMethods
+ //====================================================================================================
+ @Test
+ public void testAtMethods() throws Exception {
+ ObjectMap m = new ObjectMap("{a:[{b:'c'}]}");
+ String r;
+
+ r = m.getAt(String.class, "a/0/b");
+ assertEquals("c", r);
+
+ m.putAt("a/0/b", "d");
+ r = m.getAt(String.class, "a/0/b");
+ assertEquals("d", r);
+
+ m.postAt("a", "e");
+ r = m.getAt(String.class, "a/1");
+ assertEquals("e", r);
+
+ m.deleteAt("a/1");
+ assertEquals("{a:[{b:'d'}]}", m.toString());
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/ParserGenericsTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/ParserGenericsTest.java b/org.apache.juneau/src/test/java/org/apache/juneau/ParserGenericsTest.java
new file mode 100755
index 0000000..a0f10ee
--- /dev/null
+++ b/org.apache.juneau/src/test/java/org/apache/juneau/ParserGenericsTest.java
@@ -0,0 +1,71 @@
+/***************************************************************************************************************************
+ * 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.juneau;
+
+import static org.junit.Assert.*;
+
+import java.util.*;
+
+import org.apache.juneau.json.*;
+import org.apache.juneau.parser.*;
+import org.junit.*;
+
+@SuppressWarnings("serial")
+public class ParserGenericsTest {
+
+ //====================================================================================================
+ // Test generic maps
+ //====================================================================================================
+ @Test
+ public void testMap() throws Exception {
+ ReaderParser p = JsonParser.DEFAULT;
+
+ String t = "{foo:{bar:'baz'}}";
+ Map<String,TreeMap<String,String>> r1 = p.parse(t, TestMap1.class);
+ assertEquals(TestMap1.class, r1.getClass());
+ assertEquals(TreeMap.class, r1.get("foo").getClass());
+
+ t = "{foo:[1,2,3]}";
+ Map<String,LinkedList<Integer>> r2 = p.parse(t, TestMap2.class);
+ assertEquals(TestMap2.class, r2.getClass());
+ assertEquals(LinkedList.class, r2.get("foo").getClass());
+ assertEquals(Integer.class, r2.get("foo").get(0).getClass());
+ }
+
+ public static class TestMap1 extends LinkedHashMap<String,TreeMap<String,String>> {}
+ public static class TestMap2 extends LinkedHashMap<String,LinkedList<Integer>> {}
+
+ //====================================================================================================
+ // Test generic maps
+ //====================================================================================================
+ @Test
+ public void testCollection() throws Exception {
+ ReaderParser p = JsonParser.DEFAULT;
+
+ String t = "[{foo:{bar:'baz'}}]";
+ List<TestMap1> r1 = p.parse(t, TestCollection1.class);
+ assertEquals(TestCollection1.class, r1.getClass());
+ assertEquals(TestMap1.class, r1.get(0).getClass());
+ assertEquals(TreeMap.class, r1.get(0).get("foo").getClass());
+
+ t = "[{foo:[1,2,3]}]";
+ List<TestMap2> r2 = p.parse(t, TestCollection2.class);
+ assertEquals(TestCollection2.class, r2.getClass());
+ assertEquals(TestMap2.class, r2.get(0).getClass());
+ assertEquals(LinkedList.class, r2.get(0).get("foo").getClass());
+ assertEquals(Integer.class, r2.get(0).get("foo").get(0).getClass());
+ }
+
+ public static class TestCollection1 extends LinkedList<TestMap1> {}
+ public static class TestCollection2 extends LinkedList<TestMap2> {}
+}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/ParserReaderTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/ParserReaderTest.java b/org.apache.juneau/src/test/java/org/apache/juneau/ParserReaderTest.java
new file mode 100755
index 0000000..553814a
--- /dev/null
+++ b/org.apache.juneau/src/test/java/org/apache/juneau/ParserReaderTest.java
@@ -0,0 +1,181 @@
+/***************************************************************************************************************************
+ * 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.juneau;
+
+import static org.junit.Assert.*;
+
+import java.io.*;
+
+import org.apache.juneau.parser.*;
+import org.junit.*;
+
+public class ParserReaderTest {
+
+ //====================================================================================================
+ // testBasic
+ //====================================================================================================
+ @Test
+ public void testBasic() throws Exception {
+ String t = "01234567890123456789012345678901234567890123456789";
+
+ // Min buff size is 20.
+ ParserReader pr = new ParserReader(new StringReader(t));
+ String r = read(pr);
+ assertEquals(t, r);
+ pr.close();
+
+ pr = new ParserReader(new StringReader(t));
+ pr.read();
+ pr.unread();
+ r = read(pr);
+ assertEquals(t, r);
+ pr.close();
+
+ pr = new ParserReader(new StringReader(t));
+ assertEquals('0', (char)pr.peek());
+ assertEquals('0', (char)pr.peek());
+ r = read(pr);
+ assertEquals(t, r);
+
+ pr = new ParserReader(new StringReader(t));
+ pr.read();
+ pr.unread();
+ try {
+ pr.unread();
+ fail("Exception expected");
+ } catch (IOException e) {
+ // Good
+ }
+ }
+
+ //====================================================================================================
+ // testMarking
+ //====================================================================================================
+ @Test
+ public void testMarking() throws Exception {
+ String t = "a123456789b123456789c123456789d123456789e123456789f123456789g123456789h123456789i123456789j123456789";
+ String r = null;
+
+ // Min buff size is 20.
+ ParserReader pr = new ParserReader(t);
+ read(pr, 5);
+ pr.mark();
+ read(pr, 10);
+ r = pr.getMarked();
+ assertEquals("56789b1234", r);
+ r = read(pr);
+ assertEquals("56789c123456789d123456789e123456789f123456789g123456789h123456789i123456789j123456789", r);
+
+ // Force doubling of buffer size
+ pr = new ParserReader(t);
+ read(pr, 5);
+ pr.mark();
+ read(pr, 20);
+ r = pr.getMarked();
+ assertEquals("56789b123456789c1234", r);
+ r = read(pr);
+ assertEquals("56789d123456789e123456789f123456789g123456789h123456789i123456789j123456789", r);
+ }
+
+ //====================================================================================================
+ // testReadStrings
+ //====================================================================================================
+ @Test
+ public void testReadStrings() throws Exception {
+ String t = "a123456789b123456789c123456789d123456789e123456789f123456789g123456789h123456789i123456789j123456789";
+
+ // Min buff size is 20.
+ ParserReader pr = new ParserReader(t);
+ assertEquals("a123456789", pr.read(10));
+ pr.mark();
+ assertEquals("b123456789c123456789", pr.read(20));
+ assertEquals("d123456789e123456789f123456789", pr.read(30));
+ assertEquals("123456789c123456789d123456789e123456789f12345678", pr.getMarked(1, -1));
+ assertEquals("g123456789h123456789i123456789j123456789", pr.read(100));
+ assertEquals("", pr.read(100));
+ pr.close();
+ }
+
+ //====================================================================================================
+ // testReplace
+ //====================================================================================================
+ @Test
+ public void testReplace() throws Exception {
+ String t = "a123456789b123456789c123456789d123456789e123456789f123456789g123456789h123456789i123456789j123456789";
+
+ // Min buff size is 20.
+ ParserReader pr = new ParserReader(t);
+ assertEquals("a123456789", pr.read(10));
+ pr.mark();
+ assertEquals("b123456789", pr.read(10));
+ pr.replace('x');
+ assertEquals("c123456789", pr.read(10));
+ assertEquals("b12345678xc123456789", pr.getMarked());
+ pr.close();
+
+ pr = new ParserReader(t);
+ assertEquals("a123456789", pr.read(10));
+ pr.mark();
+ assertEquals("b123456789", pr.read(10));
+ pr.replace('x', 5);
+ assertEquals("c123456789", pr.read(10));
+ assertEquals("b1234xc123456789", pr.getMarked());
+ pr.close();
+ }
+
+ //====================================================================================================
+ // testDelete
+ //====================================================================================================
+ @Test
+ public void testDelete() throws Exception {
+ String t = "a123456789b123456789c123456789d123456789e123456789f123456789g123456789h123456789i123456789j123456789";
+
+ // Min buff size is 20.
+ ParserReader pr = new ParserReader(t);
+ assertEquals("a123456789", pr.read(10));
+ pr.mark();
+ assertEquals("b123456789", pr.read(10));
+ pr.delete();
+ assertEquals("c123456789", pr.read(10));
+ assertEquals("b12345678c123456789", pr.getMarked());
+ pr.close();
+
+ pr = new ParserReader(t);
+ assertEquals("a123456789", pr.read(10));
+ pr.mark();
+ assertEquals("b123456789", pr.read(10));
+ pr.delete(5);
+ assertEquals("c123456789", pr.read(10));
+ assertEquals("b1234c123456789", pr.getMarked());
+ pr.close();
+ }
+
+ //====================================================================================================
+ // Utility methods
+ //====================================================================================================
+
+ private String read(ParserReader r) throws IOException {
+ return read(r, Integer.MAX_VALUE);
+ }
+
+ private String read(ParserReader r, int length) throws IOException {
+ StringBuilder sb = new StringBuilder();
+ for (int i = 0; i < length; i++) {
+ int c = r.read();
+ if (c == -1)
+ return sb.toString();
+ sb.append((char)c);
+ }
+ return sb.toString();
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/PojoTransformTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/PojoTransformTest.java b/org.apache.juneau/src/test/java/org/apache/juneau/PojoTransformTest.java
new file mode 100755
index 0000000..14c5457
--- /dev/null
+++ b/org.apache.juneau/src/test/java/org/apache/juneau/PojoTransformTest.java
@@ -0,0 +1,56 @@
+/***************************************************************************************************************************
+ * 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.juneau;
+
+import static org.junit.Assert.*;
+
+import org.apache.juneau.json.*;
+import org.apache.juneau.parser.*;
+import org.apache.juneau.serializer.*;
+import org.apache.juneau.transform.*;
+import org.junit.*;
+
+public class PojoTransformTest {
+
+ //====================================================================================================
+ // Test same type
+ // If you define a PojoTransform<String,String> filter, then it should be invoked on all strings.
+ //====================================================================================================
+ @Test
+ public void testSameType() throws Exception {
+ JsonSerializer s = JsonSerializer.DEFAULT_LAX.clone().addTransforms(ATransform.class);
+ JsonParser p = JsonParser.DEFAULT.clone().addTransforms(ATransform.class);
+ String r;
+
+ r = s.serialize("foobar");
+ assertEquals("'xfoobarx'", r);
+ r = p.parse(r, String.class);
+ assertEquals("foobar", r);
+
+ ObjectMap m = new ObjectMap("{foo:'bar'}");
+ r = s.serialize(m);
+ assertEquals("{xfoox:'xbarx'}", r);
+ }
+
+ public static class ATransform extends PojoTransform<String,String> {
+ @Override
+ public String transform(String o) throws SerializeException {
+ return "x" + o + "x";
+ }
+
+ @Override
+ public String normalize(String f, ClassMeta<?> hint) throws ParseException {
+ return f.substring(1, f.length()-1);
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/PropertyNamerDashedLcTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/PropertyNamerDashedLcTest.java b/org.apache.juneau/src/test/java/org/apache/juneau/PropertyNamerDashedLcTest.java
new file mode 100755
index 0000000..e5da8a6
--- /dev/null
+++ b/org.apache.juneau/src/test/java/org/apache/juneau/PropertyNamerDashedLcTest.java
@@ -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.juneau;
+
+import static org.junit.Assert.*;
+
+import org.junit.*;
+
+public class PropertyNamerDashedLcTest {
+
+ //====================================================================================================
+ // test
+ //====================================================================================================
+ @Test
+ public void test() throws Exception {
+ PropertyNamer n = new PropertyNamerDashedLC();
+
+ assertEquals("abc", n.getPropertyName("ABC"));
+ assertEquals("abc", n.getPropertyName("abc"));
+ assertEquals("foo-bar-baz", n.getPropertyName("FooBarBaz"));
+ assertEquals("foo-bar-baz", n.getPropertyName("FooBarBAZ"));
+ assertEquals("foo-bar-baz", n.getPropertyName("fooBarBAZ"));
+ assertEquals("", n.getPropertyName(""));
+ assertNull(n.getPropertyName(null));
+ assertEquals("a", n.getPropertyName("A"));
+ assertEquals("a", n.getPropertyName("A"));
+
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/VisibilityTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/VisibilityTest.java b/org.apache.juneau/src/test/java/org/apache/juneau/VisibilityTest.java
new file mode 100755
index 0000000..af2804b
--- /dev/null
+++ b/org.apache.juneau/src/test/java/org/apache/juneau/VisibilityTest.java
@@ -0,0 +1,169 @@
+/***************************************************************************************************************************
+ * 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.juneau;
+
+import static org.apache.juneau.BeanContext.*;
+import static org.apache.juneau.Visibility.*;
+import static org.junit.Assert.*;
+
+import org.apache.juneau.a.*;
+import org.apache.juneau.json.*;
+import org.junit.*;
+
+public class VisibilityTest {
+
+ //====================================================================================================
+ // testVisibility
+ //====================================================================================================
+ @Test
+ public void testClassDefault() throws Exception {
+ JsonSerializer s1 = JsonSerializer.DEFAULT_LAX.clone().setProperty(BEAN_beansRequireSomeProperties, "false");
+ JsonSerializer s2 = JsonSerializer.DEFAULT_LAX.clone().setProperty(BEAN_beansRequireSomeProperties, "false").setProperty(BEAN_beanClassVisibility, PROTECTED);
+ JsonSerializer s3 = JsonSerializer.DEFAULT_LAX.clone().setProperty(BEAN_beansRequireSomeProperties, "false").setProperty(BEAN_beanClassVisibility, Visibility.DEFAULT);
+ JsonSerializer s4 = JsonSerializer.DEFAULT_LAX.clone().setProperty(BEAN_beansRequireSomeProperties, "false").setProperty(BEAN_beanClassVisibility, PRIVATE);
+
+ A1 a1 = A1.create();
+ String r;
+
+ s1.setProperty(BEAN_beanFieldVisibility, NONE);
+ s2.setProperty(BEAN_beanFieldVisibility, NONE);
+ s3.setProperty(BEAN_beanFieldVisibility, NONE);
+ s4.setProperty(BEAN_beanFieldVisibility, NONE);
+
+ r = s1.serialize(a1);
+ assertEquals("{f5:5}", r);
+
+ r = s2.serialize(a1);
+ assertEquals("{f5:5}", r);
+
+ r = s3.serialize(a1);
+ assertEquals("{f5:5}", r);
+
+ r = s4.serialize(a1);
+ assertEquals("{f5:5}", r);
+
+ s1.setProperty(BEAN_beanFieldVisibility, PUBLIC);
+ s2.setProperty(BEAN_beanFieldVisibility, PUBLIC);
+ s3.setProperty(BEAN_beanFieldVisibility, PUBLIC);
+ s4.setProperty(BEAN_beanFieldVisibility, PUBLIC);
+
+ r = s1.serialize(a1);
+ assertEquals("{f1:1,f5:5,g2:{f1:1,f5:5},g3:'A3',g4:'A4',g5:'A5'}", r);
+
+ r = s2.serialize(a1);
+ assertEquals("{f1:1,f5:5,g2:{f1:1,f5:5},g3:{f1:1,f5:5},g4:'A4',g5:'A5'}", r);
+
+ r = s3.serialize(a1);
+ assertEquals("{f1:1,f5:5,g2:{f1:1,f5:5},g3:{f1:1,f5:5},g4:{f1:1,f5:5},g5:'A5'}", r);
+
+ r = s4.serialize(a1);
+ assertEquals("{f1:1,f5:5,g2:{f1:1,f5:5},g3:{f1:1,f5:5},g4:{f1:1,f5:5},g5:{f1:1,f5:5}}", r);
+
+ s1.setProperty(BEAN_beanFieldVisibility, PROTECTED);
+ s2.setProperty(BEAN_beanFieldVisibility, PROTECTED);
+ s3.setProperty(BEAN_beanFieldVisibility, PROTECTED);
+ s4.setProperty(BEAN_beanFieldVisibility, PROTECTED);
+
+ r = s1.serialize(a1);
+ assertEquals("{f1:1,f2:2,f5:5,g2:{f1:1,f2:2,f5:5},g3:'A3',g4:'A4',g5:'A5'}", r);
+
+ r = s2.serialize(a1);
+ assertEquals("{f1:1,f2:2,f5:5,g2:{f1:1,f2:2,f5:5},g3:{f1:1,f2:2,f5:5},g4:'A4',g5:'A5'}", r);
+
+ r = s3.serialize(a1);
+ assertEquals("{f1:1,f2:2,f5:5,g2:{f1:1,f2:2,f5:5},g3:{f1:1,f2:2,f5:5},g4:{f1:1,f2:2,f5:5},g5:'A5'}", r);
+
+ r = s4.serialize(a1);
+ assertEquals("{f1:1,f2:2,f5:5,g2:{f1:1,f2:2,f5:5},g3:{f1:1,f2:2,f5:5},g4:{f1:1,f2:2,f5:5},g5:{f1:1,f2:2,f5:5}}", r);
+
+ s1.setProperty(BEAN_beanFieldVisibility, Visibility.DEFAULT);
+ s2.setProperty(BEAN_beanFieldVisibility, Visibility.DEFAULT);
+ s3.setProperty(BEAN_beanFieldVisibility, Visibility.DEFAULT);
+ s4.setProperty(BEAN_beanFieldVisibility, Visibility.DEFAULT);
+
+ r = s1.serialize(a1);
+ assertEquals("{f1:1,f2:2,f3:3,f5:5,g2:{f1:1,f2:2,f3:3,f5:5},g3:'A3',g4:'A4',g5:'A5'}", r);
+
+ r = s2.serialize(a1);
+ assertEquals("{f1:1,f2:2,f3:3,f5:5,g2:{f1:1,f2:2,f3:3,f5:5},g3:{f1:1,f2:2,f3:3,f5:5},g4:'A4',g5:'A5'}", r);
+
+ r = s3.serialize(a1);
+ assertEquals("{f1:1,f2:2,f3:3,f5:5,g2:{f1:1,f2:2,f3:3,f5:5},g3:{f1:1,f2:2,f3:3,f5:5},g4:{f1:1,f2:2,f3:3,f5:5},g5:'A5'}", r);
+
+ r = s4.serialize(a1);
+ assertEquals("{f1:1,f2:2,f3:3,f5:5,g2:{f1:1,f2:2,f3:3,f5:5},g3:{f1:1,f2:2,f3:3,f5:5},g4:{f1:1,f2:2,f3:3,f5:5},g5:{f1:1,f2:2,f3:3,f5:5}}", r);
+
+ s1.setProperty(BEAN_beanFieldVisibility, PRIVATE);
+ s2.setProperty(BEAN_beanFieldVisibility, PRIVATE);
+ s3.setProperty(BEAN_beanFieldVisibility, PRIVATE);
+ s4.setProperty(BEAN_beanFieldVisibility, PRIVATE);
+
+ r = s1.serialize(a1);
+ assertEquals("{f1:1,f2:2,f3:3,f4:4,f5:5,g2:{f1:1,f2:2,f3:3,f4:4,f5:5},g3:'A3',g4:'A4',g5:'A5'}", r);
+
+ r = s2.serialize(a1);
+ assertEquals("{f1:1,f2:2,f3:3,f4:4,f5:5,g2:{f1:1,f2:2,f3:3,f4:4,f5:5},g3:{f1:1,f2:2,f3:3,f4:4,f5:5},g4:'A4',g5:'A5'}", r);
+
+ r = s3.serialize(a1);
+ assertEquals("{f1:1,f2:2,f3:3,f4:4,f5:5,g2:{f1:1,f2:2,f3:3,f4:4,f5:5},g3:{f1:1,f2:2,f3:3,f4:4,f5:5},g4:{f1:1,f2:2,f3:3,f4:4,f5:5},g5:'A5'}", r);
+
+ r = s4.serialize(a1);
+ assertEquals("{f1:1,f2:2,f3:3,f4:4,f5:5,g2:{f1:1,f2:2,f3:3,f4:4,f5:5},g3:{f1:1,f2:2,f3:3,f4:4,f5:5},g4:{f1:1,f2:2,f3:3,f4:4,f5:5},g5:{f1:1,f2:2,f3:3,f4:4,f5:5}}", r);
+
+ s1.setProperty(BEAN_methodVisibility, NONE);
+ s2.setProperty(BEAN_methodVisibility, NONE);
+ s3.setProperty(BEAN_methodVisibility, NONE);
+ s4.setProperty(BEAN_methodVisibility, NONE);
+
+ r = s1.serialize(a1);
+ assertEquals("{f1:1,f2:2,f3:3,f4:4,g2:{f1:1,f2:2,f3:3,f4:4},g3:'A3',g4:'A4',g5:'A5'}", r);
+
+ r = s2.serialize(a1);
+ assertEquals("{f1:1,f2:2,f3:3,f4:4,g2:{f1:1,f2:2,f3:3,f4:4},g3:{f1:1,f2:2,f3:3,f4:4},g4:'A4',g5:'A5'}", r);
+
+ r = s3.serialize(a1);
+ assertEquals("{f1:1,f2:2,f3:3,f4:4,g2:{f1:1,f2:2,f3:3,f4:4},g3:{f1:1,f2:2,f3:3,f4:4},g4:{f1:1,f2:2,f3:3,f4:4},g5:'A5'}", r);
+
+ r = s4.serialize(a1);
+ assertEquals("{f1:1,f2:2,f3:3,f4:4,g2:{f1:1,f2:2,f3:3,f4:4},g3:{f1:1,f2:2,f3:3,f4:4},g4:{f1:1,f2:2,f3:3,f4:4},g5:{f1:1,f2:2,f3:3,f4:4}}", r);
+
+ s1.setProperty(BEAN_methodVisibility, PROTECTED);
+ s2.setProperty(BEAN_methodVisibility, PROTECTED);
+ s3.setProperty(BEAN_methodVisibility, PROTECTED);
+ s4.setProperty(BEAN_methodVisibility, PROTECTED);
+
+ r = s1.serialize(a1);
+ assertEquals("{f1:1,f2:2,f3:3,f4:4,f5:5,f6:6,g2:{f1:1,f2:2,f3:3,f4:4,f5:5,f6:6},g3:'A3',g4:'A4',g5:'A5'}", r);
+
+ r = s2.serialize(a1);
+ assertEquals("{f1:1,f2:2,f3:3,f4:4,f5:5,f6:6,g2:{f1:1,f2:2,f3:3,f4:4,f5:5,f6:6},g3:{f1:1,f2:2,f3:3,f4:4,f5:5,f6:6},g4:'A4',g5:'A5'}", r);
+
+ r = s3.serialize(a1);
+ assertEquals("{f1:1,f2:2,f3:3,f4:4,f5:5,f6:6,g2:{f1:1,f2:2,f3:3,f4:4,f5:5,f6:6},g3:{f1:1,f2:2,f3:3,f4:4,f5:5,f6:6},g4:{f1:1,f2:2,f3:3,f4:4,f5:5,f6:6},g5:'A5'}", r);
+
+ r = s4.serialize(a1);
+ assertEquals("{f1:1,f2:2,f3:3,f4:4,f5:5,f6:6,g2:{f1:1,f2:2,f3:3,f4:4,f5:5,f6:6},g3:{f1:1,f2:2,f3:3,f4:4,f5:5,f6:6},g4:{f1:1,f2:2,f3:3,f4:4,f5:5,f6:6},g5:{f1:1,f2:2,f3:3,f4:4,f5:5,f6:6}}", r);
+
+ }
+
+ static class A {
+ public int f1;
+ public A(){}
+
+ static A create() {
+ A x = new A();
+ x.f1 = 1;
+ return x;
+ }
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/CT_RoundTripAddClassAttrs.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/CT_RoundTripAddClassAttrs.java b/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/CT_RoundTripAddClassAttrs.java
deleted file mode 100755
index c9bbf93..0000000
--- a/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/CT_RoundTripAddClassAttrs.java
+++ /dev/null
@@ -1,349 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.a.rttests;
-
-import static org.apache.juneau.BeanContext.*;
-import static org.apache.juneau.a.rttests.RoundTripTest.Flags.*;
-import static org.apache.juneau.serializer.SerializerContext.*;
-import static org.junit.Assert.*;
-
-import java.util.*;
-
-import org.apache.juneau.html.*;
-import org.apache.juneau.jena.*;
-import org.apache.juneau.json.*;
-import org.apache.juneau.msgpack.*;
-import org.apache.juneau.parser.*;
-import org.apache.juneau.serializer.*;
-import org.apache.juneau.urlencoding.*;
-import org.apache.juneau.xml.*;
-import org.junit.*;
-import org.junit.runners.*;
-
-
-/**
- * Tests designed to serialize and parse objects to make sure we end up
- * with the same objects for all serializers and parsers.
- */
-public class CT_RoundTripAddClassAttrs extends RoundTripTest {
-
- @Parameterized.Parameters
- public static Collection<Object[]> getPairs() {
- return Arrays.asList(new Object[][] {
- { /* 0 */
- "JsonSerializer.DEFAULT/JsonParser.DEFAULT",
- new JsonSerializer().setProperty(SERIALIZER_addClassAttrs, true).setClassLoader(CT_RoundTripAddClassAttrs.class.getClassLoader()),
- new JsonParser().setProperty(BEAN_useInterfaceProxies, false).setClassLoader(CT_RoundTripAddClassAttrs.class.getClassLoader()),
- 0
- },
- { /* 1 */
- "JsonSerializer.DEFAULT_LAX/JsonParser.DEFAULT",
- new JsonSerializer.Simple().setProperty(SERIALIZER_addClassAttrs, true).setClassLoader(CT_RoundTripAddClassAttrs.class.getClassLoader()),
- new JsonParser().setProperty(BEAN_useInterfaceProxies, false).setClassLoader(CT_RoundTripAddClassAttrs.class.getClassLoader()),
- 0
- },
- { /* 2 */
- "JsonSerializer.DEFAULT_SQ/JsonParser.DEFAULT",
- new JsonSerializer.Simple().setProperty(SERIALIZER_addClassAttrs, true).setClassLoader(CT_RoundTripAddClassAttrs.class.getClassLoader()),
- new JsonParser().setProperty(BEAN_useInterfaceProxies, false).setClassLoader(CT_RoundTripAddClassAttrs.class.getClassLoader()),
- 0
- },
- { /* 3 */
- "XmlSerializer.DEFAULT/XmlParser.DEFAULT",
- new XmlSerializer.XmlJson().setProperty(SERIALIZER_addClassAttrs, true).setClassLoader(CT_RoundTripAddClassAttrs.class.getClassLoader()),
- new XmlParser().setProperty(BEAN_useInterfaceProxies, false).setClassLoader(CT_RoundTripAddClassAttrs.class.getClassLoader()),
- CHECK_XML_WHITESPACE | VALIDATE_XML
- },
- { /* 4 */
- "HtmlSerializer.DEFAULT/HtmlParser.DEFAULT",
- new HtmlSerializer().setProperty(SERIALIZER_addClassAttrs, true).setClassLoader(CT_RoundTripAddClassAttrs.class.getClassLoader()),
- new HtmlParser().setProperty(BEAN_useInterfaceProxies, false).setClassLoader(CT_RoundTripAddClassAttrs.class.getClassLoader()),
- CHECK_XML_WHITESPACE
- },
- { /* 5 */
- "UonSerializer.DEFAULT_ENCODING/UonParser.DEFAULT_DECODING",
- new UonSerializer.Encoding().setProperty(SERIALIZER_addClassAttrs, true).setClassLoader(CT_RoundTripAddClassAttrs.class.getClassLoader()),
- new UonParser.Decoding().setProperty(BEAN_useInterfaceProxies, false).setClassLoader(CT_RoundTripAddClassAttrs.class.getClassLoader()),
- 0
- },
- { /* 6 */
- "UonSerializer.DEFAULT/UonParser.DEFAULT",
- new UonSerializer().setProperty(SERIALIZER_addClassAttrs, true).setClassLoader(CT_RoundTripAddClassAttrs.class.getClassLoader()),
- new UonParser().setProperty(BEAN_useInterfaceProxies, false).setClassLoader(CT_RoundTripAddClassAttrs.class.getClassLoader()),
- 0
- },
- { /* 7 */
- "UrlEncodingSerializer.DEFAULT/UrlEncodingParser.DEFAULT",
- new UrlEncodingSerializer().setProperty(SERIALIZER_addClassAttrs, true).setClassLoader(CT_RoundTripAddClassAttrs.class.getClassLoader()),
- new UrlEncodingParser().setProperty(BEAN_useInterfaceProxies, false).setClassLoader(CT_RoundTripAddClassAttrs.class.getClassLoader()),
- 0
- },
- { /* 8 */
- "RdfSerializer.Xml/RdfParser.Xml",
- new RdfSerializer.Xml().setProperty(SERIALIZER_addClassAttrs, true).setClassLoader(CT_RoundTripAddClassAttrs.class.getClassLoader()),
- new RdfParser.Xml().setProperty(BEAN_useInterfaceProxies, false).setClassLoader(CT_RoundTripAddClassAttrs.class.getClassLoader()),
- 0
- },
- { /* 9 */
- "MsgPackSerializer.DEFAULT/MsgPackParser.DEFAULT",
- new MsgPackSerializer().setProperty(SERIALIZER_addClassAttrs, true).setClassLoader(CT_RoundTripAddClassAttrs.class.getClassLoader()),
- new MsgPackParser().setProperty(BEAN_useInterfaceProxies, false).setClassLoader(CT_RoundTripAddClassAttrs.class.getClassLoader()),
- 0
- }
- });
- }
-
- public CT_RoundTripAddClassAttrs(String label, Serializer s, Parser p, int flags) throws Exception {
- super(label, s, p, flags);
- }
-
- //====================================================================================================
- // testBean
- //====================================================================================================
- @Test
- public void testBean() throws Exception {
- A t = new A("foo");
- AA ta;
- IA ti;
-
- t = roundTrip(t, A.class);
- assertEquals("foo", t.getF1());
-
- ta = roundTrip(t, AA.class);
- assertEquals("foo", ta.getF1());
-
- ti = roundTrip(t, IA.class);
- assertEquals("foo", ti.getF1());
-
- t = (A)roundTrip(t, Object.class);
- assertEquals("foo", t.getF1());
- }
-
- public static interface IA {
- public String getF1();
- public void setF1(String f1);
- }
-
- public static abstract class AA implements IA {
- }
-
- public static class A extends AA {
- private String f1;
-
- @Override /* AA */
- public String getF1() {
- return f1;
- }
- @Override /* AA */
- public void setF1(String f1) {
- this.f1 = f1;
- }
-
- public A() {}
- public A(String f1) {
- this.f1 = f1;
- }
- }
-
- //====================================================================================================
- // testBeanArray
- //====================================================================================================
- @Test
- public void testBeanArray() throws Exception {
- A[] t = {new A("foo")};
- AA[] ta;
- IA[] ti;
-
- t = roundTrip(t, A[].class);
- assertEquals("foo", t[0].getF1());
-
- ta = roundTrip(t, AA[].class);
- assertEquals("foo", ta[0].getF1());
-
- ti = roundTrip(t, IA[].class);
- assertEquals("foo", ti[0].getF1());
-
- t = (A[])roundTrip(t, Object.class);
- assertEquals("foo", t[0].getF1());
- }
-
- //====================================================================================================
- // testBeanWithBeanProps
- //====================================================================================================
- @Test
- public void testBeanWithBeanProps() throws Exception {
- B t = new B("foo");
- t = roundTrip(t, B.class);
- assertEquals("foo", t.f2a.getF1());
- assertEquals("foo", t.f2b.getF1());
- assertEquals("foo", t.f2c.getF1());
- assertEquals("foo", ((A)t.f2d).getF1());
-
- t = (B)roundTrip(t, Object.class);
- assertEquals("foo", t.f2a.getF1());
- assertEquals("foo", t.f2b.getF1());
- assertEquals("foo", t.f2c.getF1());
- assertEquals("foo", ((A)t.f2d).getF1());
- }
-
- public static class B {
- public A f2a;
- public AA f2b;
- public IA f2c;
- public Object f2d;
- public B() {}
- public B(String f1) {
- f2d = f2c = f2b = f2a = new A(f1);
- }
- }
-
- //====================================================================================================
- // testMapsWithTypeParams - Maps with type parameters should not have class attributes on entries.
- //====================================================================================================
- @Test
- public void testMapsWithTypeParams() throws Exception {
- C t = new C("foo");
- t = roundTrip(t, C.class);
- assertEquals("foo", t.f3a.get("foo").getF1());
- assertEquals("foo", t.f3b.get("foo").getF1());
- assertEquals("foo", t.f3c.get("foo").getF1());
- assertEquals("foo", t.f3d.get("foo").getF1());
-
- t = (C)roundTrip(t, Object.class);
- assertEquals("foo", t.f3a.get("foo").getF1());
- assertEquals("foo", t.f3b.get("foo").getF1());
- assertEquals("foo", t.f3c.get("foo").getF1());
- assertEquals("foo", t.f3d.get("foo").getF1());
- }
-
- public static class C {
- public Map<String,A> f3a = new HashMap<String,A>();
- public Map<String,A> f3b = new HashMap<String,A>();
- public Map<String,A> f3c = new HashMap<String,A>();
- public Map<String,A> f3d = new HashMap<String,A>();
-
- public C(){}
- public C(String f1) {
- A b = new A(f1);
- f3a.put("foo", b);
- f3b.put("foo", b);
- f3c.put("foo", b);
- f3d.put("foo", b);
- }
- }
-
- //====================================================================================================
- // testMapsWithoutTypeParams - Maps without type parameters should have class attributes on entries.
- //====================================================================================================
- @Test
- public void testMapsWithoutTypeParams() throws Exception {
- D t = new D("foo");
- t = roundTrip(t, D.class);
- assertEquals("foo", t.f4a[0].getF1());
- assertEquals("foo", t.f4b[0].getF1());
- assertEquals("foo", t.f4c[0].getF1());
- assertEquals("foo", ((A)t.f4d[0]).getF1());
-
- t = (D)roundTrip(t, Object.class);
- assertEquals("foo", t.f4a[0].getF1());
- assertEquals("foo", t.f4b[0].getF1());
- assertEquals("foo", t.f4c[0].getF1());
- assertEquals("foo", ((A)t.f4d[0]).getF1());
- }
-
- public static class D {
- public A[] f4a;
- public AA[] f4b;
- public IA[] f4c;
- public Object[] f4d;
-
- public D(){}
- public D(String f1) {
- A b = new A(f1);
- f4a = new A[]{b};
- f4b = new AA[]{b};
- f4c = new IA[]{b};
- f4d = new Object[]{b};
- }
- }
-
- //====================================================================================================
- // testBeanWithListProps
- //====================================================================================================
- @Test
- public void testBeanWithListProps() throws Exception {
- E t = new E("foo");
- t = roundTrip(t, E.class);
- assertEquals("foo", t.f5a.get(0).getF1());
- assertEquals("foo", t.f5b.get(0).getF1());
- assertEquals("foo", t.f5c.get(0).getF1());
- assertEquals("foo", ((A)t.f5d.get(0)).getF1());
-
- t = (E)roundTrip(t, Object.class);
- assertEquals("foo", t.f5a.get(0).getF1());
- assertEquals("foo", t.f5b.get(0).getF1());
- assertEquals("foo", t.f5c.get(0).getF1());
- assertEquals("foo", ((A)t.f5d.get(0)).getF1());
- }
-
- public static class E {
- public List<A> f5a = new LinkedList<A>();
- public List<AA> f5b = new LinkedList<AA>();
- public List<IA> f5c = new LinkedList<IA>();
- public List<Object> f5d = new LinkedList<Object>();
-
- public E(){}
- public E(String f1) {
- A b = new A(f1);
- f5a.add(b);
- f5b.add(b);
- f5c.add(b);
- f5d.add(b);
- }
- }
-
- //====================================================================================================
- // testBeanWithListOfArraysProps
- //====================================================================================================
- @Test
- public void testBeanWithListOfArraysProps() throws Exception {
- F t = new F("foo");
- t = roundTrip(t, F.class);
- assertEquals("foo", t.f6a.get(0)[0].getF1());
- assertEquals("foo", t.f6b.get(0)[0].getF1());
- assertEquals("foo", t.f6c.get(0)[0].getF1());
- assertEquals("foo", ((A)t.f6d.get(0)[0]).getF1());
-
- t = (F)roundTrip(t, Object.class);
- assertEquals("foo", t.f6a.get(0)[0].getF1());
- assertEquals("foo", t.f6b.get(0)[0].getF1());
- assertEquals("foo", t.f6c.get(0)[0].getF1());
- assertEquals("foo", ((A)t.f6d.get(0)[0]).getF1());
- }
-
- public static class F {
- public List<A[]> f6a = new LinkedList<A[]>();
- public List<AA[]> f6b = new LinkedList<AA[]>();
- public List<IA[]> f6c = new LinkedList<IA[]>();
- public List<Object[]> f6d = new LinkedList<Object[]>();
-
- public F(){}
- public F(String f1) {
- A[] b = {new A(f1)};
- f6a.add(b);
- f6b.add(b);
- f6c.add(b);
- f6d.add(b);
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/CT_RoundTripBeanInheritance.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/CT_RoundTripBeanInheritance.java b/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/CT_RoundTripBeanInheritance.java
deleted file mode 100755
index bc118ae..0000000
--- a/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/CT_RoundTripBeanInheritance.java
+++ /dev/null
@@ -1,220 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.a.rttests;
-
-import static org.apache.juneau.TestUtils.*;
-import static org.junit.Assert.*;
-
-import org.apache.juneau.*;
-import org.apache.juneau.json.*;
-import org.apache.juneau.parser.*;
-import org.apache.juneau.serializer.*;
-import org.junit.*;
-
-
-
-/**
- * Tests designed to serialize and parse objects to make sure we end up
- * with the same objects for all serializers and parsers.
- */
-public class CT_RoundTripBeanInheritance extends RoundTripTest {
-
- public CT_RoundTripBeanInheritance(String label, Serializer s, Parser p, int flags) throws Exception {
- super(label, s, p, flags);
- }
-
- //====================================================================================================
- // testBeanInheritance
- //====================================================================================================
- @Test
- public void testBeanInheritance() throws Exception {
-
- // Skip tests that just return the same object.
- if (returnOriginalObject)
- return;
-
- A2 t1 = new A2(), t2;
- t1.init();
- t2 = roundTrip(t1, A2.class);
- assertEqualObjects(t1, t2);
-
- A3 t3 = new A3();
- t3.init();
- try {
- ClassMeta<?> cm = BeanContext.DEFAULT.getClassMeta(A3.class);
- assertEquals("No properties detected on bean class", cm.getNotABeanReason());
- roundTrip(t3, A3.class);
- fail("Exception expected");
- } catch (ParseException e) {
- } catch (SerializeException e) {
- } catch (InvalidDataConversionException e) {}
- }
-
-
- public static abstract class A1 {
- protected String x = null;
- protected String y = null;
- protected String z = null;
-
- public A1() {
- this.x = null;
- this.y = null;
- this.z = null;
- }
-
- public A1(String x, String y, String z) {
- this.x = x;
- this.y = y;
- this.z = z;
- }
-
- public void setX(String x) {
- this.x = x;
- }
-
- public void setY(String y) {
- this.y = y;
- }
-
- public void setZ(String z) {
- this.z = z;
- }
-
- @Override /* Object */
- public String toString() {
- return ("A1(x: " + this.x + ", y: " + this.y + ", z: " + this.z + ")");
- }
-
- public A1 init() {
- x = null;
- y = "";
- z = "z";
- return this;
- }
- }
-
- public static class A2 extends A1 {
- public A2() {
- super();
- }
-
- public A2(String x, String y, String z) {
- super(x, y, z);
- }
-
- public String getX() {
- return this.x;
- }
-
- public String getY() {
- return this.y;
- }
-
- public String getZ() {
- return this.z;
- }
- }
-
- // This is not supposed to be a valid bean since it has no getters defined.
- public static class A3 extends A1 {
- public A3() {
- super();
- }
-
- public A3(String x, String y, String z) {
- super(x, y, z);
- }
-
- public String isX() {
- throw new RuntimeException("Should not be called!");
- }
-
- public String isY() {
- throw new RuntimeException("Should not be called!");
- }
-
- public String isZ() {
- throw new RuntimeException("Should not be called!");
- }
- }
-
- //====================================================================================================
- // testBeanInheritance2
- //====================================================================================================
- @Test
- public void testBeanInheritance2() throws Exception {
- B1 t1 = new B1().init(), t2;
- t2 = roundTrip(t1, B1.class);
- assertEqualObjects(t1, t2);
- }
-
- public static class B1 extends B2 {
- private A2 f4;
-
- public A2 getF4() {
- return this.f4;
- }
-
- public void setF4(A2 f4) {
- this.f4 = f4;
- }
-
- @Override /* Object */
- public String toString() {
- return super.toString() + " / " + this.f4;
- }
-
- public B1 init() {
- setF1("A1");
- setF2(101);
- setF3(false);
- setF4((A2)new A2().init());
- return this;
- }
- }
-
- public static class B2 {
- private String f1 = null;
- private int f2 = -1;
- private boolean f3 = false;
-
- public String getF1() {
- return this.f1;
- }
-
- public void setF1(String f1) {
- this.f1 = f1;
- }
-
- public int getF2() {
- return this.f2;
- }
-
- public void setF2(int f2) {
- this.f2 = f2;
- }
-
- public boolean isF3() {
- return this.f3;
- }
-
- public void setF3(boolean f3) {
- this.f3 = f3;
- }
-
- @Override /* Object */
- public String toString() {
- return ("B2(f1: " + this.getF1() + ", f2: " + this.getF2() + ")");
- }
- }
-}
[41/44] incubator-juneau git commit: Rename CT_* testcases.
Posted by ja...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestParams.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestParams.java b/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestParams.java
deleted file mode 100755
index 6ecc8d1..0000000
--- a/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestParams.java
+++ /dev/null
@@ -1,716 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.server;
-
-import static javax.servlet.http.HttpServletResponse.*;
-import static org.apache.juneau.server.TestUtils.*;
-import static org.junit.Assert.*;
-
-import java.util.*;
-
-import org.apache.http.*;
-import org.apache.http.client.entity.*;
-import org.apache.http.entity.*;
-import org.apache.http.message.*;
-import org.apache.juneau.*;
-import org.apache.juneau.client.*;
-import org.apache.juneau.json.*;
-import org.junit.*;
-
-public class CT_TestParams {
-
- private static String URL = "/testParams";
- private static boolean debug = false;
-
- //====================================================================================================
- // Basic tests
- //====================================================================================================
- @Test
- public void testBasic() throws Exception {
- RestClient client = new TestRestClient(JsonSerializer.DEFAULT, JsonParser.DEFAULT);
- RestCall r;
-
- // @Override
- // @RestMethod(name="GET",pattern="/")
- // public void doGet(RestRequest req, RestResponse res) {
- // res.setOutput("No args");
- // }
- r = client.doGet(URL);
- assertEquals("GET", r.getResponse(String.class));
-
- r = client.doGet(URL + "/getx?noTrace=true");
- try {
- r.connect();
- fail("Connection should have failed.");
- } catch (RestCallException e) {
- checkErrorResponse(debug, e, SC_NOT_FOUND, "Method 'GET' not found on resource with matching pattern on path '/getx'");
- }
-
- // @RestMethod(name="GET",pattern="/get1")
- // public void doGet1(RestRequest req, RestResponse res) {
- // res.setOutput("/get1");
- // }
- r = client.doGet(URL + "/get1");
- assertEquals("GET /get1", r.getResponse(String.class));
-
- r = client.doGet(URL + "/get1a?noTrace=true");
- try {
- r.connect();
- fail("Connection should have failed.");
- } catch (RestCallException e) {
- checkErrorResponse(debug, e, SC_NOT_FOUND, "Method 'GET' not found on resource with matching pattern on path '/get1a'");
- }
-
- // @RestMethod(name="GET",pattern="/get1/{foo}")
- // public void doGet(RestRequest req, RestResponse res, String foo) {
- // res.setOutput("/get1/" + foo);
- // }
- r = client.doGet(URL + "/get1/foo");
- assertEquals("GET /get1a foo", r.getResponse(String.class));
-
- // URL-encoded part should not get decoded before finding method to invoke.
- // This should match /get1/{foo} and not /get1/{foo}/{bar}
- // NOTE: When testing on Tomcat, must specify the following system property:
- // -Dorg.apache.tomcat.util.buf.UDecoder.ALLOW_ENCODED_SLASH=true
- String x = "x%2Fy+z"; // [x/y z]
- r = client.doGet(URL + "/get1/"+x);
- assertEquals("GET /get1a x/y z", r.getResponse(String.class));
-
- r = client.doGet(URL + "/get1/"+x+"/"+x);
- assertEquals("GET /get1b x/y z,x/y z", r.getResponse(String.class));
-
- r = client.doGet(URL + "/get1/foo");
- assertEquals("GET /get1a foo", r.getResponse(String.class));
-
- r = client.doGet(URL + "/get1/foo/bar/baz?noTrace=true");
- try {
- r.connect();
- fail("Connection should have failed.");
- } catch (RestCallException e) {
- checkErrorResponse(debug, e, SC_NOT_FOUND, "Method 'GET' not found on resource with matching pattern on path '/get1/foo/bar/baz'");
- }
-
- // @RestMethod(name="GET",pattern="/get3/{foo}/{bar}/*")
- // public void doGet3(RestRequest req, RestResponse res, String foo, int bar) {
- // res.setOutput("/get3/"+foo+"/"+bar+", remainder="+req.getRemainder());
- // }
- r = client.doGet(URL + "/get3/foo/123");
- assertEquals("GET /get3/foo/123 remainder=null", r.getResponse(String.class));
-
- r = client.doGet(URL + "/get3/foo/123/xxx");
- assertEquals("GET /get3/foo/123 remainder=xxx", r.getResponse(String.class));
-
- // // Test method name with overlapping name, remainder allowed.
- // @RestMethod(name="GET2")
- // public void get2(RestRequest req, RestResponse res) {
- // res.setOutput("GET2, remainder="+req.getRemainder());
- // }
- r = client.doGet(URL + "?method=get2");
- assertEquals("GET2 remainder=null", r.getResponse(String.class));
- r = client.doGet(URL + "/foo/bar?method=get2");
- assertEquals("GET2 remainder=foo/bar", r.getResponse(String.class));
- r = client.doGet(URL + "/foo/bar?method=GET2");
- assertEquals("GET2 remainder=foo/bar", r.getResponse(String.class));
-
- // // Default POST
- // @Override
- // public void doPost(RestRequest req, RestResponse res) {
- // res.setOutput("POST, remainder="+req.getRemainder());
- // }
- r = client.doPost(URL, "");
- assertEquals("POST remainder=null", r.getResponse(String.class));
- r = client.doPost(URL + "/foo", "");
- assertEquals("POST remainder=foo", r.getResponse(String.class));
-
- // // Bunch of different argument types
- // @RestMethod(name="POST",pattern="/person/{person}")
- // public void doPost(RestRequest req, RestResponse res, Person p) {
- // res.setOutput("POST, /person, name="+p.name+", age="+p.age+" remainder="+req.getRemainder());
- // }
- r = client.doPost(URL + "/person/(name=John+Smith,birthDate=Jan+12~,+1952)", "");
- assertEquals("POST /person/{name=John Smith,birthDate.year=1952} remainder=null", r.getResponse(String.class));
-
- // Fall through to top-level POST
- r = client.doPost(URL + "/person/(name:'John+Smith',age:123)/foo", "");
- assertEquals("POST remainder=person/(name:'John Smith',age:123)/foo", r.getResponse(String.class));
-
- // // Various primitive types
- // @RestMethod(name="PUT",pattern="/primitives/{xInt}.{xShort},{xLong}/{xChar}/{xFloat}/{xDouble}/{xByte}/{xBoolean}")
- // public void doPut1(RestRequest req, RestResponse res, int xInt, short xShort, long xLong, char xChar, float xFloat, double xDouble, byte xByte, boolean xBoolean) {
- // res.setOutput("PUT, /primitives/"+xInt+"."+xShort+","+xLong+"/"+xChar+"/"+xFloat+"/"+xDouble+"/"+xByte+"/"+xBoolean);
- // }
- r = client.doPut(URL + "/primitives/1/2/3/x/4/5/6/true", "");
- assertEquals("PUT /primitives/1/2/3/x/4.0/5.0/6/true", r.getResponse(String.class));
-
- // // Various primitive objects
- // @RestMethod(name="PUT",pattern="/primitiveObjects/{xInt}/{xShort}/{xLong}/{xChar}/{xFloat}/{xDouble}/{xByte}/{xBoolean}")
- // public void doPut1(RestRequest req, RestResponse res, Integer xInt, Short xShort, Long xLong, Character xChar, Float xFloat, Double xDouble, Byte xByte, Boolean xBoolean) {
- // res.setOutput("PUT /primitives/"+xInt+"/"+xShort+"/"+xLong+"/"+xChar+"/"+xFloat+"/"+xDouble+"/"+xByte+"/"+xBoolean);
- // }
- r = client.doPut(URL + "/primitiveObjects/1/2/3/x/4/5/6/true", "");
- assertEquals("PUT /primitiveObjects/1/2/3/x/4.0/5.0/6/true", r.getResponse(String.class));
-
- // // Object with forString(String) method
- // @RestMethod(name="PUT",pattern="/uuid/{uuid}")
- // public void doPut1(RestRequest req, RestResponse res, UUID uuid) {
- // res.setOutput("PUT /uuid/"+uuid);
- // }
- UUID uuid = UUID.randomUUID();
- r = client.doPut(URL + "/uuid/"+uuid, "");
- assertEquals("PUT /uuid/"+uuid, r.getResponse(String.class));
-
- client.closeQuietly();
- }
-
- //====================================================================================================
- // @Param annotation - GET
- //====================================================================================================
- @Test
- public void testParamGet() throws Exception {
- RestClient client = new TestRestClient().setHeader("Accept", "text/plain");
- String r;
- String url = URL + "/testParamGet";
-
- r = client.doGet(url + "?p1=p1&p2=2").getResponseAsString();
- assertEquals("p1=[p1,p1,p1],p2=[2,2,2]", r);
-
- r = client.doGet(url + "?p1&p2").getResponseAsString();
- assertEquals("p1=[null,null,null],p2=[0,null,0]", r);
-
- r = client.doGet(url).getResponseAsString();
- assertEquals("p1=[null,null,null],p2=[0,null,0]", r);
-
- r = client.doGet(url + "?p1").getResponseAsString();
- assertEquals("p1=[null,null,null],p2=[0,null,0]", r);
-
- r = client.doGet(url + "?p2").getResponseAsString();
- assertEquals("p1=[null,null,null],p2=[0,null,0]", r);
-
- r = client.doGet(url + "?p1=foo&p2").getResponseAsString();
- assertEquals("p1=[foo,foo,foo],p2=[0,null,0]", r);
-
- r = client.doGet(url + "?p1&p2=1").getResponseAsString();
- assertEquals("p1=[null,null,null],p2=[1,1,1]", r);
-
- String x = "a%2Fb%25c%3Dd+e"; // [x/y%z=a+b]
- r = client.doGet(url + "?p1="+x+"&p2=1").getResponseAsString();
- assertEquals("p1=[a/b%c=d e,a/b%c=d e,a/b%c=d e],p2=[1,1,1]", r);
-
- client.closeQuietly();
- }
-
- //====================================================================================================
- // @Param(format=PLAIN) annotation - GET
- //====================================================================================================
- @Test
- public void testPlainParamGet() throws Exception {
- RestClient client = new TestRestClient().setHeader("Accept", "text/plain");
- String r;
- String url = URL + "/testPlainParamGet";
-
- r = client.doGet(url + "?p1=(p1)").getResponseAsString();
- assertEquals("p1=[(p1),(p1),p1]", r);
-
- r = client.doGet(url + "?p1=$s(p1)").getResponseAsString();
- assertEquals("p1=[$s(p1),$s(p1),p1]", r);
-
- client.closeQuietly();
- }
-
- //====================================================================================================
- // @Param annotation - POST
- //====================================================================================================
- @Test
- public void testParamPost() throws Exception {
- RestClient client = new TestRestClient().setHeader("Accept", "text/plain");
- String r;
- String url = URL + "/testParamPost";
-
- r = client.doFormPost(url, new ObjectMap("{p1:'p1',p2:2}")).getResponseAsString();
- assertEquals("p1=[p1,p1,p1],p2=[2,$n(2),2]", r);
-
- r = client.doFormPost(url, new ObjectMap("{p1:null,p2:0}")).getResponseAsString();
- assertEquals("p1=[null,\u0000,null],p2=[0,$n(0),0]", r);
-
- r = client.doFormPost(url, new ObjectMap("{}")).getResponseAsString();
- assertEquals("p1=[null,null,null],p2=[0,null,0]", r);
-
- r = client.doFormPost(url, new ObjectMap("{p1:null}")).getResponseAsString();
- assertEquals("p1=[null,\u0000,null],p2=[0,null,0]", r);
-
- r = client.doFormPost(url, new ObjectMap("{p2:0}")).getResponseAsString();
- assertEquals("p1=[null,null,null],p2=[0,$n(0),0]", r);
-
- r = client.doFormPost(url, new ObjectMap("{p1:'foo',p2:0}")).getResponseAsString();
- assertEquals("p1=[foo,foo,foo],p2=[0,$n(0),0]", r);
-
- r = client.doFormPost(url, new ObjectMap("{p1:null,p2:1}")).getResponseAsString();
- assertEquals("p1=[null,\u0000,null],p2=[1,$n(1),1]", r);
-
- r = client.doFormPost(url, new ObjectMap("{p1:'a/b%c=d e,f/g%h=i j',p2:1}")).getResponseAsString();
- assertEquals("p1=[a/b%c=d e,f/g%h=i j,a/b%c=d e,f/g%h=i j,a/b%c=d e,f/g%h=i j],p2=[1,$n(1),1]", r);
-
- client.closeQuietly();
- }
-
- //====================================================================================================
- // @Param(format=PLAIN) annotation - POST
- //====================================================================================================
- @Test
- public void testPlainParamPost() throws Exception {
- RestClient client = new TestRestClient().setHeader("Accept", "text/plain");
- String r;
- String url = URL + "/testPlainParamPost";
-
- List<NameValuePair> nvps = new ArrayList<NameValuePair>();
- nvps.add(new BasicNameValuePair("p1", "(p1)"));
- HttpEntity he = new UrlEncodedFormEntity(nvps);
-
- r = client.doPost(url, he).getResponseAsString();
- assertEquals("p1=[(p1),(p1),p1]", r);
-
- nvps = new ArrayList<NameValuePair>();
- nvps.add(new BasicNameValuePair("p1", "$s(p1)"));
- he = new UrlEncodedFormEntity(nvps);
-
- r = client.doFormPost(url, he).getResponseAsString();
- assertEquals("p1=[$s(p1),$s(p1),p1]", r);
-
- client.closeQuietly();
- }
-
- //====================================================================================================
- // @QParam annotation - GET
- //====================================================================================================
- @Test
- public void testQParamGet() throws Exception {
- RestClient client = new TestRestClient().setHeader("Accept", "text/plain");
- String r;
- String url = URL + "/testQParamGet";
-
- r = client.doGet(url + "?p1=p1&p2=2").getResponseAsString();
- assertEquals("p1=[p1,p1,p1],p2=[2,2,2]", r);
-
- r = client.doGet(url + "?p1&p2").getResponseAsString();
- assertEquals("p1=[null,null,null],p2=[0,null,0]", r);
-
- r = client.doGet(url).getResponseAsString();
- assertEquals("p1=[null,null,null],p2=[0,null,0]", r);
-
- r = client.doGet(url + "?p1").getResponseAsString();
- assertEquals("p1=[null,null,null],p2=[0,null,0]", r);
-
- r = client.doGet(url + "?p2").getResponseAsString();
- assertEquals("p1=[null,null,null],p2=[0,null,0]", r);
-
- r = client.doGet(url + "?p1=foo&p2").getResponseAsString();
- assertEquals("p1=[foo,foo,foo],p2=[0,null,0]", r);
-
- r = client.doGet(url + "?p1&p2=1").getResponseAsString();
- assertEquals("p1=[null,null,null],p2=[1,1,1]", r);
-
- String x = "a%2Fb%25c%3Dd+e"; // [x/y%z=a+b]
- r = client.doGet(url + "?p1="+x+"&p2=1").getResponseAsString();
- assertEquals("p1=[a/b%c=d e,a/b%c=d e,a/b%c=d e],p2=[1,1,1]", r);
-
- client.closeQuietly();
- }
-
- //====================================================================================================
- // @QParam(format=PLAIN) annotation - GET
- //====================================================================================================
- @Test
- public void testPlainQParamGet() throws Exception {
- RestClient client = new TestRestClient().setHeader("Accept", "text/plain");
- String r;
- String url = URL + "/testPlainQParamGet";
-
- r = client.doGet(url + "?p1=(p1)").getResponseAsString();
- assertEquals("p1=[(p1),(p1),p1]", r);
-
- r = client.doGet(url + "?p1=$s(p1)").getResponseAsString();
- assertEquals("p1=[$s(p1),$s(p1),p1]", r);
-
- client.closeQuietly();
- }
-
- //====================================================================================================
- // @QParam annotation - POST
- //====================================================================================================
- @Test
- public void testQParamPost() throws Exception {
- RestClient client = new TestRestClient().setHeader("Accept", "text/plain");
- String r;
- String url = URL + "/testQParamPost";
-
- r = client.doFormPost(url, new ObjectMap("{p1:'p1',p2:2}")).getResponseAsString();
- assertEquals("p1=[null,null,null],p2=[0,null,0]", r);
-
- r = client.doFormPost(url, new ObjectMap("{p1:null,p2:0}")).getResponseAsString();
- assertEquals("p1=[null,null,null],p2=[0,null,0]", r);
-
- r = client.doFormPost(url, new ObjectMap("{}")).getResponseAsString();
- assertEquals("p1=[null,null,null],p2=[0,null,0]", r);
-
- r = client.doFormPost(url, new ObjectMap("{p1:null}")).getResponseAsString();
- assertEquals("p1=[null,null,null],p2=[0,null,0]", r);
-
- r = client.doFormPost(url, new ObjectMap("{p2:0}")).getResponseAsString();
- assertEquals("p1=[null,null,null],p2=[0,null,0]", r);
-
- r = client.doFormPost(url, new ObjectMap("{p1:'foo',p2:0}")).getResponseAsString();
- assertEquals("p1=[null,null,null],p2=[0,null,0]", r);
-
- r = client.doFormPost(url, new ObjectMap("{p1:null,p2:1}")).getResponseAsString();
- assertEquals("p1=[null,null,null],p2=[0,null,0]", r);
-
- r = client.doFormPost(url, new ObjectMap("{p1:'a/b%c=d e,f/g%h=i j',p2:1}")).getResponseAsString();
- assertEquals("p1=[null,null,null],p2=[0,null,0]", r);
-
- client.closeQuietly();
- }
-
- //====================================================================================================
- // @HasParam annotation - GET
- //====================================================================================================
- @Test
- public void testHasParamGet() throws Exception {
- RestClient client = new TestRestClient().setHeader("Accept", "text/plain");
- String r;
- String url = URL + "/testHasParamGet";
-
- r = client.doGet(url + "?p1=p1&p2=2").getResponseAsString();
- assertEquals("p1=[true,true],p2=[true,true]", r);
-
- r = client.doGet(url + "?p1&p2").getResponseAsString();
- assertEquals("p1=[true,true],p2=[true,true]", r);
-
- r = client.doGet(url).getResponseAsString();
- assertEquals("p1=[false,false],p2=[false,false]", r);
-
- r = client.doGet(url + "?p1").getResponseAsString();
- assertEquals("p1=[true,true],p2=[false,false]", r);
-
- r = client.doGet(url + "?p2").getResponseAsString();
- assertEquals("p1=[false,false],p2=[true,true]", r);
-
- r = client.doGet(url + "?p1=foo&p2").getResponseAsString();
- assertEquals("p1=[true,true],p2=[true,true]", r);
-
- r = client.doGet(url + "?p1&p2=1").getResponseAsString();
- assertEquals("p1=[true,true],p2=[true,true]", r);
-
- String x = "x%2Fy%25z%3Da+b"; // [x/y%z=a+b]
- r = client.doGet(url + "?p1="+x+"&p2=1").getResponseAsString();
- assertEquals("p1=[true,true],p2=[true,true]", r);
-
- client.closeQuietly();
- }
-
- //====================================================================================================
- // @HasParam annotation - POST
- //====================================================================================================
- @Test
- public void testHasParamPost() throws Exception {
- RestClient client = new TestRestClient().setHeader("Accept", "text/plain");
- String r;
- String url = URL + "/testHasParamPost";
-
- r = client.doFormPost(url, new ObjectMap("{p1:'p1',p2:2}")).getResponseAsString();
- assertEquals("p1=[true,true],p2=[true,true]", r);
-
- r = client.doFormPost(url, new ObjectMap("{p1:null,p2:0}")).getResponseAsString();
- assertEquals("p1=[true,true],p2=[true,true]", r);
-
- r = client.doFormPost(url, new ObjectMap("{}")).getResponseAsString();
- assertEquals("p1=[false,false],p2=[false,false]", r);
-
- r = client.doFormPost(url, new ObjectMap("{p1:null}")).getResponseAsString();
- assertEquals("p1=[true,true],p2=[false,false]", r);
-
- r = client.doFormPost(url, new ObjectMap("{p2:0}")).getResponseAsString();
- assertEquals("p1=[false,false],p2=[true,true]", r);
-
- r = client.doFormPost(url, new ObjectMap("{p1:'foo',p2:0}")).getResponseAsString();
- assertEquals("p1=[true,true],p2=[true,true]", r);
-
- r = client.doFormPost(url, new ObjectMap("{p1:null,p2:1}")).getResponseAsString();
- assertEquals("p1=[true,true],p2=[true,true]", r);
-
- r = client.doFormPost(url, new ObjectMap("{p1:'a/b%c=d e,f/g%h=i j',p2:1}")).getResponseAsString();
- assertEquals("p1=[true,true],p2=[true,true]", r);
-
- client.closeQuietly();
- }
-
- //====================================================================================================
- // @HasQParam annotation - GET
- //====================================================================================================
- @Test
- public void testHasQParamGet() throws Exception {
- RestClient client = new TestRestClient().setHeader("Accept", "text/plain");
- String r;
- String url = URL + "/testHasQParamGet";
-
- r = client.doGet(url + "?p1=p1&p2=2").getResponseAsString();
- assertEquals("p1=[true,true],p2=[true,true]", r);
-
- r = client.doGet(url + "?p1&p2").getResponseAsString();
- assertEquals("p1=[true,true],p2=[true,true]", r);
-
- r = client.doGet(url).getResponseAsString();
- assertEquals("p1=[false,false],p2=[false,false]", r);
-
- r = client.doGet(url + "?p1").getResponseAsString();
- assertEquals("p1=[true,true],p2=[false,false]", r);
-
- r = client.doGet(url + "?p2").getResponseAsString();
- assertEquals("p1=[false,false],p2=[true,true]", r);
-
- r = client.doGet(url + "?p1=foo&p2").getResponseAsString();
- assertEquals("p1=[true,true],p2=[true,true]", r);
-
- r = client.doGet(url + "?p1&p2=1").getResponseAsString();
- assertEquals("p1=[true,true],p2=[true,true]", r);
-
- String x = "x%2Fy%25z%3Da+b"; // [x/y%z=a+b]
- r = client.doGet(url + "?p1="+x+"&p2=1").getResponseAsString();
- assertEquals("p1=[true,true],p2=[true,true]", r);
-
- client.closeQuietly();
- }
-
- //====================================================================================================
- // @HasQParam annotation - POST
- //====================================================================================================
- @Test
- public void testHasQParamPost() throws Exception {
- RestClient client = new TestRestClient().setHeader("Accept", "text/plain");
- String r;
- String url = URL + "/testHasQParamPost";
-
- r = client.doFormPost(url, new ObjectMap("{p1:'p1',p2:2}")).getResponseAsString();
- assertEquals("p1=[false,false],p2=[false,false]", r);
-
- r = client.doFormPost(url, new ObjectMap("{p1:null,p2:0}")).getResponseAsString();
- assertEquals("p1=[false,false],p2=[false,false]", r);
-
- r = client.doFormPost(url, new ObjectMap("{}")).getResponseAsString();
- assertEquals("p1=[false,false],p2=[false,false]", r);
-
- r = client.doFormPost(url, new ObjectMap("{p1:null}")).getResponseAsString();
- assertEquals("p1=[false,false],p2=[false,false]", r);
-
- r = client.doFormPost(url, new ObjectMap("{p2:0}")).getResponseAsString();
- assertEquals("p1=[false,false],p2=[false,false]", r);
-
- r = client.doFormPost(url, new ObjectMap("{p1:'foo',p2:0}")).getResponseAsString();
- assertEquals("p1=[false,false],p2=[false,false]", r);
-
- r = client.doFormPost(url, new ObjectMap("{p1:null,p2:1}")).getResponseAsString();
- assertEquals("p1=[false,false],p2=[false,false]", r);
-
- r = client.doFormPost(url, new ObjectMap("{p1:'a/b%c=d e,f/g%h=i j',p2:1}")).getResponseAsString();
- assertEquals("p1=[false,false],p2=[false,false]", r);
-
- client.closeQuietly();
- }
-
- //====================================================================================================
- // Form POSTS with @Content parameter
- //====================================================================================================
- @Test
- public void testFormPostAsContent() throws Exception {
- RestClient client = new TestRestClient().setHeader("Accept", "text/plain");
- String r;
- String url = URL + "/testFormPostAsContent";
-
- r = client.doFormPost(url, new ObjectMap("{p1:'p1',p2:2}")).getResponseAsString();
- assertEquals("bean=[{p1:'p1',p2:2}],qp1=[null],qp2=[0],hqp1=[false],hqp2=[false]", r);
-
- r = client.doFormPost(url, new ObjectMap("{}")).getResponseAsString();
- assertEquals("bean=[{p2:0}],qp1=[null],qp2=[0],hqp1=[false],hqp2=[false]", r);
-
- r = client.doFormPost(url+"?p1=p3&p2=4", new ObjectMap("{p1:'p1',p2:2}")).getResponseAsString();
- assertEquals("bean=[{p1:'p1',p2:2}],qp1=[p3],qp2=[4],hqp1=[true],hqp2=[true]", r);
-
- r = client.doFormPost(url+"?p1=p3&p2=4", new ObjectMap("{}")).getResponseAsString();
- assertEquals("bean=[{p2:0}],qp1=[p3],qp2=[4],hqp1=[true],hqp2=[true]", r);
-
- client.closeQuietly();
- }
-
- //====================================================================================================
- // Test @Param and @QParam annotations when using multi-part parameters (e.g. &key=val1,&key=val2).
- //====================================================================================================
- @Test
- public void testMultiPartParams() throws Exception {
- RestClient client = new TestRestClient().setHeader("Accept", "text/plain");
- String r;
- String url = URL + "/testMultiPartParams";
-
- String in = ""
- + "?p1=a&p1=b"
- + "&p2=1&p2=2"
- + "&p3=a&p3=b"
- + "&p4=1&p4=2"
- + "&p5=a&p5=b"
- + "&p6=1&p6=2"
- + "&p7=a&p7=b"
- + "&p8=1&p8=2"
- + "&p9=(a=1,b=2,c=false)&p9=(a=3,b=4,c=true)"
- + "&p10=(a=1,b=2,c=false)&p10=(a=3,b=4,c=true)"
- + "&p11=(a=1,b=2,c=false)&p11=(a=3,b=4,c=true)"
- + "&p12=(a=1,b=2,c=false)&p12=(a=3,b=4,c=true)";
- r = client.doGet(url + in).getResponseAsString();
- String e = "{"
- + "p1:['a','b'],"
- + "p2:[1,2],"
- + "p3:['a','b'],"
- + "p4:[1,2],"
- + "p5:['a','b'],"
- + "p6:[1,2],"
- + "p7:['a','b'],"
- + "p8:[1,2],"
- + "p9:[{a:'1',b:2,c:false},{a:'3',b:4,c:true}],"
- + "p10:[{a:'1',b:2,c:false},{a:'3',b:4,c:true}],"
- + "p11:[{a:'1',b:2,c:false},{a:'3',b:4,c:true}],"
- + "p12:[{a:'1',b:2,c:false},{a:'3',b:4,c:true}]"
- +"}";
- assertEquals(e, r);
-
- client.closeQuietly();
- }
-
- //====================================================================================================
- // Same as testMultiPartParams(), except make sure single values are still interpreted as collections.
- //====================================================================================================
- @Test
- public void testMultiPartParamsSingleValues() throws Exception {
- RestClient client = new TestRestClient().setHeader("Accept", "text/plain");
- String r;
- String url = URL + "/testMultiPartParams";
-
- String in = ""
- + "?p1=a"
- + "&p2=1"
- + "&p3=a"
- + "&p4=1"
- + "&p5=a"
- + "&p6=1"
- + "&p7=a"
- + "&p8=1"
- + "&p9=(a=1,b=2,c=false)"
- + "&p10=(a=1,b=2,c=false)"
- + "&p11=(a=1,b=2,c=false)"
- + "&p12=(a=1,b=2,c=false)";
- r = client.doGet(url + in).getResponseAsString();
- String e = "{"
- + "p1:['a'],"
- + "p2:[1],"
- + "p3:['a'],"
- + "p4:[1],"
- + "p5:['a'],"
- + "p6:[1],"
- + "p7:['a'],"
- + "p8:[1],"
- + "p9:[{a:'1',b:2,c:false}],"
- + "p10:[{a:'1',b:2,c:false}],"
- + "p11:[{a:'1',b:2,c:false}],"
- + "p12:[{a:'1',b:2,c:false}]"
- +"}";
- assertEquals(e, r);
-
- client.closeQuietly();
- }
-
- //====================================================================================================
- // Test multi-part parameter keys on bean properties of type array/Collection (i.e. &key=val1,&key=val2)
- // using URLENC_expandedParams property.
- // A simple round-trip test to verify that both serializing and parsing works.
- //====================================================================================================
- @Test
- public void testFormPostsWithMultiParamsUsingProperty() throws Exception {
- RestClient client = new TestRestClient()
- .setHeader("Content-Type", "application/x-www-form-urlencoded")
- .setHeader("Accept", "application/x-www-form-urlencoded");
- String r;
- String url = URL + "/testFormPostsWithMultiParamsUsingProperty";
-
- String in = ""
- + "f1=a&f1=b"
- + "&f2=c&f2=d"
- + "&f3=1&f3=2"
- + "&f4=3&f4=4"
- + "&f5=(e,f)&f5=(g,h)"
- + "&f6=(i,j)&f6=(k,l)"
- + "&f7=(a=a,b=1,c=true)&f7=(a=b,b=2,c=false)"
- + "&f8=(a=a,b=1,c=true)&f8=(a=b,b=2,c=false)"
- + "&f9=((a=a,b=1,c=true))&f9=((a=b,b=2,c=false))"
- + "&f10=((a=a,b=1,c=true))&f10=((a=b,b=2,c=false))"
- + "&f11=a&f11=b"
- + "&f12=c&f12=d"
- + "&f13=1&f13=2"
- + "&f14=3&f14=4"
- + "&f15=(e,f)&f15=(g,h)"
- + "&f16=(i,j)&f16=(k,l)"
- + "&f17=(a=a,b=1,c=true)&f17=(a=b,b=2,c=false)"
- + "&f18=(a=a,b=1,c=true)&f18=(a=b,b=2,c=false)"
- + "&f19=((a=a,b=1,c=true))&f19=((a=b,b=2,c=false))"
- + "&f20=((a=a,b=1,c=true))&f20=((a=b,b=2,c=false))";
- r = client.doPost(url, new StringEntity(in)).getResponseAsString();
- assertEquals(in, r);
-
- client.closeQuietly();
- }
-
- //====================================================================================================
- // Test multi-part parameter keys on bean properties of type array/Collection (i.e. &key=val1,&key=val2)
- // using @UrlEncoding(expandedParams=true) annotation.
- // A simple round-trip test to verify that both serializing and parsing works.
- //====================================================================================================
- @Test
- public void testFormPostsWithMultiParamsUsingAnnotation() throws Exception {
- RestClient client = new TestRestClient()
- .setHeader("Content-Type", "application/x-www-form-urlencoded")
- .setHeader("Accept", "application/x-www-form-urlencoded");
- String r;
- String url = URL + "/testFormPostsWithMultiParamsUsingAnnotation";
-
- String in = ""
- + "f1=a&f1=b"
- + "&f2=c&f2=d"
- + "&f3=1&f3=2"
- + "&f4=3&f4=4"
- + "&f5=(e,f)&f5=(g,h)"
- + "&f6=(i,j)&f6=(k,l)"
- + "&f7=(a=a,b=1,c=true)&f7=(a=b,b=2,c=false)"
- + "&f8=(a=a,b=1,c=true)&f8=(a=b,b=2,c=false)"
- + "&f9=((a=a,b=1,c=true))&f9=((a=b,b=2,c=false))"
- + "&f10=((a=a,b=1,c=true))&f10=((a=b,b=2,c=false))"
- + "&f11=a&f11=b"
- + "&f12=c&f12=d"
- + "&f13=1&f13=2"
- + "&f14=3&f14=4"
- + "&f15=(e,f)&f15=(g,h)"
- + "&f16=(i,j)&f16=(k,l)"
- + "&f17=(a=a,b=1,c=true)&f17=(a=b,b=2,c=false)"
- + "&f18=(a=a,b=1,c=true)&f18=(a=b,b=2,c=false)"
- + "&f19=((a=a,b=1,c=true))&f19=((a=b,b=2,c=false))"
- + "&f20=((a=a,b=1,c=true))&f20=((a=b,b=2,c=false))";
- r = client.doPost(url, new StringEntity(in)).getResponseAsString();
- assertEquals(in, r);
-
- client.closeQuietly();
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestParsers.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestParsers.java b/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestParsers.java
deleted file mode 100755
index b214f2d..0000000
--- a/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestParsers.java
+++ /dev/null
@@ -1,162 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.server;
-
-import static javax.servlet.http.HttpServletResponse.*;
-import static org.apache.juneau.server.TestUtils.*;
-import static org.junit.Assert.*;
-
-import org.apache.juneau.client.*;
-import org.apache.juneau.plaintext.*;
-import org.junit.*;
-
-public class CT_TestParsers {
-
- private static String URL = "/testParsers";
- private static boolean debug = false;
-
- //====================================================================================================
- // Parser defined on class.
- //====================================================================================================
- @Test
- public void testParserOnClass() throws Exception {
- RestClient client = new TestRestClient(PlainTextSerializer.class, PlainTextParser.class);
- String url = URL + "/testParserOnClass";
-
- client.setContentType("text/a");
- String r = client.doPut(url, "test1").getResponseAsString();
- assertEquals("text/a - test1", r);
-
- try {
- client.setContentType("text/b");
- client.doPut(url + "?noTrace=true", "test1").getResponseAsString();
- fail("Exception expected");
- } catch (RestCallException e) {
- checkErrorResponse(debug, e, SC_UNSUPPORTED_MEDIA_TYPE,
- "Unsupported media-type in request header 'Content-Type': 'text/b'",
- "Supported media-types: [text/a"
- );
- }
-
- client.setContentType("text/json").setAccept("text/json");
- r = client.doPut(url, "'test1'").getResponseAsString();
- assertEquals("\"test1\"", r);
-
- client.closeQuietly();
- }
-
- //====================================================================================================
- // Parser defined on method.
- //====================================================================================================
- @Test
- public void testParserOnMethod() throws Exception {
- RestClient client = new TestRestClient(PlainTextSerializer.class, PlainTextParser.class);
- String url = URL + "/testParserOnMethod";
-
- client.setContentType("text/b");
- String r = client.doPut(url, "test2").getResponseAsString();
- assertEquals("text/b - test2", r);
-
- try {
- client.setContentType("text/a");
- client.doPut(url + "?noTrace=true", "test2").getResponseAsString();
- fail("Exception expected");
- } catch (RestCallException e) {
- checkErrorResponse(debug, e, SC_UNSUPPORTED_MEDIA_TYPE,
- "Unsupported media-type in request header 'Content-Type': 'text/a'",
- "Supported media-types: [text/b]"
- );
- }
-
- try {
- client.setContentType("text/json");
- r = client.doPut(url + "?noTrace=true", "'test2'").getResponseAsString();
- fail("Exception expected");
- } catch (RestCallException e) {
- checkErrorResponse(debug, e, SC_UNSUPPORTED_MEDIA_TYPE,
- "Unsupported media-type in request header 'Content-Type': 'text/json'",
- "Supported media-types: [text/b]"
- );
- }
-
- client.closeQuietly();
- }
-
- //====================================================================================================
- // Parser overridden on method.
- //====================================================================================================
- @Test
- public void testParserOverriddenOnMethod() throws Exception {
- RestClient client = new TestRestClient(PlainTextSerializer.class, PlainTextParser.class);
- String url = URL + "/testParserOverriddenOnMethod";
-
- client.setContentType("text/a");
- String r = client.doPut(url, "test3").getResponseAsString();
- assertEquals("text/a - test3", r);
-
- client.setContentType("text/b");
- r = client.doPut(url, "test3").getResponseAsString();
- assertEquals("text/b - test3", r);
-
- client.setContentType("text/json");
- r = client.doPut(url, "'test3'").getResponseAsString();
- assertEquals("test3", r);
-
- client.closeQuietly();
- }
-
- //====================================================================================================
- // Parser with different Accept than Content-Type.
- //====================================================================================================
- @Test
- public void testParserWithDifferentMediaTypes() throws Exception {
- RestClient client = new TestRestClient(PlainTextSerializer.class, PlainTextParser.class);
- String url = URL + "/testParserWithDifferentMediaTypes";
-
- client.setContentType("text/a");
- String r = client.doPut(url, "test4").getResponseAsString();
- assertEquals("text/d - test4", r);
-
- client.setContentType("text/d");
- r = client.doPut(url, "test4").getResponseAsString();
- assertEquals("text/d - test4", r);
-
- client.setContentType("text/json");
- r = client.doPut(url, "'test4'").getResponseAsString();
- assertEquals("test4", r);
-
- client.closeQuietly();
- }
-
- //====================================================================================================
- // Check for valid error response.
- //====================================================================================================
- @Test
- public void testValidErrorResponse() throws Exception {
- RestClient client = new TestRestClient(PlainTextSerializer.class, PlainTextParser.class);
- String url = URL + "/testValidErrorResponse";
-
- try {
- client.setContentType("text/bad");
- client.doPut(url + "?noTrace=true", "test1").getResponseAsString();
- fail("Exception expected");
- } catch (RestCallException e) {
- checkErrorResponse(debug, e, SC_UNSUPPORTED_MEDIA_TYPE,
- "Unsupported media-type in request header 'Content-Type': 'text/bad'",
- "Supported media-types: [text/a"
- );
- }
-
- client.closeQuietly();
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestPath.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestPath.java b/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestPath.java
deleted file mode 100755
index 2af035b..0000000
--- a/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestPath.java
+++ /dev/null
@@ -1,44 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.server;
-
-import static org.junit.Assert.*;
-
-import org.apache.juneau.client.*;
-import org.apache.juneau.json.*;
-import org.junit.*;
-
-public class CT_TestPath {
-
- private static String URL = "/testPath";
-
- //====================================================================================================
- // Basic tests
- //====================================================================================================
- @Test
- public void testBasic() throws Exception {
- RestClient client = new TestRestClient(JsonSerializer.DEFAULT, JsonParser.DEFAULT);
- String r = null;
-
- r = client.doGet(URL).getResponse(String.class);
- assertEquals("/testPath", r);
-
- r = client.doGet(URL + "/testPath2").getResponse(String.class);
- assertEquals("/testPath/testPath2", r);
-
- r = client.doGet(URL + "/testPath2/testPath3").getResponse(String.class);
- assertEquals("/testPath/testPath2/testPath3", r);
-
- client.closeQuietly();
- }
-}
[32/44] incubator-juneau git commit: Rename CT_* testcases.
Posted by ja...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/BeanMapTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/BeanMapTest.java b/org.apache.juneau/src/test/java/org/apache/juneau/BeanMapTest.java
new file mode 100755
index 0000000..ec5aa6f
--- /dev/null
+++ b/org.apache.juneau/src/test/java/org/apache/juneau/BeanMapTest.java
@@ -0,0 +1,1920 @@
+/***************************************************************************************************************************
+ * 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.juneau;
+
+import static org.apache.juneau.BeanContext.*;
+import static org.apache.juneau.TestUtils.*;
+import static org.junit.Assert.*;
+
+import java.util.*;
+
+import org.apache.juneau.annotation.*;
+import org.apache.juneau.html.*;
+import org.apache.juneau.json.*;
+import org.apache.juneau.parser.*;
+import org.apache.juneau.transforms.*;
+import org.apache.juneau.urlencoding.*;
+import org.apache.juneau.utils.*;
+import org.apache.juneau.xml.*;
+import org.junit.*;
+
+@SuppressWarnings({"unchecked","rawtypes","hiding","serial","unused"})
+public class BeanMapTest {
+
+ JsonSerializer serializer = JsonSerializer.DEFAULT_LAX.clone().setClassLoader(BeanMapTest.class.getClassLoader());
+
+ //====================================================================================================
+ // Primitive field properties
+ //====================================================================================================
+ @Test
+ public void testPrimitiveFieldProperties() {
+ A t = new A();
+ Map m = BeanContext.DEFAULT.forBean(t);
+
+ // Make sure setting primitive values to null causes them to get default values.
+ m.put("i1", null);
+ m.put("s1", null);
+ m.put("l1", null);
+ m.put("d1", null);
+ m.put("f1", null);
+ m.put("b1", null);
+ assertEquals(new Integer(0), m.get("i1"));
+ assertEquals(new Short((short)0), m.get("s1"));
+ assertEquals(new Long(0l), m.get("l1"));
+ assertEquals(new Double(0d), m.get("d1"));
+ assertEquals(new Float(0f), m.get("f1"));
+ assertEquals(new Boolean(false), m.get("b1"));
+
+ // Make sure setting non-primitive values to null causes them to set to null.
+ m.put("i2", null);
+ m.put("s2", null);
+ m.put("l2", null);
+ m.put("d2", null);
+ m.put("f2", null);
+ m.put("b2", null);
+ assertNull(m.get("i2"));
+ assertNull(m.get("s2"));
+ assertNull(m.get("l2"));
+ assertNull(m.get("d2"));
+ assertNull(m.get("f2"));
+ assertNull(m.get("b2"));
+
+ // Make sure setting them all to an integer is kosher.
+ m.put("i1", 1);
+ m.put("s1", 1);
+ m.put("l1", 1);
+ m.put("d1", 1);
+ m.put("f1", 1);
+ m.put("i2", 1);
+ m.put("s2", 1);
+ m.put("l2", 1);
+ m.put("d2", 1);
+ m.put("f2", 1);
+ assertEquals(new Integer(1), m.get("i1"));
+ assertEquals(new Integer(1), m.get("i2"));
+ assertEquals(new Short((short)1), m.get("s1"));
+ assertEquals(new Short((short)1), m.get("s2"));
+ assertEquals(new Long(1), m.get("l1"));
+ assertEquals(new Long(1), m.get("l2"));
+ assertEquals(new Double(1), m.get("d1"));
+ assertEquals(new Double(1), m.get("d2"));
+ assertEquals(new Float(1), m.get("f1"));
+ assertEquals(new Float(1), m.get("f2"));
+
+ m.put("b1", true);
+ m.put("b2", new Boolean(true));
+ assertEquals(new Boolean(true), m.get("b1"));
+ assertEquals(new Boolean(true), m.get("b2"));
+ }
+
+ public static class A {
+ public int i1;
+ public Integer i2;
+ public short s1;
+ public Short s2;
+ public long l1;
+ public Long l2;
+ public double d1;
+ public Double d2;
+ public float f1;
+ public Float f2;
+ public boolean b1;
+ public Boolean b2;
+ }
+
+ //====================================================================================================
+ // Primitive method properties
+ //====================================================================================================
+ @Test
+ public void testPrimitiveMethodProperties() {
+ B t = new B();
+ Map m = BeanContext.DEFAULT.forBean(t);
+
+ // Make sure setting primitive values to null causes them to get default values.
+ m.put("i1", null);
+ m.put("s1", null);
+ m.put("l1", null);
+ m.put("d1", null);
+ m.put("f1", null);
+ m.put("b1", null);
+ assertEquals(new Integer(0), m.get("i1"));
+ assertEquals(new Short((short)0), m.get("s1"));
+ assertEquals(new Long(0l), m.get("l1"));
+ assertEquals(new Double(0d), m.get("d1"));
+ assertEquals(new Float(0f), m.get("f1"));
+ assertEquals(new Boolean(false), m.get("b1"));
+
+ // Make sure setting non-primitive values to null causes them to set to null.
+ m.put("i2", null);
+ m.put("s2", null);
+ m.put("l2", null);
+ m.put("d2", null);
+ m.put("f2", null);
+ m.put("b2", null);
+ assertNull(m.get("i2"));
+ assertNull(m.get("s2"));
+ assertNull(m.get("l2"));
+ assertNull(m.get("d2"));
+ assertNull(m.get("f2"));
+ assertNull(m.get("b2"));
+
+ // Make sure setting them all to an integer is kosher.
+ m.put("i1", 1);
+ m.put("s1", 1);
+ m.put("l1", 1);
+ m.put("d1", 1);
+ m.put("f1", 1);
+ m.put("i2", 1);
+ m.put("s2", 1);
+ m.put("l2", 1);
+ m.put("d2", 1);
+ m.put("f2", 1);
+ assertEquals(new Integer(1), m.get("i1"));
+ assertEquals(new Integer(1), m.get("i2"));
+ assertEquals(new Short((short)1), m.get("s1"));
+ assertEquals(new Short((short)1), m.get("s2"));
+ assertEquals(new Long(1), m.get("l1"));
+ assertEquals(new Long(1), m.get("l2"));
+ assertEquals(new Double(1), m.get("d1"));
+ assertEquals(new Double(1), m.get("d2"));
+ assertEquals(new Float(1), m.get("f1"));
+ assertEquals(new Float(1), m.get("f2"));
+
+ m.put("b1", true);
+ m.put("b2", true);
+ assertEquals(new Boolean(true), m.get("b1"));
+ assertEquals(new Boolean(true), m.get("b2"));
+ }
+
+ public static class B {
+ private int i1;
+ private Integer i2;
+ private short s1;
+ private Short s2;
+ private long l1;
+ private Long l2;
+ private double d1;
+ private Double d2;
+ private float f1;
+ private Float f2;
+ private boolean b1;
+ private Boolean b2;
+
+ public int getI1() {return i1;}
+ public void setI1(int i1) {this.i1 = i1;}
+ public Integer getI2() {return i2;}
+ public void setI2(Integer i2) {this.i2 = i2;}
+
+ public short getS1() {return s1;}
+ public void setS1(short s1) {this.s1 = s1;}
+ public Short getS2() {return s2;}
+ public void setS2(Short s2) {this.s2 = s2;}
+
+ public long getL1() {return l1;}
+ public void setL1(long l1) {this.l1 = l1;}
+ public Long getL2() {return l2;}
+ public void setL2(Long l2) {this.l2 = l2;}
+
+ public double getD1() {return d1;}
+ public void setD1(double d1) {this.d1 = d1;}
+ public Double getD2() {return d2;}
+ public void setD2(Double d2) {this.d2 = d2;}
+
+ public float getF1() {return f1;}
+ public void setF1(float f1) {this.f1 = f1;}
+ public Float getF2() {return f2;}
+ public void setF2(Float f2) {this.f2 = f2;}
+
+ public boolean getB1() {return b1;}
+ public void setB1(boolean b1) {this.b1 = b1;}
+ public Boolean getB2() {return b2;}
+ public void setB2(Boolean b2) {this.b2 = b2;}
+ }
+
+ //====================================================================================================
+ // testCollectionFieldProperties
+ //====================================================================================================
+ @Test
+ public void testCollectionFieldProperties() throws Exception {
+ C t = new C();
+ Map m = BeanContext.DEFAULT.forBean(t);
+
+ // Non-initialized list fields.
+ m.put("l1", new ObjectList("[1,2,3]"));
+ m.put("al1", new ObjectList("[1,2,3]"));
+ m.put("ll1", new ObjectList("[1,2,3]"));
+ m.put("c1", new ObjectList("[1,2,3]"));
+ m.put("jl1", new ObjectList("[1,2,3]"));
+
+ // al1 should be initialized with an ArrayList, since it's not a superclass of ObjectList.
+ assertEquals(ArrayList.class.getName(), m.get("al1").getClass().getName());
+
+ // The rest are proper superclasses of ObjectList.
+ assertEquals(ObjectList.class.getName(), m.get("l1").getClass().getName());
+ assertEquals(LinkedList.class.getName(), m.get("ll1").getClass().getName());
+ assertEquals(ObjectList.class.getName(), m.get("c1").getClass().getName());
+ assertEquals(ObjectList.class.getName(), m.get("jl1").getClass().getName());
+
+ // Non-initialized map fields.
+ m.put("m1", new ObjectMap("{foo:'bar'}"));
+ m.put("hm1", new ObjectMap("{foo:'bar'}"));
+ m.put("jm1", new ObjectMap("{foo:'bar'}"));
+ m.put("tm1", new ObjectMap("{foo:'bar'}"));
+
+ // tm1 should be initialized with TreeMap, since it's not a superclass of ObjectMap.
+ assertEquals(TreeMap.class.getName(), m.get("tm1").getClass().getName());
+
+ // The rest are propert superclasses of ObjectMap
+ assertEquals(ObjectMap.class.getName(), m.get("m1").getClass().getName());
+ assertEquals(HashMap.class.getName(), m.get("hm1").getClass().getName());
+ assertEquals(ObjectMap.class.getName(), m.get("jm1").getClass().getName());
+
+ // Initialized fields should reuse existing field value.
+ m.put("l2", new ObjectList("[1,2,3]"));
+ m.put("al2", new ObjectList("[1,2,3]"));
+ m.put("ll2", new ObjectList("[1,2,3]"));
+ m.put("c2", new ObjectList("[1,2,3]"));
+ m.put("m2", new ObjectMap("{foo:'bar'}"));
+ m.put("hm2", new ObjectMap("{foo:'bar'}"));
+ m.put("tm2", new ObjectMap("{foo:'bar'}"));
+ m.put("jm2", new ObjectMap("{foo:'bar'}"));
+ m.put("jl2", new ObjectList("[1,2,3]"));
+
+ assertEquals(ArrayList.class.getName(), m.get("l2").getClass().getName());
+ assertEquals(ArrayList.class.getName(), m.get("al2").getClass().getName());
+ assertEquals(LinkedList.class.getName(), m.get("ll2").getClass().getName());
+ assertEquals(ArrayList.class.getName(), m.get("c2").getClass().getName());
+ assertEquals(HashMap.class.getName(), m.get("m2").getClass().getName());
+ assertEquals(HashMap.class.getName(), m.get("hm2").getClass().getName());
+ assertEquals(TreeMap.class.getName(), m.get("tm2").getClass().getName());
+ assertEquals(ObjectMap.class.getName(), m.get("jm2").getClass().getName());
+ assertEquals(ObjectList.class.getName(), m.get("jl2").getClass().getName());
+ }
+
+ public static class C {
+ public List l1;
+ public ArrayList al1;
+ public LinkedList ll1;
+ public Collection c1;
+ public Map m1;
+ public HashMap hm1;
+ public ObjectMap jm1;
+ public TreeMap tm1;
+ public ObjectList jl1;
+ public List l2 = new ArrayList();
+ public ArrayList al2 = new ArrayList();
+ public LinkedList ll2 = new LinkedList();
+ public Collection c2 = new ArrayList();
+ public Map m2 = new HashMap();
+ public HashMap hm2 = new HashMap();
+ public TreeMap tm2 = new TreeMap();
+ public ObjectMap jm2 = new ObjectMap();
+ public ObjectList jl2 = new ObjectList();
+ }
+
+ //====================================================================================================
+ // testCollectionMethodProperties
+ //====================================================================================================
+ @Test
+ public void testCollectionMethodProperties() throws Exception {
+ D t = new D();
+ Map m = BeanContext.DEFAULT.forBean(t);
+
+ // Non-initialized list fields.
+ m.put("l1", new ObjectList("[1,2,3]"));
+ m.put("al1", new ObjectList("[1,2,3]"));
+ m.put("ll1", new ObjectList("[1,2,3]"));
+ m.put("c1", new ObjectList("[1,2,3]"));
+ m.put("jl1", new ObjectList("[1,2,3]"));
+
+ // al1 should be initialized with an ArrayList, since it's not a superclass of ObjectList.
+ assertEquals(ArrayList.class.getName(), m.get("al1").getClass().getName());
+
+ // The rest are proper superclasses of ObjectList.
+ assertEquals(ObjectList.class.getName(), m.get("l1").getClass().getName());
+ assertEquals(LinkedList.class.getName(), m.get("ll1").getClass().getName());
+ assertEquals(ObjectList.class.getName(), m.get("c1").getClass().getName());
+ assertEquals(ObjectList.class.getName(), m.get("jl1").getClass().getName());
+
+ // Non-initialized map fields.
+ m.put("m1", new ObjectMap("{foo:'bar'}"));
+ m.put("hm1", new ObjectMap("{foo:'bar'}"));
+ m.put("jm1", new ObjectMap("{foo:'bar'}"));
+ m.put("tm1", new ObjectMap("{foo:'bar'}"));
+
+ // tm1 should be initialized with TreeMap, since it's not a superclass of ObjectMap.
+ assertEquals(TreeMap.class.getName(), m.get("tm1").getClass().getName());
+
+ // The rest are propert superclasses of ObjectMap
+ assertEquals(ObjectMap.class.getName(), m.get("m1").getClass().getName());
+ assertEquals(HashMap.class.getName(), m.get("hm1").getClass().getName());
+ assertEquals(ObjectMap.class.getName(), m.get("jm1").getClass().getName());
+
+ // Initialized fields should reuse existing field value.
+ m.put("l2", new ObjectList("[1,2,3]"));
+ m.put("al2", new ObjectList("[1,2,3]"));
+ m.put("ll2", new ObjectList("[1,2,3]"));
+ m.put("c2", new ObjectList("[1,2,3]"));
+ m.put("m2", new ObjectMap("{foo:'bar'}"));
+ m.put("hm2", new ObjectMap("{foo:'bar'}"));
+ m.put("tm2", new ObjectMap("{foo:'bar'}"));
+ m.put("jm2", new ObjectMap("{foo:'bar'}"));
+ m.put("jl2", new ObjectList("[1,2,3]"));
+
+ assertEquals(ArrayList.class.getName(), m.get("l2").getClass().getName());
+ assertEquals(ArrayList.class.getName(), m.get("al2").getClass().getName());
+ assertEquals(LinkedList.class.getName(), m.get("ll2").getClass().getName());
+ assertEquals(ArrayList.class.getName(), m.get("c2").getClass().getName());
+ assertEquals(HashMap.class.getName(), m.get("m2").getClass().getName());
+ assertEquals(HashMap.class.getName(), m.get("hm2").getClass().getName());
+ assertEquals(TreeMap.class.getName(), m.get("tm2").getClass().getName());
+ assertEquals(ObjectMap.class.getName(), m.get("jm2").getClass().getName());
+ assertEquals(ObjectList.class.getName(), m.get("jl2").getClass().getName());
+ }
+
+ public static class D {
+ private List l1;
+ public List getL1() {return l1;}
+ public void setL1(List l1) {this.l1 = l1;}
+
+ private ArrayList al1;
+ public ArrayList getAl1() {return al1;}
+ public void setAl1(ArrayList al1) {this.al1 = al1;}
+
+ private LinkedList ll1;
+ public LinkedList getLl1() {return ll1;}
+ public void setLl1(LinkedList ll1) {this.ll1 = ll1;}
+
+ private Collection c1;
+ public Collection getC1() {return c1;}
+ public void setC1(Collection c1) {this.c1 = c1;}
+
+ private Map m1;
+ public Map getM1() {return m1;}
+ public void setM1(Map m1) {this.m1 = m1;}
+
+ private HashMap hm1;
+ public HashMap getHm1() {return hm1;}
+ public void setHm1(HashMap hm1) {this.hm1 = hm1;}
+
+ private ObjectMap jm1;
+ public ObjectMap getJm1() {return jm1;}
+ public void setJm1(ObjectMap jm1) {this.jm1 = jm1;}
+
+ private TreeMap tm1;
+ public TreeMap getTm1() {return tm1;}
+ public void setTm1(TreeMap tm1) {this.tm1 = tm1;}
+
+ private ObjectList jl1;
+ public ObjectList getJl1() {return jl1;}
+ public void setJl1(ObjectList jl1) {this.jl1 = jl1;}
+
+ private List l2 = new ArrayList();
+ public List getL2() {return l2;}
+ public void setL2(List l2) {this.l2 = l2;}
+
+ private ArrayList al2 = new ArrayList();
+ public ArrayList getAl2() {return al2;}
+ public void setAl2(ArrayList al2) {this.al2 = al2;}
+
+ private LinkedList ll2 = new LinkedList();
+ public LinkedList getLl2() {return ll2;}
+ public void setLl2(LinkedList ll2) {this.ll2 = ll2;}
+
+ private Collection c2 = new ArrayList();
+ public Collection getC2() {return c2;}
+ public void setC2(Collection c2) {this.c2 = c2;}
+
+ private Map m2 = new HashMap();
+ public Map getM2() {return m2;}
+ public void setM2(Map m2) {this.m2 = m2;}
+
+ private HashMap hm2 = new HashMap();
+ public HashMap getHm2() {return hm2;}
+ public void setHm2(HashMap hm2) {this.hm2 = hm2;}
+
+ private TreeMap tm2 = new TreeMap();
+ public TreeMap getTm2() {return tm2;}
+ public void setTm2(TreeMap tm2) {this.tm2 = tm2;}
+
+ private ObjectMap jm2 = new ObjectMap();
+ public ObjectMap getJm2() {return jm2;}
+ public void setJm2(ObjectMap jm2) {this.jm2 = jm2;}
+
+ private ObjectList jl2 = new ObjectList();
+ public ObjectList getJl2() {return jl2;}
+ public void setJl2(ObjectList jl2) {this.jl2 = jl2;}
+ }
+
+ //====================================================================================================
+ // testArrayProperties
+ //====================================================================================================
+ @Test
+ public void testArrayProperties() throws Exception {
+ D1 t = new D1();
+ BeanContext bc = getBeanContext();
+ Map m = bc.forBean(t);
+ m.put("b", new ObjectMap("{s:'foo'}"));
+ assertNotNull(t.b);
+ assertEquals("foo", t.b.s);
+
+ Map m2 = new TreeMap();
+ m2.put("s", "bar");
+ m.put("b", m2);
+ assertNotNull(t.b);
+ assertEquals("bar", t.b.s);
+
+ m.put("b", new D2());
+ assertEquals("default", t.b.s);
+
+ JsonParser p = new JsonParser().setClassLoader(BeanMapTest.class.getClassLoader());
+ m.put("lb1", new ObjectList("[{_class:'"+D2.class.getName()+"',s:'foobar'}]", p));
+ assertEquals(ObjectList.class.getName(), t.lb1.getClass().getName());
+ assertEquals(D2.class.getName(), t.lb1.get(0).getClass().getName());
+ assertEquals("foobar", (t.lb1.get(0)).s);
+
+ m.put("lb2", new ObjectList("[{_class:'"+D2.class.getName()+"',s:'foobar'}]", p));
+ assertEquals(ArrayList.class.getName(), t.lb2.getClass().getName());
+ assertEquals(D2.class.getName(), t.lb2.get(0).getClass().getName());
+ assertEquals("foobar", (t.lb2.get(0)).s);
+
+ m.put("ab1", new ObjectList("[{_class:'"+D2.class.getName()+"',s:'foobar'}]", p));
+ assertEquals("[L"+D2.class.getName()+";", t.ab1.getClass().getName());
+ assertEquals(D2.class.getName(), t.ab1[0].getClass().getName());
+ assertEquals("foobar", t.ab1[0].s);
+
+ m.put("ab2", new ObjectList("[{_class:'"+D2.class.getName()+"',s:'foobar'}]", p));
+ assertEquals("[L"+D2.class.getName()+";", t.ab2.getClass().getName());
+ assertEquals(D2.class.getName(), t.ab2[0].getClass().getName());
+ assertEquals("foobar", t.ab2[0].s);
+ }
+
+ public static class D1 {
+ public D2 b;
+ public List<D2> lb1;
+ public List<D2> lb2 = new ArrayList<D2>();
+ public D2[] ab1;
+ public D2[] ab2 = new D2[0];
+ }
+
+ public static class D2 {
+ public String s = "default";
+ }
+
+ //====================================================================================================
+ // testArrayPropertiesInObjectList
+ //====================================================================================================
+ @Test
+ public void testArrayPropertiesInObjectList() throws Exception {
+ E t = new E();
+ Map m = BeanContext.DEFAULT.forBean(t);
+ m.put("s", new ObjectList("['foo']"));
+ m.put("s2", new ObjectList("[['foo']]"));
+ m.put("i", new ObjectList("[1,2,3]"));
+ m.put("i2", new ObjectList("[[1,2,3],[4,5,6]]"));
+ assertEquals("{s:['foo'],s2:[['foo']],i:[1,2,3],i2:[[1,2,3],[4,5,6]]}", JsonSerializer.DEFAULT_LAX.serialize(t));
+ m.put("i", new ObjectList("[null,null,null]"));
+ m.put("i2", new ObjectList("[[null,null,null],[null,null,null]]"));
+ assertEquals("{s:['foo'],s2:[['foo']],i:[0,0,0],i2:[[0,0,0],[0,0,0]]}", JsonSerializer.DEFAULT_LAX.serialize(t));
+ }
+
+ public static class E {
+ public String[] s;
+ public String[][] s2;
+ public int[] i;
+ public int[][] i2;
+ }
+
+ //====================================================================================================
+ // BeanMap.invokeMethod()
+ //====================================================================================================
+ @Test
+ public void testInvokeMethod() throws Exception {
+ F t5 = new F();
+ ReaderParser p = JsonParser.DEFAULT;
+ BeanMap m = BeanContext.DEFAULT.forBean(t5);
+ new PojoIntrospector(t5, p).invokeMethod("doSetAProperty(java.lang.String)", "['baz']");
+ assertEquals("baz", m.get("prop"));
+ }
+
+ public static class F {
+ public String prop;
+
+ public boolean doSetAProperty(String prop) {
+ this.prop = prop;
+ return true;
+ }
+ }
+
+ //====================================================================================================
+ // @BeanProperty tests
+ //====================================================================================================
+ @Test
+ public void testBeanPropertyAnnotation() throws Exception {
+ G1 t6 = new G1();
+ BeanMap m = BeanContext.DEFAULT.forBean(t6);
+
+ try {
+ m.put("l1", "[{a:'a',i:1}]");
+ throw new Exception("Expected exception on unsettable field.");
+ } catch (Exception e) {
+ // Good.
+ }
+
+ m.put("l2", "[{a:'a',i:1}]");
+ assertEquals("java.util.LinkedList", m.get("l2").getClass().getName());
+ assertEquals("org.apache.juneau.BeanMapTest$G", ((List)m.get("l2")).get(0).getClass().getName());
+
+ m.put("l3", "[{a:'a',i:1}]");
+ assertEquals("org.apache.juneau.ObjectList", m.get("l3").getClass().getName());
+ assertEquals("org.apache.juneau.BeanMapTest$G", ((List)m.get("l3")).get(0).getClass().getName());
+
+ m.put("l4", "[{a:'a',i:1}]");
+ assertEquals("java.util.LinkedList", m.get("l4").getClass().getName());
+ assertEquals("org.apache.juneau.BeanMapTest$G", ((List)m.get("l4")).get(0).getClass().getName());
+
+ try {
+ m.put("m1", "[{a:'a',i:1}]");
+ throw new Exception("Expected exception on unsettable field.");
+ } catch (Exception e) {
+ // Good.
+ }
+
+ m.put("m2", "[{a:'a',i:1}]");
+ assertEquals("java.util.LinkedList", m.get("m2").getClass().getName());
+ assertEquals("org.apache.juneau.BeanMapTest$G", ((List)m.get("m2")).get(0).getClass().getName());
+
+ m.put("m3", "[{a:'a',i:1}]");
+ assertEquals("org.apache.juneau.ObjectList", m.get("m3").getClass().getName());
+ assertEquals("org.apache.juneau.BeanMapTest$G", ((List)m.get("m3")).get(0).getClass().getName());
+
+ m.put("m4", "[{a:'a',i:1}]");
+ assertEquals("java.util.LinkedList", m.get("m4").getClass().getName());
+ assertEquals("org.apache.juneau.BeanMapTest$G", ((List)m.get("m4")).get(0).getClass().getName());
+ }
+
+ public static class G {
+ public String a;
+ public int i;
+ }
+
+ public static class G1 {
+
+ public List<G> l1;
+
+ public List<G> l2 = new LinkedList<G>();
+
+ @BeanProperty(type=List.class,params={G.class})
+ public List<G> l3;
+
+ @BeanProperty(type=LinkedList.class,params={G.class})
+ public List<G> l4;
+
+ private List<G> m1;
+ public List<G> getM1() { return m1; }
+ public void setM1(List<G> m1) { this.m1 = m1; }
+
+ private List<G> m2 = new LinkedList<G>();
+ public List<G> getM2() { return m2; }
+ public void setM2(List<G> m2) { this.m2 = m2; }
+
+ private List<G> m3;
+ @BeanProperty(type=List.class,params={G.class})
+ public List<G> getM3() { return m3; }
+ public void setM3(List<G> m3) { this.m3 = m3; }
+
+ private List<G> m4;
+ @BeanProperty(type=LinkedList.class,params={G.class})
+ public List<G> getM4() { return m4; }
+ public void setM4(List<G> m4) { this.m4 = m4; }
+ }
+
+ //====================================================================================================
+ // Enum tests
+ //====================================================================================================
+ @Test
+ public void testEnum() throws Exception {
+ BeanContext bc = getBeanContext();
+
+ // Initialize existing bean.
+ H t7 = new H();
+ BeanMap m = bc.forBean(t7);
+ m.put("enum1", "ONE");
+ m.put("enum2", "TWO");
+ assertEquals("{enum1:'ONE',enum2:'TWO'}", serializer.serialize(t7));
+ assertEquals(HEnum.ONE, t7.enum1);
+ assertEquals(HEnum.TWO, t7.getEnum2());
+
+ // Use BeanContext to create bean instance.
+ m = BeanContext.DEFAULT.newBeanMap(H.class).load("{enum1:'TWO',enum2:'THREE'}");
+ assertEquals("{enum1:'TWO',enum2:'THREE'}", serializer.serialize(m.getBean()));
+ t7 = (H)m.getBean();
+ assertEquals(HEnum.TWO, t7.enum1);
+ assertEquals(HEnum.THREE, t7.getEnum2());
+
+ // Create instance directly from JSON.
+ JsonParser p = new JsonParser().setClassLoader(BeanMapTest.class.getClassLoader());
+ t7 = (H)p.parse("{_class:'"+H.class.getName()+"',enum1:'THREE',enum2:'ONE'}", Object.class);
+ assertEquals("{enum1:'THREE',enum2:'ONE'}", serializer.serialize(t7));
+ assertEquals(HEnum.THREE, t7.enum1);
+ assertEquals(HEnum.ONE, t7.getEnum2());
+ }
+
+ public static enum HEnum {
+ ONE, TWO, THREE
+ }
+
+ public static class H {
+
+ public HEnum enum1;
+
+ private HEnum enum2;
+
+ public HEnum getEnum2() {
+ return enum2;
+ }
+
+ public void setEnum2(HEnum enum2) {
+ this.enum2 = enum2;
+ }
+ }
+
+ //====================================================================================================
+ // Automatic detection of generic types
+ //====================================================================================================
+ @Test
+ public void testAutomaticDetectionOfGenericTypes() throws Exception {
+ BeanMap bm = BeanContext.DEFAULT.newBeanMap(I.class);
+ assertEquals(String.class, bm.getProperty("p1").getMeta().getClassMeta().getElementType().getInnerClass());
+ assertEquals(Integer.class, bm.getProperty("p2").getMeta().getClassMeta().getElementType().getInnerClass());
+ assertEquals(Object.class, bm.getProperty("p3").getMeta().getClassMeta().getElementType().getInnerClass());
+ assertEquals(String.class, bm.getProperty("p4").getMeta().getClassMeta().getKeyType().getInnerClass());
+ assertEquals(Integer.class, bm.getProperty("p4").getMeta().getClassMeta().getValueType().getInnerClass());
+ assertEquals(String.class, bm.getProperty("p5").getMeta().getClassMeta().getKeyType().getInnerClass());
+ assertEquals(Integer.class, bm.getProperty("p5").getMeta().getClassMeta().getValueType().getInnerClass());
+ assertEquals(Object.class, bm.getProperty("p6").getMeta().getClassMeta().getKeyType().getInnerClass());
+ assertEquals(Object.class, bm.getProperty("p6").getMeta().getClassMeta().getValueType().getInnerClass());
+ }
+
+ public static class I {
+
+ public List<String> p1;
+
+ public List<Integer> getP2() {
+ return null;
+ }
+
+ public List<? extends Integer> p3;
+
+ public Map<String,Integer> p4;
+
+ public Map<String,Integer> getP5() {
+ return null;
+ }
+
+ public Map<String,? extends Integer> p6;
+ }
+
+ //====================================================================================================
+ // Overriding detection of generic types.
+ //====================================================================================================
+ @Test
+ public void testOverridingDetectionOfGenericTypes() throws Exception {
+ BeanMap bm = BeanContext.DEFAULT.newBeanMap(J.class);
+ assertEquals(Float.class, bm.getProperty("p1").getMeta().getClassMeta().getElementType().getInnerClass());
+ assertEquals(Float.class, bm.getProperty("p2").getMeta().getClassMeta().getElementType().getInnerClass());
+ assertEquals(Float.class, bm.getProperty("p3").getMeta().getClassMeta().getElementType().getInnerClass());
+ assertEquals(Object.class, bm.getProperty("p4").getMeta().getClassMeta().getKeyType().getInnerClass());
+ assertEquals(Float.class, bm.getProperty("p4").getMeta().getClassMeta().getValueType().getInnerClass());
+ assertEquals(Object.class, bm.getProperty("p5").getMeta().getClassMeta().getKeyType().getInnerClass());
+ assertEquals(Float.class, bm.getProperty("p5").getMeta().getClassMeta().getValueType().getInnerClass());
+ assertEquals(String.class, bm.getProperty("p6").getMeta().getClassMeta().getKeyType().getInnerClass());
+ assertEquals(Float.class, bm.getProperty("p6").getMeta().getClassMeta().getValueType().getInnerClass());
+ }
+
+ public static class J {
+
+ @BeanProperty(params={Float.class})
+ public List<String> p1;
+
+ @BeanProperty(params={Float.class})
+ public List<Integer> getP2() {
+ return null;
+ }
+
+ @BeanProperty(params={Float.class})
+ public List<? extends Integer> p3;
+
+ @BeanProperty(params={Object.class, Float.class})
+ public Map<String,Integer> p4;
+
+ @BeanProperty(params={Object.class, Float.class})
+ public Map<String,Integer> getP5() {
+ return null;
+ }
+
+ @BeanProperty(params={String.class, Float.class})
+ public Map<String,? extends Integer> p6;
+ }
+
+ //====================================================================================================
+ // Overriding detection of generic types.
+ //====================================================================================================
+ @Test
+ public void testOverridingDetectionOfGenericTypes2() throws Exception {
+ BeanMap bm = BeanContext.DEFAULT.newBeanMap(K.class);
+ assertEquals(Float.class, bm.getProperty("p1").getMeta().getClassMeta().getElementType().getInnerClass());
+ assertEquals(Float.class, bm.getProperty("p2").getMeta().getClassMeta().getElementType().getInnerClass());
+ assertEquals(Float.class, bm.getProperty("p3").getMeta().getClassMeta().getElementType().getInnerClass());
+ assertEquals(String.class, bm.getProperty("p4").getMeta().getClassMeta().getKeyType().getInnerClass());
+ assertEquals(Float.class, bm.getProperty("p4").getMeta().getClassMeta().getValueType().getInnerClass());
+ assertEquals(String.class, bm.getProperty("p5").getMeta().getClassMeta().getKeyType().getInnerClass());
+ assertEquals(Float.class, bm.getProperty("p5").getMeta().getClassMeta().getValueType().getInnerClass());
+ assertEquals(String.class, bm.getProperty("p6").getMeta().getClassMeta().getKeyType().getInnerClass());
+ assertEquals(Float.class, bm.getProperty("p6").getMeta().getClassMeta().getValueType().getInnerClass());
+ }
+
+ public static class K {
+
+ @BeanProperty(params=Float.class)
+ public List<String> p1;
+
+ @BeanProperty(params=Float.class)
+ public List<Integer> getP2() {
+ return null;
+ }
+
+ @BeanProperty(params=Float.class)
+ public List<? extends Integer> p3;
+
+ @BeanProperty(params={String.class,Float.class})
+ public Map<String,Integer> p4;
+
+ @BeanProperty(params={String.class,Float.class})
+ public Map<String,Integer> getP5() {
+ return null;
+ }
+
+ @BeanProperty(params={String.class,Float.class})
+ public Map<String,? extends Integer> p6;
+ }
+
+ //====================================================================================================
+ // List<E> subclass properties
+ //====================================================================================================
+ @Test
+ public void testGenericListSubclass() throws Exception {
+ BeanMap<L> bm = BeanContext.DEFAULT.newBeanMap(L.class);
+ bm.put("list", "[{name:'1',value:'1'},{name:'2',value:'2'}]");
+ L b = bm.getBean();
+ assertEquals("1", b.list.get(0).name);
+ }
+
+ public static class L {
+ public L1 list;
+ }
+
+ public static class L1 extends LinkedList<L2> {
+ }
+
+ public static class L2 {
+ public String name, value;
+ public L2(){}
+ public L2(String name, String value) {
+ this.name = name;
+ this.value = value;
+ }
+ }
+
+ //====================================================================================================
+ // Generic fields.
+ //====================================================================================================
+ @Test
+ public void testGenericFields() throws Exception {
+ BeanContext bc = BeanContext.DEFAULT;
+
+ M2 t1 = new M2();
+ BeanMap<M2> bm = bc.forBean(t1);
+ assertEquals(1, bm.get("x"));
+
+ M3 t2 = new M3();
+ BeanMap<M3> cm = bc.forBean(t2);
+ assertEquals(2, cm.get("x"));
+
+ M4 t3 = new M4();
+ BeanMap<M4> dm = bc.forBean(t3);
+ assertEquals(3, dm.get("x"));
+
+ M5 t4 = new M5();
+ BeanMap<M5> em = bc.forBean(t4);
+ assertEquals(4, em.get("x"));
+ }
+
+ public static class M1<T> {
+ public T x;
+ }
+
+ public static class M2 extends M1<Integer> {
+ public M2() {
+ this.x = 1;
+ }
+ }
+
+ public static class M3 extends M2 {
+ public M3() {
+ this.x = 2;
+ }
+ }
+
+ public static class M4<T extends Number> extends M1<T> {
+ public M4() {
+ this.x = (T)new Integer(3);
+ }
+ }
+
+ public static class M5 extends M4<Integer> {
+ public M5() {
+ this.x = new Integer(4);
+ }
+ }
+
+ //====================================================================================================
+ // Generic methods
+ //====================================================================================================
+ @Test
+ public void testGenericMethods() throws Exception {
+ N2 t1 = new N2();
+ BeanMap<N2> bm = BeanContext.DEFAULT.forBean(t1);
+ assertEquals(1, bm.get("x"));
+
+ N3 t2 = new N3();
+ BeanMap<N3> cm = BeanContext.DEFAULT.forBean(t2);
+ assertEquals(2, cm.get("x"));
+
+ N4 t3 = new N4();
+ BeanMap<N4> dm = BeanContext.DEFAULT.forBean(t3);
+ assertEquals(3, dm.get("x"));
+
+ N5 t4 = new N5();
+ BeanMap<N5> em = BeanContext.DEFAULT.forBean(t4);
+ assertEquals(4, em.get("x"));
+ }
+
+ public static class N1<T> {
+ private T x;
+ public void setX(T x) {
+ this.x = x;
+ }
+ public T getX() {
+ return x;
+ }
+ }
+
+ public static class N2 extends N1<Integer> {
+ public N2() {
+ setX(1);
+ }
+ }
+
+ public static class N3 extends N2 {
+ public N3() {
+ setX(2);
+ }
+ }
+
+ public static class N4<T extends Number> extends N1<T> {
+ public N4() {
+ setX((T)new Integer(3));
+ }
+ }
+
+ public static class N5 extends N4<Integer> {
+ public N5() {
+ setX(4);
+ }
+ }
+
+ //====================================================================================================
+ // Test ignoreUnknownBeanProperties setting
+ //====================================================================================================
+ @Test
+ public void testIgnoreUnknownBeanPropertiesSetting() throws Exception {
+ ReaderParser p = null;
+ O t;
+
+ // JSON
+ String json = "{baz:789,foo:123,bar:456}";
+ p = new JsonParser().setProperty(BEAN_ignoreUnknownBeanProperties, true);
+ t = p.parse(json, O.class);
+ assertEquals(123, t.foo);
+
+ try {
+ p = JsonParser.DEFAULT;
+ t = p.parse(json, O.class);
+ fail("Expected exception never occurred");
+ } catch (Exception e) {
+ // Good.
+ }
+
+ // XML
+ String xml = "<object><baz type='number'>789</baz><foo type='number'>123</foo><bar type='number'>456</bar></object>";
+ p = new XmlParser().setProperty(BEAN_ignoreUnknownBeanProperties, true);
+ t = p.parse(xml, O.class);
+ assertEquals(123, t.foo);
+
+ try {
+ p = XmlParser.DEFAULT;
+ t = p.parse(json, O.class);
+ fail("Expected exception never occurred");
+ } catch (Exception e) {
+ // Good.
+ }
+
+ // HTML
+ String html = "<table type='object'><tr><th><string>key</string></th><th><string>value</string></th></tr><tr><td><string>baz</string></td><td><number>789</number></td></tr><tr><td><string>foo</string></td><td><number>123</number></td></tr><tr><td><string>bar</string></td><td><number>456</number></td></tr></table>";
+ p = new HtmlParser().setProperty(BEAN_ignoreUnknownBeanProperties, true);
+ t = p.parse(html, O.class);
+ assertEquals(123, t.foo);
+
+ try {
+ p = HtmlParser.DEFAULT;
+ t = p.parse(json, O.class);
+ fail("Expected exception never occurred");
+ } catch (Exception e) {
+ // Good.
+ }
+
+ // UON
+ String uon = "(baz=789,foo=123,bar=456)";
+ p = new UonParser().setProperty(BEAN_ignoreUnknownBeanProperties, true);
+ t = p.parse(uon, O.class);
+ assertEquals(123, t.foo);
+
+ try {
+ p = new UonParser();
+ t = p.parse(json, O.class);
+ fail("Expected exception never occurred");
+ } catch (Exception e) {
+ // Good.
+ }
+
+ // URL-Encoding
+ String urlencoding = "baz=789&foo=123&bar=456";
+ p = new UrlEncodingParser().setProperty(BEAN_ignoreUnknownBeanProperties, true);
+ t = p.parse(urlencoding, O.class);
+ assertEquals(123, t.foo);
+
+ try {
+ p = new UrlEncodingParser();
+ t = p.parse(json, O.class);
+ fail("Expected exception never occurred");
+ } catch (Exception e) {
+ // Good.
+ }
+
+ }
+
+ public static class O {
+ public int foo;
+ }
+
+ //====================================================================================================
+ // testPropertyNameFactoryDashedLC1
+ //====================================================================================================
+ @Test
+ public void testPropertyNameFactoryDashedLC1() throws Exception {
+ BeanContext bc = BeanContext.DEFAULT;
+ BeanMap<P1> m = bc.newBeanMap(P1.class).load("{'foo':1,'bar-baz':2,'bing-boo-url':3}");
+ assertEquals(1, m.get("foo"));
+ assertEquals(2, m.get("bar-baz"));
+ assertEquals(3, m.get("bing-boo-url"));
+ P1 b = m.getBean();
+ assertEquals(1, b.foo);
+ assertEquals(2, b.barBaz);
+ assertEquals(3, b.bingBooURL);
+ m.put("foo", 4);
+ m.put("bar-baz", 5);
+ m.put("bing-boo-url", 6);
+ assertEquals(4, b.foo);
+ assertEquals(5, b.barBaz);
+ assertEquals(6, b.bingBooURL);
+ }
+
+ @Bean(propertyNamer=PropertyNamerDashedLC.class)
+ public static class P1 {
+ public int foo, barBaz, bingBooURL;
+ }
+
+ //====================================================================================================
+ // testPropertyNameFactoryDashedLC2
+ //====================================================================================================
+ @Test
+ public void testPropertyNameFactoryDashedLC2() throws Exception {
+ BeanContext bc = BeanContext.DEFAULT_SORTED;
+ BeanMap<P2> m = bc.newBeanMap(P2.class).load("{'foo-bar':1,'baz-bing':2}");
+ assertEquals(1, m.get("foo-bar"));
+ assertEquals(2, m.get("baz-bing"));
+ P2 b = m.getBean();
+ assertEquals(1, b.getFooBar());
+ assertEquals(2, b.getBazBING());
+ m.put("foo-bar", 3);
+ m.put("baz-bing", 4);
+ assertEquals(3, b.getFooBar());
+ assertEquals(4, b.getBazBING());
+ }
+
+ @Bean(propertyNamer=PropertyNamerDashedLC.class)
+ public static class P2 {
+ private int fooBar, bazBING;
+ public int getFooBar() {
+ return fooBar;
+ }
+ public void setFooBar(int fooBar) {
+ this.fooBar = fooBar;
+ }
+ public int getBazBING() {
+ return bazBING;
+ }
+ public void setBazBING(int bazBING) {
+ this.bazBING = bazBING;
+ }
+ }
+
+ //====================================================================================================
+ // testBeanWithFluentStyleSetters
+ //====================================================================================================
+ @Test
+ public void testBeanWithFluentStyleSetters() throws Exception {
+ Q2 t = new Q2();
+ BeanMap m = BeanContext.DEFAULT_SORTED.forBean(t);
+ m.put("f1", 1);
+ m.put("f2", 2);
+ m.put("f3", 3);
+
+ assertSortedObjectEquals("{f1:1,f2:2,f3:0}", m);
+ }
+
+ public static class Q1 {}
+
+ public static class Q2 extends Q1 {
+ private int f1, f2, f3;
+
+ public Q1 setF1(int f1) {
+ this.f1 = f1;
+ return this;
+ }
+
+ public Q2 setF2(int f2) {
+ this.f2 = f2;
+ return this;
+ }
+
+ // Shouldn't be detected as a setter.
+ public String setF3(int f3) {
+ this.f3 = f3;
+ return null;
+ }
+
+ public int getF1() { return f1; }
+ public int getF2() { return f2; }
+ public int getF3() { return f3; }
+ }
+
+ //====================================================================================================
+ // testCastWithNormalBean
+ //====================================================================================================
+ @Test
+ public void testCastWithNormalBean() throws Exception {
+ BeanContext bc = getBeanContext();
+
+ // With _class
+ ObjectMap m = new ObjectMap(bc);
+ m.put("_class", R2.class.getName());
+ m.put("f1", 1);
+ m.put("f2", "2");
+
+ R2 t = (R2)m.cast();
+ assertEquals(1, t.f1);
+
+ t = (R2)m.cast(R1.class);
+ assertEquals(1, t.f1);
+ assertEquals(2, t.f2);
+
+ t = (R2)m.cast(bc.getClassMeta(R1.class));
+ assertEquals(1, t.f1);
+ assertEquals(2, t.f2);
+
+ // Without _class
+ m = new ObjectMap(bc);
+ m.put("f1", 1);
+ m.put("f2", "2");
+
+ m = (ObjectMap)m.cast();
+ assertEquals(1, t.f1);
+ assertEquals(2, t.f2);
+
+ t = m.cast(R2.class);
+ assertEquals(1, t.f1);
+ assertEquals(2, t.f2);
+
+ t = m.cast(bc.getClassMeta(R2.class));
+ assertEquals(1, t.f1);
+ assertEquals(2, t.f2);
+ }
+
+ // Bean with no properties
+ public static class R1 {
+ public int f1;
+ }
+
+ public static class R2 extends R1 {
+ public int f2;
+ }
+
+ //====================================================================================================
+ // testCastWithNestedBean
+ //====================================================================================================
+ @Test
+ public void testCastWithNestedBean() throws Exception {
+ BeanContext bc = getBeanContext();
+
+ // With _class
+ ObjectMap m = new ObjectMap(bc);
+ m.put("_class", S.class.getName());
+ m.put("f1", new ObjectMap(bc).append("_class", R1.class.getName()).append("f1", 1));
+
+ S t = (S)m.cast();
+ assertEquals(1, t.f1.f1);
+
+ t = m.cast(S.class);
+ assertEquals(1, t.f1.f1);
+
+ t = m.cast(bc.getClassMeta(S.class));
+ assertEquals(1, t.f1.f1);
+
+ // Without _class
+ m = new ObjectMap(bc);
+ m.put("f1", new ObjectMap(bc).append("_class", R1.class.getName()).append("f1", 1));
+
+ m = (ObjectMap)m.cast();
+ assertEquals(1, t.f1.f1);
+
+ t = m.cast(S.class);
+ assertEquals(1, t.f1.f1);
+
+ t = m.cast(bc.getClassMeta(S.class));
+ assertEquals(1, t.f1.f1);
+ }
+
+ public static class S {
+ public R1 f1;
+ }
+
+ //====================================================================================================
+ // testCastToAnotherMapType
+ //====================================================================================================
+ @Test
+ public void testCastToAnotherMapType() throws Exception {
+ BeanContext bc = BeanContext.DEFAULT;
+ Map m2;
+
+ // With _class
+ ObjectMap m = new ObjectMap();
+ m.put("_class", TreeMap.class.getName());
+ m.put("1", "ONE");
+
+ m2 = (Map)m.cast();
+ assertTrue(m2 instanceof TreeMap);
+ assertEquals("ONE", m2.get("1"));
+
+ m2 = m.cast(Map.class);
+ assertTrue(m2 instanceof TreeMap);
+ assertEquals("ONE", m2.get("1"));
+
+ m2 = m.cast(bc.getClassMeta(TreeMap.class));
+ assertTrue(m2 instanceof TreeMap);
+ assertEquals("ONE", m2.get("1"));
+
+ m2 = (Map)m.cast(bc.getMapClassMeta(TreeMap.class, Integer.class, TEnum.class));
+ assertTrue(m2 instanceof TreeMap);
+ Map.Entry e = (Map.Entry)m2.entrySet().iterator().next();
+ assertTrue(e.getKey() instanceof Integer);
+ assertTrue(e.getValue() instanceof TEnum);
+ assertEquals(TEnum.ONE, m2.get(1));
+
+ m2 = m.cast(bc.getClassMeta(TreeMap.class));
+ assertTrue(m2 instanceof TreeMap);
+ e = (Map.Entry)m2.entrySet().iterator().next();
+ assertTrue(e.getKey() instanceof String);
+ assertTrue(e.getValue() instanceof String);
+ assertEquals("ONE", m2.get("1"));
+
+ m2 = (Map)m.cast(bc.getMapClassMeta(HashMap.class, Integer.class, TEnum.class));
+ assertTrue(m2 instanceof HashMap);
+ e = (Map.Entry)m2.entrySet().iterator().next();
+ assertTrue(e.getKey() instanceof Integer);
+ assertTrue(e.getValue() instanceof TEnum);
+ assertEquals(TEnum.ONE, m2.get(1));
+
+ // Without _class
+ m = new ObjectMap();
+ m.put("1", "ONE");
+
+ m2 = (ObjectMap)m.cast();
+ assertTrue(m2 instanceof ObjectMap);
+ assertEquals("ONE", m2.get("1"));
+
+ m2 = m.cast(Map.class);
+ assertTrue(m2 instanceof ObjectMap);
+ assertEquals("ONE", m2.get("1"));
+
+ m2 = m.cast(bc.getClassMeta(TreeMap.class));
+ assertTrue(m2 instanceof TreeMap);
+ assertEquals("ONE", m2.get("1"));
+
+ m2 = (Map)m.cast(bc.getMapClassMeta(TreeMap.class, Integer.class, TEnum.class));
+ assertTrue(m2 instanceof TreeMap);
+ e = (Map.Entry)m2.entrySet().iterator().next();
+ assertTrue(e.getKey() instanceof Integer);
+ assertTrue(e.getValue() instanceof TEnum);
+ assertEquals(TEnum.ONE, m2.get(1));
+
+ m2 = m.cast(bc.getClassMeta(TreeMap.class));
+ assertTrue(m2 instanceof TreeMap);
+ e = (Map.Entry)m2.entrySet().iterator().next();
+ assertTrue(e.getKey() instanceof String);
+ assertTrue(e.getValue() instanceof String);
+ assertEquals("ONE", m2.get("1"));
+ }
+
+ public static enum TEnum {
+ ONE, TWO, THREE;
+ }
+
+ //====================================================================================================
+ // testCastToLinkedList
+ //====================================================================================================
+ @Test
+ public void testCastToLinkedList() throws Exception {
+ BeanContext bc = BeanContext.DEFAULT;
+
+ // With _class
+ ObjectMap m = new ObjectMap();
+ m.put("_class", LinkedList.class.getName());
+ m.put("items", new ObjectList().append("1").append("2"));
+
+ List l = (List)m.cast();
+ assertTrue(l instanceof LinkedList);
+ assertEquals("1", l.get(0));
+
+ l = m.cast(List.class);
+ assertTrue(l instanceof LinkedList);
+ assertEquals("1", l.get(0));
+
+ l = m.cast(bc.getClassMeta(List.class));
+ assertTrue(l instanceof LinkedList);
+ assertEquals("1", l.get(0));
+
+ l = m.cast(bc.getClassMeta(ArrayList.class));
+ assertTrue(l instanceof ArrayList);
+ assertEquals("1", l.get(0));
+
+ // Without _class
+ m = new ObjectMap();
+ m.put("items", new ObjectList().append("1").append("2"));
+
+ l = m.cast(List.class);
+ assertTrue(l instanceof ObjectList);
+ assertEquals("1", l.get(0));
+
+ l = m.cast(LinkedList.class);
+ assertTrue(l instanceof LinkedList);
+ assertEquals("1", l.get(0));
+
+ l = m.cast(bc.getClassMeta(List.class));
+ assertTrue(l instanceof ObjectList);
+ assertEquals("1", l.get(0));
+
+ l = m.cast(bc.getClassMeta(ArrayList.class));
+ assertTrue(l instanceof ArrayList);
+ assertEquals("1", l.get(0));
+
+ l = (List)m.cast(bc.getCollectionClassMeta(List.class, Integer.class));
+ assertTrue(l instanceof LinkedList);
+ assertTrue(l.get(0) instanceof Integer);
+ assertEquals(1, l.get(0));
+ }
+
+ //====================================================================================================
+ // testToLinkedListInteger - cast() to LinkedList<Integer>
+ //====================================================================================================
+ @Test
+ public void testToLinkedListInteger() throws Exception {
+ BeanContext bc = BeanContext.DEFAULT;
+
+ // With _class
+ ObjectMap m = new ObjectMap();
+ m.put("_class", LinkedList.class.getName() + "<java.lang.Integer>");
+ m.put("items", new ObjectList().append("1").append("2"));
+
+ List l = (List)m.cast();
+ assertTrue(l instanceof LinkedList);
+ assertEquals(1, l.get(0));
+
+ l = m.cast(List.class);
+ assertTrue(l instanceof LinkedList);
+ assertEquals(1, l.get(0));
+
+ l = m.cast(ArrayList.class);
+ assertTrue(l instanceof ArrayList);
+ assertEquals(1, l.get(0));
+
+ l = m.cast(bc.getClassMeta(List.class));
+ assertTrue(l instanceof LinkedList);
+ assertEquals(1, l.get(0));
+
+ l = m.cast(bc.getClassMeta(ArrayList.class));
+ assertTrue(l instanceof ArrayList);
+ assertEquals(1, l.get(0));
+
+ l = (List)m.cast(bc.getCollectionClassMeta(List.class, String.class));
+ assertTrue(l instanceof LinkedList);
+ assertTrue(l.get(0) instanceof String);
+ assertEquals("1", l.get(0));
+
+ // Without _class
+ m = new ObjectMap();
+ m.put("items", new ObjectList().append("1").append("2"));
+
+ l = m.cast(List.class);
+ assertTrue(l instanceof ObjectList);
+ assertEquals("1", l.get(0));
+
+ l = m.cast(ArrayList.class);
+ assertTrue(l instanceof ArrayList);
+ assertEquals("1", l.get(0));
+
+ l = m.cast(bc.getClassMeta(List.class));
+ assertTrue(l instanceof ObjectList);
+ assertEquals("1", l.get(0));
+
+ l = m.cast(bc.getClassMeta(ArrayList.class));
+ assertTrue(l instanceof ArrayList);
+ assertEquals("1", l.get(0));
+
+ l = (List)m.cast(bc.getCollectionClassMeta(List.class, Integer.class));
+ assertTrue(l instanceof ObjectList);
+ assertTrue(l.get(0) instanceof Integer);
+ assertEquals(1, l.get(0));
+ }
+
+ //====================================================================================================
+ // testCastToLinkedListBean - cast() to LinkedList<R1>
+ //====================================================================================================
+ @Test
+ public void testCastToLinkedListBean() throws Exception {
+ BeanContext bc = getBeanContext();
+
+ // With _class
+ ObjectMap m = new ObjectMap(bc);
+ m.put("_class", LinkedList.class.getName() + "<"+R1.class.getName()+">");
+ m.put("items", new ObjectList(bc).append("{f1:1}"));
+
+ List l = (List)m.cast();
+ assertTrue(l instanceof LinkedList);
+ assertTrue(l.get(0) instanceof R1);
+ assertEquals(1, ((R1)l.get(0)).f1);
+
+ l = m.cast(List.class);
+ assertTrue(l instanceof LinkedList);
+ assertTrue(l.get(0) instanceof R1);
+ assertEquals(1, ((R1)l.get(0)).f1);
+
+ l = m.cast(ArrayList.class);
+ assertTrue(l instanceof ArrayList);
+ assertTrue(l.get(0) instanceof R1);
+ assertEquals(1, ((R1)l.get(0)).f1);
+
+ l = m.cast(bc.getClassMeta(List.class));
+ assertTrue(l instanceof LinkedList);
+ assertTrue(l.get(0) instanceof R1);
+ assertEquals(1, ((R1)l.get(0)).f1);
+
+ l = m.cast(bc.getClassMeta(ArrayList.class));
+ assertTrue(l instanceof ArrayList);
+ assertTrue(l.get(0) instanceof R1);
+ assertEquals(1, ((R1)l.get(0)).f1);
+
+ l = (List)m.cast(bc.getCollectionClassMeta(List.class, HashMap.class));
+ assertTrue(l instanceof LinkedList);
+ assertTrue(l.get(0) instanceof HashMap);
+ assertEquals(1, ((Map)l.get(0)).get("f1"));
+
+ // Without _class
+ m = new ObjectMap(bc);
+ m.put("items", new ObjectList(bc).append("{f1:1}"));
+
+ l = m.cast(List.class);
+ assertTrue(l instanceof ObjectList);
+ assertTrue(l.get(0) instanceof String);
+ assertEquals("{f1:1}", l.get(0));
+
+ l = m.cast(ArrayList.class);
+ assertTrue(l instanceof ArrayList);
+ assertTrue(l.get(0) instanceof String);
+ assertEquals("{f1:1}", l.get(0));
+
+ l = m.cast(bc.getClassMeta(List.class));
+ assertTrue(l instanceof ObjectList);
+ assertTrue(l.get(0) instanceof String);
+ assertEquals("{f1:1}", l.get(0));
+
+ l = m.cast(bc.getClassMeta(ArrayList.class));
+ assertTrue(l instanceof ArrayList);
+ assertTrue(l.get(0) instanceof String);
+ assertEquals("{f1:1}", l.get(0));
+
+ l = (List)m.cast(bc.getCollectionClassMeta(List.class, R1.class));
+ assertTrue(l instanceof LinkedList);
+ assertTrue(l.get(0) instanceof R1);
+ assertEquals(1, ((R1)l.get(0)).f1);
+
+ l = (List)m.cast(bc.getCollectionClassMeta(List.class, HashMap.class));
+ assertTrue(l instanceof LinkedList);
+ assertTrue(l.get(0) instanceof HashMap);
+ assertEquals(1, ((Map)l.get(0)).get("f1"));
+
+ l = (List)m.cast(bc.getCollectionClassMeta(List.class, Map.class));
+ assertTrue(l instanceof LinkedList);
+ assertTrue(l.get(0) instanceof ObjectMap);
+ assertEquals(1, ((Map)l.get(0)).get("f1"));
+ }
+
+ //====================================================================================================
+ // testCastToLinkedListUsingTransform - cast() to LinkedList<Calendar> using CalendarTransform
+ //====================================================================================================
+ @Test
+ public void testCastToLinkedListUsingTransform() throws Exception {
+ BeanContext bc = ContextFactory.create().addTransforms(CalendarTransform.ISO8601DTZ.class).getBeanContext();
+
+ // With _class
+ ObjectMap m = new ObjectMap(bc);
+ m.put("_class", LinkedList.class.getName() + "<"+Calendar.class.getName()+">");
+ m.put("items", new ObjectList().append("2001-07-04T15:30:45Z"));
+
+ List l = (List)m.cast();
+ assertTrue(l instanceof LinkedList);
+ assertEquals(2001, ((Calendar)l.get(0)).get(Calendar.YEAR));
+
+ l = m.cast(List.class);
+ assertTrue(l instanceof LinkedList);
+ assertEquals(2001, ((Calendar)l.get(0)).get(Calendar.YEAR));
+
+ l = m.cast(ArrayList.class);
+ assertTrue(l instanceof ArrayList);
+ assertEquals(2001, ((Calendar)l.get(0)).get(Calendar.YEAR));
+
+ m.cast(HashSet.class);
+
+ l = m.cast(bc.getClassMeta(List.class));
+ assertTrue(l instanceof LinkedList);
+ assertEquals(2001, ((Calendar)l.get(0)).get(Calendar.YEAR));
+
+ l = m.cast(bc.getClassMeta(ArrayList.class));
+ assertTrue(l instanceof ArrayList);
+ assertEquals(2001, ((Calendar)l.get(0)).get(Calendar.YEAR));
+
+ l = (List)m.cast(bc.getCollectionClassMeta(List.class, String.class));
+ assertTrue(l instanceof LinkedList);
+ assertTrue(l.get(0) instanceof String);
+ assertEquals("2001-07-04T15:30:45Z", l.get(0));
+
+ // Without _class
+ m = new ObjectMap().setBeanContext(bc);
+ m.put("items", new ObjectList().append("2001-07-04T15:30:45Z"));
+
+ l = m.cast(List.class);
+ assertTrue(l instanceof LinkedList);
+
+ l = m.cast(ArrayList.class);
+ assertTrue(l instanceof ArrayList);
+
+ m.cast(HashSet.class);
+
+ l = m.cast(bc.getClassMeta(List.class));
+ assertTrue(l instanceof LinkedList);
+
+ l = m.cast(bc.getClassMeta(ArrayList.class));
+ assertTrue(l instanceof ArrayList);
+
+ l = (List)m.cast(bc.getCollectionClassMeta(List.class, Calendar.class));
+ assertTrue(l instanceof LinkedList);
+ assertTrue(l.get(0) instanceof Calendar);
+ assertEquals(2001, ((Calendar)l.get(0)).get(Calendar.YEAR));
+ }
+
+ //====================================================================================================
+ // testCastToStringArray - cast() to String[]
+ //====================================================================================================
+ @Test
+ public void testCastToStringArray() throws Exception {
+ BeanContext bc = BeanContext.DEFAULT;
+
+ // With _class
+ ObjectMap m = new ObjectMap();
+ m.put("_class", String[].class.getName());
+ m.put("items", new ObjectList().append("1").append("2"));
+
+ String[] l = (String[])m.cast();
+ assertEquals("1", l[0]);
+
+ l = m.cast(String[].class);
+ assertEquals("1", l[0]);
+
+ StringBuffer[] l2 = m.cast(StringBuffer[].class);
+ assertEquals("1", l2[0].toString());
+
+ int[] l3 = m.cast(int[].class);
+ assertEquals(1, l3[0]);
+
+ l = m.cast(bc.getClassMeta(String[].class));
+ assertEquals("1", l[0]);
+
+ l2 = m.cast(bc.getClassMeta(StringBuffer[].class));
+ assertEquals("1", l2[0].toString());
+
+ l3 = m.cast(bc.getClassMeta(int[].class));
+ assertEquals("1", l2[0].toString());
+
+ // Without _class
+ m = new ObjectMap();
+ m.put("items", new ObjectList().append("1").append("2"));
+
+ l = m.cast(String[].class);
+ assertEquals("1", l[0]);
+
+ l = m.cast(bc.getClassMeta(String[].class));
+ assertEquals("1", l[0]);
+
+ l2 = m.cast(bc.getClassMeta(StringBuffer[].class));
+ assertEquals("1", l[0].toString());
+ }
+
+ //====================================================================================================
+ // testCastToIntArray - cast() to int[]
+ //====================================================================================================
+ @Test
+ public void testCastToIntArray() throws Exception {
+ BeanContext bc = BeanContext.DEFAULT;
+
+ // With _class
+ ObjectMap m = new ObjectMap();
+ m.put("_class", int[].class.getName());
+ m.put("items", new ObjectList().append("1").append("2"));
+
+ int[] l = (int[])m.cast();
+ assertEquals(1, l[0]);
+
+ l = m.cast(int[].class);
+ assertEquals(1, l[0]);
+
+ l = m.cast(bc.getClassMeta(int[].class));
+ assertEquals(1, l[0]);
+
+ long[] l2;
+
+ l2 = m.cast(long[].class);
+ assertEquals(1, l2[0]);
+
+ l2 = m.cast(bc.getClassMeta(long[].class));
+ assertEquals(1, l2[0]);
+
+ // Without _class
+ m = new ObjectMap();
+ m.put("items", new ObjectList().append("1").append("2"));
+
+ l = m.cast(int[].class);
+ assertEquals(1, l[0]);
+
+ l = m.cast(bc.getClassMeta(int[].class));
+ assertEquals(1, l[0]);
+
+ l2 = m.cast(long[].class);
+ assertEquals(1, l2[0]);
+
+ l2 = m.cast(bc.getClassMeta(long[].class));
+ assertEquals(1, l2[0]);
+ }
+
+ //====================================================================================================
+ // testCastToString2dArray - cast() to String[][]
+ //====================================================================================================
+ @Test
+ public void testCastToString2dArray() throws Exception {
+ BeanContext bc = BeanContext.DEFAULT;
+
+ // With _class
+ ObjectMap m = new ObjectMap();
+ m.put("_class", String[][].class.getName());
+ m.put("items", new ObjectList().append(new ObjectList().append("1")).append(new ObjectList().append("2")));
+
+ String[][] l = (String[][])m.cast();
+ assertEquals("1", l[0][0]);
+ assertEquals("2", l[1][0]);
+
+ l = m.cast(String[][].class);
+ assertEquals("1", l[0][0]);
+
+ l = m.cast(bc.getClassMeta(String[][].class));
+ assertEquals("2", l[1][0]);
+
+ // Without _class
+ m = new ObjectMap();
+ m.put("items", new ObjectList().append(new ObjectList().append("1")).append(new ObjectList().append("2")));
+
+ l = m.cast(String[][].class);
+ assertEquals("1", l[0][0]);
+
+ l = m.cast(bc.getClassMeta(String[][].class));
+ assertEquals("2", l[1][0]);
+ }
+
+ //====================================================================================================
+ // testCastToInt2dArray - cast() to int[][]
+ //====================================================================================================
+ @Test
+ public void testCastToInt2dArray() throws Exception {
+ BeanContext bc = BeanContext.DEFAULT;
+
+ // With _class
+ ObjectMap m = new ObjectMap();
+ m.put("_class", int[][].class.getName());
+ m.put("items", new ObjectList().append(new ObjectList().append("1")).append(new ObjectList().append("2")));
+
+ int[][] l = (int[][])m.cast();
+ assertEquals(1, l[0][0]);
+ assertEquals(2, l[1][0]);
+
+ l = m.cast(int[][].class);
+ assertEquals(1, l[0][0]);
+
+ l = m.cast(bc.getClassMeta(int[][].class));
+ assertEquals(2, l[1][0]);
+
+ // Without _class
+ m = new ObjectMap();
+ m.put("items", new ObjectList().append(new ObjectList().append("1")).append(new ObjectList().append("2")));
+
+ l = m.cast(int[][].class);
+ assertEquals(1, l[0][0]);
+
+ l = m.cast(bc.getClassMeta(int[][].class));
+ assertEquals(2, l[1][0]);
+ }
+
+ //====================================================================================================
+ // testHiddenProperties
+ //====================================================================================================
+ @Test
+ public void testHiddenProperties() throws Exception {
+ JsonSerializer s = JsonSerializer.DEFAULT_LAX;
+ BeanMeta bm = s.getBeanContext().getBeanMeta(U.class);
+ assertNotNull(bm.getPropertyMeta("a"));
+ assertNotNull(bm.getPropertyMeta("b"));
+ assertNull(bm.getPropertyMeta("c"));
+ assertNull(bm.getPropertyMeta("d"));
+
+ U t = new U();
+ t.a = "a";
+ t.b = "b";
+ String r = s.serialize(t);
+ assertEquals("{a:'a',b:'b'}", r);
+
+ // Make sure setters are used if present.
+ t = JsonParser.DEFAULT.parse(r, U.class);
+ assertEquals("b(setter)", t.b);
+ }
+
+ public static class U {
+ public String a, b;
+
+ public String getA() {
+ return a;
+ }
+
+ public void setA(String a) {
+ this.a = a;
+ }
+
+ @BeanIgnore
+ public String getB() {
+ return b;
+ }
+
+ public void setB(String b) {
+ this.b = b+"(setter)";
+ }
+
+ @BeanIgnore
+ public String c;
+
+ @BeanIgnore
+ public String getD() {
+ return null;
+ }
+
+ @BeanIgnore
+ public void setD(String d) {
+ }
+ }
+
+ //====================================================================================================
+ // testBeanPropertyOrder
+ //====================================================================================================
+ @Test
+ public void testBeanPropertyOrder() throws Exception {
+ assertObjectEquals("{a1:'1',a2:'2',a3:'3',a4:'4'}", new V2());
+ assertObjectEquals("{a3:'3',a4:'4',a5:'5',a6:'6'}", new V3());
+ }
+
+ public static class V {
+ public String a1="1", a2="2";
+ }
+
+ public static class V2 extends V {
+ public String a3="3", a4="4";
+ }
+
+ @Bean(stopClass=V.class)
+ public static class V3 extends V2 {
+ public String a5="5", a6="6";
+ }
+
+ //====================================================================================================
+ // testBeanMethodOrder
+ //====================================================================================================
+ @Test
+ public void testBeanMethodOrder() throws Exception {
+ assertSortedObjectEquals("{a1:'1',a2:'2',a3:'3',a4:'4'}", new W2());
+ assertSortedObjectEquals("{a3:'3',a4:'4',a5:'5',a6:'6'}", new W3());
+ }
+
+ public static class W {
+ public String getA1() {return "1";}
+ public String getA2() {return "2";}
+ }
+
+ public static class W2 extends W {
+ public String getA3() {return "3";}
+ public String getA4() {return "4";}
+ }
+
+ @Bean(stopClass=W.class)
+ public static class W3 extends W2 {
+ public String getA5() {return "5";}
+ public String getA6() {return "6";}
+ }
+
+ //====================================================================================================
+ // testResourceDescription
+ //====================================================================================================
+ @Test
+ public void testOverriddenPropertyTypes() throws Exception {
+ JsonSerializer s = JsonSerializer.DEFAULT_LAX;
+ JsonParser p = JsonParser.DEFAULT;
+ String r;
+
+ X1 t1 = X1.create();
+ r = s.serialize(t1);
+ assertEquals("{f1:'1',f2:'2'}", r);
+ t1 = p.parse(r, X1.class);
+ assertEquals("1", t1.f1);
+ assertEquals("2", t1.getF2());
+
+ X2 t2 = X2.create();
+ r = s.serialize(t2);
+ assertEquals("{f1:1,f2:2}", r);
+ t2 = p.parse(r, X2.class);
+ assertEquals(1, t2.f1.intValue());
+ assertEquals(2, t2.getF2().intValue());
+ }
+
+ public static class X1 {
+ public Object f1;
+ private Object f2;
+
+ static X1 create() {
+ X1 x = new X1();
+ x.f1 = "1";
+ x.f2 = "2";
+ return x;
+ }
+
+ public Object getF2() {
+ return f2;
+ }
+
+ public void setF2(Object f2) {
+ this.f2 = f2;
+ }
+ }
+
+ public static class X2 extends X1 {
+ public Integer f1;
+ private Integer f2;
+
+ static X2 create() {
+ X2 x = new X2();
+ x.f1 = 1;
+ x.f2 = 2;
+ return x;
+ }
+
+ @Override /* X1 */
+ public Integer getF2() {
+ return f2;
+ }
+
+ public void setF2(Integer f2) {
+ this.f2 = f2;
+ }
+ }
+
+ private BeanContext getBeanContext() {
+ return ContextFactory.create().setClassLoader(this.getClass().getClassLoader()).getBeanContext();
+ }
+
+ @Test
+ public void testSettingCollectionPropertyMultipleTimes() throws Exception {
+
+ BeanMap m = BeanContext.DEFAULT.newBeanMap(Y.class);
+ m.put("f1", new ObjectList().append("a"));
+ m.put("f1", new ObjectList().append("b"));
+ assertEquals("{f1=[b]}", m.toString());
+ }
+
+ public static class Y {
+ public List<String> f1 = new LinkedList<String>();
+ }
+
+ //====================================================================================================
+ // entrySet(false).
+ //====================================================================================================
+ @Test
+ public void testIgnoreNulls() {
+ Z z = new Z();
+ BeanMap<Z> bm = BeanContext.DEFAULT.forBean(z);
+
+ Iterator i = bm.getValues(false, true).iterator();
+ assertFalse(i.hasNext());
+
+ z.b = "";
+ i = bm.getValues(false, true).iterator();
+ assertTrue(i.hasNext());
+ i.next();
+ assertFalse(i.hasNext());
+
+ i = bm.getValues(false, false).iterator();
+ assertTrue(i.hasNext());
+ i.next();
+ assertTrue(i.hasNext());
+ i.next();
+ assertTrue(i.hasNext());
+ i.next();
+ assertFalse(i.hasNext());
+ }
+
+ public static class Z {
+ public String a, b, c;
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/BeanTransformTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/BeanTransformTest.java b/org.apache.juneau/src/test/java/org/apache/juneau/BeanTransformTest.java
new file mode 100755
index 0000000..38f64af
--- /dev/null
+++ b/org.apache.juneau/src/test/java/org/apache/juneau/BeanTransformTest.java
@@ -0,0 +1,144 @@
+/***************************************************************************************************************************
+ * 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.juneau;
+
+import static org.junit.Assert.*;
+
+import java.util.*;
+
+import org.apache.juneau.annotation.*;
+import org.apache.juneau.json.*;
+import org.junit.*;
+
+public class BeanTransformTest {
+
+ //====================================================================================================
+ // Test sub types
+ //====================================================================================================
+ @Test
+ public void testSubTypes() throws Exception {
+ JsonSerializer s = JsonSerializer.DEFAULT_LAX;
+ JsonParser p = JsonParser.DEFAULT;
+
+ A1 a1 = new A1();
+ a1.f1 = "f1";
+ a1.fb = new B2();
+ ((B2)a1.fb).f2 = "f2";
+ String r = s.serialize(a1);
+ assertEquals("{subType:'A1',f0:'f0',fb:{subType:'B2',f0b:'f0b',f2:'f2'},f1:'f1'}", r);
+
+ A a = p.parse(r, A.class);
+ assertTrue(a instanceof A1);
+ assertTrue(a.fb instanceof B2);
+ assertEquals("f1", ((A1)a).f1);
+ assertEquals("f2", ((B2)a.fb).f2);
+
+ // Try out-of-order creation.
+ r = "{f0:'f0',f1:'f1',subType:'A1',fb:{f0b:'f0b',f2:'f2',subType:'B2'}}";
+ a = p.parse(r, A.class);
+ assertTrue(a instanceof A1);
+ assertTrue(a.fb instanceof B2);
+ assertEquals("f1", ((A1)a).f1);
+ assertEquals("f2", ((B2)a.fb).f2);
+ }
+
+ @Bean(
+ subTypeProperty="subType",
+ subTypes={
+ @BeanSubType(type=A1.class, id="A1"),
+ @BeanSubType(type=A2.class, id="A2")
+ }
+ )
+ public static abstract class A {
+ public String f0 = "f0";
+ public B fb;
+ }
+
+ public static class A1 extends A {
+ public String f1;
+ }
+
+ public static class A2 extends A {
+ public String f2;
+ }
+
+ @Bean(
+ subTypeProperty="subType",
+ subTypes={
+ @BeanSubType(type=B1.class, id="B1"),
+ @BeanSubType(type=B2.class, id="B2")
+ }
+ )
+ public static abstract class B {
+ public String f0b = "f0b";
+ }
+
+ public static class B1 extends B {
+ public String f1;
+ }
+
+ public static class B2 extends B {
+ public String f2;
+ }
+
+ //====================================================================================================
+ // Test parent class used as transform
+ //====================================================================================================
+ @Test
+ public void testParentClassTransform() throws Exception {
+ JsonSerializer s = new JsonSerializer.Simple().addTransforms(C1.class);
+
+ C1 c1 = new C2();
+ String r = s.serialize(c1);
+ assertEquals("{f0:'f0'}", r);
+
+ List<C1> l = new LinkedList<C1>();
+ l.add(new C2());
+ r = s.serialize(l);
+ assertEquals("[{f0:'f0'}]", r);
+ }
+
+ public static class C1 {
+ public String f0 = "f0";
+ }
+
+ public static class C2 extends C1 {
+ public String f1 = "f1";
+ }
+
+ //====================================================================================================
+ // Test non-static parent class used as transform
+ //====================================================================================================
+ @Test
+ public void testParentClassTransform2() throws Exception {
+ JsonSerializer s = new JsonSerializer.Simple().addTransforms(D1.class);
+
+ D1 d1 = new D2();
+ String r = s.serialize(d1);
+ assertEquals("{f0:'f0'}", r);
+
+ List<D1> l = new LinkedList<D1>();
+ l.add(new D2());
+ r = s.serialize(l);
+ assertEquals("[{f0:'f0'}]", r);
+ }
+
+ public class D1 {
+ public String f0 = "f0";
+ }
+
+ public class D2 extends D1 {
+ public String f1 = "f1";
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/CT_Annotations.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/CT_Annotations.java b/org.apache.juneau/src/test/java/org/apache/juneau/CT_Annotations.java
deleted file mode 100755
index 9131a5a..0000000
--- a/org.apache.juneau/src/test/java/org/apache/juneau/CT_Annotations.java
+++ /dev/null
@@ -1,82 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau;
-
-import static org.apache.juneau.TestUtils.*;
-import static org.junit.Assert.*;
-
-import org.apache.juneau.annotation.*;
-import org.junit.*;
-
-
-@SuppressWarnings({"rawtypes"})
-public class CT_Annotations {
-
- //====================================================================================================
- // Bean with explicitly specified properties.
- //====================================================================================================
- @Test
- public void testBeanWithExplicitProperties() throws Exception {
- BeanContext bc = BeanContext.DEFAULT;
- BeanMap bm = null;
-
- // Basic test
- bm = bc.newBeanMap(Person1.class).load("{age:21,name:'foobar'}");
- assertNotNull(bm);
- assertNotNull(bm.getBean());
- assertEquals(bm.get("age"), 21);
- assertEquals(bm.get("name"), "foobar");
-
- bm.put("age", 65);
- bm.put("name", "futbol");
- assertEquals(bm.get("age"), 65);
- assertEquals(bm.get("name"), "futbol");
- }
-
- /** Class with explicitly specified properties */
- @Bean(properties = { "age", "name" })
- public static class Person1 {
- public int age;
- private String name;
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- }
-
- //====================================================================================================
- // Private/protected/default fields should be ignored.
- //====================================================================================================
- @Test
- public void testForOnlyPublicFields() throws Exception {
- BeanContext bc = BeanContext.DEFAULT;
- BeanMap bm = null;
-
- // Make sure only public fields are detected
- bm = bc.newBeanMap(A.class).load("{publicField:123}");
- assertNotNull("F1", bm);
- assertNotNull("F2", bm.getBean());
- assertObjectEquals("{publicField:123}", bm.getBean());
-
- }
-
- public static class A {
- public int publicField;
- protected int protectedField;
- @SuppressWarnings("unused")
- private int privateField;
- int defaultField;
- }
-}
\ No newline at end of file
[02/44] incubator-juneau git commit: Rename CT_* testcases.
Posted by ja...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/xml/CT_XmlCollapsed.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/xml/CT_XmlCollapsed.java b/org.apache.juneau/src/test/java/org/apache/juneau/xml/CT_XmlCollapsed.java
deleted file mode 100755
index f1387bc..0000000
--- a/org.apache.juneau/src/test/java/org/apache/juneau/xml/CT_XmlCollapsed.java
+++ /dev/null
@@ -1,459 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.xml;
-
-import static org.apache.juneau.TestUtils.*;
-import static org.apache.juneau.xml.annotation.XmlFormat.*;
-import static org.junit.Assert.*;
-
-import java.util.*;
-
-import org.apache.juneau.*;
-import org.apache.juneau.annotation.*;
-import org.apache.juneau.serializer.*;
-import org.apache.juneau.xml.annotation.*;
-import org.junit.*;
-
-@SuppressWarnings({"serial"})
-public class CT_XmlCollapsed {
-
- //====================================================================================================
- // testBasic - @Xml.format=COLLAPSED
- //====================================================================================================
- @Test
- public void testBasic() throws Exception {
- XmlSerializer s = XmlSerializer.DEFAULT_SIMPLE_SQ;
- XmlParser p = XmlParser.DEFAULT;
- A t = new A();
-
- t.f1 = new LinkedList<String>(){{add("f1a");add("f1b");}};
- t.f2 = new String[]{"f2a","f2b"};
- t.f3 = new LinkedList<String>(){{add("f3a");add("f3b");}};
- t.f4 = new String[]{"f4a","f4b"};
-
- String xml = s.serialize(t);
- assertEquals("<object><f1>f1a</f1><f1>f1b</f1><f2>f2a</f2><f2>f2b</f2><xf3>f3a</xf3><xf3>f3b</xf3><xf4>f4a</xf4><xf4>f4b</xf4></object>", xml);
- t = p.parse(xml, A.class);
- assertEquals("f1a", t.f1.get(0));
- assertEquals("f2a", t.f2[0]);
- assertEquals("f3a", t.f3.get(0));
- assertEquals("f4a", t.f4[0]);
-
- validateXml(t, s);
- }
-
- public static class A {
-
- @Xml(format=COLLAPSED)
- public List<String> f1 = new LinkedList<String>();
-
- @Xml(format=COLLAPSED)
- public String[] f2 = new String[0];
-
- @Xml(format=COLLAPSED,childName="xf3")
- public List<String> f3 = new LinkedList<String>();
-
- @Xml(format=COLLAPSED,childName="xf4")
- public String[] f4 = new String[0];
- }
-
- //====================================================================================================
- // testUninitializedFields - @Xml.format=COLLAPSED, uninitialized fields.
- //====================================================================================================
- @Test
- public void testUninitializedFields() throws Exception {
- XmlSerializer s = XmlSerializer.DEFAULT_SIMPLE_SQ;
- XmlParser p = XmlParser.DEFAULT;
- B t = new B();
-
- t.f1 = new LinkedList<String>(){{add("f1a");add("f1b");}};
- t.f2 = new String[]{"f2a","f2b"};
- t.f3 = new LinkedList<String>(){{add("f3a");add("f3b");}};
- t.f4 = new String[]{"f4a","f4b"};
-
- String xml = s.serialize(t);
- assertEquals("<object><f1>f1a</f1><f1>f1b</f1><f2>f2a</f2><f2>f2b</f2><xf3>f3a</xf3><xf3>f3b</xf3><xf4>f4a</xf4><xf4>f4b</xf4></object>", xml);
- t = p.parse(xml, B.class);
- assertEquals("f1a", t.f1.get(0));
- assertEquals("f2a", t.f2[0]);
- assertEquals("f3a", t.f3.get(0));
- assertEquals("f4a", t.f4[0]);
-
- validateXml(t, s);
- }
-
- public static class B {
-
- @Xml(format=COLLAPSED)
- public List<String> f1;
-
- @Xml(format=COLLAPSED)
- public String[] f2;
-
- @Xml(format=COLLAPSED,childName="xf3")
- public List<String> f3;
-
- @Xml(format=COLLAPSED,childName="xf4")
- public String[] f4;
- }
-
- //====================================================================================================
- // testInitializedFields - @Xml.format=COLLAPSED, initialized fields.
- //====================================================================================================
- @Test
- public void testInitializedFields() throws Exception {
- XmlSerializer s = XmlSerializer.DEFAULT_SIMPLE_SQ;
- XmlParser p = XmlParser.DEFAULT;
- C t = new C();
-
- t.f1 = new LinkedList<String>(){{add("f1b");}};
- t.f2 = new String[]{"f2b"};
- t.f3 = new LinkedList<String>(){{add("f3b");}};
- t.f4 = new String[]{"f4b"};
-
- String xml = s.serialize(t);
- assertEquals("<object><f1>f1b</f1><f2>f2b</f2><xf3>f3b</xf3><xf4>f4b</xf4></object>", xml);
-
- // Note that existing fields should be reused and appended to.
- t = p.parse(xml, C.class);
- assertEquals("f1a", t.f1.get(0));
- assertEquals("f1b", t.f1.get(1));
- assertEquals("f2a", t.f2[0]);
- assertEquals("f2b", t.f2[1]);
- assertEquals("f3a", t.f3.get(0));
- assertEquals("f3b", t.f3.get(1));
- assertEquals("f4a", t.f4[0]);
- assertEquals("f4b", t.f4[1]);
-
- validateXml(t, s);
- }
-
- public static class C {
-
- @Xml(format=COLLAPSED)
- public List<String> f1 = new LinkedList<String>(){{add("f1a");}};
-
- @Xml(format=COLLAPSED)
- public String[] f2 = {"f2a"};
-
- @Xml(format=COLLAPSED,childName="xf3")
- public List<String> f3 = new LinkedList<String>(){{add("f3a");}};
-
- @Xml(format=COLLAPSED,childName="xf4")
- public String[] f4 = {"f4a"};
- }
-
- //====================================================================================================
- // testGetters - @Xml.format=COLLAPSED, getters.
- //====================================================================================================
- @Test
- @SuppressWarnings("synthetic-access")
- public void testGetters() throws Exception {
- XmlSerializer s = XmlSerializer.DEFAULT_SIMPLE_SQ;
- XmlParser p = XmlParser.DEFAULT;
- D t = new D();
-
- t.f1 = new LinkedList<String>(){{add("f1a");}};
- t.f2 = new String[]{"f2a"};
- t.f3 = new LinkedList<String>(){{add("f3a");}};
- t.f4 = new String[]{"f4a"};
-
- String xml = s.serialize(t);
- assertEquals("<object><f1>f1a</f1><f2>f2a</f2><xf3>f3a</xf3><xf4>f4a</xf4></object>", xml);
-
- // Note that existing fields should be reused and appended to.
- t = p.parse(xml, D.class);
- assertEquals("f1a", t.f1.get(0));
- assertEquals("f2a", t.f2[0]);
- assertEquals("f3a", t.f3.get(0));
- assertEquals("f4a", t.f4[0]);
-
- validateXml(t, s);
- }
-
- @Bean(properties={"f1","f2","f3","f4"})
- public static class D {
-
- private List<String> f1 = new LinkedList<String>(), f3 = new LinkedList<String>();
- private String[] f2, f4;
-
- @Xml(format=COLLAPSED)
- public List<String> getF1() {
- return f1;
- }
-
- @Xml(format=COLLAPSED)
- public String[] getF2() {
- return f2;
- }
- public void setF2(String[] f2) {
- this.f2 = f2;
- }
-
- @Xml(format=COLLAPSED,childName="xf3")
- public List<String> getF3() {
- return f3;
- }
-
- @Xml(format=COLLAPSED,childName="xf4")
- public String[] getF4() {
- return f4;
- }
- public void setF4(String[] f4) {
- this.f4 = f4;
- }
- }
-
- //====================================================================================================
- // testNullConstructibleCollectionFields - @Xml.format=COLLAPSED, null constructible collection fields.
- //====================================================================================================
- @Test
- @SuppressWarnings("synthetic-access")
- public void testNullConstructibleCollectionFields() throws Exception {
- XmlSerializer s = XmlSerializer.DEFAULT_SIMPLE_SQ;
- XmlParser p = XmlParser.DEFAULT;
- E t = new E();
-
- t.f1 = new LinkedList<String>(){{add("f1a");}};
- t.f2 = new LinkedList<String>(){{add("f2a");}};
-
- String xml = s.serialize(t);
- assertEquals("<object><f1>f1a</f1><xf2>f2a</xf2></object>", xml);
-
- // Note that existing fields should be reused and appended to.
- t = p.parse(xml, E.class);
- assertEquals("f1a", t.f1.get(0));
- assertEquals("f2a", t.f2.get(0));
-
- validateXml(t, s);
- }
-
- @Bean(properties={"f1","f2"})
- public static class E {
-
- private LinkedList<String> f1, f2;
-
- @Xml(format=COLLAPSED)
- public LinkedList<String> getF1() {
- return f1;
- }
- public void setF1(LinkedList<String> f1) {
- this.f1 = f1;
- }
-
- @Xml(format=COLLAPSED,childName="xf2")
- public LinkedList<String> getF2() {
- return f2;
- }
- public void setF2(LinkedList<String> f2) {
- this.f2 = f2;
- }
- }
-
-
- //====================================================================================================
- // testElementNameOnElementClass - @Xml.format=COLLAPSED, element name defined on element class.
- //====================================================================================================
- @Test
- public void testElementNameOnElementClass() throws Exception {
- XmlSerializer s = XmlSerializer.DEFAULT_SIMPLE_SQ;
- XmlParser p = XmlParser.DEFAULT;
- Object t1 = FA.newInstance(), t2;
- String r;
-
- r = s.serialize(t1);
- assertEquals("<object><xf1>x1</xf1><xf1>x2</xf1></object>", r);
- t2 = p.parse(r, FA.class);
- assertEqualObjects(t1, t2);
- validateXml(t1, s);
-
- t1 = FB.newInstance();
- r = s.serialize(t1);
- assertEquals("<object><xf1>x1</xf1><xf1>x2</xf1></object>", r);
- t2 = p.parse(r, FB.class);
- assertEqualObjects(t1, t2);
- validateXml(t1, s);
-
- t1 = FC.newInstance();
- try {
- r = s.serialize(t1);
- fail("Exception expected.");
- } catch (SerializeException e) {
- assertEquals("org.apache.juneau.xml.CT_XmlCollapsed$FC: Multiple properties found with the name 'xf1'.", e.getLocalizedMessage());
- }
- }
-
- public static class FA {
-
- @Xml(format=COLLAPSED)
- public List<F1> f1;
-
- public static FA newInstance() {
- FA t = new FA();
- t.f1 = new LinkedList<F1>();
- t.f1.add(F1.newInstance("x1"));
- t.f1.add(F1.newInstance("x2"));
- return t;
- }
- }
-
- public static class FB {
- @Xml(format=COLLAPSED)
- public F1[] f1;
-
- public static FB newInstance() {
- FB t = new FB();
- t.f1 = new F1[]{
- F1.newInstance("x1"),
- F1.newInstance("x2")
- };
- return t;
- }
- }
-
- // Should cause name collision.
- public static class FC {
-
- @Xml(format=COLLAPSED)
- public List<F1> f1;
-
- @Xml(format=COLLAPSED)
- public F1[] f2;
-
- public static FC newInstance() {
- FC t = new FC();
- return t;
- }
- }
-
- @Xml(name="xf1")
- public static class F1 {
-
- @Xml(format=CONTENT)
- public String text;
-
- public static F1 newInstance(String text) {
- F1 t = new F1();
- t.text = text;
- return t;
- }
- }
-
-
- //====================================================================================================
- // testElementNameOnElementClassOverridden - @Xml.format=COLLAPSED, element name defined on element class,
- // but overridden by @Xml.childName on property.
- //====================================================================================================
- @Test
- public void testElementNameOnElementClassOverridden() throws Exception {
- XmlSerializer s = XmlSerializer.DEFAULT_SIMPLE_SQ;
- XmlParser p = XmlParser.DEFAULT;
- G t = G.newInstance(), t2;
-
- String xml = s.serialize(t);
- assertEquals("<object><yf1>x1</yf1><yf1>x2</yf1></object>", xml);
-
- // Note that existing fields should be reused and appended to.
- t2 = p.parse(xml, G.class);
- assertEqualObjects(t, t2);
-
- validateXml(t, s);
- }
-
- public static class G {
-
- @Xml(format=COLLAPSED, childName="yf1")
- public List<F1> f1;
-
- public static G newInstance() {
- G t = new G();
- t.f1 = new LinkedList<F1>();
- t.f1.add(F1.newInstance("x1"));
- t.f1.add(F1.newInstance("x2"));
- return t;
- }
- }
-
-
- //====================================================================================================
- // testElementNameOnCollectionClass - @Xml.format=COLLAPSED, element name defined on bean class.
- //====================================================================================================
- @Test
- public void testElementNameOnCollectionClass() throws Exception {
- XmlSerializer s = XmlSerializer.DEFAULT_SIMPLE_SQ;
- XmlParser p = XmlParser.DEFAULT;
- H t = H.newInstance(), t2;
-
- String xml = s.serialize(t);
- assertEquals("<object><xf1>x1</xf1><xf1>x2</xf1></object>", xml);
-
- // Note that existing fields should be reused and appended to.
- t2 = p.parse(xml, H.class);
- assertEqualObjects(t, t2);
-
- validateXml(t, s);
- }
-
- public static class H {
-
- @Xml(format=COLLAPSED)
- public H1 f1;
-
- public static H newInstance() {
- H t = new H();
- t.f1 = new H1();
- t.f1.add("x1");
- t.f1.add("x2");
- return t;
- }
- }
-
- @Xml(childName="xf1")
- public static class H1 extends LinkedList<String> {
- }
-
-
- //====================================================================================================
- // testElementNameOnCollectionClassOverridden - @Xml.format=COLLAPSED, element name defined on element class,
- // but overridden by @Xml.childName on property.
- //====================================================================================================
- @Test
- public void testElementNameOnCollectionClassOverridden() throws Exception {
- XmlSerializer s = XmlSerializer.DEFAULT_SIMPLE_SQ;
- XmlParser p = XmlParser.DEFAULT;
- G t = G.newInstance(), t2;
-
- String xml = s.serialize(t);
- assertEquals("<object><yf1>x1</yf1><yf1>x2</yf1></object>", xml);
-
- // Note that existing fields should be reused and appended to.
- t2 = p.parse(xml, G.class);
- assertEqualObjects(t, t2);
-
- validateXml(t, s);
- }
-
- public static class I {
-
- @Xml(format=COLLAPSED, childName="yf1")
- public H1 f1;
-
- public static I newInstance() {
- I t = new I();
- t.f1 = new H1();
- t.f1.add("x1");
- t.f1.add("x2");
- return t;
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/xml/CT_XmlContent.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/xml/CT_XmlContent.java b/org.apache.juneau/src/test/java/org/apache/juneau/xml/CT_XmlContent.java
deleted file mode 100755
index d111b1f..0000000
--- a/org.apache.juneau/src/test/java/org/apache/juneau/xml/CT_XmlContent.java
+++ /dev/null
@@ -1,301 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.xml;
-
-import static org.apache.juneau.TestUtils.*;
-import static org.apache.juneau.serializer.SerializerContext.*;
-import static org.apache.juneau.xml.XmlSerializerContext.*;
-import static org.apache.juneau.xml.XmlUtils.*;
-import static org.apache.juneau.xml.annotation.XmlFormat.*;
-import static org.junit.Assert.*;
-
-import java.io.*;
-
-import javax.xml.stream.*;
-
-import org.apache.juneau.*;
-import org.apache.juneau.xml.annotation.*;
-import org.junit.*;
-
-public class CT_XmlContent {
-
- //--------------------------------------------------------------------------------
- // Test beans with @Xml(format=CONTENT)
- //--------------------------------------------------------------------------------
- @Test
- public void testContentFormat() throws Exception {
- A t = A.newInstance(), t2;
- XmlSerializer s1 = XmlSerializer.DEFAULT_SIMPLE_SQ,
- s2 = new XmlSerializer().setProperty(SERIALIZER_quoteChar, '\'').setProperty(SERIALIZER_useIndentation, true).setProperty(XML_enableNamespaces, false);
- XmlParser p = XmlParser.DEFAULT;
- XmlSerializerSession session;
- String r;
- StringWriter sw;
-
- //----------------------------------------------------------------
- // Null
- //----------------------------------------------------------------
- t.f2 = null;
-
- sw = new StringWriter();
- session = s1.createSession(sw, new ObjectMap("{"+SERIALIZER_trimNullProperties+":false}"), null);
- s1.serialize(session, t);
- r = sw.toString();
- assertEquals("<A f1='f1'>_x0000_</A>", r);
- t2 = p.parse(r, A.class);
- assertEqualObjects(t, t2);
-
- sw = new StringWriter();
- session = s2.createSession(sw, new ObjectMap("{"+SERIALIZER_trimNullProperties+":false}"), null);
- s2.serialize(session, t);
- r = sw.toString();
- assertEquals("<A f1='f1'>\n\t_x0000_\n</A>\n", r);
- t2 = p.parse(r, A.class);
- assertEqualObjects(t, t2);
-
- //----------------------------------------------------------------
- // Normal text
- //----------------------------------------------------------------
- t.f2 = "foobar";
-
- r = s1.serialize(t);
- assertEquals("<A f1='f1'>foobar</A>", r);
- t2 = p.parse(r, A.class);
- assertEqualObjects(t, t2);
-
- r = s2.serialize(t);
- assertEquals("<A f1='f1'>\n\tfoobar\n</A>\n", r);
- t2 = p.parse(r, A.class);
- assertEqualObjects(t, t2);
-
- //----------------------------------------------------------------
- // Special characters
- //----------------------------------------------------------------
- t.f2 = "~!@#$%^&*()_+`-={}|[]\\:\";'<>?,.\n\r\t\b";
-
- r = s1.serialize(t);
- assertEquals("<A f1='f1'>~!@#$%^&*()_+`-={}|[]\\:\";'<>?,.

	_x0008_</A>", r);
- t2 = p.parse(r, A.class);
- assertEqualObjects(t, t2);
-
- r = s2.serialize(t);
- assertEquals("<A f1='f1'>\n\t~!@#$%^&*()_+`-={}|[]\\:\";'<>?,.

	_x0008_\n</A>\n", r);
- t2 = p.parse(r, A.class);
- assertEqualObjects(t, t2);
-
- //----------------------------------------------------------------
- // Leading spaces
- //----------------------------------------------------------------
- t.f2 = " foobar";
-
- r = s1.serialize(t);
- assertEquals("<A f1='f1'>_x0020_ foobar</A>", r);
- t2 = p.parse(r, A.class);
- assertEqualObjects(t, t2);
-
- r = s2.serialize(t);
- assertEquals("<A f1='f1'>\n\t_x0020_ foobar\n</A>\n", r);
- t2 = p.parse(r, A.class);
- assertEqualObjects(t, t2);
-
- //----------------------------------------------------------------
- // Trailing spaces
- //----------------------------------------------------------------
- t.f2 = "foobar ";
-
- r = s1.serialize(t);
- assertEquals("<A f1='f1'>foobar _x0020_</A>", r);
- t2 = p.parse(r, A.class);
- assertEqualObjects(t, t2);
-
- r = s2.serialize(t);
- assertEquals("<A f1='f1'>\n\tfoobar _x0020_\n</A>\n", r);
- t2 = p.parse(r, A.class);
- assertEqualObjects(t, t2);
- }
-
- @Xml(name="A")
- public static class A {
- @Xml(format=ATTR) public String f1;
- @Xml(format=CONTENT) public String f2;
-
- public static A newInstance() {
- A t = new A();
- t.f1 = "f1";
- t.f2 = null;
- return t;
- }
- }
-
- //--------------------------------------------------------------------------------
- // Test beans with @Xml(format=XMLCONTENT)
- //--------------------------------------------------------------------------------
- @Test
- public void testXmlContentFormat() throws Exception {
- B t = B.newInstance(), t2;
- XmlSerializer s1 = XmlSerializer.DEFAULT_SIMPLE_SQ,
- s2 = new XmlSerializer().setProperty(SERIALIZER_quoteChar, '\'').setProperty(SERIALIZER_useIndentation, true).setProperty(XML_enableNamespaces, false);
- XmlParser p = XmlParser.DEFAULT;
- XmlSerializerSession session;
- String r;
- StringWriter sw;
-
- //----------------------------------------------------------------
- // Null
- //----------------------------------------------------------------
- t.f2 = null;
-
- sw = new StringWriter();
- session = s1.createSession(sw, new ObjectMap("{"+SERIALIZER_trimNullProperties+":false}"), null);
- s1.serialize(session, t);
- r = sw.toString();
- assertEquals("<A f1='f1'>_x0000_</A>", r);
- t2 = p.parse(r, B.class);
- assertEqualObjects(t, t2);
-
- sw = new StringWriter();
- session = s2.createSession(sw, new ObjectMap("{"+SERIALIZER_trimNullProperties+":false}"), null);
- s2.serialize(session, t);
- r = sw.toString();
- assertEquals("<A f1='f1'>\n\t_x0000_\n</A>\n", r);
- t2 = p.parse(r, B.class);
- assertEqualObjects(t, t2);
-
- //----------------------------------------------------------------
- // Normal text
- //----------------------------------------------------------------
- t.f2 = "foobar";
-
- r = s1.serialize(t);
- assertEquals("<A f1='f1'>foobar</A>", r);
- t2 = p.parse(r, B.class);
- assertEqualObjects(t, t2);
-
- r = s2.serialize(t);
- assertEquals("<A f1='f1'>\n\tfoobar\n</A>\n", r);
- t2 = p.parse(r, B.class);
- assertEqualObjects(t, t2);
-
- //----------------------------------------------------------------
- // Normal XML
- //----------------------------------------------------------------
- t.f2 = "<xxx>foobar<yyy>baz</yyy>foobar</xxx>";
-
- r = s1.serialize(t);
- assertEquals("<A f1='f1'><xxx>foobar<yyy>baz</yyy>foobar</xxx></A>", r);
- t2 = p.parse(r, B.class);
- assertEqualObjects(t, t2);
-
- r = s2.serialize(t);
- assertEquals("<A f1='f1'>\n\t<xxx>foobar<yyy>baz</yyy>foobar</xxx>\n</A>\n", r);
- t2 = p.parse(r, B.class);
- assertEqualObjects(t, t2);
-
- //----------------------------------------------------------------
- // Normal XML with leading and trailing space
- //----------------------------------------------------------------
- t.f2 = " <xxx>foobar<yyy>baz</yyy>foobar</xxx> ";
-
- r = s1.serialize(t);
- assertEquals("<A f1='f1'>_x0020_ <xxx>foobar<yyy>baz</yyy>foobar</xxx> _x0020_</A>", r);
- t2 = p.parse(r, B.class);
- assertEqualObjects(t, t2);
-
- r = s2.serialize(t);
- assertEquals("<A f1='f1'>\n\t_x0020_ <xxx>foobar<yyy>baz</yyy>foobar</xxx> _x0020_\n</A>\n", r);
- t2 = p.parse(r, B.class);
- assertEqualObjects(t, t2);
-
- //----------------------------------------------------------------
- // XML with attributes
- //----------------------------------------------------------------
- t.f2 = "<xxx x=\"x\">foobar</xxx>";
-
- r = s1.serialize(t);
- assertEquals("<A f1='f1'><xxx x=\"x\">foobar</xxx></A>", r);
- t2 = p.parse(r, B.class);
- assertEqualObjects(t, t2);
-
- r = s2.serialize(t);
- assertEquals("<A f1='f1'>\n\t<xxx x=\"x\">foobar</xxx>\n</A>\n", r);
- t2 = p.parse(r, B.class);
- assertEqualObjects(t, t2);
-
- //----------------------------------------------------------------
- // XML with embedded entities
- //----------------------------------------------------------------
- t.f2 = "<xxx x=\"x\">foo<>bar</xxx>";
-
- r = s1.serialize(t);
- assertEquals("<A f1='f1'><xxx x=\"x\">foo<>bar</xxx></A>", r);
- t2 = p.parse(r, B.class);
- assertEqualObjects(t, t2);
-
- r = s2.serialize(t);
- assertEquals("<A f1='f1'>\n\t<xxx x=\"x\">foo<>bar</xxx>\n</A>\n", r);
- t2 = p.parse(r, B.class);
- assertEqualObjects(t, t2);
- }
-
- @Xml(name="A")
- public static class B {
- @Xml(format=ATTR) public String f1;
- @Xml(format=CONTENT, contentHandler=BContentHandler.class) public String f2;
-
- public static B newInstance() {
- B t = new B();
- t.f1 = "f1";
- t.f2 = null;
- return t;
- }
- }
-
- public static class BContentHandler implements XmlContentHandler<B> {
-
- @Override /* XmlContentHandler */
- public void parse(XMLStreamReader r, B b) throws Exception {
- b.f2 = decode(readXmlContents(r).trim());
- }
-
- @Override /* XmlContentHandler */
- public void serialize(XmlWriter w, B b) throws Exception {
- w.encodeTextInvalidChars(b.f2);
- }
-
- }
-
- //--------------------------------------------------------------------------------
- // Test beans with too many @Xml.format=CONTENT/XMLCONTENT annotations.
- //--------------------------------------------------------------------------------
- @Test
- public void testBadContent() throws Exception {
- XmlSerializer s = XmlSerializer.DEFAULT_SIMPLE_SQ;
- try {
- s.serialize(new C1());
- fail("Exception expected");
- } catch (Exception e) {
- assertTrue(e.getMessage().contains("Multiple instances of CONTENT properties defined on class"));
- }
- // Run twice to make sure we throw exceptions after the first call.
- try {
- s.serialize(new C1());
- fail("Exception expected");
- } catch (Exception e) {
- assertTrue(e.getMessage().contains("Multiple instances of CONTENT properties defined on class"));
- }
- }
- public static class C1 {
- @Xml(format=CONTENT) public String f1;
- @Xml(format=CONTENT) public String f2;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/xml/CT_XmlParser.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/xml/CT_XmlParser.java b/org.apache.juneau/src/test/java/org/apache/juneau/xml/CT_XmlParser.java
deleted file mode 100755
index 450ea4d..0000000
--- a/org.apache.juneau/src/test/java/org/apache/juneau/xml/CT_XmlParser.java
+++ /dev/null
@@ -1,95 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.xml;
-
-import static org.apache.juneau.xml.XmlParserContext.*;
-import static org.junit.Assert.*;
-
-import org.apache.juneau.*;
-import org.apache.juneau.parser.*;
-import org.junit.*;
-
-public class CT_XmlParser {
-
- @Test
- public void testGenericAttributes() throws Exception {
- String xml = "<A b='1'><c>2</c></A>";
- ObjectMap m = XmlParser.DEFAULT.parse(xml, ObjectMap.class);
- assertEquals("{b:'1',c:'2'}", m.toString());
- }
-
- @Test
- public void testGenericWithChildElements() throws Exception {
- String xml;
- ObjectMap m;
-
- xml = "<A><B><C>c</C></B></A>";
- m = XmlParser.DEFAULT.parse(xml, ObjectMap.class);
- assertEquals("{B:{C:'c'}}", m.toString());
-
- xml = "<A><B><C1>c1</C1><C2>c2</C2></B></A>";
- m = XmlParser.DEFAULT.parse(xml, ObjectMap.class);
- assertEquals("{B:{C1:'c1',C2:'c2'}}", m.toString());
-
- xml = "<A><B><C><D1>d1</D1><D2>d2</D2></C></B></A>";
- m = XmlParser.DEFAULT.parse(xml, ObjectMap.class);
- assertEquals("{B:{C:{D1:'d1',D2:'d2'}}}", m.toString());
-
- xml = "<A><B><C><D1 d1a='d1av'><E1>e1</E1></D1><D2 d2a='d2av'><E2>e2</E2></D2></C></B></A>";
- m = XmlParser.DEFAULT.parse(xml, ObjectMap.class);
- assertEquals("{B:{C:{D1:{d1a:'d1av',E1:'e1'},D2:{d2a:'d2av',E2:'e2'}}}}", m.toString());
-
- xml = "<A><B b='b'><C>c</C></B></A>";
- m = XmlParser.DEFAULT.parse(xml, ObjectMap.class);
- assertEquals("{B:{b:'b',C:'c'}}", m.toString());
-
- xml = "<A><B b='b'>c</B></A>";
- m = XmlParser.DEFAULT.parse(xml, ObjectMap.class);
- assertEquals("{B:{b:'b',contents:'c'}}", m.toString());
-
- xml = "<A><B>b1</B><B>b2</B></A>";
- m = XmlParser.DEFAULT.parse(xml, ObjectMap.class);
- assertEquals("{B:['b1','b2']}", m.toString());
-
- xml = "<A><B><C>c1</C><C>c2</C></B></A>";
- m = XmlParser.DEFAULT.parse(xml, ObjectMap.class);
- assertEquals("{B:{C:['c1','c2']}}", m.toString());
-
- xml = "<A><B v='v1'>b1</B><B v='v2'>b2</B></A>";
- m = XmlParser.DEFAULT.parse(xml, ObjectMap.class);
- assertEquals("{B:[{v:'v1',contents:'b1'},{v:'v2',contents:'b2'}]}", m.toString());
-
- xml = "<A><B><C v='v1'>c1</C><C v='v2'>c2</C></B></A>";
- m = XmlParser.DEFAULT.parse(xml, ObjectMap.class);
- assertEquals("{B:{C:[{v:'v1',contents:'c1'},{v:'v2',contents:'c2'}]}}", m.toString());
-
- xml = "<A><B c='c1'><c>c2</c></B></A>";
- m = XmlParser.DEFAULT.parse(xml, ObjectMap.class);
- assertEquals("{B:{c:['c1','c2']}}", m.toString());
- }
-
- @Test
- public void testPreserveRootElement() throws Exception {
- String xml;
- ObjectMap m;
- ReaderParser p = new XmlParser().setProperty(XML_preserveRootElement, true);
-
- xml = "<A><B><C>c</C></B></A>";
- m = p.parse(xml, ObjectMap.class);
- assertEquals("{A:{B:{C:'c'}}}", m.toString());
-
- xml = "<A></A>";
- m = p.parse(xml, ObjectMap.class);
- assertEquals("{A:{}}", m.toString());
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/xml/CommonParserTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/xml/CommonParserTest.java b/org.apache.juneau/src/test/java/org/apache/juneau/xml/CommonParserTest.java
new file mode 100755
index 0000000..9432288
--- /dev/null
+++ b/org.apache.juneau/src/test/java/org/apache/juneau/xml/CommonParserTest.java
@@ -0,0 +1,179 @@
+/***************************************************************************************************************************
+ * 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.juneau.xml;
+
+import static org.apache.juneau.BeanContext.*;
+import static org.junit.Assert.*;
+
+import java.util.*;
+
+import org.apache.juneau.*;
+import org.apache.juneau.parser.*;
+import org.junit.*;
+
+@SuppressWarnings({"rawtypes","serial"})
+public class CommonParserTest {
+
+ //====================================================================================================
+ // testFromSerializer
+ //====================================================================================================
+ @Test
+ public void testFromSerializer() throws Exception {
+ ReaderParser p = XmlParser.DEFAULT;
+
+ Map m = null;
+ m = (Map)p.parse("<object><a type='number'>1</a></object>", Object.class);
+ assertEquals(1, m.get("a"));
+ m = (Map)p.parse("<object><a type='number'>1</a><b type='string'>foo bar</b></object>", Object.class);
+ assertEquals(1, m.get("a"));
+ assertEquals("foo bar", m.get("b"));
+ m = (Map)p.parse("<object><a type='number'>1</a><b type='string'>foo bar</b><c type='boolean'>false</c></object>", Object.class);
+ assertEquals(1, m.get("a"));
+ assertEquals(false, m.get("c"));
+ m = (Map)p.parse(" <object> <a type='number'> 1 </a> <b type='string'> foo </b> <c type='boolean'> false </c> </object> ", Object.class);
+ assertEquals(1, m.get("a"));
+ assertEquals("foo", m.get("b"));
+ assertEquals(false, m.get("c"));
+
+ m = (Map)p.parse("<object><x type='string'>org.apache.juneau.test.Person</x><addresses type='array'><object><x type='string'>org.apache.juneau.test.Address</x><city type='string'>city A</city><state type='string'>state A</state><street type='string'>street A</street><zip type='number'>12345</zip></object></addresses></object>", Object.class);
+ assertEquals("org.apache.juneau.test.Person", m.get("x"));
+ List l = (List)m.get("addresses");
+ assertNotNull(l);
+ m = (Map)l.get(0);
+ assertNotNull(m);
+ assertEquals("org.apache.juneau.test.Address", m.get("x"));
+ assertEquals("city A", m.get("city"));
+ assertEquals("state A", m.get("state"));
+ assertEquals("street A", m.get("street"));
+ assertEquals(12345, m.get("zip"));
+
+ ObjectList jl = (ObjectList)p.parse("<array><object><attribute type='string'>value</attribute></object><object><attribute type='string'>value</attribute></object></array>", Object.class);
+ assertEquals("value", jl.getObjectMap(0).getString("attribute"));
+ assertEquals("value", jl.getObjectMap(1).getString("attribute"));
+
+ try {
+ jl = (ObjectList)p.parse("<array><object><attribute type='string'>value</attribute></object><object><attribute type='string'>value</attribute></object></array>", Object.class);
+ assertEquals("value", jl.getObjectMap(0).getString("attribute"));
+ assertEquals("value", jl.getObjectMap(1).getString("attribute"));
+ } catch (Exception e) {
+ fail(e.getLocalizedMessage());
+ }
+
+ A1 t1 = new A1();
+ A2 t2 = new A2();
+ t2.add(new A3("name0","value0"));
+ t2.add(new A3("name1","value1"));
+ t1.list = t2;
+ String r = XmlSerializer.DEFAULT.serialize(t1);
+ t1 = p.parse(r, A1.class);
+ assertEquals("value1", t1.list.get(1).value);
+
+ r = XmlSerializer.DEFAULT.serialize(t1);
+ t1 = p.parse(r, A1.class);
+ assertEquals("value1", t1.list.get(1).value);
+ }
+
+ public static class A1 {
+ public A2 list;
+ }
+
+ public static class A2 extends LinkedList<A3> {
+ }
+
+ public static class A3 {
+ public String name, value;
+ public A3(){}
+ public A3(String name, String value) {
+ this.name = name;
+ this.value = value;
+ }
+ }
+
+ //====================================================================================================
+ // Correct handling of unknown properties.
+ //====================================================================================================
+ @Test
+ public void testCorrectHandlingOfUnknownProperties() throws Exception {
+ ReaderParser p = new XmlParser().setProperty(BEAN_ignoreUnknownBeanProperties, true);
+ B t;
+
+ String in = "<object><a>1</a><unknown>foo</unknown><b>2</b></object>";
+ t = p.parse(in, B.class);
+ assertEquals(t.a, 1);
+ assertEquals(t.b, 2);
+
+ in = "<object><a>1</a><unknown><object><a type='string'>foo</a></object></unknown><b>2</b></object>";
+ t = p.parse(in, B.class);
+ assertEquals(t.a, 1);
+ assertEquals(t.b, 2);
+
+
+ try {
+ p = new XmlParser();
+ p.parse(in, B.class);
+ fail("Exception expected");
+ } catch (ParseException e) {}
+ }
+
+ public static class B {
+ public int a, b;
+ }
+
+ //====================================================================================================
+ // Writing to Collection properties with no setters.
+ //====================================================================================================
+ @Test
+ public void testCollectionPropertiesWithNoSetters() throws Exception {
+
+ ReaderParser p = XmlParser.DEFAULT;
+
+ String in = "<object><ints type='array'><number>1</number><number>2</number><number>3</number></ints><beans type='array'><object><a type='number'>1</a><b type='number'>2</b></object></beans></object>";
+ C t = p.parse(in, C.class);
+ assertEquals(t.getInts().size(), 3);
+ assertEquals(t.getBeans().get(0).b, 2);
+ }
+
+ public static class C {
+ private Collection<Integer> ints = new LinkedList<Integer>();
+ private List<B> beans = new LinkedList<B>();
+ public Collection<Integer> getInts() {
+ return ints;
+ }
+ public List<B> getBeans() {
+ return beans;
+ }
+ }
+
+ //====================================================================================================
+ // Parser listeners.
+ //====================================================================================================
+ @Test
+ public void testParserListeners() throws Exception {
+ final List<String> events = new LinkedList<String>();
+ XmlParser p = new XmlParser().setProperty(BEAN_ignoreUnknownBeanProperties, true);
+ p.addListener(
+ new ParserListener() {
+ @Override /* ParserListener */
+ public <T> void onUnknownProperty(String propertyName, Class<T> beanClass, T bean, int line, int col) {
+ events.add(propertyName + "," + line + "," + col);
+ }
+ }
+ );
+
+ String in = "<object><a type='number'>1</a><unknownProperty type='string'>foo</unknownProperty><b type='number'>2</b></object>";
+ p.parse(in, B.class);
+ assertEquals(1, events.size());
+ // XML parser may or may not support line numbers.
+ assertTrue(events.get(0).startsWith("unknownProperty,"));
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/xml/CommonTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/xml/CommonTest.java b/org.apache.juneau/src/test/java/org/apache/juneau/xml/CommonTest.java
new file mode 100755
index 0000000..886f615
--- /dev/null
+++ b/org.apache.juneau/src/test/java/org/apache/juneau/xml/CommonTest.java
@@ -0,0 +1,453 @@
+/***************************************************************************************************************************
+ * 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.juneau.xml;
+
+import static org.apache.juneau.TestUtils.*;
+import static org.apache.juneau.serializer.SerializerContext.*;
+import static org.apache.juneau.xml.XmlSerializerContext.*;
+import static org.apache.juneau.xml.annotation.XmlFormat.*;
+import static org.junit.Assert.*;
+
+import java.net.*;
+import java.net.URI;
+import java.util.*;
+
+import org.apache.juneau.*;
+import org.apache.juneau.annotation.*;
+import org.apache.juneau.serializer.*;
+import org.apache.juneau.testbeans.*;
+import org.apache.juneau.xml.annotation.*;
+import org.junit.*;
+
+@SuppressWarnings({"serial"})
+public class CommonTest {
+
+ //====================================================================================================
+ // Trim nulls from beans
+ //====================================================================================================
+ @Test
+ public void testTrimNullsFromBeans() throws Exception {
+ XmlSerializer s = new XmlSerializer.SimpleSq();
+ XmlParser p = new XmlParser();
+ A t1 = A.create(), t2;
+
+ s.setProperty(SERIALIZER_trimNullProperties, false);
+ String r = s.serialize(t1);
+ assertEquals("<object><s1 nil='true'/><s2>s2</s2></object>", r);
+ t2 = p.parse(r, A.class);
+ assertEqualObjects(t1, t2);
+
+ s.setProperty(SERIALIZER_trimNullProperties, true);
+ r = s.serialize(t1);
+ assertEquals("<object><s2>s2</s2></object>", r);
+ t2 = p.parse(r, A.class);
+ assertEqualObjects(t1, t2);
+ }
+
+ public static class A {
+ public String s1, s2;
+
+ public static A create() {
+ A t = new A();
+ t.s2 = "s2";
+ return t;
+ }
+ }
+
+ //====================================================================================================
+ // Trim empty maps
+ //====================================================================================================
+ @Test
+ public void testTrimEmptyMaps() throws Exception {
+ XmlSerializer s = new XmlSerializer.SimpleSq();
+ XmlParser p = XmlParser.DEFAULT;
+ B t1 = B.create(), t2;
+ String r;
+
+ s.setProperty(SERIALIZER_trimEmptyMaps, false);
+ r = s.serialize(t1);
+ assertEquals("<object><f1/><f2><f2a nil='true'/><f2b><s2>s2</s2></f2b></f2></object>", r);
+ t2 = p.parse(r, B.class);
+ assertEqualObjects(t1, t2);
+
+ s.setProperty(SERIALIZER_trimEmptyMaps, true);
+ r = s.serialize(t1);
+ assertEquals("<object><f2><f2a nil='true'/><f2b><s2>s2</s2></f2b></f2></object>", r);
+ t2 = p.parse(r, B.class);
+ assertNull(t2.f1);
+ }
+
+ public static class B {
+ public TreeMap<String,A> f1, f2;
+
+ public static B create() {
+ B t = new B();
+ t.f1 = new TreeMap<String,A>();
+ t.f2 = new TreeMap<String,A>(){{put("f2a",null);put("f2b",A.create());}};
+ return t;
+ }
+ }
+
+ //====================================================================================================
+ // Trim empty lists
+ //====================================================================================================
+ @Test
+ public void testTrimEmptyLists() throws Exception {
+ XmlSerializer s = new XmlSerializer.SimpleSq();
+ XmlParser p = XmlParser.DEFAULT;
+ C t1 = C.create(), t2;
+ String r;
+
+ s.setProperty(SERIALIZER_trimEmptyLists, false);
+ r = s.serialize(t1);
+ assertEquals("<object><f1></f1><f2><null/><object><s2>s2</s2></object></f2></object>", r);
+ t2 = p.parse(r, C.class);
+ assertEqualObjects(t1, t2);
+
+ s.setProperty(SERIALIZER_trimEmptyLists, true);
+ r = s.serialize(t1);
+ assertEquals("<object><f2><null/><object><s2>s2</s2></object></f2></object>", r);
+ t2 = p.parse(r, C.class);
+ assertNull(t2.f1);
+ }
+
+ public static class C {
+ public List<A> f1, f2;
+
+ public static C create() {
+ C t = new C();
+ t.f1 = new LinkedList<A>();
+ t.f2 = new LinkedList<A>(){{add(null);add(A.create());}};
+ return t;
+ }
+ }
+
+ //====================================================================================================
+ // Trim empty arrays
+ //====================================================================================================
+ @Test
+ public void testTrimEmptyArrays() throws Exception {
+ XmlSerializer s = new XmlSerializer.SimpleSq();
+ XmlParser p = XmlParser.DEFAULT;
+ D t1 = D.create(), t2;
+ String r;
+
+ s.setProperty(SERIALIZER_trimEmptyLists, false);
+ r = s.serialize(t1);
+ assertEquals("<object><f1></f1><f2><null/><object><s2>s2</s2></object></f2></object>", r);
+ t2 = p.parse(r, D.class);
+ assertEqualObjects(t1, t2);
+
+ s.setProperty(SERIALIZER_trimEmptyLists, true);
+ r = s.serialize(t1);
+ assertEquals("<object><f2><null/><object><s2>s2</s2></object></f2></object>", r);
+ t2 = p.parse(r, D.class);
+ assertNull(t2.f1);
+ }
+
+ public static class D {
+ public A[] f1, f2;
+
+ public static D create() {
+ D t = new D();
+ t.f1 = new A[]{};
+ t.f2 = new A[]{null, A.create()};
+ return t;
+ }
+ }
+
+ //====================================================================================================
+ // @BeanProperty.properties annotation.
+ //====================================================================================================
+ @Test
+ public void testBeanPropertyProperties() throws Exception {
+ XmlSerializer s = XmlSerializer.DEFAULT_SIMPLE_SQ;
+ E1 t = new E1();
+ String r = s.serialize(t);
+ assertEquals("<object><x1 f2='2'><f1>1</f1></x1><x2><f1>1</f1></x2><x3><object f2='2'><f1>1</f1></object></x3><x4><object f2='2'><f1>1</f1></object></x4><x5><object><f1>1</f1></object></x5><x6><object><f1>1</f1></object></x6></object>", r);
+ TestUtils.validateXml(t);
+ }
+
+ public static class E1 {
+ @BeanProperty(properties={"f1","f2"}) public E2 x1 = new E2();
+ @BeanProperty(properties={"f1","f2"}) public Map<String,Integer> x2 = new LinkedHashMap<String,Integer>() {{
+ put("f1",1); put("f3",3);
+ }};
+ @BeanProperty(properties={"f1","f2"}) public E2[] x3 = {new E2()};
+ @BeanProperty(properties={"f1","f2"}) public List<E2> x4 = new LinkedList<E2>() {{
+ add(new E2());
+ }};
+ @BeanProperty(properties={"f1"}) public ObjectMap[] x5 = {new ObjectMap().append("f1",1).append("f3",3)};
+ @BeanProperty(properties={"f1"}) public List<ObjectMap> x6 = new LinkedList<ObjectMap>() {{
+ add(new ObjectMap().append("f1",1).append("f3",3));
+ }};
+ }
+
+ public static class E2 {
+ public int f1 = 1;
+ @Xml(format=ATTR) public int f2 = 2;
+ public int f3 = 3;
+ @Xml(format=ATTR) public int f4 = 4;
+ }
+
+ //====================================================================================================
+ // @BeanProperty.properties annotation on list of beans.
+ //====================================================================================================
+ @Test
+ public void testBeanPropertyPropertiesOnListOfBeans() throws Exception {
+ XmlSerializer s = XmlSerializer.DEFAULT_SIMPLE_SQ;
+ List<Test7b> l = new LinkedList<Test7b>();
+ Test7b t = new Test7b();
+ t.x1.add(new Test7b());
+ l.add(t);
+ String xml = s.serialize(l);
+ assertEquals("<array><object><x1><object><x2>2</x2></object></x1><x2>2</x2></object></array>", xml);
+ }
+
+ public static class Test7b {
+ @BeanProperty(properties={"x2"}) public List<Test7b> x1 = new LinkedList<Test7b>();
+ public int x2 = 2;
+ }
+
+ //====================================================================================================
+ // Test that URLs and URIs are serialized and parsed correctly.
+ //====================================================================================================
+ @Test
+ public void testURIAttr() throws Exception {
+ XmlSerializer s = XmlSerializer.DEFAULT_SIMPLE_SQ;
+ XmlParser p = XmlParser.DEFAULT;
+
+ G t = new G();
+ t.uri = new URI("http://uri");
+ t.f1 = new URI("http://f1");
+ t.f2 = new URL("http://f2");
+
+ String xml = s.serialize(t);
+ t = p.parse(xml, G.class);
+ assertEquals("http://uri", t.uri.toString());
+ assertEquals("http://f1", t.f1.toString());
+ assertEquals("http://f2", t.f2.toString());
+ }
+
+ public static class G {
+ @BeanProperty(beanUri=true) public URI uri;
+ public URI f1;
+ public URL f2;
+ }
+
+ //====================================================================================================
+ // Test URIs with URI_CONTEXT and URI_AUTHORITY
+ //====================================================================================================
+ @Test
+ public void testUris() throws Exception {
+ WriterSerializer s = new XmlSerializer.SimpleSq();
+ TestURI t = new TestURI();
+ String r;
+ String expected;
+
+ s.setProperty(SERIALIZER_relativeUriBase, null);
+ r = s.serialize(t);
+ expected = ""
+ +"<object f0='f0/x0'>"
+ +"<f1>f1/x1</f1>"
+ +"<f2>/f2/x2</f2>"
+ +"<f3>http://www.ibm.com/f3/x3</f3>"
+ +"<f4>f4/x4</f4>"
+ +"<f5>/f5/x5</f5>"
+ +"<f6>http://www.ibm.com/f6/x6</f6>"
+ +"<f7>http://www.ibm.com/f7/x7</f7>"
+ +"<f8>f8/x8</f8>"
+ +"<f9>f9/x9</f9>"
+ +"<fa>http://www.ibm.com/fa/xa#MY_LABEL</fa>"
+ +"<fb>http://www.ibm.com/fb/xb?label=MY_LABEL&foo=bar</fb>"
+ +"<fc>http://www.ibm.com/fc/xc?foo=bar&label=MY_LABEL</fc>"
+ +"<fd>http://www.ibm.com/fd/xd?label2=MY_LABEL&foo=bar</fd>"
+ +"<fe>http://www.ibm.com/fe/xe?foo=bar&label2=MY_LABEL</fe>"
+ +"</object>";
+ assertEquals(expected, r);
+
+ s.setProperty(SERIALIZER_relativeUriBase, ""); // Same as null.
+ r = s.serialize(t);
+ assertEquals(expected, r);
+
+ s.setProperty(SERIALIZER_relativeUriBase, "/cr");
+ r = s.serialize(t);
+ expected = ""
+ +"<object f0='/cr/f0/x0'>"
+ +"<f1>/cr/f1/x1</f1>"
+ +"<f2>/f2/x2</f2>"
+ +"<f3>http://www.ibm.com/f3/x3</f3>"
+ +"<f4>/cr/f4/x4</f4>"
+ +"<f5>/f5/x5</f5>"
+ +"<f6>http://www.ibm.com/f6/x6</f6>"
+ +"<f7>http://www.ibm.com/f7/x7</f7>"
+ +"<f8>/cr/f8/x8</f8>"
+ +"<f9>/cr/f9/x9</f9>"
+ +"<fa>http://www.ibm.com/fa/xa#MY_LABEL</fa>"
+ +"<fb>http://www.ibm.com/fb/xb?label=MY_LABEL&foo=bar</fb>"
+ +"<fc>http://www.ibm.com/fc/xc?foo=bar&label=MY_LABEL</fc>"
+ +"<fd>http://www.ibm.com/fd/xd?label2=MY_LABEL&foo=bar</fd>"
+ +"<fe>http://www.ibm.com/fe/xe?foo=bar&label2=MY_LABEL</fe>"
+ +"</object>";
+ assertEquals(expected, r);
+
+ s.setProperty(SERIALIZER_relativeUriBase, "/cr/"); // Same as above
+ r = s.serialize(t);
+ assertEquals(expected, r);
+
+ s.setProperty(SERIALIZER_relativeUriBase, "/");
+ r = s.serialize(t);
+ expected = ""
+ +"<object f0='/f0/x0'>"
+ +"<f1>/f1/x1</f1>"
+ +"<f2>/f2/x2</f2>"
+ +"<f3>http://www.ibm.com/f3/x3</f3>"
+ +"<f4>/f4/x4</f4>"
+ +"<f5>/f5/x5</f5>"
+ +"<f6>http://www.ibm.com/f6/x6</f6>"
+ +"<f7>http://www.ibm.com/f7/x7</f7>"
+ +"<f8>/f8/x8</f8>"
+ +"<f9>/f9/x9</f9>"
+ +"<fa>http://www.ibm.com/fa/xa#MY_LABEL</fa>"
+ +"<fb>http://www.ibm.com/fb/xb?label=MY_LABEL&foo=bar</fb>"
+ +"<fc>http://www.ibm.com/fc/xc?foo=bar&label=MY_LABEL</fc>"
+ +"<fd>http://www.ibm.com/fd/xd?label2=MY_LABEL&foo=bar</fd>"
+ +"<fe>http://www.ibm.com/fe/xe?foo=bar&label2=MY_LABEL</fe>"
+ +"</object>";
+ assertEquals(expected, r);
+
+ s.setProperty(SERIALIZER_relativeUriBase, null);
+
+ s.setProperty(SERIALIZER_absolutePathUriBase, "http://foo");
+ r = s.serialize(t);
+ expected = ""
+ +"<object f0='f0/x0'>"
+ +"<f1>f1/x1</f1>"
+ +"<f2>http://foo/f2/x2</f2>"
+ +"<f3>http://www.ibm.com/f3/x3</f3>"
+ +"<f4>f4/x4</f4>"
+ +"<f5>http://foo/f5/x5</f5>"
+ +"<f6>http://www.ibm.com/f6/x6</f6>"
+ +"<f7>http://www.ibm.com/f7/x7</f7>"
+ +"<f8>f8/x8</f8>"
+ +"<f9>f9/x9</f9>"
+ +"<fa>http://www.ibm.com/fa/xa#MY_LABEL</fa>"
+ +"<fb>http://www.ibm.com/fb/xb?label=MY_LABEL&foo=bar</fb>"
+ +"<fc>http://www.ibm.com/fc/xc?foo=bar&label=MY_LABEL</fc>"
+ +"<fd>http://www.ibm.com/fd/xd?label2=MY_LABEL&foo=bar</fd>"
+ +"<fe>http://www.ibm.com/fe/xe?foo=bar&label2=MY_LABEL</fe>"
+ +"</object>";
+ assertEquals(expected, r);
+
+ s.setProperty(SERIALIZER_absolutePathUriBase, "http://foo/");
+ r = s.serialize(t);
+ assertEquals(expected, r);
+
+ s.setProperty(SERIALIZER_absolutePathUriBase, ""); // Same as null.
+ r = s.serialize(t);
+ expected = ""
+ +"<object f0='f0/x0'>"
+ +"<f1>f1/x1</f1>"
+ +"<f2>/f2/x2</f2>"
+ +"<f3>http://www.ibm.com/f3/x3</f3>"
+ +"<f4>f4/x4</f4>"
+ +"<f5>/f5/x5</f5>"
+ +"<f6>http://www.ibm.com/f6/x6</f6>"
+ +"<f7>http://www.ibm.com/f7/x7</f7>"
+ +"<f8>f8/x8</f8>"
+ +"<f9>f9/x9</f9>"
+ +"<fa>http://www.ibm.com/fa/xa#MY_LABEL</fa>"
+ +"<fb>http://www.ibm.com/fb/xb?label=MY_LABEL&foo=bar</fb>"
+ +"<fc>http://www.ibm.com/fc/xc?foo=bar&label=MY_LABEL</fc>"
+ +"<fd>http://www.ibm.com/fd/xd?label2=MY_LABEL&foo=bar</fd>"
+ +"<fe>http://www.ibm.com/fe/xe?foo=bar&label2=MY_LABEL</fe>"
+ +"</object>";
+ assertEquals(expected, r);
+ }
+
+ //====================================================================================================
+ // Validate that you cannot update properties on locked serializer.
+ //====================================================================================================
+ @Test
+ public void testLockedSerializer() throws Exception {
+ XmlSerializer s = new XmlSerializer().lock();
+ try {
+ s.setProperty(XmlSerializerContext.XML_enableNamespaces, true);
+ fail("Locked exception not thrown");
+ } catch (LockedException e) {}
+ try {
+ s.setProperty(SerializerContext.SERIALIZER_addClassAttrs, true);
+ fail("Locked exception not thrown");
+ } catch (LockedException e) {}
+ try {
+ s.setProperty(BeanContext.BEAN_beanMapPutReturnsOldValue, true);
+ fail("Locked exception not thrown");
+ } catch (LockedException e) {}
+ }
+
+ //====================================================================================================
+ // Recursion
+ //====================================================================================================
+ @Test
+ public void testRecursion() throws Exception {
+ XmlSerializer s = new XmlSerializer().setProperty(XML_enableNamespaces, false);
+
+ R1 r1 = new R1();
+ R2 r2 = new R2();
+ R3 r3 = new R3();
+ r1.r2 = r2;
+ r2.r3 = r3;
+ r3.r1 = r1;
+
+ // No recursion detection
+ try {
+ s.serialize(r1);
+ fail("Exception expected!");
+ } catch (Exception e) {
+ String msg = e.getLocalizedMessage();
+ assertTrue(msg.contains("It's recommended you use the SerializerContext.SERIALIZER_detectRecursions setting to help locate the loop."));
+ }
+
+ // Recursion detection, no ignore
+ s.setProperty(SERIALIZER_detectRecursions, true);
+ try {
+ s.serialize(r1);
+ fail("Exception expected!");
+ } catch (Exception e) {
+ String msg = e.getLocalizedMessage();
+ assertTrue(msg.contains("[0]<noname>:org.apache.juneau.xml.CommonTest$R1"));
+ assertTrue(msg.contains("->[1]r2:org.apache.juneau.xml.CommonTest$R2"));
+ assertTrue(msg.contains("->[2]r3:org.apache.juneau.xml.CommonTest$R3"));
+ assertTrue(msg.contains("->[3]r1:org.apache.juneau.xml.CommonTest$R1"));
+ }
+
+ s.setProperty(SERIALIZER_ignoreRecursions, true);
+ assertEquals("<object><name>foo</name><r2><name>bar</name><r3><name>baz</name></r3></r2></object>", s.serialize(r1));
+
+ // Make sure this doesn't blow up.
+ s.getSchemaSerializer().serialize(r1);
+ }
+
+ public static class R1 {
+ public String name = "foo";
+ public R2 r2;
+ }
+ public static class R2 {
+ public String name = "bar";
+ public R3 r3;
+ }
+ public static class R3 {
+ public String name = "baz";
+ public R1 r1;
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/xml/CommonXmlTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/xml/CommonXmlTest.java b/org.apache.juneau/src/test/java/org/apache/juneau/xml/CommonXmlTest.java
new file mode 100755
index 0000000..c5e4c3b
--- /dev/null
+++ b/org.apache.juneau/src/test/java/org/apache/juneau/xml/CommonXmlTest.java
@@ -0,0 +1,81 @@
+/***************************************************************************************************************************
+ * 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.juneau.xml;
+
+import static org.apache.juneau.TestUtils.*;
+import static org.apache.juneau.xml.XmlSerializerContext.*;
+import static org.apache.juneau.xml.annotation.XmlFormat.*;
+import static org.junit.Assert.*;
+
+import java.net.*;
+
+import org.apache.juneau.annotation.*;
+import org.apache.juneau.xml.annotation.*;
+import org.junit.*;
+
+public class CommonXmlTest {
+
+ //====================================================================================================
+ // Test 18a - @Bean.uri annotation
+ //====================================================================================================
+ @Test
+ public void testBeanUriAnnotation() throws Exception {
+ XmlParser p = XmlParser.DEFAULT;
+ XmlSerializer s = XmlSerializer.DEFAULT_SIMPLE_SQ;
+
+ A t = new A("http://foo", 123, "bar");
+ String xml = s.serialize(t);
+ assertEquals("<object url='http://foo' id='123'><name>bar</name></object>", xml);
+
+ t = p.parse(xml, A.class);
+ assertEquals("http://foo", t.url.toString());
+ assertEquals(123, t.id);
+ assertEquals("bar", t.name);
+
+ validateXml(t, s);
+ }
+
+ public static class A {
+ @BeanProperty(beanUri=true) public URL url;
+ @Xml(format=ATTR) public int id;
+ public String name;
+ public A() {}
+ public A(String url, int id, String name) throws Exception {
+ this.url = new URL(url);
+ this.id = id;
+ this.name = name;
+ }
+ }
+
+ //====================================================================================================
+ // Bean.uri annotation, only uri property
+ //====================================================================================================
+ @Test
+ public void testBeanUriAnnotationOnlyUriProperty() throws Exception {
+ XmlSerializer s = new XmlSerializer.Sq().setProperty(XML_addNamespaceUrisToRoot, false);
+
+ B t = new B("http://foo");
+ String xml = s.serialize(t);
+ assertEquals("<object url='http://foo'><url2>http://foo/2</url2></object>", xml);
+ }
+
+ public static class B {
+ @BeanProperty(beanUri=true) public URL url;
+ public URL url2;
+ public B() {}
+ public B(String url) throws Exception {
+ this.url = new URL(url);
+ this.url2 = new URL(url+"/2");
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/xml/XmlCollapsedTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/xml/XmlCollapsedTest.java b/org.apache.juneau/src/test/java/org/apache/juneau/xml/XmlCollapsedTest.java
new file mode 100755
index 0000000..2bfa4e6
--- /dev/null
+++ b/org.apache.juneau/src/test/java/org/apache/juneau/xml/XmlCollapsedTest.java
@@ -0,0 +1,459 @@
+/***************************************************************************************************************************
+ * 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.juneau.xml;
+
+import static org.apache.juneau.TestUtils.*;
+import static org.apache.juneau.xml.annotation.XmlFormat.*;
+import static org.junit.Assert.*;
+
+import java.util.*;
+
+import org.apache.juneau.*;
+import org.apache.juneau.annotation.*;
+import org.apache.juneau.serializer.*;
+import org.apache.juneau.xml.annotation.*;
+import org.junit.*;
+
+@SuppressWarnings({"serial"})
+public class XmlCollapsedTest {
+
+ //====================================================================================================
+ // testBasic - @Xml.format=COLLAPSED
+ //====================================================================================================
+ @Test
+ public void testBasic() throws Exception {
+ XmlSerializer s = XmlSerializer.DEFAULT_SIMPLE_SQ;
+ XmlParser p = XmlParser.DEFAULT;
+ A t = new A();
+
+ t.f1 = new LinkedList<String>(){{add("f1a");add("f1b");}};
+ t.f2 = new String[]{"f2a","f2b"};
+ t.f3 = new LinkedList<String>(){{add("f3a");add("f3b");}};
+ t.f4 = new String[]{"f4a","f4b"};
+
+ String xml = s.serialize(t);
+ assertEquals("<object><f1>f1a</f1><f1>f1b</f1><f2>f2a</f2><f2>f2b</f2><xf3>f3a</xf3><xf3>f3b</xf3><xf4>f4a</xf4><xf4>f4b</xf4></object>", xml);
+ t = p.parse(xml, A.class);
+ assertEquals("f1a", t.f1.get(0));
+ assertEquals("f2a", t.f2[0]);
+ assertEquals("f3a", t.f3.get(0));
+ assertEquals("f4a", t.f4[0]);
+
+ validateXml(t, s);
+ }
+
+ public static class A {
+
+ @Xml(format=COLLAPSED)
+ public List<String> f1 = new LinkedList<String>();
+
+ @Xml(format=COLLAPSED)
+ public String[] f2 = new String[0];
+
+ @Xml(format=COLLAPSED,childName="xf3")
+ public List<String> f3 = new LinkedList<String>();
+
+ @Xml(format=COLLAPSED,childName="xf4")
+ public String[] f4 = new String[0];
+ }
+
+ //====================================================================================================
+ // testUninitializedFields - @Xml.format=COLLAPSED, uninitialized fields.
+ //====================================================================================================
+ @Test
+ public void testUninitializedFields() throws Exception {
+ XmlSerializer s = XmlSerializer.DEFAULT_SIMPLE_SQ;
+ XmlParser p = XmlParser.DEFAULT;
+ B t = new B();
+
+ t.f1 = new LinkedList<String>(){{add("f1a");add("f1b");}};
+ t.f2 = new String[]{"f2a","f2b"};
+ t.f3 = new LinkedList<String>(){{add("f3a");add("f3b");}};
+ t.f4 = new String[]{"f4a","f4b"};
+
+ String xml = s.serialize(t);
+ assertEquals("<object><f1>f1a</f1><f1>f1b</f1><f2>f2a</f2><f2>f2b</f2><xf3>f3a</xf3><xf3>f3b</xf3><xf4>f4a</xf4><xf4>f4b</xf4></object>", xml);
+ t = p.parse(xml, B.class);
+ assertEquals("f1a", t.f1.get(0));
+ assertEquals("f2a", t.f2[0]);
+ assertEquals("f3a", t.f3.get(0));
+ assertEquals("f4a", t.f4[0]);
+
+ validateXml(t, s);
+ }
+
+ public static class B {
+
+ @Xml(format=COLLAPSED)
+ public List<String> f1;
+
+ @Xml(format=COLLAPSED)
+ public String[] f2;
+
+ @Xml(format=COLLAPSED,childName="xf3")
+ public List<String> f3;
+
+ @Xml(format=COLLAPSED,childName="xf4")
+ public String[] f4;
+ }
+
+ //====================================================================================================
+ // testInitializedFields - @Xml.format=COLLAPSED, initialized fields.
+ //====================================================================================================
+ @Test
+ public void testInitializedFields() throws Exception {
+ XmlSerializer s = XmlSerializer.DEFAULT_SIMPLE_SQ;
+ XmlParser p = XmlParser.DEFAULT;
+ C t = new C();
+
+ t.f1 = new LinkedList<String>(){{add("f1b");}};
+ t.f2 = new String[]{"f2b"};
+ t.f3 = new LinkedList<String>(){{add("f3b");}};
+ t.f4 = new String[]{"f4b"};
+
+ String xml = s.serialize(t);
+ assertEquals("<object><f1>f1b</f1><f2>f2b</f2><xf3>f3b</xf3><xf4>f4b</xf4></object>", xml);
+
+ // Note that existing fields should be reused and appended to.
+ t = p.parse(xml, C.class);
+ assertEquals("f1a", t.f1.get(0));
+ assertEquals("f1b", t.f1.get(1));
+ assertEquals("f2a", t.f2[0]);
+ assertEquals("f2b", t.f2[1]);
+ assertEquals("f3a", t.f3.get(0));
+ assertEquals("f3b", t.f3.get(1));
+ assertEquals("f4a", t.f4[0]);
+ assertEquals("f4b", t.f4[1]);
+
+ validateXml(t, s);
+ }
+
+ public static class C {
+
+ @Xml(format=COLLAPSED)
+ public List<String> f1 = new LinkedList<String>(){{add("f1a");}};
+
+ @Xml(format=COLLAPSED)
+ public String[] f2 = {"f2a"};
+
+ @Xml(format=COLLAPSED,childName="xf3")
+ public List<String> f3 = new LinkedList<String>(){{add("f3a");}};
+
+ @Xml(format=COLLAPSED,childName="xf4")
+ public String[] f4 = {"f4a"};
+ }
+
+ //====================================================================================================
+ // testGetters - @Xml.format=COLLAPSED, getters.
+ //====================================================================================================
+ @Test
+ @SuppressWarnings("synthetic-access")
+ public void testGetters() throws Exception {
+ XmlSerializer s = XmlSerializer.DEFAULT_SIMPLE_SQ;
+ XmlParser p = XmlParser.DEFAULT;
+ D t = new D();
+
+ t.f1 = new LinkedList<String>(){{add("f1a");}};
+ t.f2 = new String[]{"f2a"};
+ t.f3 = new LinkedList<String>(){{add("f3a");}};
+ t.f4 = new String[]{"f4a"};
+
+ String xml = s.serialize(t);
+ assertEquals("<object><f1>f1a</f1><f2>f2a</f2><xf3>f3a</xf3><xf4>f4a</xf4></object>", xml);
+
+ // Note that existing fields should be reused and appended to.
+ t = p.parse(xml, D.class);
+ assertEquals("f1a", t.f1.get(0));
+ assertEquals("f2a", t.f2[0]);
+ assertEquals("f3a", t.f3.get(0));
+ assertEquals("f4a", t.f4[0]);
+
+ validateXml(t, s);
+ }
+
+ @Bean(properties={"f1","f2","f3","f4"})
+ public static class D {
+
+ private List<String> f1 = new LinkedList<String>(), f3 = new LinkedList<String>();
+ private String[] f2, f4;
+
+ @Xml(format=COLLAPSED)
+ public List<String> getF1() {
+ return f1;
+ }
+
+ @Xml(format=COLLAPSED)
+ public String[] getF2() {
+ return f2;
+ }
+ public void setF2(String[] f2) {
+ this.f2 = f2;
+ }
+
+ @Xml(format=COLLAPSED,childName="xf3")
+ public List<String> getF3() {
+ return f3;
+ }
+
+ @Xml(format=COLLAPSED,childName="xf4")
+ public String[] getF4() {
+ return f4;
+ }
+ public void setF4(String[] f4) {
+ this.f4 = f4;
+ }
+ }
+
+ //====================================================================================================
+ // testNullConstructibleCollectionFields - @Xml.format=COLLAPSED, null constructible collection fields.
+ //====================================================================================================
+ @Test
+ @SuppressWarnings("synthetic-access")
+ public void testNullConstructibleCollectionFields() throws Exception {
+ XmlSerializer s = XmlSerializer.DEFAULT_SIMPLE_SQ;
+ XmlParser p = XmlParser.DEFAULT;
+ E t = new E();
+
+ t.f1 = new LinkedList<String>(){{add("f1a");}};
+ t.f2 = new LinkedList<String>(){{add("f2a");}};
+
+ String xml = s.serialize(t);
+ assertEquals("<object><f1>f1a</f1><xf2>f2a</xf2></object>", xml);
+
+ // Note that existing fields should be reused and appended to.
+ t = p.parse(xml, E.class);
+ assertEquals("f1a", t.f1.get(0));
+ assertEquals("f2a", t.f2.get(0));
+
+ validateXml(t, s);
+ }
+
+ @Bean(properties={"f1","f2"})
+ public static class E {
+
+ private LinkedList<String> f1, f2;
+
+ @Xml(format=COLLAPSED)
+ public LinkedList<String> getF1() {
+ return f1;
+ }
+ public void setF1(LinkedList<String> f1) {
+ this.f1 = f1;
+ }
+
+ @Xml(format=COLLAPSED,childName="xf2")
+ public LinkedList<String> getF2() {
+ return f2;
+ }
+ public void setF2(LinkedList<String> f2) {
+ this.f2 = f2;
+ }
+ }
+
+
+ //====================================================================================================
+ // testElementNameOnElementClass - @Xml.format=COLLAPSED, element name defined on element class.
+ //====================================================================================================
+ @Test
+ public void testElementNameOnElementClass() throws Exception {
+ XmlSerializer s = XmlSerializer.DEFAULT_SIMPLE_SQ;
+ XmlParser p = XmlParser.DEFAULT;
+ Object t1 = FA.newInstance(), t2;
+ String r;
+
+ r = s.serialize(t1);
+ assertEquals("<object><xf1>x1</xf1><xf1>x2</xf1></object>", r);
+ t2 = p.parse(r, FA.class);
+ assertEqualObjects(t1, t2);
+ validateXml(t1, s);
+
+ t1 = FB.newInstance();
+ r = s.serialize(t1);
+ assertEquals("<object><xf1>x1</xf1><xf1>x2</xf1></object>", r);
+ t2 = p.parse(r, FB.class);
+ assertEqualObjects(t1, t2);
+ validateXml(t1, s);
+
+ t1 = FC.newInstance();
+ try {
+ r = s.serialize(t1);
+ fail("Exception expected.");
+ } catch (SerializeException e) {
+ assertEquals("org.apache.juneau.xml.XmlCollapsedTest$FC: Multiple properties found with the name 'xf1'.", e.getLocalizedMessage());
+ }
+ }
+
+ public static class FA {
+
+ @Xml(format=COLLAPSED)
+ public List<F1> f1;
+
+ public static FA newInstance() {
+ FA t = new FA();
+ t.f1 = new LinkedList<F1>();
+ t.f1.add(F1.newInstance("x1"));
+ t.f1.add(F1.newInstance("x2"));
+ return t;
+ }
+ }
+
+ public static class FB {
+ @Xml(format=COLLAPSED)
+ public F1[] f1;
+
+ public static FB newInstance() {
+ FB t = new FB();
+ t.f1 = new F1[]{
+ F1.newInstance("x1"),
+ F1.newInstance("x2")
+ };
+ return t;
+ }
+ }
+
+ // Should cause name collision.
+ public static class FC {
+
+ @Xml(format=COLLAPSED)
+ public List<F1> f1;
+
+ @Xml(format=COLLAPSED)
+ public F1[] f2;
+
+ public static FC newInstance() {
+ FC t = new FC();
+ return t;
+ }
+ }
+
+ @Xml(name="xf1")
+ public static class F1 {
+
+ @Xml(format=CONTENT)
+ public String text;
+
+ public static F1 newInstance(String text) {
+ F1 t = new F1();
+ t.text = text;
+ return t;
+ }
+ }
+
+
+ //====================================================================================================
+ // testElementNameOnElementClassOverridden - @Xml.format=COLLAPSED, element name defined on element class,
+ // but overridden by @Xml.childName on property.
+ //====================================================================================================
+ @Test
+ public void testElementNameOnElementClassOverridden() throws Exception {
+ XmlSerializer s = XmlSerializer.DEFAULT_SIMPLE_SQ;
+ XmlParser p = XmlParser.DEFAULT;
+ G t = G.newInstance(), t2;
+
+ String xml = s.serialize(t);
+ assertEquals("<object><yf1>x1</yf1><yf1>x2</yf1></object>", xml);
+
+ // Note that existing fields should be reused and appended to.
+ t2 = p.parse(xml, G.class);
+ assertEqualObjects(t, t2);
+
+ validateXml(t, s);
+ }
+
+ public static class G {
+
+ @Xml(format=COLLAPSED, childName="yf1")
+ public List<F1> f1;
+
+ public static G newInstance() {
+ G t = new G();
+ t.f1 = new LinkedList<F1>();
+ t.f1.add(F1.newInstance("x1"));
+ t.f1.add(F1.newInstance("x2"));
+ return t;
+ }
+ }
+
+
+ //====================================================================================================
+ // testElementNameOnCollectionClass - @Xml.format=COLLAPSED, element name defined on bean class.
+ //====================================================================================================
+ @Test
+ public void testElementNameOnCollectionClass() throws Exception {
+ XmlSerializer s = XmlSerializer.DEFAULT_SIMPLE_SQ;
+ XmlParser p = XmlParser.DEFAULT;
+ H t = H.newInstance(), t2;
+
+ String xml = s.serialize(t);
+ assertEquals("<object><xf1>x1</xf1><xf1>x2</xf1></object>", xml);
+
+ // Note that existing fields should be reused and appended to.
+ t2 = p.parse(xml, H.class);
+ assertEqualObjects(t, t2);
+
+ validateXml(t, s);
+ }
+
+ public static class H {
+
+ @Xml(format=COLLAPSED)
+ public H1 f1;
+
+ public static H newInstance() {
+ H t = new H();
+ t.f1 = new H1();
+ t.f1.add("x1");
+ t.f1.add("x2");
+ return t;
+ }
+ }
+
+ @Xml(childName="xf1")
+ public static class H1 extends LinkedList<String> {
+ }
+
+
+ //====================================================================================================
+ // testElementNameOnCollectionClassOverridden - @Xml.format=COLLAPSED, element name defined on element class,
+ // but overridden by @Xml.childName on property.
+ //====================================================================================================
+ @Test
+ public void testElementNameOnCollectionClassOverridden() throws Exception {
+ XmlSerializer s = XmlSerializer.DEFAULT_SIMPLE_SQ;
+ XmlParser p = XmlParser.DEFAULT;
+ G t = G.newInstance(), t2;
+
+ String xml = s.serialize(t);
+ assertEquals("<object><yf1>x1</yf1><yf1>x2</yf1></object>", xml);
+
+ // Note that existing fields should be reused and appended to.
+ t2 = p.parse(xml, G.class);
+ assertEqualObjects(t, t2);
+
+ validateXml(t, s);
+ }
+
+ public static class I {
+
+ @Xml(format=COLLAPSED, childName="yf1")
+ public H1 f1;
+
+ public static I newInstance() {
+ I t = new I();
+ t.f1 = new H1();
+ t.f1.add("x1");
+ t.f1.add("x2");
+ return t;
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/xml/XmlContentTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/xml/XmlContentTest.java b/org.apache.juneau/src/test/java/org/apache/juneau/xml/XmlContentTest.java
new file mode 100755
index 0000000..42fb2b7
--- /dev/null
+++ b/org.apache.juneau/src/test/java/org/apache/juneau/xml/XmlContentTest.java
@@ -0,0 +1,301 @@
+/***************************************************************************************************************************
+ * 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.juneau.xml;
+
+import static org.apache.juneau.TestUtils.*;
+import static org.apache.juneau.serializer.SerializerContext.*;
+import static org.apache.juneau.xml.XmlSerializerContext.*;
+import static org.apache.juneau.xml.XmlUtils.*;
+import static org.apache.juneau.xml.annotation.XmlFormat.*;
+import static org.junit.Assert.*;
+
+import java.io.*;
+
+import javax.xml.stream.*;
+
+import org.apache.juneau.*;
+import org.apache.juneau.xml.annotation.*;
+import org.junit.*;
+
+public class XmlContentTest {
+
+ //--------------------------------------------------------------------------------
+ // Test beans with @Xml(format=CONTENT)
+ //--------------------------------------------------------------------------------
+ @Test
+ public void testContentFormat() throws Exception {
+ A t = A.newInstance(), t2;
+ XmlSerializer s1 = XmlSerializer.DEFAULT_SIMPLE_SQ,
+ s2 = new XmlSerializer().setProperty(SERIALIZER_quoteChar, '\'').setProperty(SERIALIZER_useIndentation, true).setProperty(XML_enableNamespaces, false);
+ XmlParser p = XmlParser.DEFAULT;
+ XmlSerializerSession session;
+ String r;
+ StringWriter sw;
+
+ //----------------------------------------------------------------
+ // Null
+ //----------------------------------------------------------------
+ t.f2 = null;
+
+ sw = new StringWriter();
+ session = s1.createSession(sw, new ObjectMap("{"+SERIALIZER_trimNullProperties+":false}"), null);
+ s1.serialize(session, t);
+ r = sw.toString();
+ assertEquals("<A f1='f1'>_x0000_</A>", r);
+ t2 = p.parse(r, A.class);
+ assertEqualObjects(t, t2);
+
+ sw = new StringWriter();
+ session = s2.createSession(sw, new ObjectMap("{"+SERIALIZER_trimNullProperties+":false}"), null);
+ s2.serialize(session, t);
+ r = sw.toString();
+ assertEquals("<A f1='f1'>\n\t_x0000_\n</A>\n", r);
+ t2 = p.parse(r, A.class);
+ assertEqualObjects(t, t2);
+
+ //----------------------------------------------------------------
+ // Normal text
+ //----------------------------------------------------------------
+ t.f2 = "foobar";
+
+ r = s1.serialize(t);
+ assertEquals("<A f1='f1'>foobar</A>", r);
+ t2 = p.parse(r, A.class);
+ assertEqualObjects(t, t2);
+
+ r = s2.serialize(t);
+ assertEquals("<A f1='f1'>\n\tfoobar\n</A>\n", r);
+ t2 = p.parse(r, A.class);
+ assertEqualObjects(t, t2);
+
+ //----------------------------------------------------------------
+ // Special characters
+ //----------------------------------------------------------------
+ t.f2 = "~!@#$%^&*()_+`-={}|[]\\:\";'<>?,.\n\r\t\b";
+
+ r = s1.serialize(t);
+ assertEquals("<A f1='f1'>~!@#$%^&*()_+`-={}|[]\\:\";'<>?,.

	_x0008_</A>", r);
+ t2 = p.parse(r, A.class);
+ assertEqualObjects(t, t2);
+
+ r = s2.serialize(t);
+ assertEquals("<A f1='f1'>\n\t~!@#$%^&*()_+`-={}|[]\\:\";'<>?,.

	_x0008_\n</A>\n", r);
+ t2 = p.parse(r, A.class);
+ assertEqualObjects(t, t2);
+
+ //----------------------------------------------------------------
+ // Leading spaces
+ //----------------------------------------------------------------
+ t.f2 = " foobar";
+
+ r = s1.serialize(t);
+ assertEquals("<A f1='f1'>_x0020_ foobar</A>", r);
+ t2 = p.parse(r, A.class);
+ assertEqualObjects(t, t2);
+
+ r = s2.serialize(t);
+ assertEquals("<A f1='f1'>\n\t_x0020_ foobar\n</A>\n", r);
+ t2 = p.parse(r, A.class);
+ assertEqualObjects(t, t2);
+
+ //----------------------------------------------------------------
+ // Trailing spaces
+ //----------------------------------------------------------------
+ t.f2 = "foobar ";
+
+ r = s1.serialize(t);
+ assertEquals("<A f1='f1'>foobar _x0020_</A>", r);
+ t2 = p.parse(r, A.class);
+ assertEqualObjects(t, t2);
+
+ r = s2.serialize(t);
+ assertEquals("<A f1='f1'>\n\tfoobar _x0020_\n</A>\n", r);
+ t2 = p.parse(r, A.class);
+ assertEqualObjects(t, t2);
+ }
+
+ @Xml(name="A")
+ public static class A {
+ @Xml(format=ATTR) public String f1;
+ @Xml(format=CONTENT) public String f2;
+
+ public static A newInstance() {
+ A t = new A();
+ t.f1 = "f1";
+ t.f2 = null;
+ return t;
+ }
+ }
+
+ //--------------------------------------------------------------------------------
+ // Test beans with @Xml(format=XMLCONTENT)
+ //--------------------------------------------------------------------------------
+ @Test
+ public void testXmlContentFormat() throws Exception {
+ B t = B.newInstance(), t2;
+ XmlSerializer s1 = XmlSerializer.DEFAULT_SIMPLE_SQ,
+ s2 = new XmlSerializer().setProperty(SERIALIZER_quoteChar, '\'').setProperty(SERIALIZER_useIndentation, true).setProperty(XML_enableNamespaces, false);
+ XmlParser p = XmlParser.DEFAULT;
+ XmlSerializerSession session;
+ String r;
+ StringWriter sw;
+
+ //----------------------------------------------------------------
+ // Null
+ //----------------------------------------------------------------
+ t.f2 = null;
+
+ sw = new StringWriter();
+ session = s1.createSession(sw, new ObjectMap("{"+SERIALIZER_trimNullProperties+":false}"), null);
+ s1.serialize(session, t);
+ r = sw.toString();
+ assertEquals("<A f1='f1'>_x0000_</A>", r);
+ t2 = p.parse(r, B.class);
+ assertEqualObjects(t, t2);
+
+ sw = new StringWriter();
+ session = s2.createSession(sw, new ObjectMap("{"+SERIALIZER_trimNullProperties+":false}"), null);
+ s2.serialize(session, t);
+ r = sw.toString();
+ assertEquals("<A f1='f1'>\n\t_x0000_\n</A>\n", r);
+ t2 = p.parse(r, B.class);
+ assertEqualObjects(t, t2);
+
+ //----------------------------------------------------------------
+ // Normal text
+ //----------------------------------------------------------------
+ t.f2 = "foobar";
+
+ r = s1.serialize(t);
+ assertEquals("<A f1='f1'>foobar</A>", r);
+ t2 = p.parse(r, B.class);
+ assertEqualObjects(t, t2);
+
+ r = s2.serialize(t);
+ assertEquals("<A f1='f1'>\n\tfoobar\n</A>\n", r);
+ t2 = p.parse(r, B.class);
+ assertEqualObjects(t, t2);
+
+ //----------------------------------------------------------------
+ // Normal XML
+ //----------------------------------------------------------------
+ t.f2 = "<xxx>foobar<yyy>baz</yyy>foobar</xxx>";
+
+ r = s1.serialize(t);
+ assertEquals("<A f1='f1'><xxx>foobar<yyy>baz</yyy>foobar</xxx></A>", r);
+ t2 = p.parse(r, B.class);
+ assertEqualObjects(t, t2);
+
+ r = s2.serialize(t);
+ assertEquals("<A f1='f1'>\n\t<xxx>foobar<yyy>baz</yyy>foobar</xxx>\n</A>\n", r);
+ t2 = p.parse(r, B.class);
+ assertEqualObjects(t, t2);
+
+ //----------------------------------------------------------------
+ // Normal XML with leading and trailing space
+ //----------------------------------------------------------------
+ t.f2 = " <xxx>foobar<yyy>baz</yyy>foobar</xxx> ";
+
+ r = s1.serialize(t);
+ assertEquals("<A f1='f1'>_x0020_ <xxx>foobar<yyy>baz</yyy>foobar</xxx> _x0020_</A>", r);
+ t2 = p.parse(r, B.class);
+ assertEqualObjects(t, t2);
+
+ r = s2.serialize(t);
+ assertEquals("<A f1='f1'>\n\t_x0020_ <xxx>foobar<yyy>baz</yyy>foobar</xxx> _x0020_\n</A>\n", r);
+ t2 = p.parse(r, B.class);
+ assertEqualObjects(t, t2);
+
+ //----------------------------------------------------------------
+ // XML with attributes
+ //----------------------------------------------------------------
+ t.f2 = "<xxx x=\"x\">foobar</xxx>";
+
+ r = s1.serialize(t);
+ assertEquals("<A f1='f1'><xxx x=\"x\">foobar</xxx></A>", r);
+ t2 = p.parse(r, B.class);
+ assertEqualObjects(t, t2);
+
+ r = s2.serialize(t);
+ assertEquals("<A f1='f1'>\n\t<xxx x=\"x\">foobar</xxx>\n</A>\n", r);
+ t2 = p.parse(r, B.class);
+ assertEqualObjects(t, t2);
+
+ //----------------------------------------------------------------
+ // XML with embedded entities
+ //----------------------------------------------------------------
+ t.f2 = "<xxx x=\"x\">foo<>bar</xxx>";
+
+ r = s1.serialize(t);
+ assertEquals("<A f1='f1'><xxx x=\"x\">foo<>bar</xxx></A>", r);
+ t2 = p.parse(r, B.class);
+ assertEqualObjects(t, t2);
+
+ r = s2.serialize(t);
+ assertEquals("<A f1='f1'>\n\t<xxx x=\"x\">foo<>bar</xxx>\n</A>\n", r);
+ t2 = p.parse(r, B.class);
+ assertEqualObjects(t, t2);
+ }
+
+ @Xml(name="A")
+ public static class B {
+ @Xml(format=ATTR) public String f1;
+ @Xml(format=CONTENT, contentHandler=BContentHandler.class) public String f2;
+
+ public static B newInstance() {
+ B t = new B();
+ t.f1 = "f1";
+ t.f2 = null;
+ return t;
+ }
+ }
+
+ public static class BContentHandler implements XmlContentHandler<B> {
+
+ @Override /* XmlContentHandler */
+ public void parse(XMLStreamReader r, B b) throws Exception {
+ b.f2 = decode(readXmlContents(r).trim());
+ }
+
+ @Override /* XmlContentHandler */
+ public void serialize(XmlWriter w, B b) throws Exception {
+ w.encodeTextInvalidChars(b.f2);
+ }
+
+ }
+
+ //--------------------------------------------------------------------------------
+ // Test beans with too many @Xml.format=CONTENT/XMLCONTENT annotations.
+ //--------------------------------------------------------------------------------
+ @Test
+ public void testBadContent() throws Exception {
+ XmlSerializer s = XmlSerializer.DEFAULT_SIMPLE_SQ;
+ try {
+ s.serialize(new C1());
+ fail("Exception expected");
+ } catch (Exception e) {
+ assertTrue(e.getMessage().contains("Multiple instances of CONTENT properties defined on class"));
+ }
+ // Run twice to make sure we throw exceptions after the first call.
+ try {
+ s.serialize(new C1());
+ fail("Exception expected");
+ } catch (Exception e) {
+ assertTrue(e.getMessage().contains("Multiple instances of CONTENT properties defined on class"));
+ }
+ }
+ public static class C1 {
+ @Xml(format=CONTENT) public String f1;
+ @Xml(format=CONTENT) public String f2;
+ }
+}
[29/44] incubator-juneau git commit: Rename CT_* testcases.
Posted by ja...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/CT_ContextFactory.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/CT_ContextFactory.java b/org.apache.juneau/src/test/java/org/apache/juneau/CT_ContextFactory.java
deleted file mode 100644
index 271410c..0000000
--- a/org.apache.juneau/src/test/java/org/apache/juneau/CT_ContextFactory.java
+++ /dev/null
@@ -1,823 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau;
-
-import static org.apache.juneau.TestUtils.*;
-import static org.junit.Assert.*;
-
-import java.util.*;
-
-import org.apache.juneau.xml.*;
-import org.junit.*;
-
-
-@SuppressWarnings({"rawtypes"})
-public class CT_ContextFactory {
-
- //====================================================================================================
- // testSimpleProperties()
- //====================================================================================================
- @Test
- public void testSimpleProperties() {
- ContextFactory f = ContextFactory.create();
-
- f.setProperty("A.f1", "1");
- f.setProperty("A.f2", "2");
-
- assertObjectEquals("{'A.f1':'1','A.f2':'2'}", f.getPropertyMap("A").asMap());
-
- f.setProperty("B.f3", "3");
- f.setProperty("A.f1", String.class);
- f.setProperty("A.f2", 4);
-
- assertObjectEquals("{'A.f1':'java.lang.String','A.f2':4}", f.getPropertyMap("A").asMap());
-
- f.setProperty("A.f2", null);
- f.setProperty("A.f2", null);
- assertObjectEquals("{'A.f1':'java.lang.String'}", f.getPropertyMap("A").asMap());
-
- try {
- f.setProperty(null, null);
- fail("Exception expected");
- } catch (Exception e) {
- assertEquals("Invalid property name specified: 'null'", e.getMessage());
- }
-
- try {
- f.addToProperty("A.f1", "foo");
- fail("Exception expected");
- } catch (Exception e) {
- assertEquals("Cannot add value 'foo' (java.lang.String) to property 'A.f1' (SIMPLE).", e.getMessage());
- }
-
- try {
- f.removeFromProperty("A.f1", "foo");
- fail("Exception expected");
- } catch (Exception e) {
- assertEquals("Cannot remove value 'foo' (java.lang.String) from property 'A.f1' (SIMPLE).", e.getMessage());
- }
-
- try {
- f.putToProperty("A.f1", "foo", "bar");
- fail("Exception expected");
- } catch (Exception e) {
- assertEquals("Cannot put value 'foo'(java.lang.String)->'bar'(java.lang.String) to property 'A.f1' (SIMPLE).", e.getMessage());
- }
-
- try {
- f.putToProperty("A.f1", "foo");
- fail("Exception expected");
- } catch (Exception e) {
- assertEquals("Cannot put value 'foo' (java.lang.String) to property 'A.f1' (SIMPLE).", e.getMessage());
- }
- }
-
- //====================================================================================================
- // testSetProperties()
- //====================================================================================================
- @Test
- public void testSetProperties() {
- ContextFactory f = ContextFactory.create();
- String key = "A.f1.set";
-
- f.setProperty(key, Arrays.asList(2,3,1));
- assertObjectEquals("[1,2,3]", f.getProperty(key, int[].class, null));
-
- f.addToProperty(key, 0);
- f.addToProperty(key, new int[]{4,5});
- assertObjectEquals("[0,1,2,3,4,5]", f.getProperty(key, int[].class, null));
- f.addToProperty(key, new HashSet<String>(Arrays.asList("6","7")));
- assertObjectEquals("[0,1,2,3,4,5,6,7]", f.getProperty(key, int[].class, null));
- f.addToProperty(key, new int[]{4,5});
- assertObjectEquals("[0,1,2,3,4,5,6,7]", f.getProperty(key, int[].class, null));
-
- f.removeFromProperty(key, 4);
- f.removeFromProperty(key, new HashSet<String>(Arrays.asList("1")));
- f.removeFromProperty(key, new String[]{"2","9"});
- assertObjectEquals("[0,3,5,6,7]", f.getProperty(key, int[].class, null));
- assertObjectEquals("['0','3','5','6','7']", f.getProperty(key, String[].class, null));
-
- f.setProperty(key, Arrays.asList("foo","bar","baz"));
- assertObjectEquals("['bar','baz','foo']", f.getProperty(key, String[].class, null));
-
- f.setProperty(key, "[1,2,3]");
- assertObjectEquals("[1,2,3]", f.getProperty(key, int[].class, null));
-
- f.setProperty(key, "['1','2','3']");
- assertObjectEquals("[1,2,3]", f.getProperty(key, int[].class, null));
-
- try {
- f.putToProperty("A.f1.set", "foo");
- fail("Exception expected");
- } catch (Exception e) {
- assertEquals("Cannot put value 'foo' (java.lang.String) to property 'A.f1.set' (SET).", e.getMessage());
- }
-
- try {
- f.putToProperty("A.f1.set", "foo", "bar");
- fail("Exception expected");
- } catch (Exception e) {
- assertEquals("Cannot put value 'foo'(java.lang.String)->'bar'(java.lang.String) to property 'A.f1.set' (SET).", e.getMessage());
- }
- }
-
- //====================================================================================================
- // testListProperties()
- //====================================================================================================
- @Test
- public void testListProperties() {
- ContextFactory f = ContextFactory.create();
- String key = "A.f1.list";
-
- f.setProperty(key, Arrays.asList(2,3,1));
- assertObjectEquals("[2,3,1]", f.getProperty(key, int[].class, null));
-
- f.addToProperty(key, 0);
- f.addToProperty(key, new int[]{4,5});
- assertObjectEquals("[4,5,0,2,3,1]", f.getProperty(key, int[].class, null));
- f.addToProperty(key, new TreeSet<String>(Arrays.asList("6","7")));
- assertObjectEquals("[6,7,4,5,0,2,3,1]", f.getProperty(key, int[].class, null));
- f.addToProperty(key, new int[]{4,5});
- assertObjectEquals("[4,5,6,7,0,2,3,1]", f.getProperty(key, int[].class, null));
-
- f.removeFromProperty(key, 4);
- f.removeFromProperty(key, new HashSet<String>(Arrays.asList("1")));
- f.removeFromProperty(key, new String[]{"2","9"});
- assertObjectEquals("[5,6,7,0,3]", f.getProperty(key, int[].class, null));
- assertObjectEquals("['5','6','7','0','3']", f.getProperty(key, String[].class, null));
-
- f.setProperty(key, Arrays.asList("foo","bar","baz"));
- assertObjectEquals("['foo','bar','baz']", f.getProperty(key, String[].class, null));
- }
-
- //====================================================================================================
- // testMapProperties()
- //====================================================================================================
- @SuppressWarnings("serial")
- @Test
- public void testMapProperties() {
- ContextFactory f = ContextFactory.create();
- String key = "A.f1.map";
-
- f.setProperty(key, new HashMap<String,String>(){{put("1","1");put("3","3");put("2","2");}});
- assertObjectEquals("{'1':1,'2':2,'3':3}", f.getMap(key, Integer.class, Integer.class, null));
-
- f.setProperty(key, "{'1':1,'2':2,'3':3}");
- assertObjectEquals("{'1':1,'2':2,'3':3}", f.getMap(key, Integer.class, Integer.class, null));
-
- f.putToProperty(key, "{'3':4,'4':5,'5':6}");
- assertObjectEquals("{'1':1,'2':2,'3':4,'4':5,'5':6}", f.getMap(key, Integer.class, Integer.class, null));
- }
-
- //====================================================================================================
- // Hash code and comparison
- //====================================================================================================
- @SuppressWarnings({ "serial" })
- @Test
- public void testHashCodes() throws Exception {
- ContextFactory f1 = ContextFactory.create();
- f1.setProperty("A.a", 1);
- f1.setProperty("A.b", true);
- f1.setProperty("A.c", String.class);
- f1.setProperty("A.d.set", new Object[]{1, true, String.class});
- f1.setProperty("A.e.map", new HashMap<Object,Object>(){{put(true,true);put(1,1);put(String.class,String.class);}});
-
- ContextFactory f2 = ContextFactory.create();
- f2.setProperty("A.e.map", new HashMap<Object,Object>(){{put("1","1");put("true","true");put("java.lang.String","java.lang.String");}});
- f2.setProperty("A.d.set", new Object[]{"true","1","java.lang.String"});
- f2.setProperty("A.c", "java.lang.String");
- f2.setProperty("A.b", "true");
- f2.setProperty("A.a", "1");
-
- ContextFactory.PropertyMap p1 = f1.getPropertyMap("A");
- ContextFactory.PropertyMap p2 = f2.getPropertyMap("A");
- assertEquals(p1.hashCode(), p2.hashCode());
- }
-
- @SuppressWarnings("unchecked")
- private static class ConversionTest {
- ContextFactory config = ContextFactory.create();
- String pName;
- Object in;
-
- private ConversionTest(String pName, Object in) {
- this.pName = pName;
- this.in = in;
- }
-
- private ConversionTest test(Class c, String expected) {
- try {
- config.setProperty(pName, in);
- assertObjectEquals(expected, config.getProperty(pName, c, null));
- } catch (Exception x) {
- assertEquals(expected.toString(), x.getLocalizedMessage());
- }
- return this;
- }
-
- private ConversionTest testMap(Class k, Class v, String expected) {
- try {
- config.setProperty(pName, in);
- assertObjectEquals(expected, config.getMap(pName, k, v, null));
- } catch (Exception x) {
- assertEquals(expected, x.getLocalizedMessage());
- }
- return this;
- }
- }
-
- //====================================================================================================
- // Conversions on simple properties
- //====================================================================================================
- @Test
- @SuppressWarnings({ "serial" })
- public void testConversionsOnSimpleProperties() throws Exception {
- String pName = "A.a";
-
- //--------------------------------------------------------------------------------
- // boolean
- //--------------------------------------------------------------------------------
- new ConversionTest(pName, true)
- .test(boolean.class, "true")
- .test(int.class, "1")
- .test(String.class, "'true'")
- .test(Class.class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'java.lang.Boolean' to type 'java.lang.Class'. Value=true.")
- .test(TestEnum.class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'java.lang.Boolean' to type 'org.apache.juneau.CT_ContextFactory$TestEnum'. Value=true.")
- .test(String[].class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'java.lang.Boolean' to type 'java.lang.String[]'. Value=true.")
- .test(Class[].class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'java.lang.Boolean' to type 'java.lang.Class[]'. Value=true.")
- .test(TestEnum[].class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'java.lang.Boolean' to type 'org.apache.juneau.CT_ContextFactory$TestEnum[]'. Value=true.")
- .testMap(String.class, String.class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'java.lang.Boolean' to type 'java.util.LinkedHashMap<java.lang.String,java.lang.String>'. Value=true.")
- .testMap(Class.class, Class.class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'java.lang.Boolean' to type 'java.util.LinkedHashMap<java.lang.Class,java.lang.Class>'. Value=true.")
- ;
-
- //--------------------------------------------------------------------------------
- // int
- //--------------------------------------------------------------------------------
- new ConversionTest(pName, 123)
- .test(boolean.class, "true")
- .test(int.class, "123")
- .test(String.class, "'123'")
- .test(Class.class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'java.lang.Integer' to type 'java.lang.Class'. Value=123.")
- .test(TestEnum.class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'java.lang.Integer' to type 'org.apache.juneau.CT_ContextFactory$TestEnum'. Value=123.")
- .test(String[].class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'java.lang.Integer' to type 'java.lang.String[]'. Value=123.")
- .test(Class[].class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'java.lang.Integer' to type 'java.lang.Class[]'. Value=123.")
- .test(TestEnum[].class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'java.lang.Integer' to type 'org.apache.juneau.CT_ContextFactory$TestEnum[]'. Value=123.")
- .testMap(String.class, String.class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'java.lang.Integer' to type 'java.util.LinkedHashMap<java.lang.String,java.lang.String>'. Value=123.")
- .testMap(Class.class, Class.class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'java.lang.Integer' to type 'java.util.LinkedHashMap<java.lang.Class,java.lang.Class>'. Value=123.")
- ;
-
- //--------------------------------------------------------------------------------
- // Class
- //--------------------------------------------------------------------------------
- new ConversionTest(pName, String.class)
- .test(boolean.class, "false")
- .test(int.class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'java.lang.Class' to type 'int'. Value='java.lang.String'.")
- .test(String.class, "'java.lang.String'")
- .test(Class.class, "'java.lang.String'")
- .test(TestEnum.class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'java.lang.Class' to type 'org.apache.juneau.CT_ContextFactory$TestEnum'. Value='java.lang.String'.")
- .test(String[].class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'java.lang.Class' to type 'java.lang.String[]'. Value='java.lang.String'.")
- .test(Class[].class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'java.lang.Class' to type 'java.lang.Class[]'. Value='java.lang.String'.")
- .test(TestEnum[].class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'java.lang.Class' to type 'org.apache.juneau.CT_ContextFactory$TestEnum[]'. Value='java.lang.String'.")
- .testMap(String.class, String.class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'java.lang.Class' to type 'java.util.LinkedHashMap<java.lang.String,java.lang.String>'. Value='java.lang.String'.")
- .testMap(Class.class, Class.class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'java.lang.Class' to type 'java.util.LinkedHashMap<java.lang.Class,java.lang.Class>'. Value='java.lang.String'.")
- ;
-
- //--------------------------------------------------------------------------------
- // String
- //--------------------------------------------------------------------------------
- new ConversionTest(pName, "foo")
- .test(boolean.class, "false")
- .test(int.class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'java.lang.String' to type 'int'. Value='foo'.")
- .test(String.class, "'foo'")
- .test(Class.class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'java.lang.String' to type 'java.lang.Class'. Value='foo'.")
- .test(TestEnum.class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'java.lang.String' to type 'org.apache.juneau.CT_ContextFactory$TestEnum'. Value='foo'.")
- .test(String[].class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'java.lang.String' to type 'java.lang.String[]'. Value='foo'.")
- .test(Class[].class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'java.lang.String' to type 'java.lang.Class[]'. Value='foo'.")
- .test(TestEnum[].class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'java.lang.String' to type 'org.apache.juneau.CT_ContextFactory$TestEnum[]'. Value='foo'.")
- .testMap(String.class, String.class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'java.lang.String' to type 'java.util.LinkedHashMap<java.lang.String,java.lang.String>'. Value='foo'.")
- .testMap(Class.class, Class.class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'java.lang.String' to type 'java.util.LinkedHashMap<java.lang.Class,java.lang.Class>'. Value='foo'.")
- ;
- new ConversionTest(pName, "java.lang.String")
- .test(Class.class, "'java.lang.String'")
- ;
- new ConversionTest(pName, "true")
- .test(boolean.class, "true")
- ;
- new ConversionTest(pName, "ONE")
- .test(TestEnum.class, "'ONE'")
- ;
- new ConversionTest(pName, "123")
- .test(int.class, "123")
- ;
-
- //--------------------------------------------------------------------------------
- // enum
- //--------------------------------------------------------------------------------
- new ConversionTest(pName, TestEnum.ONE)
- .test(boolean.class, "false")
- .test(int.class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'org.apache.juneau.CT_ContextFactory$TestEnum' to type 'int'. Value='ONE'.")
- .test(String.class, "'ONE'")
- .test(Class.class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'org.apache.juneau.CT_ContextFactory$TestEnum' to type 'java.lang.Class'. Value='ONE'.")
- .test(TestEnum.class, "'ONE'")
- .test(String[].class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'org.apache.juneau.CT_ContextFactory$TestEnum' to type 'java.lang.String[]'. Value='ONE'.")
- .test(Class[].class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'org.apache.juneau.CT_ContextFactory$TestEnum' to type 'java.lang.Class[]'. Value='ONE'.")
- .test(TestEnum[].class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'org.apache.juneau.CT_ContextFactory$TestEnum' to type 'org.apache.juneau.CT_ContextFactory$TestEnum[]'. Value='ONE'.")
- .testMap(String.class, String.class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'org.apache.juneau.CT_ContextFactory$TestEnum' to type 'java.util.LinkedHashMap<java.lang.String,java.lang.String>'. Value='ONE'.")
- .testMap(Class.class, Class.class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'org.apache.juneau.CT_ContextFactory$TestEnum' to type 'java.util.LinkedHashMap<java.lang.Class,java.lang.Class>'. Value='ONE'.")
- ;
-
- //--------------------------------------------------------------------------------
- // String[]
- //--------------------------------------------------------------------------------
- new ConversionTest(pName, new String[]{"foo","bar"})
- .test(boolean.class, "false")
- .test(int.class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'java.lang.String[]' to type 'int'. Value=['foo','bar'].")
- .test(String.class, "'[\\'foo\\',\\'bar\\']'")
- .test(Class.class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'java.lang.String[]' to type 'java.lang.Class'. Value=['foo','bar'].")
- .test(TestEnum.class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'java.lang.String[]' to type 'org.apache.juneau.CT_ContextFactory$TestEnum'. Value=['foo','bar'].")
- .test(String[].class, "['foo','bar']")
- .test(Class[].class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'java.lang.String[]' to type 'java.lang.Class[]'. Value=['foo','bar'].")
- .test(TestEnum[].class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'java.lang.String[]' to type 'org.apache.juneau.CT_ContextFactory$TestEnum[]'. Value=['foo','bar'].")
- .testMap(String.class, String.class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'java.lang.String[]' to type 'java.util.LinkedHashMap<java.lang.String,java.lang.String>'. Value=['foo','bar'].")
- .testMap(Class.class, Class.class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'java.lang.String[]' to type 'java.util.LinkedHashMap<java.lang.Class,java.lang.Class>'. Value=['foo','bar'].")
- ;
- new ConversionTest(pName, new String[]{"ONE","TWO"})
- .test(TestEnum[].class, "['ONE','TWO']")
- ;
- new ConversionTest(pName, new String[]{"true","false"})
- .test(boolean[].class, "[true,false]")
- ;
- new ConversionTest(pName, new String[]{"java.lang.String","java.lang.Integer"})
- .test(Class[].class, "['java.lang.String','java.lang.Integer']")
- ;
-
- //--------------------------------------------------------------------------------
- // Class[]
- //--------------------------------------------------------------------------------
- new ConversionTest(pName, new Class[]{String.class,Integer.class})
- .test(boolean.class, "false")
- .test(int.class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'java.lang.Class[]' to type 'int'. Value=['java.lang.String','java.lang.Integer'].")
- .test(String.class, "'[\\'java.lang.String\\',\\'java.lang.Integer\\']'")
- .test(Class.class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'java.lang.Class[]' to type 'java.lang.Class'. Value=['java.lang.String','java.lang.Integer'].")
- .test(TestEnum.class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'java.lang.Class[]' to type 'org.apache.juneau.CT_ContextFactory$TestEnum'. Value=['java.lang.String','java.lang.Integer'].")
- .test(String[].class, "['java.lang.String','java.lang.Integer']")
- .test(Class[].class, "['java.lang.String','java.lang.Integer']")
- .test(TestEnum[].class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'java.lang.Class[]' to type 'org.apache.juneau.CT_ContextFactory$TestEnum[]'. Value=['java.lang.String','java.lang.Integer'].")
- .testMap(String.class, String.class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'java.lang.Class[]' to type 'java.util.LinkedHashMap<java.lang.String,java.lang.String>'. Value=['java.lang.String','java.lang.Integer'].")
- .testMap(Class.class, Class.class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'java.lang.Class[]' to type 'java.util.LinkedHashMap<java.lang.Class,java.lang.Class>'. Value=['java.lang.String','java.lang.Integer'].")
- ;
-
- //--------------------------------------------------------------------------------
- // enum[]
- //--------------------------------------------------------------------------------
- new ConversionTest(pName, new TestEnum[]{TestEnum.ONE,TestEnum.TWO})
- .test(boolean.class, "false")
- .test(int.class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'org.apache.juneau.CT_ContextFactory$TestEnum[]' to type 'int'. Value=['ONE','TWO'].")
- .test(String.class, "'[\\'ONE\\',\\'TWO\\']'")
- .test(Class.class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'org.apache.juneau.CT_ContextFactory$TestEnum[]' to type 'java.lang.Class'. Value=['ONE','TWO'].")
- .test(TestEnum.class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'org.apache.juneau.CT_ContextFactory$TestEnum[]' to type 'org.apache.juneau.CT_ContextFactory$TestEnum'. Value=['ONE','TWO'].")
- .test(String[].class, "['ONE','TWO']")
- .test(Class[].class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'org.apache.juneau.CT_ContextFactory$TestEnum[]' to type 'java.lang.Class[]'. Value=['ONE','TWO'].")
- .test(TestEnum[].class, "['ONE','TWO']")
- .testMap(String.class, String.class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'org.apache.juneau.CT_ContextFactory$TestEnum[]' to type 'java.util.LinkedHashMap<java.lang.String,java.lang.String>'. Value=['ONE','TWO'].")
- .testMap(Class.class, Class.class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'org.apache.juneau.CT_ContextFactory$TestEnum[]' to type 'java.util.LinkedHashMap<java.lang.Class,java.lang.Class>'. Value=['ONE','TWO'].")
- ;
-
- //--------------------------------------------------------------------------------
- // Map<String,String>
- //--------------------------------------------------------------------------------
- LinkedHashMap<String,String> m1 = new LinkedHashMap<String,String>();
- m1.put("foo","bar");
- new ConversionTest(pName, m1)
- .test(boolean.class, "false")
- .test(int.class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'java.util.LinkedHashMap' to type 'int'. Value={foo:'bar'}.")
- .test(String.class, "'{foo:\\'bar\\'}'")
- .test(Class.class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'java.util.LinkedHashMap' to type 'java.lang.Class'. Value={foo:'bar'}.")
- .test(TestEnum.class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'java.util.LinkedHashMap' to type 'org.apache.juneau.CT_ContextFactory$TestEnum'. Value={foo:'bar'}.")
- .test(String[].class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'java.util.LinkedHashMap' to type 'java.lang.String[]'. Value={foo:'bar'}.")
- .test(Class[].class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'java.util.LinkedHashMap' to type 'java.lang.Class[]'. Value={foo:'bar'}.")
- .test(TestEnum[].class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'java.util.LinkedHashMap' to type 'org.apache.juneau.CT_ContextFactory$TestEnum[]'. Value={foo:'bar'}.")
- .testMap(String.class, String.class, "{foo:'bar'}")
- .testMap(Class.class, Class.class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'java.util.LinkedHashMap' to type 'java.util.LinkedHashMap<java.lang.Class,java.lang.Class>'. Value={foo:'bar'}.")
- ;
-
- //--------------------------------------------------------------------------------
- // Map<Class,Class>
- //--------------------------------------------------------------------------------
- LinkedHashMap<Class,Class> m2 = new LinkedHashMap<Class,Class>();
- m2.put(String.class, Integer.class);
- new ConversionTest(pName, m2)
- .test(boolean.class, "false")
- .test(int.class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'java.util.LinkedHashMap' to type 'int'. Value={'java.lang.String':'java.lang.Integer'}.")
- .test(String.class, "'{\\'java.lang.String\\':\\'java.lang.Integer\\'}'")
- .test(Class.class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'java.util.LinkedHashMap' to type 'java.lang.Class'. Value={'java.lang.String':'java.lang.Integer'}.")
- .test(TestEnum.class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'java.util.LinkedHashMap' to type 'org.apache.juneau.CT_ContextFactory$TestEnum'. Value={'java.lang.String':'java.lang.Integer'}.")
- .test(String[].class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'java.util.LinkedHashMap' to type 'java.lang.String[]'. Value={'java.lang.String':'java.lang.Integer'}.")
- .test(Class[].class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'java.util.LinkedHashMap' to type 'java.lang.Class[]'. Value={'java.lang.String':'java.lang.Integer'}.")
- .test(TestEnum[].class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'java.util.LinkedHashMap' to type 'org.apache.juneau.CT_ContextFactory$TestEnum[]'. Value={'java.lang.String':'java.lang.Integer'}.")
- .testMap(String.class, String.class, "{'java.lang.String':'java.lang.Integer'}")
- .testMap(Class.class, Class.class, "{'java.lang.String':'java.lang.Integer'}")
- ;
-
- //--------------------------------------------------------------------------------
- // Namespace
- //--------------------------------------------------------------------------------
- final Namespace n = new Namespace("foo","bar");
- new ConversionTest(pName, n)
- .test(String.class, "'{name:\\'foo\\',uri:\\'bar\\'}'")
- .test(Namespace.class, "{name:'foo',uri:'bar'}");
-
- //--------------------------------------------------------------------------------
- // Namespace[]
- //--------------------------------------------------------------------------------
- new ConversionTest(pName, new Namespace[]{n})
- .test(String.class, "'[{name:\\'foo\\',uri:\\'bar\\'}]'")
- .test(Namespace[].class, "[{name:'foo',uri:'bar'}]");
-
- //--------------------------------------------------------------------------------
- // Map<Namespace,Namespace>
- //--------------------------------------------------------------------------------
- new ConversionTest(pName, new LinkedHashMap<Namespace,Namespace>(){{put(n,n);}})
- .testMap(Namespace.class, Namespace.class, "{'{name:\\'foo\\',uri:\\'bar\\'}':{name:'foo',uri:'bar'}}")
- .testMap(String.class, String.class, "{'{name:\\'foo\\',uri:\\'bar\\'}':'{name:\\'foo\\',uri:\\'bar\\'}'}");
- }
-
- //====================================================================================================
- // Conversions on set properties
- //====================================================================================================
- @Test
- @SuppressWarnings({ "serial" })
- public void testConversionsOnSetProperties() throws Exception {
- String pName = "A.a.set";
-
- //--------------------------------------------------------------------------------
- // boolean
- //--------------------------------------------------------------------------------
- new ConversionTest(pName, true)
- .test(boolean.class, "false")
- .test(int.class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'int'. Value=[true].")
- .test(String.class, "'[true]'")
- .test(Class.class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'java.lang.Class'. Value=[true].")
- .test(TestEnum.class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'org.apache.juneau.CT_ContextFactory$TestEnum'. Value=[true].")
- .test(String[].class, "['true']")
- .test(Class[].class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'java.lang.Class[]'. Value=[true].")
- .test(TestEnum[].class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'org.apache.juneau.CT_ContextFactory$TestEnum[]'. Value=[true].")
- .testMap(String.class, String.class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'java.util.LinkedHashMap<java.lang.String,java.lang.String>'. Value=[true].")
- .testMap(Class.class, Class.class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'java.util.LinkedHashMap<java.lang.Class,java.lang.Class>'. Value=[true].")
- ;
-
- //--------------------------------------------------------------------------------
- // int
- //--------------------------------------------------------------------------------
- new ConversionTest(pName, 123)
- .test(boolean.class, "false")
- .test(int.class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'int'. Value=[123].")
- .test(String.class, "'[123]'")
- .test(Class.class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'java.lang.Class'. Value=[123].")
- .test(TestEnum.class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'org.apache.juneau.CT_ContextFactory$TestEnum'. Value=[123].")
- .test(String[].class, "['123']")
- .test(Class[].class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'java.lang.Class[]'. Value=[123].")
- .test(TestEnum[].class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'org.apache.juneau.CT_ContextFactory$TestEnum[]'. Value=[123].")
- .testMap(String.class, String.class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'java.util.LinkedHashMap<java.lang.String,java.lang.String>'. Value=[123].")
- .testMap(Class.class, Class.class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'java.util.LinkedHashMap<java.lang.Class,java.lang.Class>'. Value=[123].")
- ;
-
- //--------------------------------------------------------------------------------
- // Class
- //--------------------------------------------------------------------------------
- new ConversionTest(pName, String.class)
- .test(boolean.class, "false")
- .test(int.class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'int'. Value=['java.lang.String'].")
- .test(String.class, "'[\\'java.lang.String\\']'")
- .test(Class.class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'java.lang.Class'. Value=['java.lang.String'].")
- .test(TestEnum.class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'org.apache.juneau.CT_ContextFactory$TestEnum'. Value=['java.lang.String'].")
- .test(String[].class, "['java.lang.String']")
- .test(Class[].class, "['java.lang.String']")
- .test(TestEnum[].class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'org.apache.juneau.CT_ContextFactory$TestEnum[]'. Value=['java.lang.String'].")
- .testMap(String.class, String.class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'java.util.LinkedHashMap<java.lang.String,java.lang.String>'. Value=['java.lang.String'].")
- .testMap(Class.class, Class.class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'java.util.LinkedHashMap<java.lang.Class,java.lang.Class>'. Value=['java.lang.String'].")
- ;
-
- //--------------------------------------------------------------------------------
- // String
- //--------------------------------------------------------------------------------
- new ConversionTest(pName, "foo")
- .test(boolean.class, "false")
- .test(int.class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'int'. Value=['foo'].")
- .test(String.class, "'[\\'foo\\']'")
- .test(Class.class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'java.lang.Class'. Value=['foo'].")
- .test(TestEnum.class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'org.apache.juneau.CT_ContextFactory$TestEnum'. Value=['foo'].")
- .test(String[].class, "['foo']")
- .test(Class[].class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'java.lang.Class[]'. Value=['foo'].")
- .test(TestEnum[].class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'org.apache.juneau.CT_ContextFactory$TestEnum[]'. Value=['foo'].")
- .testMap(String.class, String.class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'java.util.LinkedHashMap<java.lang.String,java.lang.String>'. Value=['foo'].")
- .testMap(Class.class, Class.class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'java.util.LinkedHashMap<java.lang.Class,java.lang.Class>'. Value=['foo'].")
- ;
- new ConversionTest(pName, Arrays.asList("java.lang.String"))
- .test(Class[].class, "['java.lang.String']")
- ;
- new ConversionTest(pName, Arrays.asList("true"))
- .test(boolean[].class, "[true]")
- ;
- new ConversionTest(pName, Arrays.asList("ONE"))
- .test(TestEnum[].class, "['ONE']")
- ;
- new ConversionTest(pName, Arrays.asList("123"))
- .test(int[].class, "[123]")
- ;
-
- //--------------------------------------------------------------------------------
- // enum
- //--------------------------------------------------------------------------------
- new ConversionTest(pName, TestEnum.ONE)
- .test(boolean.class, "false")
- .test(int.class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'int'. Value=['ONE'].")
- .test(String.class, "'[\\'ONE\\']'")
- .test(Class.class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'java.lang.Class'. Value=['ONE'].")
- .test(TestEnum.class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'org.apache.juneau.CT_ContextFactory$TestEnum'. Value=['ONE'].")
- .test(String[].class, "['ONE']")
- .test(Class[].class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'java.lang.Class[]'. Value=['ONE'].")
- .test(TestEnum[].class, "['ONE']")
- .testMap(String.class, String.class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'java.util.LinkedHashMap<java.lang.String,java.lang.String>'. Value=['ONE'].")
- .testMap(Class.class, Class.class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'java.util.LinkedHashMap<java.lang.Class,java.lang.Class>'. Value=['ONE'].")
- ;
-
- //--------------------------------------------------------------------------------
- // String[]
- //--------------------------------------------------------------------------------
- new ConversionTest(pName, new String[]{"foo","bar"})
- .test(boolean.class, "false")
- .test(int.class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'int'. Value=['bar','foo'].")
- .test(String.class, "'[\\'bar\\',\\'foo\\']'")
- .test(Class.class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'java.lang.Class'. Value=['bar','foo'].")
- .test(TestEnum.class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'org.apache.juneau.CT_ContextFactory$TestEnum'. Value=['bar','foo'].")
- .test(String[].class, "['bar','foo']")
- .test(Class[].class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'java.lang.Class[]'. Value=['bar','foo'].")
- .test(TestEnum[].class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'org.apache.juneau.CT_ContextFactory$TestEnum[]'. Value=['bar','foo'].")
- .testMap(String.class, String.class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'java.util.LinkedHashMap<java.lang.String,java.lang.String>'. Value=['bar','foo'].")
- .testMap(Class.class, Class.class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'java.util.LinkedHashMap<java.lang.Class,java.lang.Class>'. Value=['bar','foo'].")
- ;
- new ConversionTest(pName, new String[]{"ONE","TWO"})
- .test(TestEnum[].class, "['ONE','TWO']")
- ;
- new ConversionTest(pName, new String[]{"true","false"})
- .test(boolean[].class, "[false,true]")
- ;
- new ConversionTest(pName, new String[]{"java.lang.String","java.lang.Integer"})
- .test(Class[].class, "['java.lang.Integer','java.lang.String']")
- ;
-
- //--------------------------------------------------------------------------------
- // Class[]
- //--------------------------------------------------------------------------------
- new ConversionTest(pName, new Class[]{String.class,Integer.class})
- .test(boolean.class, "false")
- .test(int.class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'int'. Value=['java.lang.Integer','java.lang.String'].")
- .test(String.class, "'[\\'java.lang.Integer\\',\\'java.lang.String\\']'")
- .test(Class.class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'java.lang.Class'. Value=['java.lang.Integer','java.lang.String'].")
- .test(TestEnum.class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'org.apache.juneau.CT_ContextFactory$TestEnum'. Value=['java.lang.Integer','java.lang.String'].")
- .test(String[].class, "['java.lang.Integer','java.lang.String']")
- .test(Class[].class, "['java.lang.Integer','java.lang.String']")
- .test(TestEnum[].class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'org.apache.juneau.CT_ContextFactory$TestEnum[]'. Value=['java.lang.Integer','java.lang.String'].")
- .testMap(String.class, String.class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'java.util.LinkedHashMap<java.lang.String,java.lang.String>'. Value=['java.lang.Integer','java.lang.String'].")
- .testMap(Class.class, Class.class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'java.util.LinkedHashMap<java.lang.Class,java.lang.Class>'. Value=['java.lang.Integer','java.lang.String'].")
- ;
-
- //--------------------------------------------------------------------------------
- // enum[]
- //--------------------------------------------------------------------------------
- new ConversionTest(pName, new TestEnum[]{TestEnum.ONE,TestEnum.TWO})
- .test(boolean.class, "false")
- .test(int.class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'int'. Value=['ONE','TWO'].")
- .test(String.class, "'[\\'ONE\\',\\'TWO\\']'")
- .test(Class.class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'java.lang.Class'. Value=['ONE','TWO'].")
- .test(TestEnum.class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'org.apache.juneau.CT_ContextFactory$TestEnum'. Value=['ONE','TWO'].")
- .test(String[].class, "['ONE','TWO']")
- .test(Class[].class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'java.lang.Class[]'. Value=['ONE','TWO'].")
- .test(TestEnum[].class, "['ONE','TWO']")
- .testMap(String.class, String.class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'java.util.LinkedHashMap<java.lang.String,java.lang.String>'. Value=['ONE','TWO'].")
- .testMap(Class.class, Class.class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'java.util.LinkedHashMap<java.lang.Class,java.lang.Class>'. Value=['ONE','TWO'].")
- ;
-
- //--------------------------------------------------------------------------------
- // Map<String,String>
- //--------------------------------------------------------------------------------
- LinkedHashMap<String,String> m1 = new LinkedHashMap<String,String>();
- m1.put("foo","bar");
- new ConversionTest(pName, m1)
- .test(boolean.class, "false")
- .test(int.class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'int'. Value=[{foo:'bar'}].")
- .test(String.class, "'[{foo:\\'bar\\'}]'")
- .test(Class.class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'java.lang.Class'. Value=[{foo:'bar'}].")
- .test(TestEnum.class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'org.apache.juneau.CT_ContextFactory$TestEnum'. Value=[{foo:'bar'}].")
- .test(String[].class, "['{foo:\\'bar\\'}']")
- .test(Class[].class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'java.lang.Class[]'. Value=[{foo:'bar'}].")
- .test(TestEnum[].class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'org.apache.juneau.CT_ContextFactory$TestEnum[]'. Value=[{foo:'bar'}].")
- .testMap(String.class, String.class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'java.util.LinkedHashMap<java.lang.String,java.lang.String>'. Value=[{foo:'bar'}].")
- .testMap(Class.class, Class.class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'java.util.LinkedHashMap<java.lang.Class,java.lang.Class>'. Value=[{foo:'bar'}].")
- ;
-
- //--------------------------------------------------------------------------------
- // Map<Class,Class>
- //--------------------------------------------------------------------------------
- LinkedHashMap<Class,Class> m2 = new LinkedHashMap<Class,Class>();
- m2.put(String.class, Integer.class);
- new ConversionTest(pName, m2)
- .test(boolean.class, "false")
- .test(int.class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'int'. Value=[{'java.lang.String':'java.lang.Integer'}].")
- .test(String.class, "'[{\\'java.lang.String\\':\\'java.lang.Integer\\'}]'")
- .test(Class.class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'java.lang.Class'. Value=[{'java.lang.String':'java.lang.Integer'}].")
- .test(TestEnum.class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'org.apache.juneau.CT_ContextFactory$TestEnum'. Value=[{'java.lang.String':'java.lang.Integer'}].")
- .test(String[].class, "['{\\'java.lang.String\\':\\'java.lang.Integer\\'}']")
- .test(Class[].class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'java.lang.Class[]'. Value=[{'java.lang.String':'java.lang.Integer'}].")
- .test(TestEnum[].class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'org.apache.juneau.CT_ContextFactory$TestEnum[]'. Value=[{'java.lang.String':'java.lang.Integer'}].")
- .testMap(String.class, String.class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'java.util.LinkedHashMap<java.lang.String,java.lang.String>'. Value=[{'java.lang.String':'java.lang.Integer'}].")
- .testMap(Class.class, Class.class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'java.util.LinkedHashMap<java.lang.Class,java.lang.Class>'. Value=[{'java.lang.String':'java.lang.Integer'}].")
- ;
-
- //--------------------------------------------------------------------------------
- // Namespace
- //--------------------------------------------------------------------------------
- final Namespace n = new Namespace("foo","bar");
- new ConversionTest(pName, Arrays.asList(n))
- .test(String.class, "'[{name:\\'foo\\',uri:\\'bar\\'}]'")
- .test(Namespace.class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'org.apache.juneau.xml.Namespace'. Value=[{name:'foo',uri:'bar'}].");
-
- //--------------------------------------------------------------------------------
- // Namespace[]
- //--------------------------------------------------------------------------------
- new ConversionTest(pName, new Namespace[]{n})
- .test(String.class, "'[{name:\\'foo\\',uri:\\'bar\\'}]'")
- .test(Namespace[].class, "[{name:'foo',uri:'bar'}]");
-
- //--------------------------------------------------------------------------------
- // Map<Namespace,Namespace>
- //--------------------------------------------------------------------------------
- new ConversionTest(pName, new LinkedHashMap<Namespace,Namespace>(){{put(n,n);}})
- .testMap(Namespace.class, Namespace.class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'java.util.LinkedHashMap<org.apache.juneau.xml.Namespace,org.apache.juneau.xml.Namespace>'. Value=[{'{name:\\'foo\\',uri:\\'bar\\'}':{name:'foo',uri:'bar'}}].")
- .testMap(String.class, String.class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'java.util.LinkedHashMap<java.lang.String,java.lang.String>'. Value=[{'{name:\\'foo\\',uri:\\'bar\\'}':{name:'foo',uri:'bar'}}].");
- }
-
-
- //====================================================================================================
- // Conversions on map properties
- //====================================================================================================
- @Test
- @SuppressWarnings({ "serial" })
- public void testConversionsOnMapProperties() throws Exception {
- String pName = "A.a.map";
-
- //--------------------------------------------------------------------------------
- // boolean
- //--------------------------------------------------------------------------------
- new ConversionTest(pName, true)
- .test(boolean.class, "Cannot put value true (java.lang.Boolean) to property 'A.a.map' (MAP).")
- ;
-
- //--------------------------------------------------------------------------------
- // int
- //--------------------------------------------------------------------------------
- new ConversionTest(pName, 123)
- .test(int.class, "Cannot put value 123 (java.lang.Integer) to property 'A.a.map' (MAP).")
- ;
-
- //--------------------------------------------------------------------------------
- // Class
- //--------------------------------------------------------------------------------
- new ConversionTest(pName, String.class)
- .test(Class.class, "Cannot put value 'java.lang.String' (java.lang.Class) to property 'A.a.map' (MAP).")
- ;
-
- //--------------------------------------------------------------------------------
- // String
- //--------------------------------------------------------------------------------
- new ConversionTest(pName, "foo")
- .test(String.class, "Cannot put value 'foo' (java.lang.String) to property 'A.a.map' (MAP).")
- ;
-
- //--------------------------------------------------------------------------------
- // enum
- //--------------------------------------------------------------------------------
- new ConversionTest(pName, TestEnum.ONE)
- .test(TestEnum.class, "Cannot put value 'ONE' (org.apache.juneau.CT_ContextFactory$TestEnum) to property 'A.a.map' (MAP).")
- ;
-
- //--------------------------------------------------------------------------------
- // String[]
- //--------------------------------------------------------------------------------
- new ConversionTest(pName, new String[]{"foo","bar"})
- .test(String[].class, "Cannot put value ['foo','bar'] (java.lang.String[]) to property 'A.a.map' (MAP).")
- ;
-
- //--------------------------------------------------------------------------------
- // Class[]
- //--------------------------------------------------------------------------------
- new ConversionTest(pName, new Class[]{String.class,Integer.class})
- .test(Class[].class, "Cannot put value ['java.lang.String','java.lang.Integer'] (java.lang.Class[]) to property 'A.a.map' (MAP).")
- ;
-
- //--------------------------------------------------------------------------------
- // enum[]
- //--------------------------------------------------------------------------------
- new ConversionTest(pName, new TestEnum[]{TestEnum.ONE,TestEnum.TWO})
- .test(TestEnum[].class, "Cannot put value ['ONE','TWO'] (org.apache.juneau.CT_ContextFactory$TestEnum[]) to property 'A.a.map' (MAP).")
- ;
-
- //--------------------------------------------------------------------------------
- // Map<String,String>
- //--------------------------------------------------------------------------------
- LinkedHashMap<String,String> m1 = new LinkedHashMap<String,String>();
- m1.put("foo","bar");
- new ConversionTest(pName, m1)
- .test(boolean.class, "false")
- .test(int.class, "Could not retrieve config property 'A.a.map'. Invalid data conversion from type 'java.util.Collections$SynchronizedMap' to type 'int'. Value={foo:'bar'}.")
- .test(String.class, "'{foo:\\'bar\\'}'")
- .test(Class.class, "Could not retrieve config property 'A.a.map'. Invalid data conversion from type 'java.util.Collections$SynchronizedMap' to type 'java.lang.Class'. Value={foo:'bar'}.")
- .test(TestEnum.class, "Could not retrieve config property 'A.a.map'. Invalid data conversion from type 'java.util.Collections$SynchronizedMap' to type 'org.apache.juneau.CT_ContextFactory$TestEnum'. Value={foo:'bar'}.")
- .test(String[].class, "Could not retrieve config property 'A.a.map'. Invalid data conversion from type 'java.util.Collections$SynchronizedMap' to type 'java.lang.String[]'. Value={foo:'bar'}.")
- .test(Class[].class, "Could not retrieve config property 'A.a.map'. Invalid data conversion from type 'java.util.Collections$SynchronizedMap' to type 'java.lang.Class[]'. Value={foo:'bar'}.")
- .test(TestEnum[].class, "Could not retrieve config property 'A.a.map'. Invalid data conversion from type 'java.util.Collections$SynchronizedMap' to type 'org.apache.juneau.CT_ContextFactory$TestEnum[]'. Value={foo:'bar'}.")
- .testMap(String.class, String.class, "{foo:'bar'}")
- .testMap(Class.class, Class.class, "Could not retrieve config property 'A.a.map'. Invalid data conversion from type 'java.util.Collections$SynchronizedMap' to type 'java.util.LinkedHashMap<java.lang.Class,java.lang.Class>'. Value={foo:'bar'}.")
- ;
-
- //--------------------------------------------------------------------------------
- // Map<Class,Class>
- //--------------------------------------------------------------------------------
- LinkedHashMap<Class,Class> m2 = new LinkedHashMap<Class,Class>();
- m2.put(String.class, Integer.class);
- new ConversionTest(pName, m2)
- .test(boolean.class, "false")
- .test(int.class, "Could not retrieve config property 'A.a.map'. Invalid data conversion from type 'java.util.Collections$SynchronizedMap' to type 'int'. Value={'java.lang.String':'java.lang.Integer'}.")
- .test(String.class, "'{\\'java.lang.String\\':\\'java.lang.Integer\\'}'")
- .test(Class.class, "Could not retrieve config property 'A.a.map'. Invalid data conversion from type 'java.util.Collections$SynchronizedMap' to type 'java.lang.Class'. Value={'java.lang.String':'java.lang.Integer'}.")
- .test(TestEnum.class, "Could not retrieve config property 'A.a.map'. Invalid data conversion from type 'java.util.Collections$SynchronizedMap' to type 'org.apache.juneau.CT_ContextFactory$TestEnum'. Value={'java.lang.String':'java.lang.Integer'}.")
- .test(String[].class, "Could not retrieve config property 'A.a.map'. Invalid data conversion from type 'java.util.Collections$SynchronizedMap' to type 'java.lang.String[]'. Value={'java.lang.String':'java.lang.Integer'}.")
- .test(Class[].class, "Could not retrieve config property 'A.a.map'. Invalid data conversion from type 'java.util.Collections$SynchronizedMap' to type 'java.lang.Class[]'. Value={'java.lang.String':'java.lang.Integer'}.")
- .test(TestEnum[].class, "Could not retrieve config property 'A.a.map'. Invalid data conversion from type 'java.util.Collections$SynchronizedMap' to type 'org.apache.juneau.CT_ContextFactory$TestEnum[]'. Value={'java.lang.String':'java.lang.Integer'}.")
- .testMap(String.class, String.class, "{'java.lang.String':'java.lang.Integer'}")
- .testMap(Class.class, Class.class, "{'java.lang.String':'java.lang.Integer'}")
- ;
-
- //--------------------------------------------------------------------------------
- // Namespace
- //--------------------------------------------------------------------------------
- final Namespace n = new Namespace("foo","bar");
- new ConversionTest(pName, Arrays.asList(n))
- .test(String.class, "Cannot put value [{name:'foo',uri:'bar'}] (java.util.Arrays$ArrayList) to property 'A.a.map' (MAP).")
- ;
-
- //--------------------------------------------------------------------------------
- // Namespace[]
- //--------------------------------------------------------------------------------
- new ConversionTest(pName, new Namespace[]{n})
- .test(String.class, "Cannot put value [{name:'foo',uri:'bar'}] (org.apache.juneau.xml.Namespace[]) to property 'A.a.map' (MAP).")
- ;
-
- //--------------------------------------------------------------------------------
- // Map<Namespace,Namespace>
- //--------------------------------------------------------------------------------
- new ConversionTest(pName, new LinkedHashMap<Namespace,Namespace>(){{put(n,n);}})
- .testMap(Namespace.class, Namespace.class, "{'{name:\\'foo\\',uri:\\'bar\\'}':{name:'foo',uri:'bar'}}")
- .testMap(String.class, String.class, "{'{name:\\'foo\\',uri:\\'bar\\'}':'{name:\\'foo\\',uri:\\'bar\\'}'}");
- }
-
- public enum TestEnum {
- ONE,TWO,TREE;
- }
-
- //====================================================================================================
- // testSystemPropertyDefaults()
- //====================================================================================================
- @Test
- public void testSystemPropertyDefaults() {
- System.setProperty("Foo.f1", "true");
- System.setProperty("Foo.f2", "123");
- System.setProperty("Foo.f3", "TWO");
-
- ContextFactory f = ContextFactory.create();
-
- assertObjectEquals("true", f.getProperty("Foo.f1", boolean.class, false));
- assertObjectEquals("123", f.getProperty("Foo.f2", int.class, 0));
- assertObjectEquals("'TWO'", f.getProperty("Foo.f3", TestEnum.class, TestEnum.ONE));
-
- f.setProperty("Foo.f1", false);
- f.setProperty("Foo.f2", 456);
- f.setProperty("Foo.f3", TestEnum.TREE);
-
- assertObjectEquals("false", f.getProperty("Foo.f1", boolean.class, false));
- assertObjectEquals("456", f.getProperty("Foo.f2", int.class, 0));
- assertObjectEquals("'TREE'", f.getProperty("Foo.f3", TestEnum.class, TestEnum.ONE));
- }
-
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/CT_DataConversionTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/CT_DataConversionTest.java b/org.apache.juneau/src/test/java/org/apache/juneau/CT_DataConversionTest.java
deleted file mode 100755
index f8a1190..0000000
--- a/org.apache.juneau/src/test/java/org/apache/juneau/CT_DataConversionTest.java
+++ /dev/null
@@ -1,145 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau;
-
-import static org.junit.Assert.*;
-
-import java.util.*;
-
-import org.apache.juneau.transforms.*;
-import org.junit.*;
-
-@SuppressWarnings({"unchecked","rawtypes"})
-public class CT_DataConversionTest {
-
- //====================================================================================================
- // testBasic
- //====================================================================================================
- @Test
- public void testBasic() throws Exception {
- ObjectMap m = new ObjectMap();
-
- // *** Number ***
- m.put("x", 123);
- assertEquals((int)m.getInt("x"), 123);
- assertEquals((long)m.getLong("x"), 123);
-
- // *** Boolean ***
- m.put("x", true);
- assertEquals((boolean)m.getBoolean("x"), true);
-
- // *** Null ***
- m.put("x", null);
- assertNull(m.getString("x"));
- assertNull(m.getInt("x"));
- assertNull(m.getLong("x"));
- assertNull(m.getBoolean("x"));
- assertNull(m.getMap("x"));
- assertNull(m.getObjectMap("x"));
- assertNull(m.getList("x"));
- assertNull(m.getObjectList("x"));
-
- // *** Map ***
- m.put("x", new HashMap());
- assertEquals(m.getString("x"), "{}");
-
- // *** ObjectMap ***
- m.put("x", new ObjectMap("{foo:123}"));
- assertEquals(m.getString("x"), "{foo:123}");
-
- // *** Collection ***
- Set s = new HashSet();
- s.add(123);
- m.put("x", s);
- assertEquals(m.getString("x"), "[123]");
-
- // *** ObjectList ***
- m.put("x", new ObjectList("[123]"));
- assertEquals(m.getString("x"), "[123]");
- assertEquals(m.getList("x").size(), 1);
- assertEquals(m.getObjectList("x").size(), 1);
-
- // *** Array ***
- m.put("x", new Integer[]{123});
- assertEquals(m.getString("x"), "[123]");
- assertEquals(m.getList("x").size(), 1);
- assertEquals(m.getObjectList("x").size(), 1);
-
- // *** Enum ***
- m.put("x", TestEnum.ENUM2);
- assertEquals(m.getString("x"), "ENUM2");
- assertFalse(m.getBoolean("x"));
- try {
- m.getMap("x");
- fail("Invalid conversion from Enum to Map");
- } catch (InvalidDataConversionException e) {}
- try {
- m.getObjectMap("x");
- fail("Invalid conversion from Enum to ObjectMap");
- } catch (InvalidDataConversionException e) {}
-
- // *** Not a bean ***
- m.put("x", new NotABean("foo"));
- assertEquals(m.getString("x"), "foo");
- try {
- m.getInt("x");
- fail("Invalid conversion from NotABean to Integer");
- } catch (InvalidDataConversionException e) {}
- try {
- m.getLong("x");
- fail("Invalid conversion from NotABean to Long");
- } catch (InvalidDataConversionException e) {}
- assertFalse(m.getBoolean("x"));
- try {
- m.getMap("x");
- fail("Invalid conversion from NotABean to Map");
- } catch (InvalidDataConversionException e) {}
- try {
- m.getObjectMap("x");
- fail("Invalid conversion from NotABean to ObjectMap");
- } catch (InvalidDataConversionException e) {}
-
- }
-
- public enum TestEnum {
- ENUM0, ENUM1, ENUM2
- }
-
- public class NotABean {
- private String arg;
-
- public NotABean(String arg) {
- this.arg = arg;
- }
-
- @Override /* Object */
- public String toString() {
- return arg;
- }
- }
-
- //====================================================================================================
- // Data conversions with object transforms.
- //====================================================================================================
- @Test
- public void testObjectTransforms() throws Exception {
- String s = "Jan 12, 2001";
- BeanContext bc = ContextFactory.create().addTransforms(CalendarTransform.Medium.class).getBeanContext();
- Calendar c = bc.convertToType(s, GregorianCalendar.class);
- assertEquals(2001, c.get(Calendar.YEAR));
- c = bc.convertToType(s, Calendar.class);
- assertEquals(2001, c.get(Calendar.YEAR));
- s = bc.convertToType(c, String.class);
- assertEquals("Jan 12, 2001", s);
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/CT_IgnoredClasses.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/CT_IgnoredClasses.java b/org.apache.juneau/src/test/java/org/apache/juneau/CT_IgnoredClasses.java
deleted file mode 100755
index fd6fe7b..0000000
--- a/org.apache.juneau/src/test/java/org/apache/juneau/CT_IgnoredClasses.java
+++ /dev/null
@@ -1,72 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau;
-
-import static org.apache.juneau.BeanContext.*;
-import static org.apache.juneau.TestUtils.*;
-import static org.junit.Assert.*;
-import static org.junit.Assume.*;
-
-import java.io.*;
-
-import org.apache.juneau.json.*;
-import org.junit.*;
-
-public class CT_IgnoredClasses {
-
- //====================================================================================================
- // testFilesRenderedAsStrings
- //====================================================================================================
- @Test
- public void testFilesRenderedAsStrings() throws Exception {
- assumeTrue(System.getProperty("os.name").toLowerCase().startsWith("win"));
- // Files should be rendered as strings.
- File f = new File("C:/temp");
- assertObjectEquals("'C:\\\\temp'", f);
- }
-
- //====================================================================================================
- // testIgnorePackages
- //====================================================================================================
- @Test
- public void testIgnorePackages() throws Exception {
- A a = new A();
- JsonSerializer s = new JsonSerializer.Simple();
- assertEquals("{f1:'isBean'}", s.serialize(a));
- s.setProperty(BEAN_notBeanPackages_add, "org.apache.juneau");
- assertEquals("'isNotBean'", s.serialize(a));
- s.setProperty(BEAN_notBeanPackages_remove, "org.apache.juneau");
- assertEquals("{f1:'isBean'}", s.serialize(a));
- s.setProperty(BEAN_notBeanPackages_add, "org.apache.juneau.*");
- assertEquals("'isNotBean'", s.serialize(a));
- s.setProperty(BEAN_notBeanPackages_remove, "org.apache.juneau.*");
- assertEquals("{f1:'isBean'}", s.serialize(a));
- s.setProperty(BEAN_notBeanPackages_add, "org.apache.juneau.*");
- assertEquals("'isNotBean'", s.serialize(a));
- s.setProperty(BEAN_notBeanPackages_remove, "org.apache.juneau.*");
- assertEquals("{f1:'isBean'}", s.serialize(a));
- s.setProperty(BEAN_notBeanPackages_add, "org.apache.juneau");
- assertEquals("'isNotBean'", s.serialize(a));
- s.setProperty(BEAN_notBeanPackages_add, "org.apache.juneau.x");
- assertEquals("'isNotBean'", s.serialize(a));
- }
-
- public static class A {
- public String f1 = "isBean";
- @Override /* Object */
- public String toString() {
- return "isNotBean";
- }
- }
- // TODO - Ignored packages.
-}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/CT_JacocoDummy.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/CT_JacocoDummy.java b/org.apache.juneau/src/test/java/org/apache/juneau/CT_JacocoDummy.java
deleted file mode 100755
index dd73f6a..0000000
--- a/org.apache.juneau/src/test/java/org/apache/juneau/CT_JacocoDummy.java
+++ /dev/null
@@ -1,49 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau;
-
-import java.lang.reflect.*;
-
-import org.apache.juneau.ini.*;
-import org.apache.juneau.internal.*;
-import org.apache.juneau.jena.*;
-import org.apache.juneau.transform.*;
-import org.apache.juneau.xml.annotation.*;
-import org.junit.*;
-
-
-public class CT_JacocoDummy {
-
- //====================================================================================================
- // Dummy code to add test coverage in Jacoco.
- //====================================================================================================
- @Test
- public void accessPrivateConstructorsOnStaticUtilityClasses() throws Exception {
-
- Class<?>[] classes = new Class[] {
- StringUtils.class, ArrayUtils.class, ClassUtils.class, CollectionUtils.class, ConfigUtils.class
- };
-
- for (Class<?> c : classes) {
- Constructor<?> c1 = c.getDeclaredConstructor();
- c1.setAccessible(true);
- c1.newInstance();
- }
-
- ConfigFileFormat.valueOf(ConfigFileFormat.INI.toString());
- Transform.TransformType.valueOf(Transform.TransformType.POJO.toString());
- RdfCollectionFormat.valueOf(RdfCollectionFormat.DEFAULT.toString());
- XmlFormat.valueOf(XmlFormat.NORMAL.toString());
- Visibility.valueOf(Visibility.DEFAULT.toString());
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/CT_ObjectList.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/CT_ObjectList.java b/org.apache.juneau/src/test/java/org/apache/juneau/CT_ObjectList.java
deleted file mode 100755
index 1be1fe6..0000000
--- a/org.apache.juneau/src/test/java/org/apache/juneau/CT_ObjectList.java
+++ /dev/null
@@ -1,98 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau;
-
-import static org.junit.Assert.*;
-
-import java.util.*;
-
-import org.junit.*;
-
-public class CT_ObjectList {
-
- //====================================================================================================
- // testBasic
- //====================================================================================================
- @Test
- public void testBasic() throws Exception {
-
- assertEquals(
- "['A','B','C']",
- new ObjectList((Object[])new String[]{"A","B","C"}).toString()
- );
-
- assertEquals(
- "['A','B','C']",
- new ObjectList("A","B","C").toString()
- );
-
- assertEquals(
- "['A','B','C']",
- new ObjectList(Arrays.asList(new String[]{"A","B","C"})).toString()
- );
- }
-
- //====================================================================================================
- // testIterateAs
- //====================================================================================================
- @Test
- public void testIterateAs() throws Exception {
-
- // Iterate over a list of ObjectMaps.
- ObjectList l = new ObjectList("[{foo:'bar'},{baz:123}]");
- Iterator<ObjectMap> i1 = l.elements(ObjectMap.class).iterator();
- assertEquals("bar", i1.next().getString("foo"));
- assertEquals(123, (int)i1.next().getInt("baz"));
-
- // Iterate over a list of ints.
- l = new ObjectList("[1,2,3]");
- Iterator<Integer> i2 = l.elements(Integer.class).iterator();
- assertEquals(1, (int)i2.next());
- assertEquals(2, (int)i2.next());
- assertEquals(3, (int)i2.next());
-
- // Iterate over a list of beans.
- // Automatically converts to beans.
- l = new ObjectList("[{name:'John Smith',age:45}]");
- Iterator<Person> i3 = l.elements(Person.class).iterator();
- assertEquals("John Smith", i3.next().name);
- }
-
- public static class Person {
- public String name;
- public int age;
- }
-
- //====================================================================================================
- // testAtMethods
- //====================================================================================================
- @Test
- public void testAtMethods() throws Exception {
- ObjectList l = new ObjectList("[{foo:'bar'},{baz:123}]");
- String r;
-
- r = l.getAt(String.class, "0/foo");
- assertEquals("bar", r);
-
- l.putAt("0/foo", "bing");
- r = l.getAt(String.class, "0/foo");
- assertEquals("bing", r);
-
- l.postAt("", new ObjectMap("{a:'b'}"));
- r = l.getAt(String.class, "2/a");
- assertEquals("b", r);
-
- l.deleteAt("2");
- assertEquals("[{foo:'bing'},{baz:123}]", l.toString());
- }
-}
\ No newline at end of file
[27/44] incubator-juneau git commit: Rename CT_* testcases.
Posted by ja...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/ContextFactoryTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/ContextFactoryTest.java b/org.apache.juneau/src/test/java/org/apache/juneau/ContextFactoryTest.java
new file mode 100644
index 0000000..f0aff8e
--- /dev/null
+++ b/org.apache.juneau/src/test/java/org/apache/juneau/ContextFactoryTest.java
@@ -0,0 +1,823 @@
+/***************************************************************************************************************************
+ * 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.juneau;
+
+import static org.apache.juneau.TestUtils.*;
+import static org.junit.Assert.*;
+
+import java.util.*;
+
+import org.apache.juneau.xml.*;
+import org.junit.*;
+
+
+@SuppressWarnings({"rawtypes"})
+public class ContextFactoryTest {
+
+ //====================================================================================================
+ // testSimpleProperties()
+ //====================================================================================================
+ @Test
+ public void testSimpleProperties() {
+ ContextFactory f = ContextFactory.create();
+
+ f.setProperty("A.f1", "1");
+ f.setProperty("A.f2", "2");
+
+ assertObjectEquals("{'A.f1':'1','A.f2':'2'}", f.getPropertyMap("A").asMap());
+
+ f.setProperty("B.f3", "3");
+ f.setProperty("A.f1", String.class);
+ f.setProperty("A.f2", 4);
+
+ assertObjectEquals("{'A.f1':'java.lang.String','A.f2':4}", f.getPropertyMap("A").asMap());
+
+ f.setProperty("A.f2", null);
+ f.setProperty("A.f2", null);
+ assertObjectEquals("{'A.f1':'java.lang.String'}", f.getPropertyMap("A").asMap());
+
+ try {
+ f.setProperty(null, null);
+ fail("Exception expected");
+ } catch (Exception e) {
+ assertEquals("Invalid property name specified: 'null'", e.getMessage());
+ }
+
+ try {
+ f.addToProperty("A.f1", "foo");
+ fail("Exception expected");
+ } catch (Exception e) {
+ assertEquals("Cannot add value 'foo' (java.lang.String) to property 'A.f1' (SIMPLE).", e.getMessage());
+ }
+
+ try {
+ f.removeFromProperty("A.f1", "foo");
+ fail("Exception expected");
+ } catch (Exception e) {
+ assertEquals("Cannot remove value 'foo' (java.lang.String) from property 'A.f1' (SIMPLE).", e.getMessage());
+ }
+
+ try {
+ f.putToProperty("A.f1", "foo", "bar");
+ fail("Exception expected");
+ } catch (Exception e) {
+ assertEquals("Cannot put value 'foo'(java.lang.String)->'bar'(java.lang.String) to property 'A.f1' (SIMPLE).", e.getMessage());
+ }
+
+ try {
+ f.putToProperty("A.f1", "foo");
+ fail("Exception expected");
+ } catch (Exception e) {
+ assertEquals("Cannot put value 'foo' (java.lang.String) to property 'A.f1' (SIMPLE).", e.getMessage());
+ }
+ }
+
+ //====================================================================================================
+ // testSetProperties()
+ //====================================================================================================
+ @Test
+ public void testSetProperties() {
+ ContextFactory f = ContextFactory.create();
+ String key = "A.f1.set";
+
+ f.setProperty(key, Arrays.asList(2,3,1));
+ assertObjectEquals("[1,2,3]", f.getProperty(key, int[].class, null));
+
+ f.addToProperty(key, 0);
+ f.addToProperty(key, new int[]{4,5});
+ assertObjectEquals("[0,1,2,3,4,5]", f.getProperty(key, int[].class, null));
+ f.addToProperty(key, new HashSet<String>(Arrays.asList("6","7")));
+ assertObjectEquals("[0,1,2,3,4,5,6,7]", f.getProperty(key, int[].class, null));
+ f.addToProperty(key, new int[]{4,5});
+ assertObjectEquals("[0,1,2,3,4,5,6,7]", f.getProperty(key, int[].class, null));
+
+ f.removeFromProperty(key, 4);
+ f.removeFromProperty(key, new HashSet<String>(Arrays.asList("1")));
+ f.removeFromProperty(key, new String[]{"2","9"});
+ assertObjectEquals("[0,3,5,6,7]", f.getProperty(key, int[].class, null));
+ assertObjectEquals("['0','3','5','6','7']", f.getProperty(key, String[].class, null));
+
+ f.setProperty(key, Arrays.asList("foo","bar","baz"));
+ assertObjectEquals("['bar','baz','foo']", f.getProperty(key, String[].class, null));
+
+ f.setProperty(key, "[1,2,3]");
+ assertObjectEquals("[1,2,3]", f.getProperty(key, int[].class, null));
+
+ f.setProperty(key, "['1','2','3']");
+ assertObjectEquals("[1,2,3]", f.getProperty(key, int[].class, null));
+
+ try {
+ f.putToProperty("A.f1.set", "foo");
+ fail("Exception expected");
+ } catch (Exception e) {
+ assertEquals("Cannot put value 'foo' (java.lang.String) to property 'A.f1.set' (SET).", e.getMessage());
+ }
+
+ try {
+ f.putToProperty("A.f1.set", "foo", "bar");
+ fail("Exception expected");
+ } catch (Exception e) {
+ assertEquals("Cannot put value 'foo'(java.lang.String)->'bar'(java.lang.String) to property 'A.f1.set' (SET).", e.getMessage());
+ }
+ }
+
+ //====================================================================================================
+ // testListProperties()
+ //====================================================================================================
+ @Test
+ public void testListProperties() {
+ ContextFactory f = ContextFactory.create();
+ String key = "A.f1.list";
+
+ f.setProperty(key, Arrays.asList(2,3,1));
+ assertObjectEquals("[2,3,1]", f.getProperty(key, int[].class, null));
+
+ f.addToProperty(key, 0);
+ f.addToProperty(key, new int[]{4,5});
+ assertObjectEquals("[4,5,0,2,3,1]", f.getProperty(key, int[].class, null));
+ f.addToProperty(key, new TreeSet<String>(Arrays.asList("6","7")));
+ assertObjectEquals("[6,7,4,5,0,2,3,1]", f.getProperty(key, int[].class, null));
+ f.addToProperty(key, new int[]{4,5});
+ assertObjectEquals("[4,5,6,7,0,2,3,1]", f.getProperty(key, int[].class, null));
+
+ f.removeFromProperty(key, 4);
+ f.removeFromProperty(key, new HashSet<String>(Arrays.asList("1")));
+ f.removeFromProperty(key, new String[]{"2","9"});
+ assertObjectEquals("[5,6,7,0,3]", f.getProperty(key, int[].class, null));
+ assertObjectEquals("['5','6','7','0','3']", f.getProperty(key, String[].class, null));
+
+ f.setProperty(key, Arrays.asList("foo","bar","baz"));
+ assertObjectEquals("['foo','bar','baz']", f.getProperty(key, String[].class, null));
+ }
+
+ //====================================================================================================
+ // testMapProperties()
+ //====================================================================================================
+ @SuppressWarnings("serial")
+ @Test
+ public void testMapProperties() {
+ ContextFactory f = ContextFactory.create();
+ String key = "A.f1.map";
+
+ f.setProperty(key, new HashMap<String,String>(){{put("1","1");put("3","3");put("2","2");}});
+ assertObjectEquals("{'1':1,'2':2,'3':3}", f.getMap(key, Integer.class, Integer.class, null));
+
+ f.setProperty(key, "{'1':1,'2':2,'3':3}");
+ assertObjectEquals("{'1':1,'2':2,'3':3}", f.getMap(key, Integer.class, Integer.class, null));
+
+ f.putToProperty(key, "{'3':4,'4':5,'5':6}");
+ assertObjectEquals("{'1':1,'2':2,'3':4,'4':5,'5':6}", f.getMap(key, Integer.class, Integer.class, null));
+ }
+
+ //====================================================================================================
+ // Hash code and comparison
+ //====================================================================================================
+ @SuppressWarnings({ "serial" })
+ @Test
+ public void testHashCodes() throws Exception {
+ ContextFactory f1 = ContextFactory.create();
+ f1.setProperty("A.a", 1);
+ f1.setProperty("A.b", true);
+ f1.setProperty("A.c", String.class);
+ f1.setProperty("A.d.set", new Object[]{1, true, String.class});
+ f1.setProperty("A.e.map", new HashMap<Object,Object>(){{put(true,true);put(1,1);put(String.class,String.class);}});
+
+ ContextFactory f2 = ContextFactory.create();
+ f2.setProperty("A.e.map", new HashMap<Object,Object>(){{put("1","1");put("true","true");put("java.lang.String","java.lang.String");}});
+ f2.setProperty("A.d.set", new Object[]{"true","1","java.lang.String"});
+ f2.setProperty("A.c", "java.lang.String");
+ f2.setProperty("A.b", "true");
+ f2.setProperty("A.a", "1");
+
+ ContextFactory.PropertyMap p1 = f1.getPropertyMap("A");
+ ContextFactory.PropertyMap p2 = f2.getPropertyMap("A");
+ assertEquals(p1.hashCode(), p2.hashCode());
+ }
+
+ @SuppressWarnings("unchecked")
+ private static class ConversionTest {
+ ContextFactory config = ContextFactory.create();
+ String pName;
+ Object in;
+
+ private ConversionTest(String pName, Object in) {
+ this.pName = pName;
+ this.in = in;
+ }
+
+ private ConversionTest test(Class c, String expected) {
+ try {
+ config.setProperty(pName, in);
+ assertObjectEquals(expected, config.getProperty(pName, c, null));
+ } catch (Exception x) {
+ assertEquals(expected.toString(), x.getLocalizedMessage());
+ }
+ return this;
+ }
+
+ private ConversionTest testMap(Class k, Class v, String expected) {
+ try {
+ config.setProperty(pName, in);
+ assertObjectEquals(expected, config.getMap(pName, k, v, null));
+ } catch (Exception x) {
+ assertEquals(expected, x.getLocalizedMessage());
+ }
+ return this;
+ }
+ }
+
+ //====================================================================================================
+ // Conversions on simple properties
+ //====================================================================================================
+ @Test
+ @SuppressWarnings({ "serial" })
+ public void testConversionsOnSimpleProperties() throws Exception {
+ String pName = "A.a";
+
+ //--------------------------------------------------------------------------------
+ // boolean
+ //--------------------------------------------------------------------------------
+ new ConversionTest(pName, true)
+ .test(boolean.class, "true")
+ .test(int.class, "1")
+ .test(String.class, "'true'")
+ .test(Class.class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'java.lang.Boolean' to type 'java.lang.Class'. Value=true.")
+ .test(TestEnum.class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'java.lang.Boolean' to type 'org.apache.juneau.ContextFactoryTest$TestEnum'. Value=true.")
+ .test(String[].class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'java.lang.Boolean' to type 'java.lang.String[]'. Value=true.")
+ .test(Class[].class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'java.lang.Boolean' to type 'java.lang.Class[]'. Value=true.")
+ .test(TestEnum[].class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'java.lang.Boolean' to type 'org.apache.juneau.ContextFactoryTest$TestEnum[]'. Value=true.")
+ .testMap(String.class, String.class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'java.lang.Boolean' to type 'java.util.LinkedHashMap<java.lang.String,java.lang.String>'. Value=true.")
+ .testMap(Class.class, Class.class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'java.lang.Boolean' to type 'java.util.LinkedHashMap<java.lang.Class,java.lang.Class>'. Value=true.")
+ ;
+
+ //--------------------------------------------------------------------------------
+ // int
+ //--------------------------------------------------------------------------------
+ new ConversionTest(pName, 123)
+ .test(boolean.class, "true")
+ .test(int.class, "123")
+ .test(String.class, "'123'")
+ .test(Class.class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'java.lang.Integer' to type 'java.lang.Class'. Value=123.")
+ .test(TestEnum.class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'java.lang.Integer' to type 'org.apache.juneau.ContextFactoryTest$TestEnum'. Value=123.")
+ .test(String[].class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'java.lang.Integer' to type 'java.lang.String[]'. Value=123.")
+ .test(Class[].class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'java.lang.Integer' to type 'java.lang.Class[]'. Value=123.")
+ .test(TestEnum[].class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'java.lang.Integer' to type 'org.apache.juneau.ContextFactoryTest$TestEnum[]'. Value=123.")
+ .testMap(String.class, String.class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'java.lang.Integer' to type 'java.util.LinkedHashMap<java.lang.String,java.lang.String>'. Value=123.")
+ .testMap(Class.class, Class.class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'java.lang.Integer' to type 'java.util.LinkedHashMap<java.lang.Class,java.lang.Class>'. Value=123.")
+ ;
+
+ //--------------------------------------------------------------------------------
+ // Class
+ //--------------------------------------------------------------------------------
+ new ConversionTest(pName, String.class)
+ .test(boolean.class, "false")
+ .test(int.class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'java.lang.Class' to type 'int'. Value='java.lang.String'.")
+ .test(String.class, "'java.lang.String'")
+ .test(Class.class, "'java.lang.String'")
+ .test(TestEnum.class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'java.lang.Class' to type 'org.apache.juneau.ContextFactoryTest$TestEnum'. Value='java.lang.String'.")
+ .test(String[].class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'java.lang.Class' to type 'java.lang.String[]'. Value='java.lang.String'.")
+ .test(Class[].class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'java.lang.Class' to type 'java.lang.Class[]'. Value='java.lang.String'.")
+ .test(TestEnum[].class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'java.lang.Class' to type 'org.apache.juneau.ContextFactoryTest$TestEnum[]'. Value='java.lang.String'.")
+ .testMap(String.class, String.class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'java.lang.Class' to type 'java.util.LinkedHashMap<java.lang.String,java.lang.String>'. Value='java.lang.String'.")
+ .testMap(Class.class, Class.class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'java.lang.Class' to type 'java.util.LinkedHashMap<java.lang.Class,java.lang.Class>'. Value='java.lang.String'.")
+ ;
+
+ //--------------------------------------------------------------------------------
+ // String
+ //--------------------------------------------------------------------------------
+ new ConversionTest(pName, "foo")
+ .test(boolean.class, "false")
+ .test(int.class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'java.lang.String' to type 'int'. Value='foo'.")
+ .test(String.class, "'foo'")
+ .test(Class.class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'java.lang.String' to type 'java.lang.Class'. Value='foo'.")
+ .test(TestEnum.class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'java.lang.String' to type 'org.apache.juneau.ContextFactoryTest$TestEnum'. Value='foo'.")
+ .test(String[].class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'java.lang.String' to type 'java.lang.String[]'. Value='foo'.")
+ .test(Class[].class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'java.lang.String' to type 'java.lang.Class[]'. Value='foo'.")
+ .test(TestEnum[].class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'java.lang.String' to type 'org.apache.juneau.ContextFactoryTest$TestEnum[]'. Value='foo'.")
+ .testMap(String.class, String.class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'java.lang.String' to type 'java.util.LinkedHashMap<java.lang.String,java.lang.String>'. Value='foo'.")
+ .testMap(Class.class, Class.class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'java.lang.String' to type 'java.util.LinkedHashMap<java.lang.Class,java.lang.Class>'. Value='foo'.")
+ ;
+ new ConversionTest(pName, "java.lang.String")
+ .test(Class.class, "'java.lang.String'")
+ ;
+ new ConversionTest(pName, "true")
+ .test(boolean.class, "true")
+ ;
+ new ConversionTest(pName, "ONE")
+ .test(TestEnum.class, "'ONE'")
+ ;
+ new ConversionTest(pName, "123")
+ .test(int.class, "123")
+ ;
+
+ //--------------------------------------------------------------------------------
+ // enum
+ //--------------------------------------------------------------------------------
+ new ConversionTest(pName, TestEnum.ONE)
+ .test(boolean.class, "false")
+ .test(int.class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'org.apache.juneau.ContextFactoryTest$TestEnum' to type 'int'. Value='ONE'.")
+ .test(String.class, "'ONE'")
+ .test(Class.class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'org.apache.juneau.ContextFactoryTest$TestEnum' to type 'java.lang.Class'. Value='ONE'.")
+ .test(TestEnum.class, "'ONE'")
+ .test(String[].class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'org.apache.juneau.ContextFactoryTest$TestEnum' to type 'java.lang.String[]'. Value='ONE'.")
+ .test(Class[].class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'org.apache.juneau.ContextFactoryTest$TestEnum' to type 'java.lang.Class[]'. Value='ONE'.")
+ .test(TestEnum[].class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'org.apache.juneau.ContextFactoryTest$TestEnum' to type 'org.apache.juneau.ContextFactoryTest$TestEnum[]'. Value='ONE'.")
+ .testMap(String.class, String.class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'org.apache.juneau.ContextFactoryTest$TestEnum' to type 'java.util.LinkedHashMap<java.lang.String,java.lang.String>'. Value='ONE'.")
+ .testMap(Class.class, Class.class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'org.apache.juneau.ContextFactoryTest$TestEnum' to type 'java.util.LinkedHashMap<java.lang.Class,java.lang.Class>'. Value='ONE'.")
+ ;
+
+ //--------------------------------------------------------------------------------
+ // String[]
+ //--------------------------------------------------------------------------------
+ new ConversionTest(pName, new String[]{"foo","bar"})
+ .test(boolean.class, "false")
+ .test(int.class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'java.lang.String[]' to type 'int'. Value=['foo','bar'].")
+ .test(String.class, "'[\\'foo\\',\\'bar\\']'")
+ .test(Class.class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'java.lang.String[]' to type 'java.lang.Class'. Value=['foo','bar'].")
+ .test(TestEnum.class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'java.lang.String[]' to type 'org.apache.juneau.ContextFactoryTest$TestEnum'. Value=['foo','bar'].")
+ .test(String[].class, "['foo','bar']")
+ .test(Class[].class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'java.lang.String[]' to type 'java.lang.Class[]'. Value=['foo','bar'].")
+ .test(TestEnum[].class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'java.lang.String[]' to type 'org.apache.juneau.ContextFactoryTest$TestEnum[]'. Value=['foo','bar'].")
+ .testMap(String.class, String.class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'java.lang.String[]' to type 'java.util.LinkedHashMap<java.lang.String,java.lang.String>'. Value=['foo','bar'].")
+ .testMap(Class.class, Class.class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'java.lang.String[]' to type 'java.util.LinkedHashMap<java.lang.Class,java.lang.Class>'. Value=['foo','bar'].")
+ ;
+ new ConversionTest(pName, new String[]{"ONE","TWO"})
+ .test(TestEnum[].class, "['ONE','TWO']")
+ ;
+ new ConversionTest(pName, new String[]{"true","false"})
+ .test(boolean[].class, "[true,false]")
+ ;
+ new ConversionTest(pName, new String[]{"java.lang.String","java.lang.Integer"})
+ .test(Class[].class, "['java.lang.String','java.lang.Integer']")
+ ;
+
+ //--------------------------------------------------------------------------------
+ // Class[]
+ //--------------------------------------------------------------------------------
+ new ConversionTest(pName, new Class[]{String.class,Integer.class})
+ .test(boolean.class, "false")
+ .test(int.class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'java.lang.Class[]' to type 'int'. Value=['java.lang.String','java.lang.Integer'].")
+ .test(String.class, "'[\\'java.lang.String\\',\\'java.lang.Integer\\']'")
+ .test(Class.class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'java.lang.Class[]' to type 'java.lang.Class'. Value=['java.lang.String','java.lang.Integer'].")
+ .test(TestEnum.class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'java.lang.Class[]' to type 'org.apache.juneau.ContextFactoryTest$TestEnum'. Value=['java.lang.String','java.lang.Integer'].")
+ .test(String[].class, "['java.lang.String','java.lang.Integer']")
+ .test(Class[].class, "['java.lang.String','java.lang.Integer']")
+ .test(TestEnum[].class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'java.lang.Class[]' to type 'org.apache.juneau.ContextFactoryTest$TestEnum[]'. Value=['java.lang.String','java.lang.Integer'].")
+ .testMap(String.class, String.class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'java.lang.Class[]' to type 'java.util.LinkedHashMap<java.lang.String,java.lang.String>'. Value=['java.lang.String','java.lang.Integer'].")
+ .testMap(Class.class, Class.class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'java.lang.Class[]' to type 'java.util.LinkedHashMap<java.lang.Class,java.lang.Class>'. Value=['java.lang.String','java.lang.Integer'].")
+ ;
+
+ //--------------------------------------------------------------------------------
+ // enum[]
+ //--------------------------------------------------------------------------------
+ new ConversionTest(pName, new TestEnum[]{TestEnum.ONE,TestEnum.TWO})
+ .test(boolean.class, "false")
+ .test(int.class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'org.apache.juneau.ContextFactoryTest$TestEnum[]' to type 'int'. Value=['ONE','TWO'].")
+ .test(String.class, "'[\\'ONE\\',\\'TWO\\']'")
+ .test(Class.class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'org.apache.juneau.ContextFactoryTest$TestEnum[]' to type 'java.lang.Class'. Value=['ONE','TWO'].")
+ .test(TestEnum.class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'org.apache.juneau.ContextFactoryTest$TestEnum[]' to type 'org.apache.juneau.ContextFactoryTest$TestEnum'. Value=['ONE','TWO'].")
+ .test(String[].class, "['ONE','TWO']")
+ .test(Class[].class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'org.apache.juneau.ContextFactoryTest$TestEnum[]' to type 'java.lang.Class[]'. Value=['ONE','TWO'].")
+ .test(TestEnum[].class, "['ONE','TWO']")
+ .testMap(String.class, String.class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'org.apache.juneau.ContextFactoryTest$TestEnum[]' to type 'java.util.LinkedHashMap<java.lang.String,java.lang.String>'. Value=['ONE','TWO'].")
+ .testMap(Class.class, Class.class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'org.apache.juneau.ContextFactoryTest$TestEnum[]' to type 'java.util.LinkedHashMap<java.lang.Class,java.lang.Class>'. Value=['ONE','TWO'].")
+ ;
+
+ //--------------------------------------------------------------------------------
+ // Map<String,String>
+ //--------------------------------------------------------------------------------
+ LinkedHashMap<String,String> m1 = new LinkedHashMap<String,String>();
+ m1.put("foo","bar");
+ new ConversionTest(pName, m1)
+ .test(boolean.class, "false")
+ .test(int.class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'java.util.LinkedHashMap' to type 'int'. Value={foo:'bar'}.")
+ .test(String.class, "'{foo:\\'bar\\'}'")
+ .test(Class.class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'java.util.LinkedHashMap' to type 'java.lang.Class'. Value={foo:'bar'}.")
+ .test(TestEnum.class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'java.util.LinkedHashMap' to type 'org.apache.juneau.ContextFactoryTest$TestEnum'. Value={foo:'bar'}.")
+ .test(String[].class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'java.util.LinkedHashMap' to type 'java.lang.String[]'. Value={foo:'bar'}.")
+ .test(Class[].class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'java.util.LinkedHashMap' to type 'java.lang.Class[]'. Value={foo:'bar'}.")
+ .test(TestEnum[].class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'java.util.LinkedHashMap' to type 'org.apache.juneau.ContextFactoryTest$TestEnum[]'. Value={foo:'bar'}.")
+ .testMap(String.class, String.class, "{foo:'bar'}")
+ .testMap(Class.class, Class.class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'java.util.LinkedHashMap' to type 'java.util.LinkedHashMap<java.lang.Class,java.lang.Class>'. Value={foo:'bar'}.")
+ ;
+
+ //--------------------------------------------------------------------------------
+ // Map<Class,Class>
+ //--------------------------------------------------------------------------------
+ LinkedHashMap<Class,Class> m2 = new LinkedHashMap<Class,Class>();
+ m2.put(String.class, Integer.class);
+ new ConversionTest(pName, m2)
+ .test(boolean.class, "false")
+ .test(int.class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'java.util.LinkedHashMap' to type 'int'. Value={'java.lang.String':'java.lang.Integer'}.")
+ .test(String.class, "'{\\'java.lang.String\\':\\'java.lang.Integer\\'}'")
+ .test(Class.class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'java.util.LinkedHashMap' to type 'java.lang.Class'. Value={'java.lang.String':'java.lang.Integer'}.")
+ .test(TestEnum.class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'java.util.LinkedHashMap' to type 'org.apache.juneau.ContextFactoryTest$TestEnum'. Value={'java.lang.String':'java.lang.Integer'}.")
+ .test(String[].class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'java.util.LinkedHashMap' to type 'java.lang.String[]'. Value={'java.lang.String':'java.lang.Integer'}.")
+ .test(Class[].class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'java.util.LinkedHashMap' to type 'java.lang.Class[]'. Value={'java.lang.String':'java.lang.Integer'}.")
+ .test(TestEnum[].class, "Could not retrieve config property 'A.a'. Invalid data conversion from type 'java.util.LinkedHashMap' to type 'org.apache.juneau.ContextFactoryTest$TestEnum[]'. Value={'java.lang.String':'java.lang.Integer'}.")
+ .testMap(String.class, String.class, "{'java.lang.String':'java.lang.Integer'}")
+ .testMap(Class.class, Class.class, "{'java.lang.String':'java.lang.Integer'}")
+ ;
+
+ //--------------------------------------------------------------------------------
+ // Namespace
+ //--------------------------------------------------------------------------------
+ final Namespace n = new Namespace("foo","bar");
+ new ConversionTest(pName, n)
+ .test(String.class, "'{name:\\'foo\\',uri:\\'bar\\'}'")
+ .test(Namespace.class, "{name:'foo',uri:'bar'}");
+
+ //--------------------------------------------------------------------------------
+ // Namespace[]
+ //--------------------------------------------------------------------------------
+ new ConversionTest(pName, new Namespace[]{n})
+ .test(String.class, "'[{name:\\'foo\\',uri:\\'bar\\'}]'")
+ .test(Namespace[].class, "[{name:'foo',uri:'bar'}]");
+
+ //--------------------------------------------------------------------------------
+ // Map<Namespace,Namespace>
+ //--------------------------------------------------------------------------------
+ new ConversionTest(pName, new LinkedHashMap<Namespace,Namespace>(){{put(n,n);}})
+ .testMap(Namespace.class, Namespace.class, "{'{name:\\'foo\\',uri:\\'bar\\'}':{name:'foo',uri:'bar'}}")
+ .testMap(String.class, String.class, "{'{name:\\'foo\\',uri:\\'bar\\'}':'{name:\\'foo\\',uri:\\'bar\\'}'}");
+ }
+
+ //====================================================================================================
+ // Conversions on set properties
+ //====================================================================================================
+ @Test
+ @SuppressWarnings({ "serial" })
+ public void testConversionsOnSetProperties() throws Exception {
+ String pName = "A.a.set";
+
+ //--------------------------------------------------------------------------------
+ // boolean
+ //--------------------------------------------------------------------------------
+ new ConversionTest(pName, true)
+ .test(boolean.class, "false")
+ .test(int.class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'int'. Value=[true].")
+ .test(String.class, "'[true]'")
+ .test(Class.class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'java.lang.Class'. Value=[true].")
+ .test(TestEnum.class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'org.apache.juneau.ContextFactoryTest$TestEnum'. Value=[true].")
+ .test(String[].class, "['true']")
+ .test(Class[].class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'java.lang.Class[]'. Value=[true].")
+ .test(TestEnum[].class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'org.apache.juneau.ContextFactoryTest$TestEnum[]'. Value=[true].")
+ .testMap(String.class, String.class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'java.util.LinkedHashMap<java.lang.String,java.lang.String>'. Value=[true].")
+ .testMap(Class.class, Class.class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'java.util.LinkedHashMap<java.lang.Class,java.lang.Class>'. Value=[true].")
+ ;
+
+ //--------------------------------------------------------------------------------
+ // int
+ //--------------------------------------------------------------------------------
+ new ConversionTest(pName, 123)
+ .test(boolean.class, "false")
+ .test(int.class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'int'. Value=[123].")
+ .test(String.class, "'[123]'")
+ .test(Class.class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'java.lang.Class'. Value=[123].")
+ .test(TestEnum.class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'org.apache.juneau.ContextFactoryTest$TestEnum'. Value=[123].")
+ .test(String[].class, "['123']")
+ .test(Class[].class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'java.lang.Class[]'. Value=[123].")
+ .test(TestEnum[].class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'org.apache.juneau.ContextFactoryTest$TestEnum[]'. Value=[123].")
+ .testMap(String.class, String.class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'java.util.LinkedHashMap<java.lang.String,java.lang.String>'. Value=[123].")
+ .testMap(Class.class, Class.class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'java.util.LinkedHashMap<java.lang.Class,java.lang.Class>'. Value=[123].")
+ ;
+
+ //--------------------------------------------------------------------------------
+ // Class
+ //--------------------------------------------------------------------------------
+ new ConversionTest(pName, String.class)
+ .test(boolean.class, "false")
+ .test(int.class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'int'. Value=['java.lang.String'].")
+ .test(String.class, "'[\\'java.lang.String\\']'")
+ .test(Class.class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'java.lang.Class'. Value=['java.lang.String'].")
+ .test(TestEnum.class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'org.apache.juneau.ContextFactoryTest$TestEnum'. Value=['java.lang.String'].")
+ .test(String[].class, "['java.lang.String']")
+ .test(Class[].class, "['java.lang.String']")
+ .test(TestEnum[].class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'org.apache.juneau.ContextFactoryTest$TestEnum[]'. Value=['java.lang.String'].")
+ .testMap(String.class, String.class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'java.util.LinkedHashMap<java.lang.String,java.lang.String>'. Value=['java.lang.String'].")
+ .testMap(Class.class, Class.class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'java.util.LinkedHashMap<java.lang.Class,java.lang.Class>'. Value=['java.lang.String'].")
+ ;
+
+ //--------------------------------------------------------------------------------
+ // String
+ //--------------------------------------------------------------------------------
+ new ConversionTest(pName, "foo")
+ .test(boolean.class, "false")
+ .test(int.class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'int'. Value=['foo'].")
+ .test(String.class, "'[\\'foo\\']'")
+ .test(Class.class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'java.lang.Class'. Value=['foo'].")
+ .test(TestEnum.class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'org.apache.juneau.ContextFactoryTest$TestEnum'. Value=['foo'].")
+ .test(String[].class, "['foo']")
+ .test(Class[].class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'java.lang.Class[]'. Value=['foo'].")
+ .test(TestEnum[].class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'org.apache.juneau.ContextFactoryTest$TestEnum[]'. Value=['foo'].")
+ .testMap(String.class, String.class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'java.util.LinkedHashMap<java.lang.String,java.lang.String>'. Value=['foo'].")
+ .testMap(Class.class, Class.class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'java.util.LinkedHashMap<java.lang.Class,java.lang.Class>'. Value=['foo'].")
+ ;
+ new ConversionTest(pName, Arrays.asList("java.lang.String"))
+ .test(Class[].class, "['java.lang.String']")
+ ;
+ new ConversionTest(pName, Arrays.asList("true"))
+ .test(boolean[].class, "[true]")
+ ;
+ new ConversionTest(pName, Arrays.asList("ONE"))
+ .test(TestEnum[].class, "['ONE']")
+ ;
+ new ConversionTest(pName, Arrays.asList("123"))
+ .test(int[].class, "[123]")
+ ;
+
+ //--------------------------------------------------------------------------------
+ // enum
+ //--------------------------------------------------------------------------------
+ new ConversionTest(pName, TestEnum.ONE)
+ .test(boolean.class, "false")
+ .test(int.class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'int'. Value=['ONE'].")
+ .test(String.class, "'[\\'ONE\\']'")
+ .test(Class.class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'java.lang.Class'. Value=['ONE'].")
+ .test(TestEnum.class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'org.apache.juneau.ContextFactoryTest$TestEnum'. Value=['ONE'].")
+ .test(String[].class, "['ONE']")
+ .test(Class[].class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'java.lang.Class[]'. Value=['ONE'].")
+ .test(TestEnum[].class, "['ONE']")
+ .testMap(String.class, String.class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'java.util.LinkedHashMap<java.lang.String,java.lang.String>'. Value=['ONE'].")
+ .testMap(Class.class, Class.class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'java.util.LinkedHashMap<java.lang.Class,java.lang.Class>'. Value=['ONE'].")
+ ;
+
+ //--------------------------------------------------------------------------------
+ // String[]
+ //--------------------------------------------------------------------------------
+ new ConversionTest(pName, new String[]{"foo","bar"})
+ .test(boolean.class, "false")
+ .test(int.class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'int'. Value=['bar','foo'].")
+ .test(String.class, "'[\\'bar\\',\\'foo\\']'")
+ .test(Class.class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'java.lang.Class'. Value=['bar','foo'].")
+ .test(TestEnum.class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'org.apache.juneau.ContextFactoryTest$TestEnum'. Value=['bar','foo'].")
+ .test(String[].class, "['bar','foo']")
+ .test(Class[].class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'java.lang.Class[]'. Value=['bar','foo'].")
+ .test(TestEnum[].class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'org.apache.juneau.ContextFactoryTest$TestEnum[]'. Value=['bar','foo'].")
+ .testMap(String.class, String.class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'java.util.LinkedHashMap<java.lang.String,java.lang.String>'. Value=['bar','foo'].")
+ .testMap(Class.class, Class.class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'java.util.LinkedHashMap<java.lang.Class,java.lang.Class>'. Value=['bar','foo'].")
+ ;
+ new ConversionTest(pName, new String[]{"ONE","TWO"})
+ .test(TestEnum[].class, "['ONE','TWO']")
+ ;
+ new ConversionTest(pName, new String[]{"true","false"})
+ .test(boolean[].class, "[false,true]")
+ ;
+ new ConversionTest(pName, new String[]{"java.lang.String","java.lang.Integer"})
+ .test(Class[].class, "['java.lang.Integer','java.lang.String']")
+ ;
+
+ //--------------------------------------------------------------------------------
+ // Class[]
+ //--------------------------------------------------------------------------------
+ new ConversionTest(pName, new Class[]{String.class,Integer.class})
+ .test(boolean.class, "false")
+ .test(int.class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'int'. Value=['java.lang.Integer','java.lang.String'].")
+ .test(String.class, "'[\\'java.lang.Integer\\',\\'java.lang.String\\']'")
+ .test(Class.class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'java.lang.Class'. Value=['java.lang.Integer','java.lang.String'].")
+ .test(TestEnum.class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'org.apache.juneau.ContextFactoryTest$TestEnum'. Value=['java.lang.Integer','java.lang.String'].")
+ .test(String[].class, "['java.lang.Integer','java.lang.String']")
+ .test(Class[].class, "['java.lang.Integer','java.lang.String']")
+ .test(TestEnum[].class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'org.apache.juneau.ContextFactoryTest$TestEnum[]'. Value=['java.lang.Integer','java.lang.String'].")
+ .testMap(String.class, String.class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'java.util.LinkedHashMap<java.lang.String,java.lang.String>'. Value=['java.lang.Integer','java.lang.String'].")
+ .testMap(Class.class, Class.class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'java.util.LinkedHashMap<java.lang.Class,java.lang.Class>'. Value=['java.lang.Integer','java.lang.String'].")
+ ;
+
+ //--------------------------------------------------------------------------------
+ // enum[]
+ //--------------------------------------------------------------------------------
+ new ConversionTest(pName, new TestEnum[]{TestEnum.ONE,TestEnum.TWO})
+ .test(boolean.class, "false")
+ .test(int.class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'int'. Value=['ONE','TWO'].")
+ .test(String.class, "'[\\'ONE\\',\\'TWO\\']'")
+ .test(Class.class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'java.lang.Class'. Value=['ONE','TWO'].")
+ .test(TestEnum.class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'org.apache.juneau.ContextFactoryTest$TestEnum'. Value=['ONE','TWO'].")
+ .test(String[].class, "['ONE','TWO']")
+ .test(Class[].class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'java.lang.Class[]'. Value=['ONE','TWO'].")
+ .test(TestEnum[].class, "['ONE','TWO']")
+ .testMap(String.class, String.class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'java.util.LinkedHashMap<java.lang.String,java.lang.String>'. Value=['ONE','TWO'].")
+ .testMap(Class.class, Class.class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'java.util.LinkedHashMap<java.lang.Class,java.lang.Class>'. Value=['ONE','TWO'].")
+ ;
+
+ //--------------------------------------------------------------------------------
+ // Map<String,String>
+ //--------------------------------------------------------------------------------
+ LinkedHashMap<String,String> m1 = new LinkedHashMap<String,String>();
+ m1.put("foo","bar");
+ new ConversionTest(pName, m1)
+ .test(boolean.class, "false")
+ .test(int.class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'int'. Value=[{foo:'bar'}].")
+ .test(String.class, "'[{foo:\\'bar\\'}]'")
+ .test(Class.class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'java.lang.Class'. Value=[{foo:'bar'}].")
+ .test(TestEnum.class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'org.apache.juneau.ContextFactoryTest$TestEnum'. Value=[{foo:'bar'}].")
+ .test(String[].class, "['{foo:\\'bar\\'}']")
+ .test(Class[].class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'java.lang.Class[]'. Value=[{foo:'bar'}].")
+ .test(TestEnum[].class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'org.apache.juneau.ContextFactoryTest$TestEnum[]'. Value=[{foo:'bar'}].")
+ .testMap(String.class, String.class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'java.util.LinkedHashMap<java.lang.String,java.lang.String>'. Value=[{foo:'bar'}].")
+ .testMap(Class.class, Class.class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'java.util.LinkedHashMap<java.lang.Class,java.lang.Class>'. Value=[{foo:'bar'}].")
+ ;
+
+ //--------------------------------------------------------------------------------
+ // Map<Class,Class>
+ //--------------------------------------------------------------------------------
+ LinkedHashMap<Class,Class> m2 = new LinkedHashMap<Class,Class>();
+ m2.put(String.class, Integer.class);
+ new ConversionTest(pName, m2)
+ .test(boolean.class, "false")
+ .test(int.class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'int'. Value=[{'java.lang.String':'java.lang.Integer'}].")
+ .test(String.class, "'[{\\'java.lang.String\\':\\'java.lang.Integer\\'}]'")
+ .test(Class.class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'java.lang.Class'. Value=[{'java.lang.String':'java.lang.Integer'}].")
+ .test(TestEnum.class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'org.apache.juneau.ContextFactoryTest$TestEnum'. Value=[{'java.lang.String':'java.lang.Integer'}].")
+ .test(String[].class, "['{\\'java.lang.String\\':\\'java.lang.Integer\\'}']")
+ .test(Class[].class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'java.lang.Class[]'. Value=[{'java.lang.String':'java.lang.Integer'}].")
+ .test(TestEnum[].class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'org.apache.juneau.ContextFactoryTest$TestEnum[]'. Value=[{'java.lang.String':'java.lang.Integer'}].")
+ .testMap(String.class, String.class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'java.util.LinkedHashMap<java.lang.String,java.lang.String>'. Value=[{'java.lang.String':'java.lang.Integer'}].")
+ .testMap(Class.class, Class.class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'java.util.LinkedHashMap<java.lang.Class,java.lang.Class>'. Value=[{'java.lang.String':'java.lang.Integer'}].")
+ ;
+
+ //--------------------------------------------------------------------------------
+ // Namespace
+ //--------------------------------------------------------------------------------
+ final Namespace n = new Namespace("foo","bar");
+ new ConversionTest(pName, Arrays.asList(n))
+ .test(String.class, "'[{name:\\'foo\\',uri:\\'bar\\'}]'")
+ .test(Namespace.class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'org.apache.juneau.xml.Namespace'. Value=[{name:'foo',uri:'bar'}].");
+
+ //--------------------------------------------------------------------------------
+ // Namespace[]
+ //--------------------------------------------------------------------------------
+ new ConversionTest(pName, new Namespace[]{n})
+ .test(String.class, "'[{name:\\'foo\\',uri:\\'bar\\'}]'")
+ .test(Namespace[].class, "[{name:'foo',uri:'bar'}]");
+
+ //--------------------------------------------------------------------------------
+ // Map<Namespace,Namespace>
+ //--------------------------------------------------------------------------------
+ new ConversionTest(pName, new LinkedHashMap<Namespace,Namespace>(){{put(n,n);}})
+ .testMap(Namespace.class, Namespace.class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'java.util.LinkedHashMap<org.apache.juneau.xml.Namespace,org.apache.juneau.xml.Namespace>'. Value=[{'{name:\\'foo\\',uri:\\'bar\\'}':{name:'foo',uri:'bar'}}].")
+ .testMap(String.class, String.class, "Could not retrieve config property 'A.a.set'. Invalid data conversion from type 'java.util.concurrent.ConcurrentSkipListSet' to type 'java.util.LinkedHashMap<java.lang.String,java.lang.String>'. Value=[{'{name:\\'foo\\',uri:\\'bar\\'}':{name:'foo',uri:'bar'}}].");
+ }
+
+
+ //====================================================================================================
+ // Conversions on map properties
+ //====================================================================================================
+ @Test
+ @SuppressWarnings({ "serial" })
+ public void testConversionsOnMapProperties() throws Exception {
+ String pName = "A.a.map";
+
+ //--------------------------------------------------------------------------------
+ // boolean
+ //--------------------------------------------------------------------------------
+ new ConversionTest(pName, true)
+ .test(boolean.class, "Cannot put value true (java.lang.Boolean) to property 'A.a.map' (MAP).")
+ ;
+
+ //--------------------------------------------------------------------------------
+ // int
+ //--------------------------------------------------------------------------------
+ new ConversionTest(pName, 123)
+ .test(int.class, "Cannot put value 123 (java.lang.Integer) to property 'A.a.map' (MAP).")
+ ;
+
+ //--------------------------------------------------------------------------------
+ // Class
+ //--------------------------------------------------------------------------------
+ new ConversionTest(pName, String.class)
+ .test(Class.class, "Cannot put value 'java.lang.String' (java.lang.Class) to property 'A.a.map' (MAP).")
+ ;
+
+ //--------------------------------------------------------------------------------
+ // String
+ //--------------------------------------------------------------------------------
+ new ConversionTest(pName, "foo")
+ .test(String.class, "Cannot put value 'foo' (java.lang.String) to property 'A.a.map' (MAP).")
+ ;
+
+ //--------------------------------------------------------------------------------
+ // enum
+ //--------------------------------------------------------------------------------
+ new ConversionTest(pName, TestEnum.ONE)
+ .test(TestEnum.class, "Cannot put value 'ONE' (org.apache.juneau.ContextFactoryTest$TestEnum) to property 'A.a.map' (MAP).")
+ ;
+
+ //--------------------------------------------------------------------------------
+ // String[]
+ //--------------------------------------------------------------------------------
+ new ConversionTest(pName, new String[]{"foo","bar"})
+ .test(String[].class, "Cannot put value ['foo','bar'] (java.lang.String[]) to property 'A.a.map' (MAP).")
+ ;
+
+ //--------------------------------------------------------------------------------
+ // Class[]
+ //--------------------------------------------------------------------------------
+ new ConversionTest(pName, new Class[]{String.class,Integer.class})
+ .test(Class[].class, "Cannot put value ['java.lang.String','java.lang.Integer'] (java.lang.Class[]) to property 'A.a.map' (MAP).")
+ ;
+
+ //--------------------------------------------------------------------------------
+ // enum[]
+ //--------------------------------------------------------------------------------
+ new ConversionTest(pName, new TestEnum[]{TestEnum.ONE,TestEnum.TWO})
+ .test(TestEnum[].class, "Cannot put value ['ONE','TWO'] (org.apache.juneau.ContextFactoryTest$TestEnum[]) to property 'A.a.map' (MAP).")
+ ;
+
+ //--------------------------------------------------------------------------------
+ // Map<String,String>
+ //--------------------------------------------------------------------------------
+ LinkedHashMap<String,String> m1 = new LinkedHashMap<String,String>();
+ m1.put("foo","bar");
+ new ConversionTest(pName, m1)
+ .test(boolean.class, "false")
+ .test(int.class, "Could not retrieve config property 'A.a.map'. Invalid data conversion from type 'java.util.Collections$SynchronizedMap' to type 'int'. Value={foo:'bar'}.")
+ .test(String.class, "'{foo:\\'bar\\'}'")
+ .test(Class.class, "Could not retrieve config property 'A.a.map'. Invalid data conversion from type 'java.util.Collections$SynchronizedMap' to type 'java.lang.Class'. Value={foo:'bar'}.")
+ .test(TestEnum.class, "Could not retrieve config property 'A.a.map'. Invalid data conversion from type 'java.util.Collections$SynchronizedMap' to type 'org.apache.juneau.ContextFactoryTest$TestEnum'. Value={foo:'bar'}.")
+ .test(String[].class, "Could not retrieve config property 'A.a.map'. Invalid data conversion from type 'java.util.Collections$SynchronizedMap' to type 'java.lang.String[]'. Value={foo:'bar'}.")
+ .test(Class[].class, "Could not retrieve config property 'A.a.map'. Invalid data conversion from type 'java.util.Collections$SynchronizedMap' to type 'java.lang.Class[]'. Value={foo:'bar'}.")
+ .test(TestEnum[].class, "Could not retrieve config property 'A.a.map'. Invalid data conversion from type 'java.util.Collections$SynchronizedMap' to type 'org.apache.juneau.ContextFactoryTest$TestEnum[]'. Value={foo:'bar'}.")
+ .testMap(String.class, String.class, "{foo:'bar'}")
+ .testMap(Class.class, Class.class, "Could not retrieve config property 'A.a.map'. Invalid data conversion from type 'java.util.Collections$SynchronizedMap' to type 'java.util.LinkedHashMap<java.lang.Class,java.lang.Class>'. Value={foo:'bar'}.")
+ ;
+
+ //--------------------------------------------------------------------------------
+ // Map<Class,Class>
+ //--------------------------------------------------------------------------------
+ LinkedHashMap<Class,Class> m2 = new LinkedHashMap<Class,Class>();
+ m2.put(String.class, Integer.class);
+ new ConversionTest(pName, m2)
+ .test(boolean.class, "false")
+ .test(int.class, "Could not retrieve config property 'A.a.map'. Invalid data conversion from type 'java.util.Collections$SynchronizedMap' to type 'int'. Value={'java.lang.String':'java.lang.Integer'}.")
+ .test(String.class, "'{\\'java.lang.String\\':\\'java.lang.Integer\\'}'")
+ .test(Class.class, "Could not retrieve config property 'A.a.map'. Invalid data conversion from type 'java.util.Collections$SynchronizedMap' to type 'java.lang.Class'. Value={'java.lang.String':'java.lang.Integer'}.")
+ .test(TestEnum.class, "Could not retrieve config property 'A.a.map'. Invalid data conversion from type 'java.util.Collections$SynchronizedMap' to type 'org.apache.juneau.ContextFactoryTest$TestEnum'. Value={'java.lang.String':'java.lang.Integer'}.")
+ .test(String[].class, "Could not retrieve config property 'A.a.map'. Invalid data conversion from type 'java.util.Collections$SynchronizedMap' to type 'java.lang.String[]'. Value={'java.lang.String':'java.lang.Integer'}.")
+ .test(Class[].class, "Could not retrieve config property 'A.a.map'. Invalid data conversion from type 'java.util.Collections$SynchronizedMap' to type 'java.lang.Class[]'. Value={'java.lang.String':'java.lang.Integer'}.")
+ .test(TestEnum[].class, "Could not retrieve config property 'A.a.map'. Invalid data conversion from type 'java.util.Collections$SynchronizedMap' to type 'org.apache.juneau.ContextFactoryTest$TestEnum[]'. Value={'java.lang.String':'java.lang.Integer'}.")
+ .testMap(String.class, String.class, "{'java.lang.String':'java.lang.Integer'}")
+ .testMap(Class.class, Class.class, "{'java.lang.String':'java.lang.Integer'}")
+ ;
+
+ //--------------------------------------------------------------------------------
+ // Namespace
+ //--------------------------------------------------------------------------------
+ final Namespace n = new Namespace("foo","bar");
+ new ConversionTest(pName, Arrays.asList(n))
+ .test(String.class, "Cannot put value [{name:'foo',uri:'bar'}] (java.util.Arrays$ArrayList) to property 'A.a.map' (MAP).")
+ ;
+
+ //--------------------------------------------------------------------------------
+ // Namespace[]
+ //--------------------------------------------------------------------------------
+ new ConversionTest(pName, new Namespace[]{n})
+ .test(String.class, "Cannot put value [{name:'foo',uri:'bar'}] (org.apache.juneau.xml.Namespace[]) to property 'A.a.map' (MAP).")
+ ;
+
+ //--------------------------------------------------------------------------------
+ // Map<Namespace,Namespace>
+ //--------------------------------------------------------------------------------
+ new ConversionTest(pName, new LinkedHashMap<Namespace,Namespace>(){{put(n,n);}})
+ .testMap(Namespace.class, Namespace.class, "{'{name:\\'foo\\',uri:\\'bar\\'}':{name:'foo',uri:'bar'}}")
+ .testMap(String.class, String.class, "{'{name:\\'foo\\',uri:\\'bar\\'}':'{name:\\'foo\\',uri:\\'bar\\'}'}");
+ }
+
+ public enum TestEnum {
+ ONE,TWO,TREE;
+ }
+
+ //====================================================================================================
+ // testSystemPropertyDefaults()
+ //====================================================================================================
+ @Test
+ public void testSystemPropertyDefaults() {
+ System.setProperty("Foo.f1", "true");
+ System.setProperty("Foo.f2", "123");
+ System.setProperty("Foo.f3", "TWO");
+
+ ContextFactory f = ContextFactory.create();
+
+ assertObjectEquals("true", f.getProperty("Foo.f1", boolean.class, false));
+ assertObjectEquals("123", f.getProperty("Foo.f2", int.class, 0));
+ assertObjectEquals("'TWO'", f.getProperty("Foo.f3", TestEnum.class, TestEnum.ONE));
+
+ f.setProperty("Foo.f1", false);
+ f.setProperty("Foo.f2", 456);
+ f.setProperty("Foo.f3", TestEnum.TREE);
+
+ assertObjectEquals("false", f.getProperty("Foo.f1", boolean.class, false));
+ assertObjectEquals("456", f.getProperty("Foo.f2", int.class, 0));
+ assertObjectEquals("'TREE'", f.getProperty("Foo.f3", TestEnum.class, TestEnum.ONE));
+ }
+
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/DataConversionTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/DataConversionTest.java b/org.apache.juneau/src/test/java/org/apache/juneau/DataConversionTest.java
new file mode 100755
index 0000000..0882444
--- /dev/null
+++ b/org.apache.juneau/src/test/java/org/apache/juneau/DataConversionTest.java
@@ -0,0 +1,145 @@
+/***************************************************************************************************************************
+ * 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.juneau;
+
+import static org.junit.Assert.*;
+
+import java.util.*;
+
+import org.apache.juneau.transforms.*;
+import org.junit.*;
+
+@SuppressWarnings({"unchecked","rawtypes"})
+public class DataConversionTest {
+
+ //====================================================================================================
+ // testBasic
+ //====================================================================================================
+ @Test
+ public void testBasic() throws Exception {
+ ObjectMap m = new ObjectMap();
+
+ // *** Number ***
+ m.put("x", 123);
+ assertEquals((int)m.getInt("x"), 123);
+ assertEquals((long)m.getLong("x"), 123);
+
+ // *** Boolean ***
+ m.put("x", true);
+ assertEquals((boolean)m.getBoolean("x"), true);
+
+ // *** Null ***
+ m.put("x", null);
+ assertNull(m.getString("x"));
+ assertNull(m.getInt("x"));
+ assertNull(m.getLong("x"));
+ assertNull(m.getBoolean("x"));
+ assertNull(m.getMap("x"));
+ assertNull(m.getObjectMap("x"));
+ assertNull(m.getList("x"));
+ assertNull(m.getObjectList("x"));
+
+ // *** Map ***
+ m.put("x", new HashMap());
+ assertEquals(m.getString("x"), "{}");
+
+ // *** ObjectMap ***
+ m.put("x", new ObjectMap("{foo:123}"));
+ assertEquals(m.getString("x"), "{foo:123}");
+
+ // *** Collection ***
+ Set s = new HashSet();
+ s.add(123);
+ m.put("x", s);
+ assertEquals(m.getString("x"), "[123]");
+
+ // *** ObjectList ***
+ m.put("x", new ObjectList("[123]"));
+ assertEquals(m.getString("x"), "[123]");
+ assertEquals(m.getList("x").size(), 1);
+ assertEquals(m.getObjectList("x").size(), 1);
+
+ // *** Array ***
+ m.put("x", new Integer[]{123});
+ assertEquals(m.getString("x"), "[123]");
+ assertEquals(m.getList("x").size(), 1);
+ assertEquals(m.getObjectList("x").size(), 1);
+
+ // *** Enum ***
+ m.put("x", TestEnum.ENUM2);
+ assertEquals(m.getString("x"), "ENUM2");
+ assertFalse(m.getBoolean("x"));
+ try {
+ m.getMap("x");
+ fail("Invalid conversion from Enum to Map");
+ } catch (InvalidDataConversionException e) {}
+ try {
+ m.getObjectMap("x");
+ fail("Invalid conversion from Enum to ObjectMap");
+ } catch (InvalidDataConversionException e) {}
+
+ // *** Not a bean ***
+ m.put("x", new NotABean("foo"));
+ assertEquals(m.getString("x"), "foo");
+ try {
+ m.getInt("x");
+ fail("Invalid conversion from NotABean to Integer");
+ } catch (InvalidDataConversionException e) {}
+ try {
+ m.getLong("x");
+ fail("Invalid conversion from NotABean to Long");
+ } catch (InvalidDataConversionException e) {}
+ assertFalse(m.getBoolean("x"));
+ try {
+ m.getMap("x");
+ fail("Invalid conversion from NotABean to Map");
+ } catch (InvalidDataConversionException e) {}
+ try {
+ m.getObjectMap("x");
+ fail("Invalid conversion from NotABean to ObjectMap");
+ } catch (InvalidDataConversionException e) {}
+
+ }
+
+ public enum TestEnum {
+ ENUM0, ENUM1, ENUM2
+ }
+
+ public class NotABean {
+ private String arg;
+
+ public NotABean(String arg) {
+ this.arg = arg;
+ }
+
+ @Override /* Object */
+ public String toString() {
+ return arg;
+ }
+ }
+
+ //====================================================================================================
+ // Data conversions with object transforms.
+ //====================================================================================================
+ @Test
+ public void testObjectTransforms() throws Exception {
+ String s = "Jan 12, 2001";
+ BeanContext bc = ContextFactory.create().addTransforms(CalendarTransform.Medium.class).getBeanContext();
+ Calendar c = bc.convertToType(s, GregorianCalendar.class);
+ assertEquals(2001, c.get(Calendar.YEAR));
+ c = bc.convertToType(s, Calendar.class);
+ assertEquals(2001, c.get(Calendar.YEAR));
+ s = bc.convertToType(c, String.class);
+ assertEquals("Jan 12, 2001", s);
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/IgnoredClassesTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/IgnoredClassesTest.java b/org.apache.juneau/src/test/java/org/apache/juneau/IgnoredClassesTest.java
new file mode 100755
index 0000000..753f731
--- /dev/null
+++ b/org.apache.juneau/src/test/java/org/apache/juneau/IgnoredClassesTest.java
@@ -0,0 +1,72 @@
+/***************************************************************************************************************************
+ * 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.juneau;
+
+import static org.apache.juneau.BeanContext.*;
+import static org.apache.juneau.TestUtils.*;
+import static org.junit.Assert.*;
+import static org.junit.Assume.*;
+
+import java.io.*;
+
+import org.apache.juneau.json.*;
+import org.junit.*;
+
+public class IgnoredClassesTest {
+
+ //====================================================================================================
+ // testFilesRenderedAsStrings
+ //====================================================================================================
+ @Test
+ public void testFilesRenderedAsStrings() throws Exception {
+ assumeTrue(System.getProperty("os.name").toLowerCase().startsWith("win"));
+ // Files should be rendered as strings.
+ File f = new File("C:/temp");
+ assertObjectEquals("'C:\\\\temp'", f);
+ }
+
+ //====================================================================================================
+ // testIgnorePackages
+ //====================================================================================================
+ @Test
+ public void testIgnorePackages() throws Exception {
+ A a = new A();
+ JsonSerializer s = new JsonSerializer.Simple();
+ assertEquals("{f1:'isBean'}", s.serialize(a));
+ s.setProperty(BEAN_notBeanPackages_add, "org.apache.juneau");
+ assertEquals("'isNotBean'", s.serialize(a));
+ s.setProperty(BEAN_notBeanPackages_remove, "org.apache.juneau");
+ assertEquals("{f1:'isBean'}", s.serialize(a));
+ s.setProperty(BEAN_notBeanPackages_add, "org.apache.juneau.*");
+ assertEquals("'isNotBean'", s.serialize(a));
+ s.setProperty(BEAN_notBeanPackages_remove, "org.apache.juneau.*");
+ assertEquals("{f1:'isBean'}", s.serialize(a));
+ s.setProperty(BEAN_notBeanPackages_add, "org.apache.juneau.*");
+ assertEquals("'isNotBean'", s.serialize(a));
+ s.setProperty(BEAN_notBeanPackages_remove, "org.apache.juneau.*");
+ assertEquals("{f1:'isBean'}", s.serialize(a));
+ s.setProperty(BEAN_notBeanPackages_add, "org.apache.juneau");
+ assertEquals("'isNotBean'", s.serialize(a));
+ s.setProperty(BEAN_notBeanPackages_add, "org.apache.juneau.x");
+ assertEquals("'isNotBean'", s.serialize(a));
+ }
+
+ public static class A {
+ public String f1 = "isBean";
+ @Override /* Object */
+ public String toString() {
+ return "isNotBean";
+ }
+ }
+ // TODO - Ignored packages.
+}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/JacocoDummyTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/JacocoDummyTest.java b/org.apache.juneau/src/test/java/org/apache/juneau/JacocoDummyTest.java
new file mode 100755
index 0000000..56c6dfc
--- /dev/null
+++ b/org.apache.juneau/src/test/java/org/apache/juneau/JacocoDummyTest.java
@@ -0,0 +1,49 @@
+/***************************************************************************************************************************
+ * 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.juneau;
+
+import java.lang.reflect.*;
+
+import org.apache.juneau.ini.*;
+import org.apache.juneau.internal.*;
+import org.apache.juneau.jena.*;
+import org.apache.juneau.transform.*;
+import org.apache.juneau.xml.annotation.*;
+import org.junit.*;
+
+
+public class JacocoDummyTest {
+
+ //====================================================================================================
+ // Dummy code to add test coverage in Jacoco.
+ //====================================================================================================
+ @Test
+ public void accessPrivateConstructorsOnStaticUtilityClasses() throws Exception {
+
+ Class<?>[] classes = new Class[] {
+ StringUtils.class, ArrayUtils.class, ClassUtils.class, CollectionUtils.class, ConfigUtils.class
+ };
+
+ for (Class<?> c : classes) {
+ Constructor<?> c1 = c.getDeclaredConstructor();
+ c1.setAccessible(true);
+ c1.newInstance();
+ }
+
+ ConfigFileFormat.valueOf(ConfigFileFormat.INI.toString());
+ Transform.TransformType.valueOf(Transform.TransformType.POJO.toString());
+ RdfCollectionFormat.valueOf(RdfCollectionFormat.DEFAULT.toString());
+ XmlFormat.valueOf(XmlFormat.NORMAL.toString());
+ Visibility.valueOf(Visibility.DEFAULT.toString());
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/ObjectListTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/ObjectListTest.java b/org.apache.juneau/src/test/java/org/apache/juneau/ObjectListTest.java
new file mode 100755
index 0000000..db58d2e
--- /dev/null
+++ b/org.apache.juneau/src/test/java/org/apache/juneau/ObjectListTest.java
@@ -0,0 +1,98 @@
+/***************************************************************************************************************************
+ * 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.juneau;
+
+import static org.junit.Assert.*;
+
+import java.util.*;
+
+import org.junit.*;
+
+public class ObjectListTest {
+
+ //====================================================================================================
+ // testBasic
+ //====================================================================================================
+ @Test
+ public void testBasic() throws Exception {
+
+ assertEquals(
+ "['A','B','C']",
+ new ObjectList((Object[])new String[]{"A","B","C"}).toString()
+ );
+
+ assertEquals(
+ "['A','B','C']",
+ new ObjectList("A","B","C").toString()
+ );
+
+ assertEquals(
+ "['A','B','C']",
+ new ObjectList(Arrays.asList(new String[]{"A","B","C"})).toString()
+ );
+ }
+
+ //====================================================================================================
+ // testIterateAs
+ //====================================================================================================
+ @Test
+ public void testIterateAs() throws Exception {
+
+ // Iterate over a list of ObjectMaps.
+ ObjectList l = new ObjectList("[{foo:'bar'},{baz:123}]");
+ Iterator<ObjectMap> i1 = l.elements(ObjectMap.class).iterator();
+ assertEquals("bar", i1.next().getString("foo"));
+ assertEquals(123, (int)i1.next().getInt("baz"));
+
+ // Iterate over a list of ints.
+ l = new ObjectList("[1,2,3]");
+ Iterator<Integer> i2 = l.elements(Integer.class).iterator();
+ assertEquals(1, (int)i2.next());
+ assertEquals(2, (int)i2.next());
+ assertEquals(3, (int)i2.next());
+
+ // Iterate over a list of beans.
+ // Automatically converts to beans.
+ l = new ObjectList("[{name:'John Smith',age:45}]");
+ Iterator<Person> i3 = l.elements(Person.class).iterator();
+ assertEquals("John Smith", i3.next().name);
+ }
+
+ public static class Person {
+ public String name;
+ public int age;
+ }
+
+ //====================================================================================================
+ // testAtMethods
+ //====================================================================================================
+ @Test
+ public void testAtMethods() throws Exception {
+ ObjectList l = new ObjectList("[{foo:'bar'},{baz:123}]");
+ String r;
+
+ r = l.getAt(String.class, "0/foo");
+ assertEquals("bar", r);
+
+ l.putAt("0/foo", "bing");
+ r = l.getAt(String.class, "0/foo");
+ assertEquals("bing", r);
+
+ l.postAt("", new ObjectMap("{a:'b'}"));
+ r = l.getAt(String.class, "2/a");
+ assertEquals("b", r);
+
+ l.deleteAt("2");
+ assertEquals("[{foo:'bing'},{baz:123}]", l.toString());
+ }
+}
\ No newline at end of file
[39/44] incubator-juneau git commit: Rename CT_* testcases.
Posted by ja...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestTransforms.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestTransforms.java b/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestTransforms.java
deleted file mode 100755
index 49a9030..0000000
--- a/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestTransforms.java
+++ /dev/null
@@ -1,68 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.server;
-
-import static org.junit.Assert.*;
-
-import org.apache.juneau.client.*;
-import org.apache.juneau.json.*;
-import org.junit.*;
-
-public class CT_TestTransforms {
-
- private static String URL = "/testTransforms";
-
- //====================================================================================================
- // test1 - Test class transform overrides parent class transform
- // Should return "A2-1".
- //====================================================================================================
- @Test
- public void testClassTransformOverridesParentClassTransform() throws Exception {
- RestClient client = new TestRestClient(JsonSerializer.DEFAULT, JsonParser.DEFAULT);
- String r;
- String url = URL + "/testClassTransformOverridesParentClassTransform";
-
- r = client.doGet(url).getResponse(String.class);
- assertEquals("A2-0", r);
-
- r = client.doPut(url, "A2-1").getResponse(String.class);
- assertEquals("A2-1", r);
-
- r = client.doPut(url + "/A2-2", "").getResponse(String.class);
- assertEquals("A2-2", r);
-
- client.closeQuietly();
- }
-
- //====================================================================================================
- // Test method transform overrides class transform
- // Should return "A3-1".
- //====================================================================================================
- @Test
- public void testMethodTransformOverridesClassTransform() throws Exception {
- RestClient client = new TestRestClient(JsonSerializer.DEFAULT, JsonParser.DEFAULT);
- String r;
- String url = URL + "/testMethodTransformOverridesClassTransform";
-
- r = client.doGet(url).getResponse(String.class);
- assertEquals("A3-0", r);
-
- r = client.doPut(url, "A3-1").getResponse(String.class);
- assertEquals("A3-1", r);
-
- r = client.doPut(url + "/A3-2", "").getResponse(String.class);
- assertEquals("A3-2", r);
-
- client.closeQuietly();
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestUris.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestUris.java b/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestUris.java
deleted file mode 100755
index d5b1f04..0000000
--- a/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestUris.java
+++ /dev/null
@@ -1,918 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.server;
-
-import static org.junit.Assert.*;
-
-import java.util.regex.*;
-
-import org.apache.juneau.*;
-import org.apache.juneau.client.*;
-import org.apache.juneau.json.*;
-import org.junit.*;
-
-/**
- * Verifies that all the RestRequest.getXXX() methods involving URIs work correctly.
- */
-public class CT_TestUris {
-
- private static String URL2 = Constants.getServerTestUrl() + "/testuris"; // /jazz/juneau/sample/testuris
- private static int port = getPort(Constants.getServerTestUrl()); // 9443
- private static String path = Constants.getServerTestUri().getPath(); // /jazz/juneau/sample
-
- //====================================================================================================
- // testRoot - http://localhost:8080/sample/testuris
- //====================================================================================================
- @Test
- public void testRoot() throws Exception {
- RestClient client = new TestRestClient(JsonSerializer.DEFAULT, JsonParser.DEFAULT);
- ObjectMap r;
-
- //--------------------------------------------------------------------------------
- // http://localhost:8080/sample/testuris
- //--------------------------------------------------------------------------------
- r = client.doGet("/testuris").getResponse(ObjectMap.class);
- assertEquals("root.test1", r.getString("testMethod"));
- assertNull(r.getString("pathInfo"));
- assertNull(r.getString("pathRemainder"));
- assertEquals(path + "/testuris", r.getString("requestURI"));
- assertTrue(r.getString("requestURL").endsWith(port + path + "/testuris"));
- // Same for servlet
- assertEquals(path + "/testuris", r.getString("contextPath") + r.getString("servletPath")); // App may not have context path, but combination should always equal path.
- assertEquals(URL2, r.getString("servletURI"));
- assertTrue(r.getString("testURL1").endsWith(port + path + "/testuris/testURL"));
- // Always the same
- assertTrue(r.getString("testURL2").endsWith(port + "/testURL"));
- assertEquals("http://testURL", r.getString("testURL3"));
-
- //--------------------------------------------------------------------------------
- // http://localhost:8080/sample/testuris/foo
- //--------------------------------------------------------------------------------
- r = client.doGet("/testuris/foo").getResponse(ObjectMap.class);
- assertEquals("root.test1", r.getString("testMethod"));
- assertEquals("/foo", r.getString("pathInfo"));
- assertEquals("foo", r.getString("pathRemainder"));
- assertEquals(path + "/testuris", r.getString("requestParentURI"));
- assertEquals(path + "/testuris/foo", r.getString("requestURI"));
- assertTrue(r.getString("requestURL").endsWith(port + path + "/testuris/foo"));
- // Same for servlet
- assertEquals(path + "/testuris", r.getString("contextPath") + r.getString("servletPath")); // App may not have context path, but combination should always equal path.
- assertEquals(URL2, r.getString("servletURI"));
- assertTrue(r.getString("testURL1").endsWith(port + path + "/testuris/testURL"));
- // Always the same
- assertTrue(r.getString("testURL2").endsWith(port + "/testURL"));
- assertEquals("http://testURL", r.getString("testURL3"));
-
- //--------------------------------------------------------------------------------
- // http://localhost:8080/sample/testuris/foo/bar
- //--------------------------------------------------------------------------------
- r = client.doGet("/testuris/foo/bar").getResponse(ObjectMap.class);
- assertEquals("root.test1", r.getString("testMethod"));
- assertEquals("/foo/bar", r.getString("pathInfo"));
- assertEquals("foo/bar", r.getString("pathRemainder"));
- assertEquals(path + "/testuris/foo", r.getString("requestParentURI"));
- assertEquals(path + "/testuris/foo/bar", r.getString("requestURI"));
- assertTrue(r.getString("requestURL").endsWith(port + path + "/testuris/foo/bar"));
- // Same for servlet
- assertEquals(path + "/testuris", r.getString("contextPath") + r.getString("servletPath")); // App may not have context path, but combination should always equal path.
- assertEquals(URL2, r.getString("servletURI"));
- assertTrue(r.getString("testURL1").endsWith(port + path + "/testuris/testURL"));
- // Always the same
- assertTrue(r.getString("testURL2").endsWith(port + "/testURL"));
- assertEquals("http://testURL", r.getString("testURL3"));
-
- //--------------------------------------------------------------------------------
- // http://localhost:8080/sample/testuris/foo/bar%2Fbaz
- //--------------------------------------------------------------------------------
- r = client.doGet("/testuris/foo/bar%2Fbaz").getResponse(ObjectMap.class);
- assertEquals("root.test1", r.getString("testMethod"));
- assertEquals("/foo/bar/baz", r.getString("pathInfo"));
- assertEquals("foo/bar/baz", r.getString("pathRemainder"));
- assertEquals(path + "/testuris/foo", r.getString("requestParentURI"));
- assertEquals(path + "/testuris/foo/bar%2Fbaz", r.getString("requestURI"));
- assertTrue(r.getString("requestURL").endsWith(port + path + "/testuris/foo/bar%2Fbaz"));
- // Same for servlet
- assertEquals(path + "/testuris", r.getString("contextPath") + r.getString("servletPath")); // App may not have context path, but combination should always equal path.
- assertEquals(URL2, r.getString("servletURI"));
- assertTrue(r.getString("testURL1").endsWith(port + path + "/testuris/testURL"));
- // Always the same
- assertTrue(r.getString("testURL2").endsWith(port + "/testURL"));
- assertEquals("http://testURL", r.getString("testURL3"));
-
- //--------------------------------------------------------------------------------
- // http://localhost:8080/sample/testuris/test2
- //--------------------------------------------------------------------------------
- r = client.doGet("/testuris/test2").getResponse(ObjectMap.class);
- assertEquals("root.test2", r.getString("testMethod"));
- assertEquals("/test2", r.getString("pathInfo"));
- assertNull(r.getString("pathRemainder"));
- assertEquals(path + "/testuris", r.getString("requestParentURI"));
- assertEquals(path + "/testuris/test2", r.getString("requestURI"));
- assertTrue(r.getString("requestURL").endsWith(port + path + "/testuris/test2"));
- // Same for servlet
- assertEquals(path + "/testuris", r.getString("contextPath") + r.getString("servletPath")); // App may not have context path, but combination should always equal path.
- assertEquals(URL2, r.getString("servletURI"));
- assertTrue(r.getString("testURL1").endsWith(port + path + "/testuris/testURL"));
- // Always the same
- assertTrue(r.getString("testURL2").endsWith(port + "/testURL"));
- assertEquals("http://testURL", r.getString("testURL3"));
-
- //--------------------------------------------------------------------------------
- // http://localhost:8080/sample/testuris/test2/foo
- //--------------------------------------------------------------------------------
- r = client.doGet("/testuris/test2/foo").getResponse(ObjectMap.class);
- assertEquals("root.test2", r.getString("testMethod"));
- assertEquals("/test2/foo", r.getString("pathInfo"));
- assertEquals("foo", r.getString("pathRemainder"));
- assertEquals(path + "/testuris/test2", r.getString("requestParentURI"));
- assertEquals(path + "/testuris/test2/foo", r.getString("requestURI"));
- assertTrue(r.getString("requestURL").endsWith(port + path + "/testuris/test2/foo"));
- // Same for servlet
- assertEquals(path + "/testuris", r.getString("contextPath") + r.getString("servletPath")); // App may not have context path, but combination should always equal path.
- assertEquals(URL2, r.getString("servletURI"));
- assertTrue(r.getString("testURL1").endsWith(port + path + "/testuris/testURL"));
- // Always the same
- assertTrue(r.getString("testURL2").endsWith(port + "/testURL"));
- assertEquals("http://testURL", r.getString("testURL3"));
-
- //--------------------------------------------------------------------------------
- // http://localhost:8080/sample/testuris/test2/foo/bar
- //--------------------------------------------------------------------------------
- r = client.doGet("/testuris/test2/foo/bar").getResponse(ObjectMap.class);
- assertEquals("root.test2", r.getString("testMethod"));
- assertEquals("/test2/foo/bar", r.getString("pathInfo"));
- assertEquals("foo/bar", r.getString("pathRemainder"));
- assertEquals(path + "/testuris/test2/foo", r.getString("requestParentURI"));
- assertEquals(path + "/testuris/test2/foo/bar", r.getString("requestURI"));
- assertTrue(r.getString("requestURL").endsWith(port + path + "/testuris/test2/foo/bar"));
- // Same for servlet
- assertEquals(path + "/testuris", r.getString("contextPath") + r.getString("servletPath")); // App may not have context path, but combination should always equal path.
- assertEquals(URL2, r.getString("servletURI"));
- assertTrue(r.getString("testURL1").endsWith(port + path + "/testuris/testURL"));
- // Always the same
- assertTrue(r.getString("testURL2").endsWith(port + "/testURL"));
- assertEquals("http://testURL", r.getString("testURL3"));
-
- //--------------------------------------------------------------------------------
- // http://localhost:8080/sample/testuris/test3%2Ftest3
- //--------------------------------------------------------------------------------
- r = client.doGet("/testuris/test3%2Ftest3").getResponse(ObjectMap.class);
- assertEquals("root.test3", r.getString("testMethod"));
- assertEquals("/test3/test3", r.getString("pathInfo"));
- assertNull(r.getString("pathRemainder"));
- assertEquals(path + "/testuris", r.getString("requestParentURI"));
- assertEquals(path + "/testuris/test3%2Ftest3", r.getString("requestURI"));
- assertTrue(r.getString("requestURL").endsWith(port + path + "/testuris/test3%2Ftest3"));
- // Same for servlet
- assertEquals(path + "/testuris", r.getString("contextPath") + r.getString("servletPath")); // App may not have context path, but combination should always equal path.
- assertEquals(URL2, r.getString("servletURI"));
- assertTrue(r.getString("testURL1").endsWith(port + path + "/testuris/testURL"));
- // Always the same
- assertTrue(r.getString("testURL2").endsWith(port + "/testURL"));
- assertEquals("http://testURL", r.getString("testURL3"));
-
- //--------------------------------------------------------------------------------
- // http://localhost:8080/sample/testuris/test3%2Ftest3/foo
- //--------------------------------------------------------------------------------
- r = client.doGet("/testuris/test3%2Ftest3/foo").getResponse(ObjectMap.class);
- assertEquals("root.test3", r.getString("testMethod"));
- assertEquals("/test3/test3/foo", r.getString("pathInfo"));
- assertEquals("foo", r.getString("pathRemainder"));
- assertEquals(path + "/testuris/test3%2Ftest3", r.getString("requestParentURI"));
- assertEquals(path + "/testuris/test3%2Ftest3/foo", r.getString("requestURI"));
- assertTrue(r.getString("requestURL").endsWith(port + path + "/testuris/test3%2Ftest3/foo"));
- // Same for servlet
- assertEquals(path + "/testuris", r.getString("contextPath") + r.getString("servletPath")); // App may not have context path, but combination should always equal path.
- assertEquals(URL2, r.getString("servletURI"));
- assertTrue(r.getString("testURL1").endsWith(port + path + "/testuris/testURL"));
- // Always the same
- assertTrue(r.getString("testURL2").endsWith(port + "/testURL"));
- assertEquals("http://testURL", r.getString("testURL3"));
-
- //--------------------------------------------------------------------------------
- // http://localhost:8080/sample/testuris/test3%2Ftest3/foo/bar
- //--------------------------------------------------------------------------------
- r = client.doGet("/testuris/test3%2Ftest3/foo/bar").getResponse(ObjectMap.class);
- assertEquals("root.test3", r.getString("testMethod"));
- assertEquals("/test3/test3/foo/bar", r.getString("pathInfo"));
- assertEquals("foo/bar", r.getString("pathRemainder"));
- assertEquals(path + "/testuris/test3%2Ftest3/foo", r.getString("requestParentURI"));
- assertEquals(path + "/testuris/test3%2Ftest3/foo/bar", r.getString("requestURI"));
- assertTrue(r.getString("requestURL").endsWith(port + path + "/testuris/test3%2Ftest3/foo/bar"));
- // Same for servlet
- assertEquals(path + "/testuris", r.getString("contextPath") + r.getString("servletPath")); // App may not have context path, but combination should always equal path.
- assertEquals(URL2, r.getString("servletURI"));
- assertTrue(r.getString("testURL1").endsWith(port + path + "/testuris/testURL"));
- // Always the same
- assertTrue(r.getString("testURL2").endsWith(port + "/testURL"));
- assertEquals("http://testURL", r.getString("testURL3"));
-
- //--------------------------------------------------------------------------------
- // http://localhost:8080/sample/testuris/test3%2Ftest3/foo/bar%2Fbaz
- //--------------------------------------------------------------------------------
- r = client.doGet("/testuris/test3%2Ftest3/foo/bar%2Fbaz").getResponse(ObjectMap.class);
- assertEquals("root.test3", r.getString("testMethod"));
- assertEquals("/test3/test3/foo/bar/baz", r.getString("pathInfo"));
- assertEquals("foo/bar/baz", r.getString("pathRemainder"));
- assertEquals(path + "/testuris/test3%2Ftest3/foo", r.getString("requestParentURI"));
- assertEquals(path + "/testuris/test3%2Ftest3/foo/bar%2Fbaz", r.getString("requestURI"));
- assertTrue(r.getString("requestURL").endsWith(port + path + "/testuris/test3%2Ftest3/foo/bar%2Fbaz"));
- // Same for servlet
- assertEquals(path + "/testuris", r.getString("contextPath") + r.getString("servletPath")); // App may not have context path, but combination should always equal path.
- assertEquals(URL2, r.getString("servletURI"));
- assertTrue(r.getString("testURL1").endsWith(port + path + "/testuris/testURL"));
- // Always the same
- assertTrue(r.getString("testURL2").endsWith(port + "/testURL"));
- assertEquals("http://testURL", r.getString("testURL3"));
-
- //--------------------------------------------------------------------------------
- // http://localhost:8080/sample/testuris/test4/test4
- //--------------------------------------------------------------------------------
- r = client.doGet("/testuris/test4/test4").getResponse(ObjectMap.class);
- assertEquals("root.test4", r.getString("testMethod"));
- assertEquals("/test4/test4", r.getString("pathInfo"));
- assertNull(r.getString("pathRemainder"));
- assertEquals(path + "/testuris/test4", r.getString("requestParentURI"));
- assertEquals(path + "/testuris/test4/test4", r.getString("requestURI"));
- assertTrue(r.getString("requestURL").endsWith(port + path + "/testuris/test4/test4"));
- // Same for servlet
- assertEquals(path + "/testuris", r.getString("contextPath") + r.getString("servletPath")); // App may not have context path, but combination should always equal path.
- assertEquals(URL2, r.getString("servletURI"));
- assertTrue(r.getString("testURL1").endsWith(port + path + "/testuris/testURL"));
- // Always the same
- assertTrue(r.getString("testURL2").endsWith(port + "/testURL"));
- assertEquals("http://testURL", r.getString("testURL3"));
-
- //--------------------------------------------------------------------------------
- // http://localhost:8080/sample/testuris/test4/test4/foo
- //--------------------------------------------------------------------------------
- r = client.doGet("/testuris/test4/test4/foo").getResponse(ObjectMap.class);
- assertEquals("root.test4", r.getString("testMethod"));
- assertEquals("/test4/test4/foo", r.getString("pathInfo"));
- assertEquals("foo", r.getString("pathRemainder"));
- assertEquals(path + "/testuris/test4/test4", r.getString("requestParentURI"));
- assertEquals(path + "/testuris/test4/test4/foo", r.getString("requestURI"));
- assertTrue(r.getString("requestURL").endsWith(port + path + "/testuris/test4/test4/foo"));
- // Same for servlet
- assertEquals(path + "/testuris", r.getString("contextPath") + r.getString("servletPath")); // App may not have context path, but combination should always equal path.
- assertEquals(URL2, r.getString("servletURI"));
- assertTrue(r.getString("testURL1").endsWith(port + path + "/testuris/testURL"));
- // Always the same
- assertTrue(r.getString("testURL2").endsWith(port + "/testURL"));
- assertEquals("http://testURL", r.getString("testURL3"));
-
- //--------------------------------------------------------------------------------
- // http://localhost:8080/sample/testuris/test4/test4/foo/bar
- //--------------------------------------------------------------------------------
- r = client.doGet("/testuris/test4/test4/foo/bar").getResponse(ObjectMap.class);
- assertEquals("root.test4", r.getString("testMethod"));
- assertEquals("/test4/test4/foo/bar", r.getString("pathInfo"));
- assertEquals("foo/bar", r.getString("pathRemainder"));
- assertEquals(path + "/testuris/test4/test4/foo", r.getString("requestParentURI"));
- assertEquals(path + "/testuris/test4/test4/foo/bar", r.getString("requestURI"));
- assertTrue(r.getString("requestURL").endsWith(port + path + "/testuris/test4/test4/foo/bar"));
- // Same for servlet
- assertEquals(path + "/testuris", r.getString("contextPath") + r.getString("servletPath")); // App may not have context path, but combination should always equal path.
- assertEquals(URL2, r.getString("servletURI"));
- assertTrue(r.getString("testURL1").endsWith(port + path + "/testuris/testURL"));
- // Always the same
- assertTrue(r.getString("testURL2").endsWith(port + "/testURL"));
- assertEquals("http://testURL", r.getString("testURL3"));
-
- //--------------------------------------------------------------------------------
- // http://localhost:8080/sample/testuris/test4/test4/foo/bar%2Fbaz
- //--------------------------------------------------------------------------------
- r = client.doGet("/testuris/test4/test4/foo/bar%2Fbaz").getResponse(ObjectMap.class);
- assertEquals("root.test4", r.getString("testMethod"));
- assertEquals("/test4/test4/foo/bar/baz", r.getString("pathInfo"));
- assertEquals("foo/bar/baz", r.getString("pathRemainder"));
- assertEquals(path + "/testuris/test4/test4/foo", r.getString("requestParentURI"));
- assertEquals(path + "/testuris/test4/test4/foo/bar%2Fbaz", r.getString("requestURI"));
- assertTrue(r.getString("requestURL").endsWith(port + path + "/testuris/test4/test4/foo/bar%2Fbaz"));
- // Same for servlet
- assertEquals(path + "/testuris", r.getString("contextPath") + r.getString("servletPath")); // App may not have context path, but combination should always equal path.
- assertEquals(URL2, r.getString("servletURI"));
- assertTrue(r.getString("testURL1").endsWith(port + path + "/testuris/testURL"));
- // Always the same
- assertTrue(r.getString("testURL2").endsWith(port + "/testURL"));
- assertEquals("http://testURL", r.getString("testURL3"));
-
- client.closeQuietly();
- }
-
- //====================================================================================================
- // testChild - http://localhost:8080/sample/testuris/child
- //====================================================================================================
- @Test
- public void testChild() throws Exception {
- RestClient client = new TestRestClient(JsonSerializer.DEFAULT, JsonParser.DEFAULT);
- ObjectMap r;
-
- //--------------------------------------------------------------------------------
- // http://localhost:8080/sample/testuris/child
- //--------------------------------------------------------------------------------
- r = client.doGet("/testuris/child").getResponse(ObjectMap.class);
- assertEquals("child.test1", r.getString("testMethod"));
- assertNull(r.getString("pathInfo"));
- assertNull(r.getString("pathRemainder"));
- assertEquals(path + "/testuris", r.getString("requestParentURI"));
- assertEquals(path + "/testuris/child", r.getString("requestURI"));
- assertTrue(r.getString("requestURL").endsWith(port + path + "/testuris/child"));
- // Same for servlet
- assertEquals(path + "/testuris/child", r.getString("contextPath") + r.getString("servletPath")); // App may not have context path, but combination should always equal path.
- assertEquals(URL2 + "/child", r.getString("servletURI"));
- assertTrue(r.getString("testURL1").endsWith(port + path + "/testuris/child/testURL"));
- // Always the same
- assertTrue(r.getString("testURL2").endsWith(port + "/testURL"));
- assertEquals("http://testURL", r.getString("testURL3"));
-
- //--------------------------------------------------------------------------------
- // http://localhost:8080/sample/testuris/child/foo
- //--------------------------------------------------------------------------------
- r = client.doGet("/testuris/child/foo").getResponse(ObjectMap.class);
- assertEquals("child.test1", r.getString("testMethod"));
- assertEquals("/foo", r.getString("pathInfo"));
- assertEquals("foo", r.getString("pathRemainder"));
- assertEquals(path + "/testuris/child", r.getString("requestParentURI"));
- assertEquals(path + "/testuris/child/foo", r.getString("requestURI"));
- assertTrue(r.getString("requestURL").endsWith(port + path + "/testuris/child/foo"));
- // Same for servlet
- assertEquals(path + "/testuris/child", r.getString("contextPath") + r.getString("servletPath")); // App may not have context path, but combination should always equal path.
- assertEquals(URL2 + "/child", r.getString("servletURI"));
- assertTrue(r.getString("testURL1").endsWith(port + path + "/testuris/child/testURL"));
- // Always the same
- assertTrue(r.getString("testURL2").endsWith(port + "/testURL"));
- assertEquals("http://testURL", r.getString("testURL3"));
-
- //--------------------------------------------------------------------------------
- // http://localhost:8080/sample/testuris/child/foo/bar
- //--------------------------------------------------------------------------------
- r = client.doGet("/testuris/child/foo/bar").getResponse(ObjectMap.class);
- assertEquals("child.test1", r.getString("testMethod"));
- assertEquals("/foo/bar", r.getString("pathInfo"));
- assertEquals("foo/bar", r.getString("pathRemainder"));
- assertEquals(path + "/testuris/child/foo", r.getString("requestParentURI"));
- assertEquals(path + "/testuris/child/foo/bar", r.getString("requestURI"));
- assertTrue(r.getString("requestURL").endsWith(port + path + "/testuris/child/foo/bar"));
- // Same for servlet
- assertEquals(path + "/testuris/child", r.getString("contextPath") + r.getString("servletPath")); // App may not have context path, but combination should always equal path.
- assertEquals(URL2 + "/child", r.getString("servletURI"));
- assertTrue(r.getString("testURL1").endsWith(port + path + "/testuris/child/testURL"));
- // Always the same
- assertTrue(r.getString("testURL2").endsWith(port + "/testURL"));
- assertEquals("http://testURL", r.getString("testURL3"));
-
- //--------------------------------------------------------------------------------
- // http://localhost:8080/sample/testuris/child/foo/bar%2Fbaz
- //--------------------------------------------------------------------------------
- r = client.doGet("/testuris/child/foo/bar%2Fbaz").getResponse(ObjectMap.class);
- assertEquals("child.test1", r.getString("testMethod"));
- assertEquals("/foo/bar/baz", r.getString("pathInfo"));
- assertEquals("foo/bar/baz", r.getString("pathRemainder"));
- assertEquals(path + "/testuris/child/foo", r.getString("requestParentURI"));
- assertEquals(path + "/testuris/child/foo/bar%2Fbaz", r.getString("requestURI"));
- assertTrue(r.getString("requestURL").endsWith(port + path + "/testuris/child/foo/bar%2Fbaz"));
- // Same for servlet
- assertEquals(path + "/testuris/child", r.getString("contextPath") + r.getString("servletPath")); // App may not have context path, but combination should always equal path.
- assertEquals(URL2 + "/child", r.getString("servletURI"));
- assertTrue(r.getString("testURL1").endsWith(port + path + "/testuris/child/testURL"));
- // Always the same
- assertTrue(r.getString("testURL2").endsWith(port + "/testURL"));
- assertEquals("http://testURL", r.getString("testURL3"));
-
- //--------------------------------------------------------------------------------
- // http://localhost:8080/sample/testuris/child/test2
- //--------------------------------------------------------------------------------
- r = client.doGet("/testuris/child/test2").getResponse(ObjectMap.class);
- assertEquals("child.test2", r.getString("testMethod"));
- assertEquals("/test2", r.getString("pathInfo"));
- assertNull(r.getString("pathRemainder"));
- assertEquals(path + "/testuris/child", r.getString("requestParentURI"));
- assertEquals(path + "/testuris/child/test2", r.getString("requestURI"));
- assertTrue(r.getString("requestURL").endsWith(port + path + "/testuris/child/test2"));
- // Same for servlet
- assertEquals(path + "/testuris/child", r.getString("contextPath") + r.getString("servletPath")); // App may not have context path, but combination should always equal path.
- assertEquals(URL2 + "/child", r.getString("servletURI"));
- assertTrue(r.getString("testURL1").endsWith(port + path + "/testuris/child/testURL"));
- // Always the same
- assertTrue(r.getString("testURL2").endsWith(port + "/testURL"));
- assertEquals("http://testURL", r.getString("testURL3"));
-
- //--------------------------------------------------------------------------------
- // http://localhost:8080/sample/testuris/child/test2/foo
- //--------------------------------------------------------------------------------
- r = client.doGet("/testuris/child/test2/foo").getResponse(ObjectMap.class);
- assertEquals("child.test2", r.getString("testMethod"));
- assertEquals("/test2/foo", r.getString("pathInfo"));
- assertEquals("foo", r.getString("pathRemainder"));
- assertEquals(path + "/testuris/child/test2", r.getString("requestParentURI"));
- assertEquals(path + "/testuris/child/test2/foo", r.getString("requestURI"));
- assertTrue(r.getString("requestURL").endsWith(port + path + "/testuris/child/test2/foo"));
- // Same for servlet
- assertEquals(path + "/testuris/child", r.getString("contextPath") + r.getString("servletPath")); // App may not have context path, but combination should always equal path.
- assertEquals(URL2 + "/child", r.getString("servletURI"));
- assertTrue(r.getString("testURL1").endsWith(port + path + "/testuris/child/testURL"));
- // Always the same
- assertTrue(r.getString("testURL2").endsWith(port + "/testURL"));
- assertEquals("http://testURL", r.getString("testURL3"));
-
- //--------------------------------------------------------------------------------
- // http://localhost:8080/sample/testuris/child/test2/foo/bar
- //--------------------------------------------------------------------------------
- r = client.doGet("/testuris/child/test2/foo/bar").getResponse(ObjectMap.class);
- assertEquals("child.test2", r.getString("testMethod"));
- assertEquals("/test2/foo/bar", r.getString("pathInfo"));
- assertEquals("foo/bar", r.getString("pathRemainder"));
- assertEquals(path + "/testuris/child/test2/foo", r.getString("requestParentURI"));
- assertEquals(path + "/testuris/child/test2/foo/bar", r.getString("requestURI"));
- assertTrue(r.getString("requestURL").endsWith(port + path + "/testuris/child/test2/foo/bar"));
- // Same for servlet
- assertEquals(path + "/testuris/child", r.getString("contextPath") + r.getString("servletPath")); // App may not have context path, but combination should always equal path.
- assertEquals(URL2 + "/child", r.getString("servletURI"));
- assertTrue(r.getString("testURL1").endsWith(port + path + "/testuris/child/testURL"));
- // Always the same
- assertTrue(r.getString("testURL2").endsWith(port + "/testURL"));
- assertEquals("http://testURL", r.getString("testURL3"));
-
- //--------------------------------------------------------------------------------
- // http://localhost:8080/sample/testuris/child/test2/foo/bar%2Fbaz
- //--------------------------------------------------------------------------------
- r = client.doGet("/testuris/child/test2/foo/bar%2Fbaz").getResponse(ObjectMap.class);
- assertEquals("child.test2", r.getString("testMethod"));
- assertEquals("/test2/foo/bar/baz", r.getString("pathInfo"));
- assertEquals("foo/bar/baz", r.getString("pathRemainder"));
- assertEquals(path + "/testuris/child/test2/foo", r.getString("requestParentURI"));
- assertEquals(path + "/testuris/child/test2/foo/bar%2Fbaz", r.getString("requestURI"));
- assertTrue(r.getString("requestURL").endsWith(port + path + "/testuris/child/test2/foo/bar%2Fbaz"));
- // Same for servlet
- assertEquals(path + "/testuris/child", r.getString("contextPath") + r.getString("servletPath")); // App may not have context path, but combination should always equal path.
- assertEquals(URL2 + "/child", r.getString("servletURI"));
- assertTrue(r.getString("testURL1").endsWith(port + path + "/testuris/child/testURL"));
- // Always the same
- assertTrue(r.getString("testURL2").endsWith(port + "/testURL"));
- assertEquals("http://testURL", r.getString("testURL3"));
-
- //--------------------------------------------------------------------------------
- // http://localhost:8080/sample/testuris/child/test3%2Ftest3
- //--------------------------------------------------------------------------------
- r = client.doGet("/testuris/child/test3%2Ftest3").getResponse(ObjectMap.class);
- assertEquals("child.test3", r.getString("testMethod"));
- assertEquals("/test3/test3", r.getString("pathInfo"));
- assertNull(r.getString("pathRemainder"));
- assertEquals(path + "/testuris/child", r.getString("requestParentURI"));
- assertEquals(path + "/testuris/child/test3%2Ftest3", r.getString("requestURI"));
- assertTrue(r.getString("requestURL").endsWith(port + path + "/testuris/child/test3%2Ftest3"));
- // Same for servlet
- assertEquals(path + "/testuris/child", r.getString("contextPath") + r.getString("servletPath")); // App may not have context path, but combination should always equal path.
- assertEquals(URL2 + "/child", r.getString("servletURI"));
- assertTrue(r.getString("testURL1").endsWith(port + path + "/testuris/child/testURL"));
- // Always the same
- assertTrue(r.getString("testURL2").endsWith(port + "/testURL"));
- assertEquals("http://testURL", r.getString("testURL3"));
-
- //--------------------------------------------------------------------------------
- // http://localhost:8080/sample/testuris/child/test3%2Ftest3/foo
- //--------------------------------------------------------------------------------
- r = client.doGet("/testuris/child/test3%2Ftest3/foo").getResponse(ObjectMap.class);
- assertEquals("child.test3", r.getString("testMethod"));
- assertEquals("/test3/test3/foo", r.getString("pathInfo"));
- assertEquals("foo", r.getString("pathRemainder"));
- assertEquals(path + "/testuris/child/test3%2Ftest3", r.getString("requestParentURI"));
- assertEquals(path + "/testuris/child/test3%2Ftest3/foo", r.getString("requestURI"));
- assertTrue(r.getString("requestURL").endsWith(port + path + "/testuris/child/test3%2Ftest3/foo"));
- // Same for servlet
- assertEquals(path + "/testuris/child", r.getString("contextPath") + r.getString("servletPath")); // App may not have context path, but combination should always equal path.
- assertEquals(URL2 + "/child", r.getString("servletURI"));
- assertTrue(r.getString("testURL1").endsWith(port + path + "/testuris/child/testURL"));
- // Always the same
- assertTrue(r.getString("testURL2").endsWith(port + "/testURL"));
- assertEquals("http://testURL", r.getString("testURL3"));
-
- //--------------------------------------------------------------------------------
- // http://localhost:8080/sample/testuris/child/test3%2Ftest3/foo/bar
- //--------------------------------------------------------------------------------
- r = client.doGet("/testuris/child/test3%2Ftest3/foo/bar").getResponse(ObjectMap.class);
- assertEquals("child.test3", r.getString("testMethod"));
- assertEquals("/test3/test3/foo/bar", r.getString("pathInfo"));
- assertEquals("foo/bar", r.getString("pathRemainder"));
- assertEquals(path + "/testuris/child/test3%2Ftest3/foo", r.getString("requestParentURI"));
- assertEquals(path + "/testuris/child/test3%2Ftest3/foo/bar", r.getString("requestURI"));
- assertTrue(r.getString("requestURL").endsWith(port + path + "/testuris/child/test3%2Ftest3/foo/bar"));
- // Same for servlet
- assertEquals(path + "/testuris/child", r.getString("contextPath") + r.getString("servletPath")); // App may not have context path, but combination should always equal path.
- assertEquals(URL2 + "/child", r.getString("servletURI"));
- assertTrue(r.getString("testURL1").endsWith(port + path + "/testuris/child/testURL"));
- // Always the same
- assertTrue(r.getString("testURL2").endsWith(port + "/testURL"));
- assertEquals("http://testURL", r.getString("testURL3"));
-
- //--------------------------------------------------------------------------------
- // http://localhost:8080/sample/testuris/child/test3%2Ftest3/foo/bar%2Fbaz
- //--------------------------------------------------------------------------------
- r = client.doGet("/testuris/child/test3%2Ftest3/foo/bar%2Fbaz").getResponse(ObjectMap.class);
- assertEquals("child.test3", r.getString("testMethod"));
- assertEquals("/test3/test3/foo/bar/baz", r.getString("pathInfo"));
- assertEquals("foo/bar/baz", r.getString("pathRemainder"));
- assertEquals(path + "/testuris/child/test3%2Ftest3/foo", r.getString("requestParentURI"));
- assertEquals(path + "/testuris/child/test3%2Ftest3/foo/bar%2Fbaz", r.getString("requestURI"));
- assertTrue(r.getString("requestURL").endsWith(port + path + "/testuris/child/test3%2Ftest3/foo/bar%2Fbaz"));
- // Same for servlet
- assertEquals(path + "/testuris/child", r.getString("contextPath") + r.getString("servletPath")); // App may not have context path, but combination should always equal path.
- assertEquals(URL2 + "/child", r.getString("servletURI"));
- assertTrue(r.getString("testURL1").endsWith(port + path + "/testuris/child/testURL"));
- // Always the same
- assertTrue(r.getString("testURL2").endsWith(port + "/testURL"));
- assertEquals("http://testURL", r.getString("testURL3"));
-
- //--------------------------------------------------------------------------------
- // http://localhost:8080/sample/testuris/child/test4/test4
- //--------------------------------------------------------------------------------
- r = client.doGet("/testuris/child/test4/test4").getResponse(ObjectMap.class);
- assertEquals("child.test4", r.getString("testMethod"));
- assertEquals("/test4/test4", r.getString("pathInfo"));
- assertNull(r.getString("pathRemainder"));
- assertEquals(path + "/testuris/child/test4", r.getString("requestParentURI"));
- assertEquals(path + "/testuris/child/test4/test4", r.getString("requestURI"));
- assertTrue(r.getString("requestURL").endsWith(port + path + "/testuris/child/test4/test4"));
- // Same for servlet
- assertEquals(path + "/testuris/child", r.getString("contextPath") + r.getString("servletPath")); // App may not have context path, but combination should always equal path.
- assertEquals(URL2 + "/child", r.getString("servletURI"));
- assertTrue(r.getString("testURL1").endsWith(port + path + "/testuris/child/testURL"));
- // Always the same
- assertTrue(r.getString("testURL2").endsWith(port + "/testURL"));
- assertEquals("http://testURL", r.getString("testURL3"));
-
- //--------------------------------------------------------------------------------
- // http://localhost:8080/sample/testuris/child/test4/test4/foo
- //--------------------------------------------------------------------------------
- r = client.doGet("/testuris/child/test4/test4/foo").getResponse(ObjectMap.class);
- assertEquals("child.test4", r.getString("testMethod"));
- assertEquals("/test4/test4/foo", r.getString("pathInfo"));
- assertEquals("foo", r.getString("pathRemainder"));
- assertEquals(path + "/testuris/child/test4/test4", r.getString("requestParentURI"));
- assertEquals(path + "/testuris/child/test4/test4/foo", r.getString("requestURI"));
- assertTrue(r.getString("requestURL").endsWith(port + path + "/testuris/child/test4/test4/foo"));
- // Same for servlet
- assertEquals(path + "/testuris/child", r.getString("contextPath") + r.getString("servletPath")); // App may not have context path, but combination should always equal path.
- assertEquals(URL2 + "/child", r.getString("servletURI"));
- assertTrue(r.getString("testURL1").endsWith(port + path + "/testuris/child/testURL"));
- // Always the same
- assertTrue(r.getString("testURL2").endsWith(port + "/testURL"));
- assertEquals("http://testURL", r.getString("testURL3"));
-
- //--------------------------------------------------------------------------------
- // http://localhost:8080/sample/testuris/child/test4/test4/foo/bar
- //--------------------------------------------------------------------------------
- r = client.doGet("/testuris/child/test4/test4/foo/bar").getResponse(ObjectMap.class);
- assertEquals("child.test4", r.getString("testMethod"));
- assertEquals("/test4/test4/foo/bar", r.getString("pathInfo"));
- assertEquals("foo/bar", r.getString("pathRemainder"));
- assertEquals(path + "/testuris/child/test4/test4/foo", r.getString("requestParentURI"));
- assertEquals(path + "/testuris/child/test4/test4/foo/bar", r.getString("requestURI"));
- assertTrue(r.getString("requestURL").endsWith(port + path + "/testuris/child/test4/test4/foo/bar"));
- // Same for servlet
- assertEquals(path + "/testuris/child", r.getString("contextPath") + r.getString("servletPath")); // App may not have context path, but combination should always equal path.
- assertEquals(URL2 + "/child", r.getString("servletURI"));
- assertTrue(r.getString("testURL1").endsWith(port + path + "/testuris/child/testURL"));
- // Always the same
- assertTrue(r.getString("testURL2").endsWith(port + "/testURL"));
- assertEquals("http://testURL", r.getString("testURL3"));
-
- //--------------------------------------------------------------------------------
- // http://localhost:8080/sample/testuris/child/test4/test4/foo/bar%2Fbaz
- //--------------------------------------------------------------------------------
- r = client.doGet("/testuris/child/test4/test4/foo/bar%2Fbaz").getResponse(ObjectMap.class);
- assertEquals("child.test4", r.getString("testMethod"));
- assertEquals("/test4/test4/foo/bar/baz", r.getString("pathInfo"));
- assertEquals("foo/bar/baz", r.getString("pathRemainder"));
- assertEquals(path + "/testuris/child/test4/test4/foo", r.getString("requestParentURI"));
- assertEquals(path + "/testuris/child/test4/test4/foo/bar%2Fbaz", r.getString("requestURI"));
- assertTrue(r.getString("requestURL").endsWith(port + path + "/testuris/child/test4/test4/foo/bar%2Fbaz"));
- // Same for servlet
- assertEquals(path + "/testuris/child", r.getString("contextPath") + r.getString("servletPath")); // App may not have context path, but combination should always equal path.
- assertEquals(URL2 + "/child", r.getString("servletURI"));
- assertTrue(r.getString("testURL1").endsWith(port + path + "/testuris/child/testURL"));
- // Always the same
- assertTrue(r.getString("testURL2").endsWith(port + "/testURL"));
- assertEquals("http://testURL", r.getString("testURL3"));
-
- client.closeQuietly();
- }
-
- //====================================================================================================
- // testGrandChild - http://localhost:8080/sample/testuris/child/grandchild
- //====================================================================================================
- @Test
- public void testGrandChild() throws Exception {
- RestClient client = new TestRestClient(JsonSerializer.DEFAULT, JsonParser.DEFAULT);
- ObjectMap r;
-
- //--------------------------------------------------------------------------------
- // http://localhost:8080/sample/testuris/child
- //--------------------------------------------------------------------------------
- r = client.doGet("/testuris/child/grandchild").getResponse(ObjectMap.class);
- assertEquals("grandchild.test1", r.getString("testMethod"));
- assertNull(r.getString("pathInfo"));
- assertNull(r.getString("pathRemainder"));
- assertEquals(path + "/testuris/child", r.getString("requestParentURI"));
- assertEquals(path + "/testuris/child/grandchild", r.getString("requestURI"));
- assertTrue(r.getString("requestURL").endsWith(port + path + "/testuris/child/grandchild"));
- // Same for servlet
- assertEquals(path + "/testuris/child/grandchild", r.getString("contextPath") + r.getString("servletPath")); // App may not have context path, but combination should always equal path.
- assertEquals(URL2 + "/child/grandchild", r.getString("servletURI"));
- assertTrue(r.getString("testURL1").endsWith(port + path + "/testuris/child/grandchild/testURL"));
- // Always the same
- assertTrue(r.getString("testURL2").endsWith(port + "/testURL"));
- assertEquals("http://testURL", r.getString("testURL3"));
-
- //--------------------------------------------------------------------------------
- // http://localhost:8080/sample/testuris/child/foo
- //--------------------------------------------------------------------------------
- r = client.doGet("/testuris/child/grandchild/foo").getResponse(ObjectMap.class);
- assertEquals("grandchild.test1", r.getString("testMethod"));
- assertEquals("/foo", r.getString("pathInfo"));
- assertEquals("foo", r.getString("pathRemainder"));
- assertEquals(path + "/testuris/child/grandchild", r.getString("requestParentURI"));
- assertEquals(path + "/testuris/child/grandchild/foo", r.getString("requestURI"));
- assertTrue(r.getString("requestURL").endsWith(port + path + "/testuris/child/grandchild/foo"));
- // Same for servlet
- assertEquals(path + "/testuris/child/grandchild", r.getString("contextPath") + r.getString("servletPath")); // App may not have context path, but combination should always equal path.
- assertEquals(URL2 + "/child/grandchild", r.getString("servletURI"));
- assertTrue(r.getString("testURL1").endsWith(port + path + "/testuris/child/grandchild/testURL"));
- // Always the same
- assertTrue(r.getString("testURL2").endsWith(port + "/testURL"));
- assertEquals("http://testURL", r.getString("testURL3"));
-
- //--------------------------------------------------------------------------------
- // http://localhost:8080/sample/testuris/child/foo/bar
- //--------------------------------------------------------------------------------
- r = client.doGet("/testuris/child/grandchild/foo/bar").getResponse(ObjectMap.class);
- assertEquals("grandchild.test1", r.getString("testMethod"));
- assertEquals("/foo/bar", r.getString("pathInfo"));
- assertEquals("foo/bar", r.getString("pathRemainder"));
- assertEquals(path + "/testuris/child/grandchild/foo", r.getString("requestParentURI"));
- assertEquals(path + "/testuris/child/grandchild/foo/bar", r.getString("requestURI"));
- assertTrue(r.getString("requestURL").endsWith(port + path + "/testuris/child/grandchild/foo/bar"));
- // Same for servlet
- assertEquals(path + "/testuris/child/grandchild", r.getString("contextPath") + r.getString("servletPath")); // App may not have context path, but combination should always equal path.
- assertEquals(URL2 + "/child/grandchild", r.getString("servletURI"));
- assertTrue(r.getString("testURL1").endsWith(port + path + "/testuris/child/grandchild/testURL"));
- // Always the same
- assertTrue(r.getString("testURL2").endsWith(port + "/testURL"));
- assertEquals("http://testURL", r.getString("testURL3"));
-
- //--------------------------------------------------------------------------------
- // http://localhost:8080/sample/testuris/child/foo/bar%2Fbaz
- //--------------------------------------------------------------------------------
- r = client.doGet("/testuris/child/grandchild/foo/bar%2Fbaz").getResponse(ObjectMap.class);
- assertEquals("grandchild.test1", r.getString("testMethod"));
- assertEquals("/foo/bar/baz", r.getString("pathInfo"));
- assertEquals("foo/bar/baz", r.getString("pathRemainder"));
- assertEquals(path + "/testuris/child/grandchild/foo", r.getString("requestParentURI"));
- assertEquals(path + "/testuris/child/grandchild/foo/bar%2Fbaz", r.getString("requestURI"));
- assertTrue(r.getString("requestURL").endsWith(port + path + "/testuris/child/grandchild/foo/bar%2Fbaz"));
- // Same for servlet
- assertEquals(path + "/testuris/child/grandchild", r.getString("contextPath") + r.getString("servletPath")); // App may not have context path, but combination should always equal path.
- assertEquals(URL2 + "/child/grandchild", r.getString("servletURI"));
- assertTrue(r.getString("testURL1").endsWith(port + path + "/testuris/child/grandchild/testURL"));
- // Always the same
- assertTrue(r.getString("testURL2").endsWith(port + "/testURL"));
- assertEquals("http://testURL", r.getString("testURL3"));
-
- //--------------------------------------------------------------------------------
- // http://localhost:8080/sample/testuris/child/test2
- //--------------------------------------------------------------------------------
- r = client.doGet("/testuris/child/grandchild/test2").getResponse(ObjectMap.class);
- assertEquals("grandchild.test2", r.getString("testMethod"));
- assertEquals("/test2", r.getString("pathInfo"));
- assertNull(r.getString("pathRemainder"));
- assertEquals(path + "/testuris/child/grandchild", r.getString("requestParentURI"));
- assertEquals(path + "/testuris/child/grandchild/test2", r.getString("requestURI"));
- assertTrue(r.getString("requestURL").endsWith(port + path + "/testuris/child/grandchild/test2"));
- // Same for servlet
- assertEquals(path + "/testuris/child/grandchild", r.getString("contextPath") + r.getString("servletPath")); // App may not have context path, but combination should always equal path.
- assertEquals(URL2 + "/child/grandchild", r.getString("servletURI"));
- assertTrue(r.getString("testURL1").endsWith(port + path + "/testuris/child/grandchild/testURL"));
- // Always the same
- assertTrue(r.getString("testURL2").endsWith(port + "/testURL"));
- assertEquals("http://testURL", r.getString("testURL3"));
-
- //--------------------------------------------------------------------------------
- // http://localhost:8080/sample/testuris/child/test2/foo
- //--------------------------------------------------------------------------------
- r = client.doGet("/testuris/child/grandchild/test2/foo").getResponse(ObjectMap.class);
- assertEquals("grandchild.test2", r.getString("testMethod"));
- assertEquals("/test2/foo", r.getString("pathInfo"));
- assertEquals("foo", r.getString("pathRemainder"));
- assertEquals(path + "/testuris/child/grandchild/test2", r.getString("requestParentURI"));
- assertEquals(path + "/testuris/child/grandchild/test2/foo", r.getString("requestURI"));
- assertTrue(r.getString("requestURL").endsWith(port + path + "/testuris/child/grandchild/test2/foo"));
- // Same for servlet
- assertEquals(path + "/testuris/child/grandchild", r.getString("contextPath") + r.getString("servletPath")); // App may not have context path, but combination should always equal path.
- assertEquals(URL2 + "/child/grandchild", r.getString("servletURI"));
- assertTrue(r.getString("testURL1").endsWith(port + path + "/testuris/child/grandchild/testURL"));
- // Always the same
- assertTrue(r.getString("testURL2").endsWith(port + "/testURL"));
- assertEquals("http://testURL", r.getString("testURL3"));
-
- //--------------------------------------------------------------------------------
- // http://localhost:8080/sample/testuris/child/test2/foo/bar
- //--------------------------------------------------------------------------------
- r = client.doGet("/testuris/child/grandchild/test2/foo/bar").getResponse(ObjectMap.class);
- assertEquals("grandchild.test2", r.getString("testMethod"));
- assertEquals("/test2/foo/bar", r.getString("pathInfo"));
- assertEquals("foo/bar", r.getString("pathRemainder"));
- assertEquals(path + "/testuris/child/grandchild/test2/foo", r.getString("requestParentURI"));
- assertEquals(path + "/testuris/child/grandchild/test2/foo/bar", r.getString("requestURI"));
- assertTrue(r.getString("requestURL").endsWith(port + path + "/testuris/child/grandchild/test2/foo/bar"));
- // Same for servlet
- assertEquals(path + "/testuris/child/grandchild", r.getString("contextPath") + r.getString("servletPath")); // App may not have context path, but combination should always equal path.
- assertEquals(URL2 + "/child/grandchild", r.getString("servletURI"));
- assertTrue(r.getString("testURL1").endsWith(port + path + "/testuris/child/grandchild/testURL"));
- // Always the same
- assertTrue(r.getString("testURL2").endsWith(port + "/testURL"));
- assertEquals("http://testURL", r.getString("testURL3"));
-
- //--------------------------------------------------------------------------------
- // http://localhost:8080/sample/testuris/child/test2/foo/bar%2Fbaz
- //--------------------------------------------------------------------------------
- r = client.doGet("/testuris/child/grandchild/test2/foo/bar%2Fbaz").getResponse(ObjectMap.class);
- assertEquals("grandchild.test2", r.getString("testMethod"));
- assertEquals("/test2/foo/bar/baz", r.getString("pathInfo"));
- assertEquals("foo/bar/baz", r.getString("pathRemainder"));
- assertEquals(path + "/testuris/child/grandchild/test2/foo", r.getString("requestParentURI"));
- assertEquals(path + "/testuris/child/grandchild/test2/foo/bar%2Fbaz", r.getString("requestURI"));
- assertTrue(r.getString("requestURL").endsWith(port + path + "/testuris/child/grandchild/test2/foo/bar%2Fbaz"));
- // Same for servlet
- assertEquals(path + "/testuris/child/grandchild", r.getString("contextPath") + r.getString("servletPath")); // App may not have context path, but combination should always equal path.
- assertEquals(URL2 + "/child/grandchild", r.getString("servletURI"));
- assertTrue(r.getString("testURL1").endsWith(port + path + "/testuris/child/grandchild/testURL"));
- // Always the same
- assertTrue(r.getString("testURL2").endsWith(port + "/testURL"));
- assertEquals("http://testURL", r.getString("testURL3"));
-
- //--------------------------------------------------------------------------------
- // http://localhost:8080/sample/testuris/child/test3%2Ftest3
- //--------------------------------------------------------------------------------
- r = client.doGet("/testuris/child/grandchild/test3%2Ftest3").getResponse(ObjectMap.class);
- assertEquals("grandchild.test3", r.getString("testMethod"));
- assertEquals("/test3/test3", r.getString("pathInfo"));
- assertNull(r.getString("pathRemainder"));
- assertEquals(path + "/testuris/child/grandchild", r.getString("requestParentURI"));
- assertEquals(path + "/testuris/child/grandchild/test3%2Ftest3", r.getString("requestURI"));
- assertTrue(r.getString("requestURL").endsWith(port + path + "/testuris/child/grandchild/test3%2Ftest3"));
- // Same for servlet
- assertEquals(path + "/testuris/child/grandchild", r.getString("contextPath") + r.getString("servletPath")); // App may not have context path, but combination should always equal path.
- assertEquals(URL2 + "/child/grandchild", r.getString("servletURI"));
- assertTrue(r.getString("testURL1").endsWith(port + path + "/testuris/child/grandchild/testURL"));
- // Always the same
- assertTrue(r.getString("testURL2").endsWith(port + "/testURL"));
- assertEquals("http://testURL", r.getString("testURL3"));
-
- //--------------------------------------------------------------------------------
- // http://localhost:8080/sample/testuris/child/test3%2Ftest3/foo
- //--------------------------------------------------------------------------------
- r = client.doGet("/testuris/child/grandchild/test3%2Ftest3/foo").getResponse(ObjectMap.class);
- assertEquals("grandchild.test3", r.getString("testMethod"));
- assertEquals("/test3/test3/foo", r.getString("pathInfo"));
- assertEquals("foo", r.getString("pathRemainder"));
- assertEquals(path + "/testuris/child/grandchild/test3%2Ftest3", r.getString("requestParentURI"));
- assertEquals(path + "/testuris/child/grandchild/test3%2Ftest3/foo", r.getString("requestURI"));
- assertTrue(r.getString("requestURL").endsWith(port + path + "/testuris/child/grandchild/test3%2Ftest3/foo"));
- // Same for servlet
- assertEquals(path + "/testuris/child/grandchild", r.getString("contextPath") + r.getString("servletPath")); // App may not have context path, but combination should always equal path.
- assertEquals(URL2 + "/child/grandchild", r.getString("servletURI"));
- assertTrue(r.getString("testURL1").endsWith(port + path + "/testuris/child/grandchild/testURL"));
- // Always the same
- assertTrue(r.getString("testURL2").endsWith(port + "/testURL"));
- assertEquals("http://testURL", r.getString("testURL3"));
-
- //--------------------------------------------------------------------------------
- // http://localhost:8080/sample/testuris/child/test3%2Ftest3/foo/bar
- //--------------------------------------------------------------------------------
- r = client.doGet("/testuris/child/grandchild/test3%2Ftest3/foo/bar").getResponse(ObjectMap.class);
- assertEquals("grandchild.test3", r.getString("testMethod"));
- assertEquals("/test3/test3/foo/bar", r.getString("pathInfo"));
- assertEquals("foo/bar", r.getString("pathRemainder"));
- assertEquals(path + "/testuris/child/grandchild/test3%2Ftest3/foo", r.getString("requestParentURI"));
- assertEquals(path + "/testuris/child/grandchild/test3%2Ftest3/foo/bar", r.getString("requestURI"));
- assertTrue(r.getString("requestURL").endsWith(port + path + "/testuris/child/grandchild/test3%2Ftest3/foo/bar"));
- // Same for servlet
- assertEquals(path + "/testuris/child/grandchild", r.getString("contextPath") + r.getString("servletPath")); // App may not have context path, but combination should always equal path.
- assertEquals(URL2 + "/child/grandchild", r.getString("servletURI"));
- assertTrue(r.getString("testURL1").endsWith(port + path + "/testuris/child/grandchild/testURL"));
- // Always the same
- assertTrue(r.getString("testURL2").endsWith(port + "/testURL"));
- assertEquals("http://testURL", r.getString("testURL3"));
-
- //--------------------------------------------------------------------------------
- // http://localhost:8080/sample/testuris/child/test3%2Ftest3/foo/bar%2Fbaz
- //--------------------------------------------------------------------------------
- r = client.doGet("/testuris/child/grandchild/test3%2Ftest3/foo/bar%2Fbaz").getResponse(ObjectMap.class);
- assertEquals("grandchild.test3", r.getString("testMethod"));
- assertEquals("/test3/test3/foo/bar/baz", r.getString("pathInfo"));
- assertEquals("foo/bar/baz", r.getString("pathRemainder"));
- assertEquals(path + "/testuris/child/grandchild/test3%2Ftest3/foo", r.getString("requestParentURI"));
- assertEquals(path + "/testuris/child/grandchild/test3%2Ftest3/foo/bar%2Fbaz", r.getString("requestURI"));
- assertTrue(r.getString("requestURL").endsWith(port + path + "/testuris/child/grandchild/test3%2Ftest3/foo/bar%2Fbaz"));
- // Same for servlet
- assertEquals(path + "/testuris/child/grandchild", r.getString("contextPath") + r.getString("servletPath")); // App may not have context path, but combination should always equal path.
- assertEquals(URL2 + "/child/grandchild", r.getString("servletURI"));
- assertTrue(r.getString("testURL1").endsWith(port + path + "/testuris/child/grandchild/testURL"));
- // Always the same
- assertTrue(r.getString("testURL2").endsWith(port + "/testURL"));
- assertEquals("http://testURL", r.getString("testURL3"));
-
- //--------------------------------------------------------------------------------
- // http://localhost:8080/sample/testuris/child/test4/test4
- //--------------------------------------------------------------------------------
- r = client.doGet("/testuris/child/grandchild/test4/test4").getResponse(ObjectMap.class);
- assertEquals("grandchild.test4", r.getString("testMethod"));
- assertEquals("/test4/test4", r.getString("pathInfo"));
- assertNull(r.getString("pathRemainder"));
- assertEquals(path + "/testuris/child/grandchild/test4", r.getString("requestParentURI"));
- assertEquals(path + "/testuris/child/grandchild/test4/test4", r.getString("requestURI"));
- assertTrue(r.getString("requestURL").endsWith(port + path + "/testuris/child/grandchild/test4/test4"));
- // Same for servlet
- assertEquals(path + "/testuris/child/grandchild", r.getString("contextPath") + r.getString("servletPath")); // App may not have context path, but combination should always equal path.
- assertEquals(URL2 + "/child/grandchild", r.getString("servletURI"));
- assertTrue(r.getString("testURL1").endsWith(port + path + "/testuris/child/grandchild/testURL"));
- // Always the same
- assertTrue(r.getString("testURL2").endsWith(port + "/testURL"));
- assertEquals("http://testURL", r.getString("testURL3"));
-
- //--------------------------------------------------------------------------------
- // http://localhost:8080/sample/testuris/child/test4/test4/foo
- //--------------------------------------------------------------------------------
- r = client.doGet("/testuris/child/grandchild/test4/test4/foo").getResponse(ObjectMap.class);
- assertEquals("grandchild.test4", r.getString("testMethod"));
- assertEquals("/test4/test4/foo", r.getString("pathInfo"));
- assertEquals("foo", r.getString("pathRemainder"));
- assertEquals(path + "/testuris/child/grandchild/test4/test4", r.getString("requestParentURI"));
- assertEquals(path + "/testuris/child/grandchild/test4/test4/foo", r.getString("requestURI"));
- assertTrue(r.getString("requestURL").endsWith(port + path + "/testuris/child/grandchild/test4/test4/foo"));
- // Same for servlet
- assertEquals(path + "/testuris/child/grandchild", r.getString("contextPath") + r.getString("servletPath")); // App may not have context path, but combination should always equal path.
- assertEquals(URL2 + "/child/grandchild", r.getString("servletURI"));
- assertTrue(r.getString("testURL1").endsWith(port + path + "/testuris/child/grandchild/testURL"));
- // Always the same
- assertTrue(r.getString("testURL2").endsWith(port + "/testURL"));
- assertEquals("http://testURL", r.getString("testURL3"));
-
- //--------------------------------------------------------------------------------
- // http://localhost:8080/sample/testuris/child/test4/test4/foo/bar
- //--------------------------------------------------------------------------------
- r = client.doGet("/testuris/child/grandchild/test4/test4/foo/bar").getResponse(ObjectMap.class);
- assertEquals("grandchild.test4", r.getString("testMethod"));
- assertEquals("/test4/test4/foo/bar", r.getString("pathInfo"));
- assertEquals("foo/bar", r.getString("pathRemainder"));
- assertEquals(path + "/testuris/child/grandchild/test4/test4/foo", r.getString("requestParentURI"));
- assertEquals(path + "/testuris/child/grandchild/test4/test4/foo/bar", r.getString("requestURI"));
- assertTrue(r.getString("requestURL").endsWith(port + path + "/testuris/child/grandchild/test4/test4/foo/bar"));
- // Same for servlet
- assertEquals(path + "/testuris/child/grandchild", r.getString("contextPath") + r.getString("servletPath")); // App may not have context path, but combination should always equal path.
- assertEquals(URL2 + "/child/grandchild", r.getString("servletURI"));
- assertTrue(r.getString("testURL1").endsWith(port + path + "/testuris/child/grandchild/testURL"));
- // Always the same
- assertTrue(r.getString("testURL2").endsWith(port + "/testURL"));
- assertEquals("http://testURL", r.getString("testURL3"));
-
- //--------------------------------------------------------------------------------
- // http://localhost:8080/sample/testuris/child/test4/test4/foo/bar%2Fbaz
- //--------------------------------------------------------------------------------
- r = client.doGet("/testuris/child/grandchild/test4/test4/foo/bar%2Fbaz").getResponse(ObjectMap.class);
- assertEquals("grandchild.test4", r.getString("testMethod"));
- assertEquals("/test4/test4/foo/bar/baz", r.getString("pathInfo"));
- assertEquals("foo/bar/baz", r.getString("pathRemainder"));
- assertEquals(path + "/testuris/child/grandchild/test4/test4/foo", r.getString("requestParentURI"));
- assertEquals(path + "/testuris/child/grandchild/test4/test4/foo/bar%2Fbaz", r.getString("requestURI"));
- assertTrue(r.getString("requestURL").endsWith(port + path + "/testuris/child/grandchild/test4/test4/foo/bar%2Fbaz"));
- // Same for servlet
- assertEquals(path + "/testuris/child/grandchild", r.getString("contextPath") + r.getString("servletPath")); // App may not have context path, but combination should always equal path.
- assertEquals(URL2 + "/child/grandchild", r.getString("servletURI"));
- assertTrue(r.getString("testURL1").endsWith(port + path + "/testuris/child/grandchild/testURL"));
- // Always the same
- assertTrue(r.getString("testURL2").endsWith(port + "/testURL"));
- assertEquals("http://testURL", r.getString("testURL3"));
-
- client.closeQuietly();
- }
-
- private static int getPort(String url) {
- Pattern p = Pattern.compile("\\:(\\d{2,5})");
- Matcher m = p.matcher(url);
- if (m.find())
- return Integer.parseInt(m.group(1));
- return -1;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestUrlContent.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestUrlContent.java b/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestUrlContent.java
deleted file mode 100755
index 6e291bf..0000000
--- a/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestUrlContent.java
+++ /dev/null
@@ -1,74 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.server;
-
-import static org.junit.Assert.*;
-
-import org.apache.juneau.client.*;
-import org.junit.*;
-
-public class CT_TestUrlContent {
-
- private static String URL = "/testUrlContent";
- private static RestClient client;
-
- @BeforeClass
- public static void beforeClass() {
- client = new TestRestClient().setHeader("Accept", "text/plain");
- }
-
- @AfterClass
- public static void afterClass() {
- client.closeQuietly();
- }
-
- //====================================================================================================
- // Test URL &Content parameter containing a String
- //====================================================================================================
- @Test
- public void testString() throws Exception {
- String r;
- r = client.doGet(URL + "/testString?content=\'xxx\'&Content-Type=text/json").getResponseAsString();
- assertEquals("class=java.lang.String, value=xxx", r);
- }
-
- //====================================================================================================
- // Test URL &Content parameter containing an Enum
- //====================================================================================================
- @Test
- public void testEnum() throws Exception {
- String r;
- r = client.doGet(URL + "/testEnum?content='X1'&Content-Type=text/json").getResponseAsString();
- assertEquals("class=org.apache.juneau.server.TestUrlContent$TestEnum, value=X1", r);
- }
-
- //====================================================================================================
- // Test URL &Content parameter containing a Bean
- //====================================================================================================
- @Test
- public void testBean() throws Exception {
- String r;
- r = client.doGet(URL + "/testBean?content=%7Bf1:1,f2:'foobar'%7D&Content-Type=text/json").getResponseAsString();
- assertEquals("class=org.apache.juneau.server.TestUrlContent$TestBean, value={f1:1,f2:'foobar'}", r);
- }
-
- //====================================================================================================
- // Test URL &Content parameter containing an int
- //====================================================================================================
- @Test
- public void testInt() throws Exception {
- String r;
- r = client.doGet(URL + "/testInt?content=123&Content-Type=text/json").getResponseAsString();
- assertEquals("class=java.lang.Integer, value=123", r);
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_UrlPathPattern.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_UrlPathPattern.java b/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_UrlPathPattern.java
deleted file mode 100755
index d4fb434..0000000
--- a/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_UrlPathPattern.java
+++ /dev/null
@@ -1,39 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.server;
-
-import static org.junit.Assert.*;
-
-import java.util.*;
-
-import org.apache.juneau.json.*;
-import org.junit.*;
-
-public class CT_UrlPathPattern {
- @Test
- public void testComparison() throws Exception {
- List<UrlPathPattern> l = new LinkedList<UrlPathPattern>();
-
- l.add(new UrlPathPattern("/foo"));
- l.add(new UrlPathPattern("/foo/*"));
- l.add(new UrlPathPattern("/foo/bar"));
- l.add(new UrlPathPattern("/foo/bar/*"));
- l.add(new UrlPathPattern("/foo/{id}"));
- l.add(new UrlPathPattern("/foo/{id}/*"));
- l.add(new UrlPathPattern("/foo/{id}/bar"));
- l.add(new UrlPathPattern("/foo/{id}/bar/*"));
-
- Collections.sort(l);
- assertEquals("['/foo/bar','/foo/bar/*','/foo/{id}/bar','/foo/{id}/bar/*','/foo/{id}','/foo/{id}/*','/foo','/foo/*']", JsonSerializer.DEFAULT_LAX.serialize(l));
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/JacocoDummyTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/JacocoDummyTest.java b/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/JacocoDummyTest.java
new file mode 100755
index 0000000..4123034
--- /dev/null
+++ b/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/JacocoDummyTest.java
@@ -0,0 +1,37 @@
+/***************************************************************************************************************************
+ * 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.juneau.server;
+
+import java.lang.reflect.*;
+
+import org.junit.*;
+
+public class JacocoDummyTest {
+
+ //====================================================================================================
+ // Dummy code to add test coverage in Jacoco.
+ //====================================================================================================
+ @Test
+ public void accessPrivateConstructorsOnStaticUtilityClasses() throws Exception {
+
+ Class<?>[] classes = new Class[] {
+ RestUtils.class
+ };
+
+ for (Class<?> c : classes) {
+ Constructor<?> c1 = c.getDeclaredConstructor();
+ c1.setAccessible(true);
+ c1.newInstance();
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/RestUtilsTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/RestUtilsTest.java b/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/RestUtilsTest.java
new file mode 100755
index 0000000..26a964a
--- /dev/null
+++ b/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/RestUtilsTest.java
@@ -0,0 +1,188 @@
+/***************************************************************************************************************************
+ * 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.juneau.server;
+
+import static org.apache.juneau.server.RestUtils.*;
+import static org.junit.Assert.*;
+
+import org.junit.*;
+
+public class RestUtilsTest {
+
+ //====================================================================================================
+ // decode(String)
+ //====================================================================================================
+ @Test
+ public void testDecode() throws Exception {
+ assertNull(decode(null));
+ assertEquals("foo/bar baz bing", decode("foo%2Fbar+baz++bing"));
+ }
+
+ //====================================================================================================
+ // encode(String)
+ //====================================================================================================
+ @Test
+ public void testEncode() throws Exception {
+ assertNull(encode(null));
+ assertEquals("foo%2Fbar+baz++bing", encode("foo/bar baz bing"));
+ assertEquals("foobar", encode("foobar"));
+ assertEquals("+", encode(" "));
+ assertEquals("%2F", encode("/"));
+ }
+
+ //====================================================================================================
+ // trimPathInfo(String,String)
+ //====================================================================================================
+ @Test
+ public void testGetServletURI() throws Exception {
+ String e, sp, cp;
+
+ e = "http://hostname";
+ sp = "";
+ cp = "";
+
+ for (String s : new String[]{
+ "http://hostname",
+ "http://hostname/foo",
+ "http://hostname?foo",
+ "http://hostname/?foo"})
+ assertEquals(e, trimPathInfo(new StringBuffer(s), cp, sp).toString());
+
+ for (String s : new String[]{
+ "http:/hostname?foo"}) {
+ try {
+ trimPathInfo(new StringBuffer(s), cp, sp);
+ fail("Exception expected - " + s);
+ } catch (RuntimeException ex) {}
+ }
+
+
+ e = "http://hostname";
+ sp = "/";
+ cp = "/";
+
+ for (String s : new String[]{
+ "http://hostname",
+ "http://hostname/foo",
+ "http://hostname?foo",
+ "http://hostname/?foo"})
+ assertEquals(e, trimPathInfo(new StringBuffer(s), cp, sp).toString());
+
+ e = "http://hostname/foo";
+ sp = "/foo";
+ cp = "/";
+
+ for (String s : new String[]{
+ "http://hostname/foo",
+ "http://hostname/foo/bar",
+ "http://hostname/foo?bar"})
+ assertEquals(e, trimPathInfo(new StringBuffer(s), cp, sp).toString());
+
+ for (String s : new String[]{
+ "http://hostname/foo2",
+ "http://hostname/fo2",
+ "http://hostname?foo",
+ "http://hostname/fo?bar",
+ "http:/hostname/foo"}) {
+ try {
+ trimPathInfo(new StringBuffer(s), cp, sp);
+ fail("Exception expected - " + s);
+ } catch (RuntimeException ex) {}
+ }
+
+ e = "http://hostname/foo/bar";
+ sp = "/foo/bar";
+ cp = "/";
+
+ for (String s : new String[]{
+ "http://hostname/foo/bar",
+ "http://hostname/foo/bar/baz",
+ "http://hostname/foo/bar?baz"})
+ assertEquals(e, trimPathInfo(new StringBuffer(s), cp, sp).toString());
+
+ for (String s : new String[]{
+ "http://hostname/foo2/bar",
+ "http://hostname/foo/bar2"
+ }) {
+ try {
+ trimPathInfo(new StringBuffer(s), cp, sp);
+ fail("Exception expected - " + s);
+ } catch (RuntimeException ex) {}
+ }
+
+ e = "http://hostname/foo/bar";
+ sp = "/bar";
+ cp = "/foo";
+
+ for (String s : new String[]{
+ "http://hostname/foo/bar",
+ "http://hostname/foo/bar/baz",
+ "http://hostname/foo/bar?baz"})
+ assertEquals(e, trimPathInfo(new StringBuffer(s), cp, sp).toString());
+
+ for (String s : new String[]{
+ "http://hostname/foo2/bar",
+ "http://hostname/foo/bar2"
+ }) {
+ try {
+ trimPathInfo(new StringBuffer(s), cp, sp);
+ fail("Exception expected - " + s);
+ } catch (RuntimeException ex) {}
+ }
+ }
+
+ //====================================================================================================
+ // trimSlashes(String)
+ //====================================================================================================
+ @Test
+ public void testTrimSlashes() throws Exception {
+ assertNull(trimSlashes(null));
+ assertEquals("", trimSlashes(""));
+ assertEquals("", trimSlashes("/"));
+ assertEquals("", trimSlashes("//"));
+ assertEquals("foo/bar", trimSlashes("foo/bar"));
+ assertEquals("foo/bar", trimSlashes("foo/bar//"));
+ assertEquals("foo/bar", trimSlashes("/foo/bar//"));
+ assertEquals("foo/bar", trimSlashes("//foo/bar//"));
+ }
+
+ //====================================================================================================
+ // trimTrailingSlashes(String)
+ //====================================================================================================
+ @Test
+ public void testTrimTrailingSlashes() throws Exception {
+ assertNull(trimTrailingSlashes((String)null));
+ assertEquals("", trimTrailingSlashes(""));
+ assertEquals("", trimTrailingSlashes("/"));
+ assertEquals("", trimTrailingSlashes("//"));
+ assertEquals("foo/bar", trimTrailingSlashes("foo/bar"));
+ assertEquals("foo/bar", trimTrailingSlashes("foo/bar//"));
+ assertEquals("/foo/bar", trimTrailingSlashes("/foo/bar//"));
+ assertEquals("//foo/bar", trimTrailingSlashes("//foo/bar//"));
+ }
+
+ //====================================================================================================
+ // trimTrailingSlashes(StringBuffer)
+ //====================================================================================================
+ @Test
+ public void testTrimTrailingSlashes2() throws Exception {
+ assertNull(trimTrailingSlashes((StringBuffer)null));
+ assertEquals("", trimTrailingSlashes(new StringBuffer("")).toString());
+ assertEquals("", trimTrailingSlashes(new StringBuffer("/")).toString());
+ assertEquals("", trimTrailingSlashes(new StringBuffer("//")).toString());
+ assertEquals("foo/bar", trimTrailingSlashes(new StringBuffer("foo/bar")).toString());
+ assertEquals("foo/bar", trimTrailingSlashes(new StringBuffer("foo/bar//")).toString());
+ assertEquals("/foo/bar", trimTrailingSlashes(new StringBuffer("/foo/bar//")).toString());
+ assertEquals("//foo/bar", trimTrailingSlashes(new StringBuffer("//foo/bar//")).toString());
+ }
+}
[19/44] incubator-juneau git commit: Rename CT_* testcases.
Posted by ja...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/ini/CT_ConfigFile.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/ini/CT_ConfigFile.java b/org.apache.juneau/src/test/java/org/apache/juneau/ini/CT_ConfigFile.java
deleted file mode 100755
index 9c64ce5..0000000
--- a/org.apache.juneau/src/test/java/org/apache/juneau/ini/CT_ConfigFile.java
+++ /dev/null
@@ -1,2154 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.ini;
-
-import static org.apache.juneau.TestUtils.*;
-import static org.junit.Assert.*;
-
-import java.io.*;
-import java.net.*;
-import java.util.*;
-import java.util.concurrent.*;
-
-import org.apache.juneau.*;
-import org.apache.juneau.annotation.*;
-import org.apache.juneau.internal.*;
-import org.apache.juneau.json.*;
-import org.apache.juneau.parser.*;
-import org.apache.juneau.svl.*;
-import org.apache.juneau.utils.*;
-import org.junit.*;
-
-public class CT_ConfigFile {
-
- private File getFreshFile() {
- String tempDir = System.getProperty("java.io.tmpdir");
- File f = new File(tempDir, "Test.cfg");
- if (f.exists())
- f.delete();
- f.deleteOnExit();
- return f;
- }
-
- //====================================================================================================
- // testCommentsOnly
- //====================================================================================================
- @Test
- public void testCommentsOnly() throws Exception {
-
- File f = getFreshFile();
-
- ConfigFile cf = ConfigMgr.DEFAULT.create(f)
- .addLines(null, "# c1", "\t# c2", " c3 ");
- ConfigFile cfw = cf.getResolving(VarResolver.DEFAULT);
-
- String expected = "# c1|\t# c2| c3 |";
- assertTextEquals(expected, cf);
- assertTextEquals(expected, cfw);
-
- cf.save();
- cf = ConfigMgr.DEFAULT.create(f);
- expected = "# c1|\t# c2| c3 |";
- assertTextEquals(expected, cf);
- assertTextEquals(expected, cfw);
-
- }
-
- //====================================================================================================
- // testBasics
- //====================================================================================================
- @Test
- public void testBasics() throws Exception {
-
- File f = getFreshFile();
-
- ConfigFile cf = ConfigMgr.DEFAULT.create(f)
- .addLines(null, "# c1", "\t# c2", " c3 ", "x1=1", "x2=true", "x3=null")
- .addLines("s1", "#c4", "k1=1", "#c5 foo=bar", "k2 = true", "k3 = \tnull");
- ConfigFile cfw = cf.getResolving().getResolving();
-
- String expected = "# c1|\t# c2| c3 |x1 = 1|x2 = true|x3 = null|[s1]|#c4|k1 = 1|#c5 foo=bar|k2 = true|k3 = null|";
- assertTextEquals(expected, cf);
- assertTextEquals(expected, cfw);
-
- cf.save();
- cf = ConfigMgr.DEFAULT.create(f);
- cfw = cf.getResolving(VarResolver.DEFAULT);
- assertEquals(1, cf.getInt("x1"));
- assertEquals(true, cf.getBoolean("x2"));
- assertEquals("null", cf.getString("x3"));
- assertEquals(1, cf.getInt("s1/k1"));
- assertEquals(true, cf.getBoolean("s1/k2"));
- assertEquals("null", cf.getString("s1/k3"));
-
- assertEquals(-1, cf.getInt("X1/k1", -1));
- assertEquals(true, cf.getBoolean("X1/k2", true));
- assertEquals("null", cf.getString("X1/k3", "null"));
-
- assertEquals(1, cfw.getInt("x1"));
- assertEquals(true, cfw.getBoolean("x2"));
- assertEquals("null", cfw.getString("x3"));
- assertEquals(1, cfw.getInt("s1/k1"));
- assertEquals(true, cfw.getBoolean("s1/k2"));
- assertEquals("null", cfw.getString("s1/k3"));
-
- assertEquals(-1, cfw.getInt("X1/k1", -1));
- assertEquals(true, cfw.getBoolean("X1/k2", true));
- assertEquals("null", cfw.getString("X1/k3", "null"));
-
- cf.put("x1", 2);
- cf.put("x2", false);
- cf.put("x3", "foo");
- cf.put("s1/k1", 2);
- cf.put("s1/k2", false);
- cf.put("s1/k3", "bar");
-
- expected = "# c1|\t# c2| c3 |x1 = 2|x2 = false|x3 = foo|[s1]|#c4|k1 = 2|#c5 foo=bar|k2 = false|k3 = bar|";
- assertTextEquals(expected, cf);
- assertTextEquals(expected, cfw);
-
- cfw.put("x1", 3);
- cfw.put("x2", true);
- cfw.put("x3", "bar");
- cfw.put("s1/k1", 4);
- cfw.put("s1/k2", true);
- cfw.put("s1/k3", "baz");
-
- expected = "# c1|\t# c2| c3 |x1 = 3|x2 = true|x3 = bar|[s1]|#c4|k1 = 4|#c5 foo=bar|k2 = true|k3 = baz|";
- assertTextEquals(expected, cf);
- assertTextEquals(expected, cfw);
-
- // Null strings.
- cf.put("x1", (String)null);
- expected = "# c1|\t# c2| c3 |x1 = |x2 = true|x3 = bar|[s1]|#c4|k1 = 4|#c5 foo=bar|k2 = true|k3 = baz|";
- assertTextEquals(expected, cf);
- }
-
- @Test
- public void testSerialization() throws Exception {
-
- ConfigFile cf = ConfigMgr.DEFAULT.create();
- cf.put("x1", 1);
-
- String expected = "{'default':{x1:'1'}}";
- assertObjectEquals(expected, cf);
- cf = cf.getResolving(VarResolver.DEFAULT);
- assertObjectEquals(expected, cf);
- }
-
- //====================================================================================================
- // testHeaderComments
- //====================================================================================================
- @Test
- public void testHeaderComments() throws Exception {
- ConfigFile[] cff = {
- ConfigMgr.DEFAULT.create(getFreshFile()).addLines(null, "x").addLines("s1", "#c3", "#c4").addHeaderComments("s1", "#c1", "#c2"),
- ConfigMgr.DEFAULT.create(getFreshFile()).addLines(null, "x").addLines("s1", "#c3", "#c4").addHeaderComments("s1", "#c1", "#c2").getResolving()
- };
-
- for (ConfigFile cf : cff) {
-
- String expected = "x|#c1|#c2|[s1]|#c3|#c4|";
- assertTextEquals(expected, cf);
-
- cf.save();
- cf.load();
-
- cf.clearHeaderComments("s1");
- expected = "x|[s1]|#c3|#c4|";
- assertTextEquals(expected, cf);
-
- cf.clearHeaderComments("x1");
-
- cf.addHeaderComments("s1", "#c5", "c6");
- expected = "x|#c5|#c6|[s1]|#c3|#c4|";
- assertTextEquals(expected, cf);
- }
- }
-
- //====================================================================================================
- // testRemoveEntries
- //====================================================================================================
- @Test
- public void testRemoveEntries() throws Exception {
-
- File f = getFreshFile();
-
- ConfigFile cf = ConfigMgr.DEFAULT.create(f)
- .addLines(null, "x1=1")
- .addLines("s1", "x2=2");
- ConfigFile cfw = cf.getResolving(VarResolver.DEFAULT);
-
- String expected = "x1 = 1|[s1]|x2 = 2|";
- assertTextEquals(expected, cf);
- assertTextEquals(expected, cfw);
-
- cf.save();
- cf.load();
-
- cf.removeString("x1");
- expected = "[s1]|x2 = 2|";
- assertTextEquals(expected, cf);
- assertTextEquals(expected, cfw);
-
- cfw.save();
- cfw.load();
-
- cf.removeString("s1/x2");
- expected = "[s1]|";
- assertTextEquals(expected, cf);
- assertTextEquals(expected, cfw);
-
- cf.removeSection("s1");
- assertEquals("", cf.toString());
- assertEquals("", cfw.toString());
- }
-
- //====================================================================================================
- // testPut
- //====================================================================================================
- @Test
- public void testPut() throws Exception {
-
- ConfigFile cf = ConfigMgr.DEFAULT.create();
- ConfigFile cfw = cf.getResolving(VarResolver.DEFAULT);
-
- cf.addSection(null);
- cf.put("x1", "1");
- cf.addHeaderComments(null, "#h1");
- cf.addLines(null, "#c1", "c2");
- cf.addSection("s1");
- cf.put("s1/x2", "1");
- cf.addHeaderComments("s1","#h2");
- cf.addLines("s1", "#c3", "c4");
-
- String expected = "#h1|x1 = 1|#c1|c2|#h2|[s1]|x2 = 1|#c3|c4|";
- assertTextEquals(expected, cf);
- assertTextEquals(expected, cfw);
-
- cfw.addSection(null);
- cfw.put("x2", "2");
- cfw.addHeaderComments(null, "#h2");
- cfw.addLines(null, "#c2", "c3");
- cfw.addSection("s2");
- cfw.put("s2/x3", "2");
- cfw.addHeaderComments("s2","#h3");
- cfw.addLines("s2", "#c4", "c5");
-
- expected = "#h1|#h2|x1 = 1|#c1|c2|x2 = 2|#c2|c3|#h2|[s1]|x2 = 1|#c3|c4|#h3|[s2]|x3 = 2|#c4|c5|";
- assertTextEquals(expected, cf);
- assertTextEquals(expected, cfw);
- }
-
- //====================================================================================================
- // testExampleInConfigFile - Example in ConfigFile
- //====================================================================================================
- @Test
- public void testExampleInConfigFile() throws Exception {
-
- ConfigFile cf = ConfigMgr.DEFAULT.create()
- .addLines(null, "# Default section", "key1 = 1", "key2 = true", "key3 = 1,2,3", "key4 = 'http://foo'", "")
- .addHeaderComments("section1", "# Section 1")
- .addLines("section1", "key1 = 2", "key2 = false", "key3 = 4,5,6", "key4 = 'http://bar'");
- ConfigFile cfw = cf.getResolving(VarResolver.DEFAULT);
-
- assertEquals(1, cf.getInt("key1"));
- assertEquals(true, cf.getBoolean("key2"));
- assertEquals(3, cf.getObject(int[].class, "key3")[2]);
- assertEquals(6, cf.getObject(int[].class, "xkey3", new int[]{4,5,6})[2]);
- assertEquals(6, cf.getObject(int[].class, "X/key3", new int[]{4,5,6})[2]);
- assertEquals(new URL("http://foo").toString(), cf.getObject(URL.class, "key4").toString());
-
- assertEquals(1, cfw.getInt("key1"));
- assertEquals(true, cfw.getBoolean("key2"));
- assertEquals(3, cfw.getObject(int[].class, "key3")[2]);
- assertEquals(6, cfw.getObject(int[].class, "xkey3", new int[]{4,5,6})[2]);
- assertEquals(6, cfw.getObject(int[].class, "X/key3", new int[]{4,5,6})[2]);
- assertEquals(new URL("http://foo").toString(), cfw.getObject(URL.class, "key4").toString());
-
- assertEquals(2, cf.getInt("section1/key1"));
- assertEquals(false, cf.getBoolean("section1/key2"));
- assertEquals(6, cf.getObject(int[].class, "section1/key3")[2]);
- assertEquals(new URL("http://bar").toString(), cf.getObject(URL.class, "section1/key4").toString());
-
- assertEquals(2, cfw.getInt("section1/key1"));
- assertEquals(false, cfw.getBoolean("section1/key2"));
- assertEquals(6, cfw.getObject(int[].class, "section1/key3")[2]);
- assertEquals(new URL("http://bar").toString(), cfw.getObject(URL.class, "section1/key4").toString());
-
- cf = ConfigMgr.DEFAULT.create(getFreshFile())
- .addLines(null, "# Default section")
- .addHeaderComments("section1", "# Section 1");
- cfw = cf.getResolving(VarResolver.DEFAULT);
-
- cf.put("key1", 1);
- cf.put("key2", true);
- cf.put("key3", new int[]{1,2,3});
- cf.put("key4", new URL("http://foo"));
- cf.put("section1/key1", 2);
- cf.put("section1/key2", false);
- cf.put("section1/key3", new int[]{4,5,6});
- cf.put("section1/key4", new URL("http://bar"));
-
- cf.save();
- cf.load();
-
- assertEquals(1, cf.getInt("key1"));
- assertEquals(true, cf.getBoolean("key2"));
- assertEquals(3, cf.getObject(int[].class, "key3")[2]);
- assertEquals(new URL("http://foo").toString(), cf.getObject(URL.class, "key4").toString());
-
- assertEquals(1, cfw.getInt("key1"));
- assertEquals(true, cfw.getBoolean("key2"));
- assertEquals(3, cfw.getObject(int[].class, "key3")[2]);
- assertEquals(new URL("http://foo").toString(), cfw.getObject(URL.class, "key4").toString());
-
- assertEquals(2, cf.getInt("section1/key1"));
- assertEquals(false, cf.getBoolean("section1/key2"));
- assertEquals(6, cf.getObject(int[].class, "section1/key3")[2]);
- assertEquals(new URL("http://bar").toString(), cf.getObject(URL.class, "section1/key4").toString());
-
- assertEquals(2, cfw.getInt("section1/key1"));
- assertEquals(false, cfw.getBoolean("section1/key2"));
- assertEquals(6, cfw.getObject(int[].class, "section1/key3")[2]);
- assertEquals(new URL("http://bar").toString(), cfw.getObject(URL.class, "section1/key4").toString());
-
- cfw.put("key1", 2);
- cfw.put("key2", false);
- cfw.put("key3", new int[]{4,5,6});
- cfw.put("key4", new URL("http://bar"));
- cfw.put("section1/key1", 3);
- cfw.put("section1/key2", true);
- cfw.put("section1/key3", new int[]{7,8,9});
- cfw.put("section1/key4", new URL("http://baz"));
-
- cfw.save();
- cfw.load();
-
- assertEquals(2, cf.getInt("key1"));
- assertEquals(false, cf.getBoolean("key2"));
- assertEquals(6, cf.getObject(int[].class, "key3")[2]);
- assertEquals(new URL("http://bar").toString(), cf.getObject(URL.class, "key4").toString());
-
- assertEquals(2, cfw.getInt("key1"));
- assertEquals(false, cfw.getBoolean("key2"));
- assertEquals(6, cfw.getObject(int[].class, "key3")[2]);
- assertEquals(new URL("http://bar").toString(), cfw.getObject(URL.class, "key4").toString());
-
- assertEquals(3, cf.getInt("section1/key1"));
- assertEquals(true, cf.getBoolean("section1/key2"));
- assertEquals(9, cf.getObject(int[].class, "section1/key3")[2]);
- assertEquals(new URL("http://baz").toString(), cf.getObject(URL.class, "section1/key4").toString());
-
- assertEquals(3, cfw.getInt("section1/key1"));
- assertEquals(true, cfw.getBoolean("section1/key2"));
- assertEquals(9, cfw.getObject(int[].class, "section1/key3")[2]);
- assertEquals(new URL("http://baz").toString(), cfw.getObject(URL.class, "section1/key4").toString());
- }
-
- //====================================================================================================
- // testEnum
- //====================================================================================================
- @Test
- public void testEnum() throws Exception {
- ConfigFile cf = ConfigMgr.DEFAULT.create(getFreshFile())
- .addLines(null, "key1 = 'MINUTES'");
- ConfigFile cfw = cf.getResolving(VarResolver.DEFAULT);
-
- assertEquals(TimeUnit.MINUTES, cf.getObject(TimeUnit.class, "key1"));
- assertEquals(TimeUnit.MINUTES, cfw.getObject(TimeUnit.class, "key1"));
-
- cf.save();
- cf.load();
-
- assertEquals(TimeUnit.MINUTES, cf.getObject(TimeUnit.class, "key1"));
- assertEquals(TimeUnit.MINUTES, cfw.getObject(TimeUnit.class, "key1"));
- }
-
- //====================================================================================================
- // testBatchFileGeneration
- //====================================================================================================
- @Test
- public void testBatchFileGeneration() throws Exception {
- ConfigFile cf = ConfigMgr.DEFAULT.create()
- .addLines(null, "# c1", "\t# c2", " c3 ", "", " ", "x1=1", "x2=true", "x3=null")
- .addHeaderComments(null, "header null", "", null)
- .addLines("s1", "#c4", "k1=1", "#c5 foo=bar", "k2 = true", "k3 = \tnull")
- .addHeaderComments("s1", "header s1", "", null);
- ConfigFile cfw = cf.getResolving(VarResolver.DEFAULT);
-
- String expected = "rem header null|||rem c1|rem c2|rem c3|||set x1 = 1|set x2 = true|set x3 = null|rem header s1|||rem c4|set s1_k1 = 1|rem c5 foo=bar|set s1_k2 = true|set s1_k3 = null|";
-
- StringWriter sw = new StringWriter();
- cf.serializeTo(new PrintWriter(sw), ConfigFileFormat.BATCH);
- assertTextEquals(expected, sw);
-
- sw = new StringWriter();
- cfw.serializeTo(new PrintWriter(sw), ConfigFileFormat.BATCH);
- assertTextEquals(expected, sw);
- }
-
- //====================================================================================================
- // testShellScriptGeneration
- //====================================================================================================
- @Test
- public void testShellScriptGeneration() throws Exception {
- ConfigFile cf = ConfigMgr.DEFAULT.create()
- .addLines(null, "# c1", "\t# c2", " c3 ", "", " ", "x1=1", "x2=true", "x3=null")
- .addHeaderComments(null, "header null", "", null)
- .addLines("s1", "#c4", "k1=1", "#c5 foo=bar", "k2 = true", "k3 = \tnull")
- .addHeaderComments("s1", "header s1", "", null);
- ConfigFile cfw = cf.getResolving(VarResolver.DEFAULT);
-
- String expected = "# header null|||# c1|# c2|# c3|||export x1=\"1\"|export x2=\"true\"|export x3=\"null\"|# header s1|||# c4|export s1_k1=\"1\"|# c5 foo=bar|export s1_k2=\"true\"|export s1_k3=\"null\"|";
-
- StringWriter sw = new StringWriter();
- cf.serializeTo(new PrintWriter(sw), ConfigFileFormat.SHELL);
- assertTextEquals(expected, sw);
-
- sw = new StringWriter();
- cfw.serializeTo(new PrintWriter(sw), ConfigFileFormat.SHELL);
- assertTextEquals(expected, sw);
- }
-
- //====================================================================================================
- // testEncodedValues
- //====================================================================================================
- @Test
- public void testEncodedValues() throws Exception {
- File f = getFreshFile();
-
- ConfigFile cf = ConfigMgr.DEFAULT.create(f)
- .addLines("s1", "", "foo* = mypassword")
- .getResolving(VarResolver.DEFAULT);
- ConfigFile cfw = cf.getResolving(VarResolver.DEFAULT);
-
- assertEquals("mypassword", cf.getString("s1/foo"));
- assertEquals("mypassword", cfw.getString("s1/foo"));
- assertTrue(cf.isEncoded("s1/foo"));
- assertTrue(cfw.isEncoded("s1/foo"));
- cf.save();
- String expected = "[s1]||foo* = {AwwJVhwUQFZEMg==}|";
- String actual = IOUtils.read(new FileReader(f));
- assertTextEquals(expected, actual);
- cf.load();
- assertEquals("mypassword", cf.getString("s1/foo"));
- assertEquals("mypassword", cfw.getString("s1/foo"));
-
- IOUtils.write(f, new StringReader("[s1]\nfoo* = mypassword2\n"));
- FileUtils.modifyTimestamp(f);
- cf.loadIfModified();
- assertTrue(cf.isEncoded("s1/foo"));
- assertEquals("mypassword2", cf.getString("s1/foo"));
- cf.put("s1/foo", "mypassword");
- assertTrue(cf.isEncoded("s1/foo"));
-
- // INI output should be encoded
- StringWriter sw = new StringWriter();
- cf.serializeTo(new PrintWriter(sw), ConfigFileFormat.INI);
- expected = "[s1]|foo* = {AwwJVhwUQFZEMg==}|";
- assertTextEquals(expected, sw);
-
- // BATCH output should not be encoded
- sw = new StringWriter();
- cf.serializeTo(new PrintWriter(sw), ConfigFileFormat.BATCH);
- expected = "set s1_foo = mypassword|";
- assertTextEquals(expected, sw);
-
- // SHELL output should not be encoded
- sw = new StringWriter();
- cf.serializeTo(new PrintWriter(sw), ConfigFileFormat.SHELL);
- expected = "export s1_foo=\"mypassword\"|";
- assertTextEquals(expected, sw);
- }
-
- //====================================================================================================
- // testVariables
- //====================================================================================================
- @Test
- public void testVariables() throws Exception {
-
- ConfigFile cf = ConfigMgr.DEFAULT.create()
- .addLines("s1",
- "f1 = $S{foo}",
- "f2 = $S{foo,bar}",
- "f3 = $S{$S{baz,bing},bar}"
- );
- ConfigFile cfw = cf.getResolving(VarResolver.DEFAULT);
-
- System.getProperties().remove("foo");
- System.getProperties().remove("bar");
- System.getProperties().remove("baz");
- System.getProperties().remove("bing");
-
- assertEquals("$S{foo}", cf.getString("s1/f1"));
- assertEquals("$S{foo,bar}", cf.getString("s1/f2"));
- assertEquals("$S{$S{baz,bing},bar}", cf.getString("s1/f3"));
- assertEquals("", cfw.getString("s1/f1"));
- assertEquals("bar", cfw.getString("s1/f2"));
- assertEquals("bar", cfw.getString("s1/f3"));
-
- System.setProperty("foo", "123");
- assertEquals("$S{foo}", cf.getString("s1/f1"));
- assertEquals("$S{foo,bar}", cf.getString("s1/f2"));
- assertEquals("$S{$S{baz,bing},bar}", cf.getString("s1/f3"));
- assertEquals("123", cfw.getString("s1/f1"));
- assertEquals("123", cfw.getString("s1/f2"));
- assertEquals("bar", cfw.getString("s1/f3"));
-
- System.setProperty("foo", "$S{bar}");
- System.setProperty("bar", "baz");
- assertEquals("$S{foo}", cf.getString("s1/f1"));
- assertEquals("$S{foo,bar}", cf.getString("s1/f2"));
- assertEquals("$S{$S{baz,bing},bar}", cf.getString("s1/f3"));
- assertEquals("baz", cfw.getString("s1/f1"));
- assertEquals("baz", cfw.getString("s1/f2"));
- assertEquals("bar", cfw.getString("s1/f3"));
-
- System.setProperty("bing", "$S{foo}");
- assertEquals("$S{$S{baz,bing},bar}", cf.getString("s1/f3"));
- assertEquals("baz", cfw.getString("s1/f3"));
-
- System.setProperty("baz", "foo");
- System.setProperty("foo", "123");
- assertEquals("$S{$S{baz,bing},bar}", cf.getString("s1/f3"));
- assertEquals("123", cfw.getString("s1/f3"));
- }
-
- //====================================================================================================
- // testXorEncoder
- //====================================================================================================
- @Test
- public void testXorEncoder() throws Exception {
- testXor("foo");
- testXor("");
- testXor("123");
- testXor("\u20ac"); // 3-byte UTF-8 character
- testXor("\U00024b62"); // 4-byte UTF-8 character
- }
-
- private void testXor(String in) {
- XorEncoder e = new XorEncoder();
- String s = e.encode("", in);
- String s2 = e.decode("", s);
- assertEquals(in, s2);
- }
-
- //====================================================================================================
- // testMultiLines
- //====================================================================================================
- @Test
- public void testMultiLines() throws Exception {
- ConfigFile cf = ConfigMgr.DEFAULT.create()
- .addLines("s1",
- "f1 = x \ny \n z"
- );
- ConfigFile cfw = cf.getResolving(VarResolver.DEFAULT);
-
- assertEquals("x \ny \n z", cf.getString("s1/f1"));
- assertEquals("x \ny \n z", cfw.getString("s1/f1"));
-
- StringWriter sw = new StringWriter();
- cf.serializeTo(sw);
- String expected = "[s1]|f1 = x |\ty |\t z|";
- assertTextEquals(expected, sw);
-
- sw = new StringWriter();
- cfw.serializeTo(sw);
- assertTextEquals(expected, sw);
- }
-
- //====================================================================================================
- // testNumberShortcuts
- //====================================================================================================
- @Test
- public void testNumberShortcuts() throws Exception {
- ConfigFile cf = ConfigMgr.DEFAULT.create()
- .addLines("s1",
- "f1 = 1M",
- "f2 = 1K",
- "f3 = 1 M",
- "f4 = 1 K"
- );
- ConfigFile cfw = cf.getResolving(VarResolver.DEFAULT);
-
- assertEquals(1048576, cf.getInt("s1/f1"));
- assertEquals(1024, cf.getInt("s1/f2"));
- assertEquals(1048576, cf.getInt("s1/f3"));
- assertEquals(1024, cf.getInt("s1/f4"));
-
- assertEquals(1048576, cfw.getInt("s1/f1"));
- assertEquals(1024, cfw.getInt("s1/f2"));
- assertEquals(1048576, cfw.getInt("s1/f3"));
- assertEquals(1024, cfw.getInt("s1/f4"));
- }
-
- //====================================================================================================
- // testListeners
- //====================================================================================================
- @SuppressWarnings("serial")
- @Test
- public void testListeners() throws Exception {
- ConfigFile[] cff = {
- ConfigMgr.DEFAULT.create(FileUtils.createTempFile("CT_ConfigFile.cfg")).addLines(null, "a1=1").addLines("B", "b1=1"),
- ConfigMgr.DEFAULT.create(FileUtils.createTempFile("CT_ConfigFile.cfg")).addLines(null, "a1=1").addLines("B", "b1=1").getResolving(VarResolver.DEFAULT)
- };
-
- for (ConfigFile cf : cff) {
- final Set<String> changes = new TreeSet<String>(String.CASE_INSENSITIVE_ORDER);
- final int[] count = new int[]{0};
-
- cf.addListener(
- new ConfigFileListener() {
- @Override /* ConfigFileListener */
- public void onLoad(ConfigFile f) {
- super.onLoad(f);
- changes.add("<load>");
- count[0]++;
- }
- @Override /* ConfigFileListener */
- public void onSave(ConfigFile f) {
- super.onSave(f);
- changes.add("<save>");
- count[0]++;
- }
- @Override /* ConfigFileListener */
- public void onChange(ConfigFile f, Set<String> ss) {
- super.onChange(f, ss);
- for (String sss : ss)
- changes.add(sss + '=' + f.getString(sss));
- count[0]++;
- }
- }
- );
-
- // ConfigFile.addLines(section,lines)
- changes.clear();
- count[0] = 0;
- cf.addLines(null, "a1=3", "a3=3").addLines("B", "b1=3","b3=3");
- assertObjectEquals("['a1=3','a3=3','B/b1=3','B/b3=3']", changes);
- assertEquals(2, count[0]);
-
- // ConfigFile.put(key,value,encoded)
- changes.clear();
- count[0] = 0;
- cf.put("a1", "2");
- cf.put("B/b1", "2");
- cf.put("a2", "2");
- cf.put("B/b2", "2");
- cf.put("C/c1", "2");
- cf.put("C/c2", "2");
- assertObjectEquals("['a1=2','a2=2','B/b1=2','B/b2=2','C/c1=2','C/c2=2']", changes);
- assertEquals(6, count[0]);
-
- // put(key,value,encoded)
- changes.clear();
- count[0] = 0;
- cf.put("a4", "4", true);
- cf.put("B/b4", "4", true);
- assertObjectEquals("['a4=4','B/b4=4']", changes);
- assertEquals(2, count[0]);
-
- // put(key,value)
- changes.clear();
- count[0] = 0;
- cf.put("a5", "5");
- cf.put("B/b5", "5");
- assertObjectEquals("['a5=5','B/b5=5']", changes);
- assertEquals(2, count[0]);
-
- // put(key,value,encoded)
- changes.clear();
- count[0] = 0;
- cf.put("a6", "6", true);
- cf.put("B/b6", "6", true);
- assertObjectEquals("['a6=6','B/b6=6']", changes);
- assertEquals(2, count[0]);
-
- // removeString(key)
- changes.clear();
- count[0] = 0;
- cf.removeString("a6");
- cf.removeString("B/b6");
- cf.removeString("B/bx");
- cf.removeString("X/bx");
- assertObjectEquals("['a6=null','B/b6=null']", changes);
- assertEquals(2, count[0]);
-
- // addSection(name)
- changes.clear();
- count[0] = 0;
- cf.addSection("D");
- assertObjectEquals("[]", changes);
- assertEquals(0, count[0]);
-
- // setSection(name,contents)
- changes.clear();
- count[0] = 0;
- cf.setSection("E", new LinkedHashMap<String,String>(){{put("e1", "1");put("e2", "2");}});
- assertObjectEquals("['E/e1=1','E/e2=2']", changes);
- assertEquals(1, count[0]);
- cf.removeSection("E");
-
- // removeSection(name)
- changes.clear();
- count[0] = 0;
- cf.removeSection("B");
- assertObjectEquals("['B/b1=null','B/b2=null','B/b3=null','B/b4=null','B/b5=null']", changes);
- assertEquals(1, count[0]);
-
- // removeSection(name)
- changes.clear();
- count[0] = 0;
- cf.removeSection("B");
- assertObjectEquals("[]", changes);
- assertEquals(0, count[0]);
-
- // put(key) {
- changes.clear();
- count[0] = 0;
- Section c = cf.get("C");
- cf.put("B", c);
- assertObjectEquals("['C/c1=2','C/c2=2']", changes);
- assertEquals(1, count[0]);
-
- // remove(key)
- cf.remove("B");
- cf.addLines("B", "b1=1","b2=2");
- changes.clear();
- count[0] = 0;
- cf.remove("B");
- assertObjectEquals("['B/b1=null','B/b2=null']", changes);
- assertEquals(1, count[0]);
-
- // putAll(map)
- ConfigFile cf2 = ConfigMgr.DEFAULT.create();
- cf2.addLines("D", "d1=1","d2=1").addLines("E", "e1=1","e2=2");
- changes.clear();
- count[0] = 0;
- cf.putAll(cf2);
- assertObjectEquals("['a1=null','a2=null','a3=null','a4=null','a5=null','D/d1=1','D/d2=1','E/e1=1','E/e2=2']", changes);
- assertEquals(1, count[0]);
-
- // clear()
- cf.clear();
- cf.addLines(null, "a1=1", "a2=1").addLines("B", "b1=1", "b2=1");
- changes.clear();
- count[0] = 0;
- cf.clear();
- assertObjectEquals("['a1=null','a2=null','B/b1=null','B/b2=null']", changes);
- assertEquals(1, count[0]);
-
- // entrySet()
- cf.addLines(null, "a1=1", "a2=1").addLines("B", "b1=1", "b2=1");
- changes.clear();
- count[0] = 0;
- for (Iterator<Map.Entry<String,Section>> i = cf.entrySet().iterator(); i.hasNext();) {
- i.next();
- i.remove();
- }
- assertObjectEquals("['a1=null','a2=null','B/b1=null','B/b2=null']", changes);
- assertEquals(2, count[0]);
-
- // keySet()
- cf.addLines(null, "a1=1", "a2=1").addLines("B", "b1=1", "b2=1");
- changes.clear();
- count[0] = 0;
- for (Iterator<String> i = cf.keySet().iterator(); i.hasNext();) {
- i.next();
- i.remove();
- }
- assertObjectEquals("['a1=null','a2=null','B/b1=null','B/b2=null']", changes);
- assertEquals(2, count[0]);
-
- // values()
- cf.addLines(null, "a1=1", "a2=1").addLines("B", "b1=1", "b2=1");
- changes.clear();
- count[0] = 0;
- for (Iterator<Section> i = cf.values().iterator(); i.hasNext();) {
- i.next();
- i.remove();
- }
- assertObjectEquals("['a1=null','a2=null','B/b1=null','B/b2=null']", changes);
- assertEquals(2, count[0]);
-
- // ConfigFile.merge()
- cf.clear();
- cf.addLines(null, "a1=1", "a2=1", "a3=1").addLines("B", "b1=1", "b2=1", "b3=1").addLines("C", "c1=1", "c2=1", "c3=1");
- cf2.clear();
- cf2.addLines(null, "a2=1", "a3=2", "a4=2").addLines("B", "b2=1", "b3=2", "b4=2").addLines("D", "d2=1", "d3=2", "d4=2");
- changes.clear();
- count[0] = 0;
- cf.merge(cf2);
- assertObjectEquals("['a1=null','a3=2','a4=2','B/b1=null','B/b3=2','B/b4=2','C/c1=null','C/c2=null','C/c3=null','D/d2=1','D/d3=2','D/d4=2']", changes);
- assertEquals(1, count[0]);
-
- // ConfigFile.save()
- // ConfigFile.load()
- changes.clear();
- count[0] = 0;
- cf.save();
- cf.load();
- assertObjectEquals("['<load>','<save>']", changes);
- assertEquals(2, count[0]);
-
- // Section.clear()
- cf.clear();
- cf.addLines(null, "a1=1", "a2=1").addLines("B", "b1=1", "b2=1");
- changes.clear();
- count[0] = 0;
- cf.get("default").clear();
- cf.get("B").clear();
- assertObjectEquals("['a1=null','a2=null','B/b1=null','B/b2=null']", changes);
- assertEquals(2, count[0]);
-
- // Section.put(key,value)
- cf.clear();
- cf.addLines(null, "a1=1", "a2=1").addLines("B", "b1=1", "b2=1");
- changes.clear();
- count[0] = 0;
- cf.get("default").put("a1", "2");
- cf.get("default").put("a3", "2");
- cf.get("B").put("b1", "2");
- cf.get("B").put("b3", "2");
- assertObjectEquals("['a1=2','a3=2','B/b1=2','B/b3=2']", changes);
- assertEquals(4, count[0]);
-
- // Section put(key,value,encoded)
- cf.clear();
- cf.addLines(null, "a1=1", "a2=1").addLines("B", "b1=1", "b2=1");
- changes.clear();
- count[0] = 0;
- cf.get("default").put("a1", "2", true);
- cf.get("default").put("a3", "2", true);
- cf.get("B").put("b1", "2", true);
- cf.get("B").put("b3", "2", true);
- assertObjectEquals("['a1=2','a3=2','B/b1=2','B/b3=2']", changes);
- assertEquals(4, count[0]);
-
- // Section.putAll(map)
- cf.clear();
- cf.addLines(null, "a1=1", "a2=1").addLines("B", "b1=1", "b2=1");
- changes.clear();
- count[0] = 0;
- cf.get("default").putAll(new HashMap<String,String>(){{put("a1","1");put("a2","2");put("a3","2");}});
- cf.get("B").putAll(new HashMap<String,String>(){{put("b1","1");put("b2","2");put("b3","2");}});
- assertObjectEquals("['a2=2','a3=2','B/b2=2','B/b3=2']", changes);
- assertEquals(2, count[0]);
-
- // Section.remove(key)
- cf.clear();
- cf.addLines(null, "a1=1", "a2=1").addLines("B", "b1=1", "b2=1");
- changes.clear();
- count[0] = 0;
- cf.get("default").remove("a1");
- cf.get("default").remove("ax");
- cf.get("B").remove("b1");
- cf.get("B").remove("bx");
- assertObjectEquals("['a1=null','B/b1=null']", changes);
- assertEquals(2, count[0]);
-
- // Section.entrySet()
- cf.clear();
- cf.addLines(null, "a1=1", "a2=1").addLines("B", "b1=1", "b2=1");
- changes.clear();
- count[0] = 0;
- Section n = cf.get("default");
- for (Iterator<Map.Entry<String,String>> i = n.entrySet().iterator(); i.hasNext();) {
- i.next();
- i.remove();
- }
- n = cf.get("B");
- for (Iterator<Map.Entry<String,String>> i = n.entrySet().iterator(); i.hasNext();) {
- i.next();
- i.remove();
- }
- assertObjectEquals("['a1=null','a2=null','B/b1=null','B/b2=null']", changes);
- assertEquals(4, count[0]);
-
- // Section.keySet()
- cf.clear();
- cf.addLines("default", "a1=1", "a2=1").addLines("B", "b1=1", "b2=1");
- changes.clear();
- count[0] = 0;
- for (Iterator<String> i = cf.get("default").keySet().iterator(); i.hasNext();) {
- i.next();
- i.remove();
- }
- for (Iterator<String> i = cf.get("B").keySet().iterator(); i.hasNext();) {
- i.next();
- i.remove();
- }
- assertObjectEquals("['a1=null','a2=null','B/b1=null','B/b2=null']", changes);
- assertEquals(4, count[0]);
-
- // Section.values()
- cf.clear();
- cf.addLines(null, "a1=1", "a2=1").addLines("B", "b1=1", "b2=1");
- try {
- Iterator<String> i = cf.get("default").values().iterator();
- i.next();
- i.remove();
- fail("Exception expected");
- } catch (UnsupportedOperationException e) {}
- try {
- Iterator<String> i = cf.get("B").values().iterator();
- i.next();
- i.remove();
- fail("Exception expected");
- } catch (UnsupportedOperationException e) {}
- }
- }
-
- //====================================================================================================
- // testEntryListener
- //====================================================================================================
- @Test
- public void testEntryListener() throws Exception {
- ConfigFile[] cff = {
- ConfigMgr.DEFAULT.create().addLines(null, "a1=1").addLines("B", "b1=1"),
- ConfigMgr.DEFAULT.create().addLines(null, "a1=1").addLines("B", "b1=1").getResolving(VarResolver.DEFAULT)
- };
-
- for (ConfigFile cf : cff) {
- final Set<String> changes = new TreeSet<String>(String.CASE_INSENSITIVE_ORDER);
- final int[] count = new int[]{0};
-
- cf.addListener(
- new EntryListener("a1") {
- @Override /* EntryListener */
- public void onChange(ConfigFile f) {
- super.onChange(f);
- changes.add("a1=" + f.getString("a1"));
- count[0]++;
- }
- }
- );
-
- cf.addListener(
- new EntryListener("B/b1") {
- @Override /* EntryListener */
- public void onChange(ConfigFile f) {
- changes.add("B/b1=" + f.getString("B/b1"));
- count[0]++;
- }
- }
- );
-
- cf.put("a1", "2");
- cf.put("a2", "2");
- cf.put("B/b1", "2");
- cf.put("B/b2", "2");
- assertObjectEquals("['a1=2','B/b1=2']", changes);
- assertEquals(2, count[0]);
- }
- }
-
- //====================================================================================================
- // testSectionListener
- //====================================================================================================
- @Test
- public void testSectionListener() throws Exception {
- ConfigFile[] cff = {
- ConfigMgr.DEFAULT.create().addLines(null, "a1=1").addLines("B", "b1=1"),
- ConfigMgr.DEFAULT.create().addLines(null, "a1=1").addLines("B", "b1=1").getResolving(VarResolver.DEFAULT)
- };
-
- for (ConfigFile cf : cff) {
-
- final Set<String> changes = new TreeSet<String>(String.CASE_INSENSITIVE_ORDER);
- final int[] count = new int[]{0};
-
- cf.addListener(
- new SectionListener(null) {
- @Override /* SectionListener */
- public void onChange(ConfigFile f) {
- super.onChange(f);
- changes.add("x=" + f.getString("a1"));
- count[0]++;
- }
- }
- );
-
- cf.addListener(
- new SectionListener("") {
- @Override /* SectionListener */
- public void onChange(ConfigFile f) {
- changes.add("y=" + f.getString("a1"));
- count[0]++;
- }
- }
- );
-
- cf.addListener(
- new SectionListener("B") {
- @Override /* SectionListener */
- public void onChange(ConfigFile f) {
- changes.add("z=" + f.getString("B/b1"));
- count[0]++;
- }
- }
- );
-
- cf.put("a1", "2");
- cf.put("a2", "2");
- cf.put("B/b1", "2");
- cf.put("B/b2", "2");
- assertObjectEquals("['x=2','y=2','z=2']", changes);
- assertEquals(6, count[0]);
- }
- }
-
- //====================================================================================================
- // testMerge
- //====================================================================================================
- @Test
- public void testMerge() throws Exception {
- ConfigFile cf1 = ConfigMgr.DEFAULT.create()
- .addLines(null, "# comment a1", "a1=1")
- .addLines("B", "# comment b1", "b1=1").addHeaderComments("B", "# comment B1")
- .addLines("C", "# comment c1", "bc=1").addHeaderComments("C", "# comment C1");
- ConfigFile cf2 = ConfigMgr.DEFAULT.create()
- .addLines(null, "# comment a2", "a2=2")
- .addLines("B", "# comment b2", "b2=2").addHeaderComments("B", "# comment B2")
- .addLines("D", "# comment d2", "d2=2").addHeaderComments("D", "# comment D2");
- cf1.merge(cf2);
-
- String expected = "# comment a2|a2 = 2|# comment B2|[B]|# comment b2|b2 = 2|# comment D2|[D]|# comment d2|d2 = 2|";
- assertTextEquals(expected, cf1);
-
- cf1 = ConfigMgr.DEFAULT.create()
- .addLines(null, "# comment a1", "a1=1")
- .addLines("B", "# comment b1", "b1=1").addHeaderComments("B", "# comment B1")
- .addLines("C", "# comment c1", "bc=1").addHeaderComments("C", "# comment C1").getResolving(VarResolver.DEFAULT);
- cf2 = ConfigMgr.DEFAULT.create()
- .addLines(null, "# comment a2", "a2=2")
- .addLines("B", "# comment b2", "b2=2").addHeaderComments("B", "# comment B2")
- .addLines("D", "# comment d2", "d2=2").addHeaderComments("D", "# comment D2").getResolving(VarResolver.DEFAULT);
-
- cf1.merge(cf2);
- assertTextEquals(expected, cf1);
- }
-
- //====================================================================================================
- // testDefaultSection
- // Default section should be keyed by either null, "", or "default"
- //====================================================================================================
- @Test
- public void testDefaultSection() throws Exception {
- ConfigFile[] cff = {
- ConfigMgr.DEFAULT.create().addLines(null, "a1=1").addLines("", "a2=2").addLines("default", "a3=3"),
- ConfigMgr.DEFAULT.create().addLines(null, "a1=1").addLines("", "a2=2").addLines("default", "a3=3").getResolving(VarResolver.DEFAULT)
- };
-
- for (ConfigFile cf : cff) {
- assertObjectEquals("{'default':{a1:'1',a2:'2',a3:'3'}}", cf);
- assertTextEquals("a1 = 1|a2 = 2|a3 = 3|", cf);
-
- assertObjectEquals("{a1:'1',a2:'2',a3:'3'}", cf.get(null));
- assertObjectEquals("{a1:'1',a2:'2',a3:'3'}", cf.get(""));
- assertObjectEquals("{a1:'1',a2:'2',a3:'3'}", cf.get("default"));
-
- assertEquals("1", cf.getString("a1"));
- assertEquals("1", cf.getString("default/a1"));
-
- assertObjectEquals("{a1:'1',a2:'2',a3:'3'}", cf.getSectionMap(null));
- assertObjectEquals("{a1:'1',a2:'2',a3:'3'}", cf.getSectionMap(""));
- assertObjectEquals("{a1:'1',a2:'2',a3:'3'}", cf.getSectionMap("default"));
-
- cf.put(null, cf.get(null));
- assertObjectEquals("{a1:'1',a2:'2',a3:'3'}", cf.get(null));
- cf.put("", cf.get(null));
- assertObjectEquals("{a1:'1',a2:'2',a3:'3'}", cf.get(null));
- cf.put("default", cf.get(null));
- assertObjectEquals("{a1:'1',a2:'2',a3:'3'}", cf.get(null));
- }
- }
-
- //====================================================================================================
- // ConfigFileImpl(File)
- // ConfigFileImpl()
- //====================================================================================================
- @Test
- public void testAlternateConstructors() throws Exception {
- ConfigFile cf = new ConfigFileImpl();
- cf.put("A", "a");
- try { cf.save(); fail(); } catch (UnsupportedOperationException e) {}
- cf.loadIfModified();
- assertEquals("a", cf.getString("A"));
- }
-
- //====================================================================================================
- // containsKey(Object)
- // containsValue(Object)
- // size()
- //====================================================================================================
- @Test
- public void testContains() throws Exception {
- ConfigFile cf = ConfigMgr.DEFAULT.create().addLines(null, "a1=1").addLines("", "a2=2").addLines("default", "a3=3").addLines("A", "a4=4");
- ConfigFile cfw = cf.getResolving();
-
- assertTrue(cf.containsKey(null));
- assertTrue(cf.containsKey(""));
- assertTrue(cf.containsKey("default"));
- assertTrue(cf.containsKey("A"));
- assertFalse(cf.containsKey("x"));
-
- assertTrue(cfw.containsKey(null));
- assertTrue(cfw.containsKey(""));
- assertTrue(cfw.containsKey("default"));
- assertTrue(cfw.containsKey("A"));
- assertFalse(cfw.containsKey("x"));
-
- Section s = cf.get(null);
- assertTrue(cf.containsValue(s));
- assertTrue(cfw.containsValue(s));
- s = cf.get("A");
- assertTrue(cf.containsValue(s));
- assertTrue(cfw.containsValue(s));
-
- assertFalse(cf.isEmpty());
- assertFalse(cfw.isEmpty());
-
- cf.clear();
- assertTrue(cf.isEmpty());
- assertTrue(cfw.isEmpty());
- assertFalse(cf.containsKey(null));
- assertFalse(cfw.containsKey(null));
- assertEquals(0, cf.size());
- assertEquals(0, cfw.size());
- assertEquals(0, cf.keySet().size());
- assertEquals(0, cfw.keySet().size());
- assertEquals(0, cf.entrySet().size());
- assertEquals(0, cfw.entrySet().size());
- assertEquals(0, cf.values().size());
- assertEquals(0, cfw.values().size());
- }
-
- //====================================================================================================
- // getObjectArray(Class c, String key)
- // getObjectArray(Class c, String key, T[] def)
- //====================================================================================================
- @Test
- public void testGetObjectArray() throws Exception {
- ConfigFile cf = ConfigMgr.DEFAULT.create().addLines("A", "a1=1,2,3");
- ConfigFile cfw = cf.getResolving();
- assertObjectEquals("[1,2,3]", cf.getObject(Integer[].class, "A/a1"));
- assertObjectEquals("[1,2,3]", cfw.getObject(Integer[].class, "A/a1"));
- assertObjectEquals("[4,5,6]", cf.getObject(Integer[].class, "A/a2", new Integer[]{4,5,6}));
- assertObjectEquals("[4,5,6]", cfw.getObject(Integer[].class, "A/a2", new Integer[]{4,5,6}));
- assertObjectEquals("[7,8,9]", cf.getObject(Integer[].class, "B/a1", new Integer[]{7,8,9}));
- assertObjectEquals("[7,8,9]", cfw.getObject(Integer[].class, "B/a1", new Integer[]{7,8,9}));
- assertObjectEquals("[]", cf.getObject(Integer[].class, "B/a1"));
- assertObjectEquals("[]", cfw.getObject(Integer[].class, "B/a1"));
-
- cf = ConfigMgr.DEFAULT.create().addLines("A", "a1 = 1 ,\n\t2 ,\n\t3 ");
- assertObjectEquals("[1,2,3]", cf.getObject(Integer[].class, "A/a1"));
- assertObjectEquals("[1,2,3]", cfw.getObject(Integer[].class, "A/a1"));
-
- // We cannot cast primitive arrays to Object[], so the following throws exceptions.
- assertObjectEquals("[1,2,3]", cf.getObject(int[].class, "A/a1"));
- assertEquals("int", cf.getObject(int[].class, "A/a1").getClass().getComponentType().getSimpleName());
- assertObjectEquals("[]", cf.getObject(int[].class, "B/a1"));
- assertEquals("int", cf.getObject(int[].class, "B/a1").getClass().getComponentType().getSimpleName());
- assertObjectEquals("[]", cf.getObject(int[].class, "A/a2"));
- assertEquals("int", cf.getObject(int[].class, "A/a2").getClass().getComponentType().getSimpleName());
-
- assertObjectEquals("[1,2,3]", cf.getObject(int[].class, "A/a1", new int[]{4}));
- assertEquals("int", cf.getObject(int[].class, "A/a1", new int[]{4}).getClass().getComponentType().getSimpleName());
- assertObjectEquals("[4]", cf.getObject(int[].class, "B/a1", new int[]{4}));
- assertEquals("int", cf.getObject(int[].class, "B/a1", new int[]{4}).getClass().getComponentType().getSimpleName());
- assertObjectEquals("[4]", cf.getObject(int[].class, "A/a2", new int[]{4}));
- assertEquals("int", cf.getObject(int[].class, "A/a2", new int[]{4}).getClass().getComponentType().getSimpleName());
-
- System.setProperty("X", "4,5,6");
- cf = ConfigMgr.DEFAULT.create().addLines(null, "x1=$C{A/a1}", "x2=$S{X}", "x3=$S{Y}").addLines("A", "a1=1,2,3").getResolving();
- assertObjectEquals("[1,2,3]", cf.getObject(int[].class, "x1", new int[]{9}));
- assertObjectEquals("[4,5,6]", cf.getObject(int[].class, "x2", new int[]{9}));
- assertObjectEquals("[9]", cf.getObject(int[].class, "x3", new int[]{9}));
- System.clearProperty("X");
- }
-
- //====================================================================================================
- // getStringArray(String key)
- // getStringArray(String key, String[] def)
- //====================================================================================================
- @Test
- public void testGetStringArray() throws Exception {
- ConfigFile cf = ConfigMgr.DEFAULT.create().addLines("A", "a1=1,2,3");
- ConfigFile cfw = cf.getResolving();
- assertObjectEquals("['1','2','3']", cf.getStringArray("A/a1"));
- assertObjectEquals("['1','2','3']", cfw.getStringArray("A/a1"));
- assertObjectEquals("['4','5','6']", cf.getStringArray("A/a2", new String[]{"4","5","6"}));
- assertObjectEquals("['4','5','6']", cfw.getStringArray("A/a2", new String[]{"4","5","6"}));
- assertObjectEquals("['7','8','9']", cf.getStringArray("B/a1", new String[]{"7","8","9"}));
- assertObjectEquals("['7','8','9']", cfw.getStringArray("B/a1", new String[]{"7","8","9"}));
- assertObjectEquals("[]", cf.getStringArray("B/a1"));
- assertObjectEquals("[]", cfw.getStringArray("B/a1"));
-
- cf = ConfigMgr.DEFAULT.create().addLines("A", "a1 = 1 ,\n\t2 ,\n\t3 ");
- assertObjectEquals("['1','2','3']", cf.getStringArray("A/a1"));
- assertObjectEquals("['1','2','3']", cfw.getStringArray("A/a1"));
-
- System.setProperty("X", "4,5,6");
- cf = ConfigMgr.DEFAULT.create().addLines(null, "x1=$C{A/a1}", "x2=$S{X}", "x3=$S{Y}", "x4=$S{Y,$S{X}}").addLines("A", "a1=1,2,3").getResolving();
- assertObjectEquals("['1','2','3']", cf.getStringArray("x1", new String[]{"9"}));
- assertObjectEquals("['4','5','6']", cf.getStringArray("x2", new String[]{"9"}));
- assertObjectEquals("['9']", cf.getStringArray("x3", new String[]{"9"}));
-
- // TODO - Doesn't work yet.
- // assertObjectEquals("['4','5','6']", cf.getStringArray("x4", new String[]{"9"}));
- System.clearProperty("X");
- }
-
- //====================================================================================================
- // getSectionMap(String name)
- //====================================================================================================
- @Test
- public void testGetSectionMap() throws Exception {
- ConfigFile cf = ConfigMgr.DEFAULT.create().addLines("A", "a1=1", "").addLines("D", "d1=$C{A/a1}","d2=$S{X}");
-
- assertObjectEquals("{a1:'1'}", cf.getSectionMap("A"));
- assertNull(cf.getSectionMap("B"));
- assertObjectEquals("null", cf.getSectionMap("C"));
-
- ObjectMap m = cf.getSectionMap("A");
- assertObjectEquals("{a1:'1'}", m);
-
- m = cf.getSectionMap("D");
- assertObjectEquals("{d1:'$C{A/a1}',d2:'$S{X}'}", m);
-
- cf = cf.getResolving();
-
- System.setProperty("X", "x");
- m = cf.getSectionMap("D");
- assertObjectEquals("{d1:'1',d2:'x'}", m);
- System.clearProperty("X");
- }
-
- //====================================================================================================
- // load(Reader)
- //====================================================================================================
- @Test
- public void testLoadFromReader() throws Exception {
- ConfigFile[] cff = {
- ConfigMgr.DEFAULT.create().addLines(null, "a1=1"),
- ConfigMgr.DEFAULT.create().addLines(null, "a1=1").getResolving(VarResolver.DEFAULT)
- };
-
- for (ConfigFile cf : cff) {
- cf.load(new StringReader("[B]\nb1=1"));
- assertObjectEquals("{'default':{},B:{b1:'1'}}", cf);
- }
- }
-
-
- //====================================================================================================
- // toWritable()
- //====================================================================================================
- @Test
- public void testToWritable() throws Exception {
- ConfigFile cf = ConfigMgr.DEFAULT.create()
- .addLines(null, "a=b");
- ConfigFile cfw = cf.getResolving();
-
- StringWriter sw = new StringWriter();
- cf.toWritable().writeTo(sw);
- assertTextEquals("a = b|", sw);
-
- sw = new StringWriter();
- cfw.toWritable().writeTo(sw);
- assertTextEquals("a = b|", sw);
-
- assertEquals("text/plain", cf.toWritable().getMediaType());
- assertEquals("text/plain", cfw.toWritable().getMediaType());
- }
-
- //====================================================================================================
- // containsNonEmptyKey()
- //====================================================================================================
- @Test
- public void testContainsNonEmptyKey() throws Exception {
- ConfigFile cf = ConfigMgr.DEFAULT.create()
- .addLines(null, "a=b","c=");
- ConfigFile cfw = cf.getResolving();
-
- assertTrue(cf.containsNonEmptyValue("a"));
- assertFalse(cf.containsNonEmptyValue("c"));
- assertFalse(cf.containsNonEmptyValue("d"));
-
- assertTrue(cfw.containsNonEmptyValue("a"));
- assertFalse(cfw.containsNonEmptyValue("c"));
- assertFalse(cfw.containsNonEmptyValue("d"));
-
- cf.addLines("A", "a1=$S{X}", "a2=$S{Y,$S{X}}");
- assertFalse(cfw.containsNonEmptyValue("A/a1"));
- assertFalse(cfw.containsNonEmptyValue("A/a2"));
-
- System.setProperty("X", "x");
- assertTrue(cfw.containsNonEmptyValue("A/a1"));
- assertTrue(cfw.containsNonEmptyValue("A/a2"));
- System.clearProperty("X");
- }
-
- //====================================================================================================
- // getSectionKeys(String sectionName)
- //====================================================================================================
- @Test
- public void testGetSectionKeys() throws Exception {
- ConfigFile cf = ConfigMgr.DEFAULT.create()
- .addLines(null, "x1=1", "x2=")
- .addLines("A", "a1=1", "a2=");
-
- assertObjectEquals("['x1','x2']", cf.getSectionKeys(null));
- assertObjectEquals("['x1','x2']", cf.getSectionKeys(""));
- assertObjectEquals("['x1','x2']", cf.getSectionKeys("default"));
- assertObjectEquals("['a1','a2']", cf.getSectionKeys("A"));
- assertNull(cf.getSectionKeys("B"));
-
- cf = cf.getResolving();
-
- assertObjectEquals("['x1','x2']", cf.getSectionKeys(null));
- assertObjectEquals("['x1','x2']", cf.getSectionKeys(""));
- assertObjectEquals("['x1','x2']", cf.getSectionKeys("default"));
- assertObjectEquals("['a1','a2']", cf.getSectionKeys("A"));
- assertNull(cf.getSectionKeys("B"));
- }
-
- //====================================================================================================
- // addLines(String section, String...lines)
- //====================================================================================================
- @Test
- public void testAddLines() throws Exception {
- ConfigFile cf = ConfigMgr.DEFAULT.create()
- .addLines(null, "x1=1")
- .addLines("A", "a1=1");
-
- cf.addLines(null, "# comment1", "x1=2", "x2=1", "foobar");
- cf.addLines("A", "# comment2", "a1=2", "a2=1", "foobar");
- cf.addLines("B", "# comment3", "b1=2", "b2=1", "foobar");
- cf.addLines("C", (String[])null); // Should be OK.
- cf.addLines("C", (String)null); // Should be OK.
- assertObjectEquals("{'default':{x1:'2',x2:'1'},A:{a1:'2',a2:'1'},B:{b1:'2',b2:'1'},C:{}}", cf);
- assertTextEquals("# comment1|x1 = 2|x2 = 1|foobar|[A]|# comment2|a1 = 2|a2 = 1|foobar|[B]|# comment3|b1 = 2|b2 = 1|foobar|[C]||", cf);
-
- cf = ConfigMgr.DEFAULT.create()
- .addLines(null, "x1=1")
- .addLines("A", "a1=1")
- .getResolving();
-
- cf.addLines(null, "# comment1", "x1=2", "x2=1", "foobar");
- cf.addLines("A", "# comment2", "a1=2", "a2=1", "foobar");
- cf.addLines("B", "# comment3", "b1=2", "b2=1", "foobar");
- cf.addLines("C", (String[])null); // Should be OK.
- cf.addLines("C", (String)null); // Should be OK.
- assertObjectEquals("{'default':{x1:'2',x2:'1'},A:{a1:'2',a2:'1'},B:{b1:'2',b2:'1'},C:{}}", cf);
- assertTextEquals("# comment1|x1 = 2|x2 = 1|foobar|[A]|# comment2|a1 = 2|a2 = 1|foobar|[B]|# comment3|b1 = 2|b2 = 1|foobar|[C]||", cf);
-
- cf = ConfigMgr.DEFAULT.create()
- .addLines(null, "x1=$C{A/a2}")
- .addLines("A", "a1=1")
- .getResolving();
- assertObjectEquals("{'default':{x1:'$C{A/a2}'},A:{a1:'1'}}", cf);
- assertTextEquals("x1 = $C{A/a2}|[A]|a1 = 1|", cf);
-
- assertEquals("", cf.getString("x1"));
-
- cf.addLines("A", "a2=2");
-
- assertEquals("2", cf.getString("x1"));
- }
-
-
- //====================================================================================================
- // addHeaderComments(String section, String...headerComments)
- // clearHeaderComments(String section)
- //====================================================================================================
- @Test
- public void testAddHeaderComments() throws Exception {
- ConfigFile cf = ConfigMgr.DEFAULT.create()
- .addLines(null, "x1=1")
- .addLines("A", "a1=1");
-
- cf.addHeaderComments(null, "# h1");
- cf.addHeaderComments("", "# h2");
- cf.addHeaderComments("default", "# h3");
- cf.addHeaderComments("A", "# h4");
- cf.addHeaderComments("B", "# h5");
- cf.addHeaderComments("C", (String[])null);
- cf.addHeaderComments("C", (String)null);
-
- assertTextEquals("# h1|# h2|# h3|x1 = 1|# h4|[A]|a1 = 1|# h5|[B]|#|[C]|", cf);
-
- cf = ConfigMgr.DEFAULT.create()
- .addLines(null, "x1=1")
- .addLines("A", "a1=1");
-
- cf.addHeaderComments(null, "h1");
- cf.addHeaderComments("", "h2");
- cf.addHeaderComments("default", "h3");
- cf.addHeaderComments("A", "h4");
- cf.addHeaderComments("B", "h5");
- cf.addHeaderComments("C", (String[])null);
- cf.addHeaderComments("C", (String)null);
-
- assertTextEquals("#h1|#h2|#h3|x1 = 1|#h4|[A]|a1 = 1|#h5|[B]|#|[C]|", cf);
-
- cf.clearHeaderComments(null).clearHeaderComments("A").clearHeaderComments("B").clearHeaderComments("C");
- assertTextEquals("x1 = 1|[A]|a1 = 1|[B]|[C]|", cf);
-
- cf = ConfigMgr.DEFAULT.create()
- .addLines(null, "x1=1")
- .addLines("A", "a1=1")
- .getResolving();
-
- cf.addHeaderComments(null, "h1");
- cf.addHeaderComments("", "h2");
- cf.addHeaderComments("default", "h3");
- cf.addHeaderComments("A", "h4");
- cf.addHeaderComments("B", "h5");
- cf.addHeaderComments("C", (String[])null);
- cf.addHeaderComments("C", (String)null);
-
- assertTextEquals("#h1|#h2|#h3|x1 = 1|#h4|[A]|a1 = 1|#h5|[B]|#|[C]|", cf);
-
- cf.clearHeaderComments(null).clearHeaderComments("A").clearHeaderComments("B").clearHeaderComments("C");
- assertTextEquals("x1 = 1|[A]|a1 = 1|[B]|[C]|", cf);
- }
-
- //====================================================================================================
- // getString(String key)
- // getString(String key, String def)
- //====================================================================================================
- @Test
- public void testGetString() throws Exception {
- System.setProperty("S1", "1");
- ConfigFile cf = ConfigMgr.DEFAULT.create()
- .addLines(null, "x1=1", "x2=$C{A/a2}", "x3=$S{S1,2}", "x4=$S{S2,3}")
- .addLines("A", "a1=1", "a2=$C{A/a1}", "a3=$S{S1,2}", "a4=$S{S2,3}");
-
- assertEquals("1", cf.getString("x1"));
- assertEquals("1", cf.getString("x1", "x"));
- assertEquals("$C{A/a2}", cf.getString("x2"));
- assertEquals("$C{A/a2}", cf.getString("x2", "x"));
- assertEquals("$S{S1,2}", cf.getString("x3"));
- assertEquals("$S{S1,2}", cf.getString("x3", "x"));
- assertEquals("$S{S2,3}", cf.getString("x4"));
- assertEquals("$S{S2,3}", cf.getString("x4", "x"));
- assertNull(cf.getString("x5"));
- assertEquals("x", cf.getString("x5", "x"));
-
- assertEquals("1", cf.getString("A/a1"));
- assertEquals("1", cf.getString("A/a1", "x"));
- assertEquals("$C{A/a1}", cf.getString("A/a2"));
- assertEquals("$C{A/a1}", cf.getString("A/a2", "x"));
- assertEquals("$S{S1,2}", cf.getString("A/a3"));
- assertEquals("$S{S1,2}", cf.getString("A/a3", "x"));
- assertEquals("$S{S2,3}", cf.getString("A/a4"));
- assertEquals("$S{S2,3}", cf.getString("A/a4", "x"));
- assertNull(cf.getString("A/a5"));
- assertEquals("x", cf.getString("A/a5", "x"));
-
- assertNull(cf.getString("B/b1"));
- assertEquals("x", cf.getString("B/b1", "x"));
-
- cf = cf.getResolving();
-
- assertEquals("1", cf.getString("x1"));
- assertEquals("1", cf.getString("x1", "x"));
- assertEquals("1", cf.getString("x2"));
- assertEquals("1", cf.getString("x2", "x"));
- assertEquals("1", cf.getString("x3"));
- assertEquals("1", cf.getString("x3", "x"));
- assertEquals("3", cf.getString("x4"));
- assertEquals("3", cf.getString("x4", "x"));
- assertNull(cf.getString("x5"));
- assertEquals("x", cf.getString("x5", "x"));
-
- assertEquals("1", cf.getString("A/a1"));
- assertEquals("1", cf.getString("A/a1", "x"));
- assertEquals("1", cf.getString("A/a2"));
- assertEquals("1", cf.getString("A/a2", "x"));
- assertEquals("1", cf.getString("A/a3"));
- assertEquals("1", cf.getString("A/a3", "x"));
- assertEquals("3", cf.getString("A/a4"));
- assertEquals("3", cf.getString("A/a4", "x"));
- assertNull(cf.getString("A/a5"));
- assertEquals("x", cf.getString("A/a5", "x"));
-
- assertNull(cf.getString("B/b1"));
- assertEquals("x", cf.getString("B/b1", "x"));
-
- System.clearProperty("S1");
- }
-
- //====================================================================================================
- // put(String key, Object value)
- //====================================================================================================
- @Test
- public void testPutString() throws Exception {
- ConfigFile cf = ConfigMgr.DEFAULT.create()
- .addLines(null, "x1=1")
- .addLines("A", "a1=1");
-
- cf.put("x1", 2);
- cf.put("x2", 3);
- cf.put("A/a1", 2);
- cf.put("A/a2", 3);
- cf.put("B/b1", 2);
-
- assertObjectEquals("{'default':{x1:'2',x2:'3'},A:{a1:'2',a2:'3'},B:{b1:'2'}}", cf);
- assertTextEquals("x1 = 2|x2 = 3|[A]|a1 = 2|a2 = 3|[B]|b1 = 2|", cf);
-
- cf = ConfigMgr.DEFAULT.create()
- .addLines(null, "x1=1")
- .addLines("A", "a1=1")
- .getResolving();
-
- cf.put("x1", 2);
- cf.put("x2", 3);
- cf.put("A/a1", 2);
- cf.put("A/a2", 3);
- cf.put("B/b1", 2);
-
- assertObjectEquals("{'default':{x1:'2',x2:'3'},A:{a1:'2',a2:'3'},B:{b1:'2'}}", cf);
- assertTextEquals("x1 = 2|x2 = 3|[A]|a1 = 2|a2 = 3|[B]|b1 = 2|", cf);
-
- cf.put("x1", 9);
- cf.put("x2", "$C{x1}");
- cf.put("A/a1", "$C{x1}");
- cf.put("A/a2", "$C{x1}");
- cf.put("B/b1", "$C{x1}");
-
- assertObjectEquals("{'default':{x1:'9',x2:'$C{x1}'},A:{a1:'$C{x1}',a2:'$C{x1}'},B:{b1:'$C{x1}'}}", cf);
- assertTextEquals("x1 = 9|x2 = $C{x1}|[A]|a1 = $C{x1}|a2 = $C{x1}|[B]|b1 = $C{x1}|", cf);
-
- assertEquals("9", cf.getString("x1"));
- assertEquals("9", cf.getString("x2"));
- assertEquals("9", cf.getString("A/a1"));
- assertEquals("9", cf.getString("A/a2"));
- assertEquals("9", cf.getString("B/b1"));
- }
-
- //====================================================================================================
- // put(String key, Object value, boolean encoded)
- //====================================================================================================
- @Test
- public void testPutStringEncoded() throws Exception {
- ConfigFile cf = ConfigMgr.DEFAULT.create()
- .addLines(null, "x1=1")
- .addLines("A", "a1=1");
-
- cf.put("x1", 2, true);
- cf.put("x2", 3, true);
- cf.put("A/a1", 2, true);
- cf.put("A/a2", 3, true);
- cf.put("B/b1", 2, true);
-
- assertObjectEquals("{'default':{x1:'2',x2:'3'},A:{a1:'2',a2:'3'},B:{b1:'2'}}", cf);
- assertTextEquals("x1* = {XA==}|x2* = {XQ==}|[A]|a1* = {XA==}|a2* = {XQ==}|[B]|b1* = {XA==}|", cf);
-
- cf = ConfigMgr.DEFAULT.create()
- .addLines(null, "x1=1")
- .addLines("A", "a1=1")
- .getResolving();
-
- cf.put("x1", 2, true);
- cf.put("x2", 3, true);
- cf.put("A/a1", 2, true);
- cf.put("A/a2", 3, true);
- cf.put("B/b1", 2, true);
-
- assertObjectEquals("{'default':{x1:'2',x2:'3'},A:{a1:'2',a2:'3'},B:{b1:'2'}}", cf);
- assertTextEquals("x1* = {XA==}|x2* = {XQ==}|[A]|a1* = {XA==}|a2* = {XQ==}|[B]|b1* = {XA==}|", cf);
-
- cf.put("x1", 9, true);
- cf.put("x2", "$C{x1}", true);
- cf.put("A/a1", "$C{x1}", true);
- cf.put("A/a2", "$C{x1}", true);
- cf.put("B/b1", "$C{x1}", true);
-
- assertObjectEquals("{'default':{x1:'9',x2:'$C{x1}'},A:{a1:'$C{x1}',a2:'$C{x1}'},B:{b1:'$C{x1}'}}", cf);
- assertTextEquals("x1* = {Vw==}|x2* = {SjYCT14a}|[A]|a1* = {SjYCT14a}|a2* = {SjYCT14a}|[B]|b1* = {SjYCT14a}|", cf);
-
- assertEquals("9", cf.getString("x1"));
- assertEquals("9", cf.getString("x2"));
- assertEquals("9", cf.getString("A/a1"));
- assertEquals("9", cf.getString("A/a2"));
- assertEquals("9", cf.getString("B/b1"));
- }
-
- //====================================================================================================
- // removeString(String key)
- //====================================================================================================
- @Test
- public void testRemoveString() throws Exception {
- ConfigFile cf = ConfigMgr.DEFAULT.create()
- .addLines(null, "x1=1")
- .addLines("A", "a1=1");
-
- cf.removeString("x1");
- cf.removeString("x2");
- cf.removeString("A/a1");
- cf.removeString("A/a2");
-
- assertObjectEquals("{'default':{},A:{}}", cf);
- assertTextEquals("[A]|", cf);
-
- cf = ConfigMgr.DEFAULT.create()
- .addLines(null, "x1=1")
- .addLines("A", "a1=1")
- .getResolving();
-
- cf.removeString("x1");
- cf.removeString("x2");
- cf.removeString("A/a1");
- cf.removeString("A/a2");
-
- assertObjectEquals("{'default':{},A:{}}", cf);
- assertTextEquals("[A]|", cf);
- }
-
- //====================================================================================================
- // getObject(Class c, String key)
- // getObject(Class c, String key, T def)
- //====================================================================================================
- @Test
- public void testGetObject() throws Exception {
- ConfigFile cf = ConfigMgr.DEFAULT.create().addLines("A", "a1=1,2,3", "a2=1", "a3=true", "a4=1.2", "a5=1.2,3.4");
- ConfigFile cfw = cf.getResolving();
-
- assertObjectEquals("['1','2','3']", cf.getObject(String[].class, "A/a1"));
- assertObjectEquals("'1,2,3'", cf.getObject(String.class, "A/a1"));
- assertObjectEquals("'foobar'", cf.getObject(String.class, "X/a1", "foobar"));
- assertObjectEquals("1", cf.getObject(int.class, "A/a2"));
- assertObjectEquals("1", cf.getObject(Integer.class, "A/a2"));
- assertObjectEquals("true", cf.getObject(boolean.class, "A/a3"));
- assertObjectEquals("true", cf.getObject(Boolean.class, "A/a3"));
- assertObjectEquals("1.2", cf.getObject(Float.class, "A/a4"));
- assertObjectEquals("[1.2,3.4]", cf.getObject(Float[].class, "A/a5"));
- assertObjectEquals("1.2", cf.getObject(float.class, "A/a4"));
- assertObjectEquals("[1.2,3.4]", cf.getObject(float[].class, "A/a5"));
- assertNull(cf.getObject(String.class, "B/a4"));
-
- assertObjectEquals("['1','2','3']", cfw.getObject(String[].class, "A/a1"));
- assertObjectEquals("'1,2,3'", cfw.getObject(String.class, "A/a1"));
- assertObjectEquals("'foobar'", cfw.getObject(String.class, "X/a1", "foobar"));
- assertObjectEquals("1", cfw.getObject(int.class, "A/a2"));
- assertObjectEquals("1", cfw.getObject(Integer.class, "A/a2"));
- assertObjectEquals("true", cfw.getObject(boolean.class, "A/a3"));
- assertObjectEquals("true", cfw.getObject(Boolean.class, "A/a3"));
- assertObjectEquals("1.2", cfw.getObject(Float.class, "A/a4"));
- assertObjectEquals("[1.2,3.4]", cfw.getObject(Float[].class, "A/a5"));
- assertObjectEquals("1.2", cfw.getObject(float.class, "A/a4"));
- assertObjectEquals("[1.2,3.4]", cfw.getObject(float[].class, "A/a5"));
- assertNull(cfw.getObject(String.class, "B/a4"));
- }
-
- //====================================================================================================
- // getInt(String key)
- // getInt(String key, int def)
- //====================================================================================================
- @Test
- public void testGetInt() throws Exception {
- System.setProperty("X", "1");
- ConfigFile cf = ConfigMgr.DEFAULT.create().addLines(null, "x1=$C{A/a1}", "x2=$S{X}", "x3=$S{Y}", "x4=$S{Y,2}").addLines("A", "a1=1");
-
- try {
- cf.getInt("x1");
- fail();
- } catch (NumberFormatException e) {}
- try {
- cf.getInt("x2");
- fail();
- } catch (NumberFormatException e) {}
- try {
- cf.getInt("x3");
- fail();
- } catch (NumberFormatException e) {}
- try {
- cf.getInt("x4");
- fail();
- } catch (NumberFormatException e) {}
- assertEquals(1, cf.getInt("A/a1"));
-
- cf = cf.getResolving();
-
- assertEquals(1, cf.getInt("x1"));
- assertEquals(1, cf.getInt("x2"));
- assertEquals(0, cf.getInt("x3"));
- assertEquals(9, cf.getInt("x3", 9));
- assertEquals(2, cf.getInt("x4"));
- assertEquals(9, cf.getInt("x5", 9));
- assertEquals(1, cf.getInt("A/a1"));
- assertEquals(9, cf.getInt("A/a2", 9));
- assertEquals(9, cf.getInt("B/b1", 9));
-
- System.clearProperty("X");
- }
-
- //====================================================================================================
- // getBoolean(String key)
- // getBoolean(String key, boolean def)
- //====================================================================================================
- @Test
- public void testGetBoolean() throws Exception {
- System.setProperty("X", "true");
- ConfigFile cf = ConfigMgr.DEFAULT.create().addLines(null, "x1=$C{A/a1}", "x2=$S{X}", "x3=$S{Y}", "x4=$S{Y,true}").addLines("A", "a1=true");
-
- assertFalse(cf.getBoolean("x1"));
- assertFalse(cf.getBoolean("x2"));
- assertFalse(cf.getBoolean("x3"));
- assertFalse(cf.getBoolean("x4"));
- assertTrue(cf.getBoolean("A/a1"));
-
- cf = cf.getResolving();
-
- assertTrue(cf.getBoolean("x1"));
- assertTrue(cf.getBoolean("x2"));
- assertFalse(cf.getBoolean("x3"));
- assertTrue(cf.getBoolean("x3", true));
- assertTrue(cf.getBoolean("x4"));
- assertTrue(cf.getBoolean("x5", true));
- assertTrue(cf.getBoolean("A/a1"));
- assertTrue(cf.getBoolean("A/a2", true));
- assertTrue(cf.getBoolean("B/b1", true));
-
- System.clearProperty("X");
- }
-
- //====================================================================================================
- // getSectionAsBean(String,Class)
- //====================================================================================================
- @Test
- public void testGetSectionAsBean() throws Exception {
- ConfigFile cf = ConfigMgr.DEFAULT.create();
- cf.put("A/a", "1");
- cf.put("A/b", "2");
-
- A a = cf.getSectionAsBean("A", A.class);
- assertObjectEquals("{a:1,b:2}", a);
-
- cf.put("A/c", "3");
- try { cf.getSectionAsBean("A",A.class);} catch (ParseException e) {}
- a = cf.getSectionAsBean("A", A.class, true);
- assertObjectEquals("{a:1,b:2}", a);
-
- System.setProperty("X", "3");
- cf.put("A/a", "$S{X}");
- cf.put("A/b", "$S{Y,$S{X}}");
- cf = cf.getResolving();
- a = cf.getSectionAsBean("A", A.class, true);
- assertObjectEquals("{a:3,b:3}", a);
- System.clearProperty("X");
- }
-
- public static class A {
- public int a;
- private int b;
- public int getB() {
- return b;
- }
- public void setB(int b) {
- this.b = b;
- }
- }
-
- //====================================================================================================
- // writeProperties(...)
- //====================================================================================================
- @Test
- public void testWriteProperties() throws Exception {
- ConfigFile cf = ConfigMgr.DEFAULT.create();
- cf.put("B/a", "1");
-
- B b = new B();
- cf.writeProperties("B", b, false);
- assertObjectEquals("{a:1}", b);
-
- cf.put("B/b", "2");
- try { cf.writeProperties("B", b, false);} catch (ParseException e) {}
- cf.writeProperties("B", b, true);
- assertObjectEquals("{a:1}", b);
- cf.removeString("B/b");
-
- cf.put("B/c", "2");
- try { cf.writeProperties("B", b, false);} catch (ParseException e) {}
- cf.writeProperties("B", b, true);
- assertObjectEquals("{a:1}", b);
- cf.removeString("B/c");
-
- cf.put("B/c2", "2");
- try { cf.writeProperties("B", b, false);} catch (ParseException e) {}
- cf.writeProperties("B", b, true);
- assertObjectEquals("{a:1}", b);
- cf.removeString("B/c2");
-
- cf.put("B/d", "2");
- try { cf.writeProperties("B", b, false);} catch (ParseException e) {}
- cf.writeProperties("B", b, true);
- assertObjectEquals("{a:1}", b);
- cf.removeString("B/d");
-
- cf.put("B/e", "2");
- cf.writeProperties("B", b, false);
- assertObjectEquals("{a:1,e:2}", b);
-
- cf.put("B/f", "foobar");
- try {
- cf.writeProperties("B", b, false, int.class, Integer.class);
- } catch (ParseException e) {
- assertTrue(e.getLocalizedMessage().startsWith("Invalid"));
- }
- assertObjectEquals("{a:1,e:2}", b);
-
- cf.removeString("B/f");
- System.setProperty("X", "3");
- cf.put("B/a", "$S{X}");
- cf.put("B/e", "$S{Y,$S{X}}");
- cf = cf.getResolving();
- cf.writeProperties("B", b, true);
- assertObjectEquals("{a:3,e:3}", b);
-
- System.clearProperty("X");
- }
-
- @SuppressWarnings("unused")
- @Bean(sort=true)
- public static class B {
- private int a;
- private Integer e;
- public int getA() {
- return a;
- }
- public void setA(int a) {
- this.a = a;
- }
- public static void setB(String b) {
- throw new RuntimeException("Should not be called.");
- }
- protected void setC(String c) {
- throw new RuntimeException("Should not be called.");
- }
- protected static void setC2(String c2) {
- throw new RuntimeException("Should not be called.");
- }
- public void setD(String d, String x) {
- throw new RuntimeException("Should not be called.");
- }
- public Integer getE() {
- return e;
- }
- public void setE(Integer e) {
- this.e = e;
- }
- public String getF() {
- return null;
- }
- public void setF(String f) {
- throw new RuntimeException("Should not be called.");
- }
- }
-
- //====================================================================================================
- // Bad input
- //====================================================================================================
- @Test
- public void testBadInput() throws Exception {
- ConfigFile[] cff = {
- ConfigMgr.DEFAULT.create().addLines("A", "a1=1", ""),
- ConfigMgr.DEFAULT.create().addLines("A", "a1=1", "").getResolving()
- };
-
- for (ConfigFile cf : cff) {
- try {
- cf.load(null);
- fail();
- } catch (IllegalArgumentException e) {
- assertEquals("Field 'r' cannot be null.", e.getLocalizedMessage());
- }
- try {
- cf.getString(null);
- fail();
- } catch (IllegalArgumentException e) {
- assertEquals("Field 'key' cannot be null.", e.getLocalizedMessage());
- }
- try {
- cf.getString(null, null);
- fail();
- } catch (IllegalArgumentException e) {
- assertEquals("Field 'key' cannot be null.", e.getLocalizedMessage());
- }
- try {
- cf.put(null, (Object)null);
- fail();
- } catch (IllegalArgumentException e) {
- assertEquals("Field 'key' cannot be null.", e.getLocalizedMessage());
- }
- try {
- cf.put(null, null, true);
- fail();
- } catch (IllegalArgumentException e) {
- assertEquals("Field 'key' cannot be null.", e.getLocalizedMessage());
- }
- try {
- cf.removeString(null);
- fail();
- } catch (IllegalArgumentException e) {
- assertEquals("Field 'key' cannot be null.", e.getLocalizedMessage());
- }
- try {
- cf.getObject(Object.class, null);
- fail();
- } catch (IllegalArgumentException e) {
- assertEquals("Field 'key' cannot be null.", e.getLocalizedMessage());
- }
- try {
- cf.getObject(null, "");
- fail();
- } catch (IllegalArgumentException e) {
- assertEquals("Field 'c' cannot be null.", e.getLocalizedMessage());
- }
- try {
- cf.getStringArray(null);
- fail();
- } catch (IllegalArgumentException e) {
- assertEquals("Field 'key' cannot be null.", e.getLocalizedMessage());
- }
- try {
- cf.getStringArray(null, null);
- fail();
- } catch (IllegalArgumentException e) {
- assertEquals("Field 'key' cannot be null.", e.getLocalizedMessage());
- }
- try {
- cf.getInt(null);
- fail();
- } catch (IllegalArgumentException e) {
- assertEquals("Field 'key' cannot be null.", e.getLocalizedMessage());
- }
- try {
- cf.getInt(null, -1);
- fail();
- } catch (IllegalArgumentException e) {
- assertEquals("Field 'key' cannot be null.", e.getLocalizedMessage());
- }
- try {
- cf.getBoolean(null);
- fail();
- } catch (IllegalArgumentException e) {
- assertEquals("Field 'key' cannot be null.", e.getLocalizedMessage());
- }
- try {
- cf.getBoolean(null, true);
- fail();
- } catch (IllegalArgumentException e) {
- assertEquals("Field 'key' cannot be null.", e.getLocalizedMessage());
- }
- try {
- cf.put(null, (String)null);
- fail();
- } catch (IllegalArgumentException e) {
- assertEquals("Field 'key' cannot be null.", e.getLocalizedMessage());
- }
- try {
- cf.put(null, null, true);
- fail();
- } catch (IllegalArgumentException e) {
- assertEquals("Field 'key' cannot be null.", e.getLocalizedMessage());
- }
- try {
- cf.writeProperties(null, null, true);
- fail();
- } catch (IllegalArgumentException e) {
- assertEquals("Field 'bean' cannot be null.", e.getLocalizedMessage());
- }
- try {
- cf.getSectionAsBean(null, null);
- fail();
- } catch (IllegalArgumentException e) {
- assertEquals("Field 'c' cannot be null.", e.getLocalizedMessage());
- }
- try {
- cf.getSectionAsBean(null, null, true);
- fail();
- } catch (IllegalArgumentException e) {
- assertEquals("Field 'c' cannot be null.", e.getLocalizedMessage());
- }
- try {
- cf.containsNonEmptyValue(null);
- fail();
- } catch (IllegalArgumentException e) {
- assertEquals("Field 'key' cannot be null.", e.getLocalizedMessage());
- }
- try {
- cf.isEncoded(null);
- fail();
- } catch (IllegalArgumentException e) {
- assertEquals("Field 'key' cannot be null.", e.getLocalizedMessage());
- }
- try {
- cf.addListener(null);
- fail();
- } catch (IllegalArgumentException e) {
- assertEquals("Field 'listener' cannot be null.", e.getLocalizedMessage());
- }
- try {
- cf.merge(null);
- fail();
- } catch (IllegalArgumentException e) {
- assertEquals("Field 'cf' cannot be null.", e.getLocalizedMessage());
- }
- try {
- cf.getResolving((VarResolver)null);
- fail();
- } catch (IllegalArgumentException e) {
- assertEquals("Field 'vr' cannot be null.", e.getLocalizedMessage());
- }
- }
- }
-
- //====================================================================================================
- // Config to and from JSON
- //====================================================================================================
- @Test
- public void testSerializedAsJson() throws Exception {
- ConfigFile cf = ConfigMgr.DEFAULT.create();
- cf.put("a", "1");
- cf.put("B/a", "2");
-
- String json = JsonSerializer.DEFAULT_LAX.toString(cf);
- assertEquals("{'default':{a:'1'},B:{a:'2'}}", json);
-
- cf = JsonParser.DEFAULT.parse(json, ConfigFileImpl.class);
- assertObjectEquals("{'default':{a:'1'},B:{a:'2'}}", cf);
-
- }
-
- //====================================================================================================
- // Test resolving with override
- //====================================================================================================
- @Test
- public void testResolvingWithOverride() throws Exception {
- ConfigFile cf = ConfigMgr.DEFAULT.create();
- cf.put("a", "$A{X}");
- cf.put("b", "$B{X}");
- cf.put("c", "$A{$B{X}}");
- cf.put("d", "$B{$A{X}}");
- cf.put("e", "$D{X}");
-
- VarResolver vr = new VarResolver().addVars(ALVar.class, BLVar.class);
-
- cf = cf.getResolving(vr);
-
- assertEquals("aXa", cf.getString("a"));
- assertEquals("bXb", cf.getString("b"));
- assertEquals("abXba", cf.getString("c"));
- assertEquals("baXab", cf.getString("d"));
- assertEquals("$D{X}", cf.getString("e"));
-
- // Create new resolver that addx $C and overrides $A
- VarResolver vr2 = vr.clone().addVars(AUVar.class, DUVar.class);
-
- // true == augment by adding existing as parent to the new resolver
- cf = cf.getResolving(vr2);
- assertEquals("AXA", cf.getString("a"));
- assertEquals("bXb", cf.getString("b"));
- assertEquals("AbXbA", cf.getString("c"));
- assertEquals("bAXAb", cf.getString("d"));
- assertEquals("DXD", cf.getString("e"));
- }
-
- public static class ALVar extends SimpleVar {
- public ALVar() {
- super("A");
- }
- @Override
- public String resolve(VarResolverSession session, String key) {
- return 'a' + key + 'a';
- }
- }
-
- public static class AUVar extends SimpleVar {
- public AUVar() {
- super("A");
- }
- @Override
- public String resolve(VarResolverSession session, String key) {
- return 'A' + key + 'A';
- }
- }
-
- public static class BLVar extends SimpleVar {
- public BLVar() {
- super("B");
- }
- @Override
- public String resolve(VarResolverSession session, String key) {
- return 'b' + key + 'b';
- }
- }
-
- public static class DUVar extends SimpleVar {
- public DUVar() {
- super("D");
- }
- @Override
- public String resolve(VarResolverSession session, String key) {
- return 'D' + key + 'D';
- }
- }
-
- //====================================================================================================
- // Test multiline values.
- //====================================================================================================
- @Test
- public void testMultilineValues() throws Exception {
- File f = getFreshFile();
-
- ConfigFile cf = ConfigMgr.DEFAULT.create(f);
- cf.put("a", "a,\nb,\nc");
- cf.put("A/a", "a,\nb,\nc");
-
- assertTextEquals("a = a,|\tb,|\tc|[A]|a = a,|\tb,|\tc|", cf);
- cf.save();
- assertTextEquals("a = a,|\tb,|\tc|[A]|a = a,|\tb,|\tc|", IOUtils.read(f));
-
- cf.load();
- assertEquals("a,\nb,\nc", cf.getString("a"));
- assertEquals("a,\nb,\nc", cf.getString("A/a"));
-
- assertObjectEquals("['a','b','c']", cf.getStringArray("a", null));
- assertObjectEquals("['a','b','c']", cf.getStringArray("A/a", null));
- }
-
- //====================================================================================================
- // Test special character encoding.
- //====================================================================================================
- @Test
- public void testSpecialCharacterEncoding() throws Exception {
- File f = getFreshFile();
-
- ConfigFile cf = ConfigMgr.DEFAULT.create(f);
- cf.put("a", "a,#b,=c");
- cf.put("A/a", "a,#b,=c");
-
- assertTextEquals("a = a,\\u0023b,\\u003Dc|[A]|a = a,\\u0023b,\\u003Dc|", cf);
- cf.save();
- assertTextEquals("a = a,\\u0023b,\\u003Dc|[A]|a = a,\\u0023b,\\u003Dc|", IOUtils.read(f));
-
- cf.load();
- assertEquals("a,#b,=c", cf.getString("a"));
- assertEquals("a,#b,=c", cf.getString("A/a"));
- }
-}
\ No newline at end of file
[10/44] incubator-juneau git commit: Rename CT_* testcases.
Posted by ja...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/urlencoding/CT_UonSerializer.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/urlencoding/CT_UonSerializer.java b/org.apache.juneau/src/test/java/org/apache/juneau/urlencoding/CT_UonSerializer.java
deleted file mode 100755
index 69c9bec..0000000
--- a/org.apache.juneau/src/test/java/org/apache/juneau/urlencoding/CT_UonSerializer.java
+++ /dev/null
@@ -1,460 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.urlencoding;
-
-import static org.junit.Assert.*;
-
-import org.apache.juneau.*;
-import org.junit.*;
-
-public class CT_UonSerializer {
-
- static UonSerializer s = UonSerializer.DEFAULT_ENCODING;
- static UonSerializer ss = UonSerializer.DEFAULT_SIMPLE_ENCODING;
- static UonSerializer su = UonSerializer.DEFAULT;
- static UonSerializer ssu = UonSerializer.DEFAULT_SIMPLE;
- static UonSerializer sr = UonSerializer.DEFAULT_READABLE;
-
-
- //====================================================================================================
- // Basic test
- //====================================================================================================
- @Test
- public void testBasic() throws Exception {
-
- Object t;
-
- // Simple string
- // Top level
- t = "a";
- assertEquals("a", s.serialize(t));
- assertEquals("a", ss.serialize(t));
- assertEquals("a", su.serialize(t));
- assertEquals("a", ssu.serialize(t));
- assertEquals("a", sr.serialize(t));
-
- // 2nd level
- t = new ObjectMap("{a:'a'}");
- assertEquals("$o(a=a)", s.serialize(t));
- assertEquals("(a=a)", ss.serialize(t));
- assertEquals("$o(a=a)", su.serialize(t));
- assertEquals("(a=a)", ssu.serialize(t));
- assertEquals("$o(\n\ta=a\n)", sr.serialize(t));
-
- // Simple map
- // Top level
- t = new ObjectMap("{a:'b',c:123,d:false,e:true,f:null}");
- assertEquals("$o(a=b,c=$n(123),d=$b(false),e=$b(true),f=%00)", s.serialize(t));
- assertEquals("(a=b,c=123,d=false,e=true,f=%00)", ss.serialize(t));
- assertEquals("$o(a=b,c=$n(123),d=$b(false),e=$b(true),f=\u0000)", su.serialize(t));
- assertEquals("(a=b,c=123,d=false,e=true,f=\u0000)", ssu.serialize(t));
- assertEquals("$o(\n\ta=b,\n\tc=$n(123),\n\td=$b(false),\n\te=$b(true),\n\tf=\u0000\n)", sr.serialize(t));
-
- // 2nd level
- t = new ObjectMap("{a:{a:'b',c:123,d:false,e:true,f:null}}");
- assertEquals("$o(a=$o(a=b,c=$n(123),d=$b(false),e=$b(true),f=%00))", s.serialize(t));
- assertEquals("(a=(a=b,c=123,d=false,e=true,f=%00))", ss.serialize(t));
- assertEquals("$o(a=$o(a=b,c=$n(123),d=$b(false),e=$b(true),f=\u0000))", su.serialize(t));
- assertEquals("(a=(a=b,c=123,d=false,e=true,f=\u0000))", ssu.serialize(t));
- assertEquals("$o(\n\ta=$o(\n\t\ta=b,\n\t\tc=$n(123),\n\t\td=$b(false),\n\t\te=$b(true),\n\t\tf=\u0000\n\t)\n)", sr.serialize(t));
-
- // Simple map with primitives as literals
- t = new ObjectMap("{a:'b',c:'123',d:'false',e:'true',f:'null'}");
- assertEquals("$o(a=b,c=123,d=false,e=true,f=null)", s.serialize(t));
- assertEquals("(a=b,c=123,d=false,e=true,f=null)", ss.serialize(t));
- assertEquals("$o(a=b,c=123,d=false,e=true,f=null)", su.serialize(t));
- assertEquals("(a=b,c=123,d=false,e=true,f=null)", ssu.serialize(t));
- assertEquals("$o(\n\ta=b,\n\tc=123,\n\td=false,\n\te=true,\n\tf=null\n)", sr.serialize(t));
-
- // null
- // Note that serializeParams is always encoded.
- // Top level
- t = null;
- assertEquals("%00", s.serialize(t));
- assertEquals("%00", ss.serialize(t));
- assertEquals("\u0000", su.serialize(t));
- assertEquals("\u0000", ssu.serialize(t));
- assertEquals("\u0000", sr.serialize(t));
-
- // 2nd level
- t = new ObjectMap("{null:null}");
- assertEquals("$o(%00=%00)", s.serialize(t));
- assertEquals("(%00=%00)", ss.serialize(t));
- assertEquals("$o(\u0000=\u0000)", su.serialize(t));
- assertEquals("(\u0000=\u0000)", ssu.serialize(t));
- assertEquals("$o(\n\t\u0000=\u0000\n)", sr.serialize(t));
-
- // 3rd level
- t = new ObjectMap("{null:{null:null}}");
- assertEquals("$o(%00=$o(%00=%00))", s.serialize(t));
- assertEquals("(%00=(%00=%00))", ss.serialize(t));
- assertEquals("$o(\u0000=$o(\u0000=\u0000))", su.serialize(t));
- assertEquals("(\u0000=(\u0000=\u0000))", ssu.serialize(t));
- assertEquals("$o(\n\t\u0000=$o(\n\t\t\u0000=\u0000\n\t)\n)", sr.serialize(t));
-
- // Empty array
- // Top level
- t = new String[0];
- assertEquals("$a()", s.serialize(t));
- assertEquals("()", ss.serialize(t));
- assertEquals("$a()", su.serialize(t));
- assertEquals("()", ssu.serialize(t));
- assertEquals("$a()", sr.serialize(t));
-
- // 2nd level in map
- t = new ObjectMap("{x:[]}");
- assertEquals("$o(x=$a())", s.serialize(t));
- assertEquals("(x=())", ss.serialize(t));
- assertEquals("$o(x=$a())", su.serialize(t));
- assertEquals("(x=())", ssu.serialize(t));
- assertEquals("$o(\n\tx=$a()\n)", sr.serialize(t));
-
- // Empty 2 dimensional array
- t = new String[1][0];
- assertEquals("$a($a())", s.serialize(t));
- assertEquals("(())", ss.serialize(t));
- assertEquals("$a($a())", su.serialize(t));
- assertEquals("(())", ssu.serialize(t));
- assertEquals("$a(\n\t$a()\n)", sr.serialize(t));
-
- // Array containing empty string
- // Top level
- t = new String[]{""};
- assertEquals("$a(())", s.serialize(t));
- assertEquals("(())", ss.serialize(t));
- assertEquals("$a(())", su.serialize(t));
- assertEquals("(())", ssu.serialize(t));
- assertEquals("$a(\n\t()\n)", sr.serialize(t));
-
- // 2nd level
- t = new ObjectMap("{x:['']}");
- assertEquals("$o(x=$a(()))", s.serialize(t));
- assertEquals("(x=(()))", ss.serialize(t));
- assertEquals("$o(x=$a(()))", su.serialize(t));
- assertEquals("(x=(()))", ssu.serialize(t));
- assertEquals("$o(\n\tx=$a(\n\t\t()\n\t)\n)", sr.serialize(t));
-
- // Array containing 3 empty strings
- t = new String[]{"","",""};
- assertEquals("$a(,,)", s.serialize(t));
- assertEquals("(,,)", ss.serialize(t));
- assertEquals("$a(,,)", su.serialize(t));
- assertEquals("(,,)", ssu.serialize(t));
- assertEquals("$a(\n\t(),\n\t(),\n\t()\n)", sr.serialize(t));
-
- // String containing \u0000
- // Top level
- t = "\u0000";
- assertEquals("(%00)", s.serialize(t));
- assertEquals("(%00)", ss.serialize(t));
- assertEquals("(\u0000)", su.serialize(t));
- assertEquals("(\u0000)", ssu.serialize(t));
- assertEquals("(\u0000)", sr.serialize(t));
-
- // 2nd level
- t = new ObjectMap("{'\u0000':'\u0000'}");
- assertEquals("$o((%00)=(%00))", s.serialize(t));
- assertEquals("((%00)=(%00))", ss.serialize(t));
- assertEquals("$o((\u0000)=(\u0000))", su.serialize(t));
- assertEquals("((\u0000)=(\u0000))", ssu.serialize(t));
- assertEquals("$o(\n\t(\u0000)=(\u0000)\n)", sr.serialize(t));
-
- // Boolean
- // Top level
- t = false;
- assertEquals("$b(false)", s.serialize(t));
- assertEquals("false", ss.serialize(t));
- assertEquals("$b(false)", su.serialize(t));
- assertEquals("false", ssu.serialize(t));
- assertEquals("$b(false)", sr.serialize(t));
-
- // 2nd level
- t = new ObjectMap("{x:false}");
- assertEquals("$o(x=$b(false))", s.serialize(t));
- assertEquals("(x=false)", ss.serialize(t));
- assertEquals("$o(x=$b(false))", su.serialize(t));
- assertEquals("(x=false)", ssu.serialize(t));
- assertEquals("$o(\n\tx=$b(false)\n)", sr.serialize(t));
-
- // Number
- // Top level
- t = 123;
- assertEquals("$n(123)", s.serialize(t));
- assertEquals("123", ss.serialize(t));
- assertEquals("$n(123)", su.serialize(t));
- assertEquals("123", ssu.serialize(t));
- assertEquals("$n(123)", sr.serialize(t));
-
- // 2nd level
- t = new ObjectMap("{x:123}");
- assertEquals("$o(x=$n(123))", s.serialize(t));
- assertEquals("(x=123)", ss.serialize(t));
- assertEquals("$o(x=$n(123))", su.serialize(t));
- assertEquals("(x=123)", ssu.serialize(t));
- assertEquals("$o(\n\tx=$n(123)\n)", sr.serialize(t));
-
- // Unencoded chars
- // Top level
- t = "x;/?:@-_.!*'";
- assertEquals("x;/?:@-_.!*'", s.serialize(t));
- assertEquals("x;/?:@-_.!*'", ss.serialize(t));
- assertEquals("x;/?:@-_.!*'", su.serialize(t));
- assertEquals("x;/?:@-_.!*'", ssu.serialize(t));
- assertEquals("x;/?:@-_.!*'", sr.serialize(t));
-
- // 2nd level
- t = new ObjectMap("{x:'x;/?:@-_.!*\\''}");
- assertEquals("$o(x=x;/?:@-_.!*')", s.serialize(t));
- assertEquals("(x=x;/?:@-_.!*')", ss.serialize(t));
- assertEquals("$o(x=x;/?:@-_.!*')", su.serialize(t));
- assertEquals("(x=x;/?:@-_.!*')", ssu.serialize(t));
- assertEquals("$o(\n\tx=x;/?:@-_.!*'\n)", sr.serialize(t));
-
- // Encoded chars
- // Top level
- t = "x{}|\\^[]`<>#%\"&+";
- assertEquals("x%7B%7D%7C%5C%5E%5B%5D%60%3C%3E%23%25%22%26%2B", s.serialize(t));
- assertEquals("x%7B%7D%7C%5C%5E%5B%5D%60%3C%3E%23%25%22%26%2B", ss.serialize(t));
- assertEquals("x{}|\\^[]`<>#%\"&+", su.serialize(t));
- assertEquals("x{}|\\^[]`<>#%\"&+", ssu.serialize(t));
- assertEquals("x{}|\\^[]`<>#%\"&+", sr.serialize(t));
-
- // 2nd level
- t = new ObjectMap("{'x{}|\\\\^[]`<>#%\"&+':'x{}|\\\\^[]`<>#%\"&+'}");
- assertEquals("$o(x%7B%7D%7C%5C%5E%5B%5D%60%3C%3E%23%25%22%26%2B=x%7B%7D%7C%5C%5E%5B%5D%60%3C%3E%23%25%22%26%2B)", s.serialize(t));
- assertEquals("(x%7B%7D%7C%5C%5E%5B%5D%60%3C%3E%23%25%22%26%2B=x%7B%7D%7C%5C%5E%5B%5D%60%3C%3E%23%25%22%26%2B)", ss.serialize(t));
- assertEquals("$o(x{}|\\^[]`<>#%\"&+=x{}|\\^[]`<>#%\"&+)", su.serialize(t));
- assertEquals("(x{}|\\^[]`<>#%\"&+=x{}|\\^[]`<>#%\"&+)", ssu.serialize(t));
- assertEquals("$o(\n\tx{}|\\^[]`<>#%\"&+=x{}|\\^[]`<>#%\"&+\n)", sr.serialize(t));
-
- // Escaped chars
- // Top level
- t = "x$,()~";
- assertEquals("x$,()~", s.serialize(t));
- assertEquals("x$,()~", ss.serialize(t));
- assertEquals("x$,()~", su.serialize(t));
- assertEquals("x$,()~", ssu.serialize(t));
- assertEquals("x$,()~", sr.serialize(t));
-
- // 2nd level
- // Note behavior on serializeParams() is different since 2nd-level is top level.
- t = new ObjectMap("{'x$,()~':'x$,()~'}");
- assertEquals("$o(x$~,~(~)~~=x$~,~(~)~~)", s.serialize(t));
- assertEquals("(x$~,~(~)~~=x$~,~(~)~~)", ss.serialize(t));
- assertEquals("$o(x$~,~(~)~~=x$~,~(~)~~)", su.serialize(t));
- assertEquals("(x$~,~(~)~~=x$~,~(~)~~)", ssu.serialize(t));
- assertEquals("$o(\n\tx$~,~(~)~~=x$~,~(~)~~\n)", sr.serialize(t));
-
- // 3rd level
- // Note behavior on serializeParams().
- t = new ObjectMap("{'x$,()~':{'x$,()~':'x$,()~'}}");
- assertEquals("$o(x$~,~(~)~~=$o(x$~,~(~)~~=x$~,~(~)~~))", s.serialize(t));
- assertEquals("(x$~,~(~)~~=(x$~,~(~)~~=x$~,~(~)~~))", ss.serialize(t));
- assertEquals("$o(x$~,~(~)~~=$o(x$~,~(~)~~=x$~,~(~)~~))", su.serialize(t));
- assertEquals("(x$~,~(~)~~=(x$~,~(~)~~=x$~,~(~)~~))", ssu.serialize(t));
- assertEquals("$o(\n\tx$~,~(~)~~=$o(\n\t\tx$~,~(~)~~=x$~,~(~)~~\n\t)\n)", sr.serialize(t));
-
- // Equals sign
- // Gets encoded at top level, and encoded+escaped at 2nd level.
- // Top level
- t = "x=";
- assertEquals("x=", s.serialize(t));
- assertEquals("x=", ss.serialize(t));
- assertEquals("x=", su.serialize(t));
- assertEquals("x=", ssu.serialize(t));
- assertEquals("x=", sr.serialize(t));
-
- // 2nd level
- t = new ObjectMap("{'x=':'x='}");
- assertEquals("$o(x~==x~=)", s.serialize(t));
- assertEquals("(x~==x~=)", ss.serialize(t));
- assertEquals("$o(x~==x~=)", su.serialize(t));
- assertEquals("(x~==x~=)", ssu.serialize(t));
- assertEquals("$o(\n\tx~==x~=\n)", sr.serialize(t));
-
- // 3rd level
- t = new ObjectMap("{'x=':{'x=':'x='}}");
- assertEquals("$o(x~==$o(x~==x~=))", s.serialize(t));
- assertEquals("(x~==(x~==x~=))", ss.serialize(t));
- assertEquals("$o(x~==$o(x~==x~=))", su.serialize(t));
- assertEquals("(x~==(x~==x~=))", ssu.serialize(t));
- assertEquals("$o(\n\tx~==$o(\n\t\tx~==x~=\n\t)\n)", sr.serialize(t));
-
- // String starting with parenthesis
- // Top level
- t = "()";
- assertEquals("(~(~))", s.serialize(t));
- assertEquals("(~(~))", ss.serialize(t));
- assertEquals("(~(~))", su.serialize(t));
- assertEquals("(~(~))", ssu.serialize(t));
- assertEquals("(~(~))", sr.serialize(t));
-
- // 2nd level
- t = new ObjectMap("{'()':'()'}");
- assertEquals("$o((~(~))=(~(~)))", s.serialize(t));
- assertEquals("((~(~))=(~(~)))", ss.serialize(t));
- assertEquals("$o((~(~))=(~(~)))", su.serialize(t));
- assertEquals("((~(~))=(~(~)))", ssu.serialize(t));
- assertEquals("$o(\n\t(~(~))=(~(~))\n)", sr.serialize(t));
-
- // String starting with $
- // Top level
- t = "$a";
- assertEquals("($a)", s.serialize(t));
- assertEquals("($a)", ss.serialize(t));
- assertEquals("($a)", su.serialize(t));
- assertEquals("($a)", ssu.serialize(t));
- assertEquals("($a)", sr.serialize(t));
-
- // 2nd level
- t = new ObjectMap("{$a:'$a'}");
- assertEquals("$o(($a)=($a))", s.serialize(t));
- assertEquals("(($a)=($a))", ss.serialize(t));
- assertEquals("$o(($a)=($a))", su.serialize(t));
- assertEquals("(($a)=($a))", ssu.serialize(t));
- assertEquals("$o(\n\t($a)=($a)\n)", sr.serialize(t));
-
- // Blank string
- // Top level
- t = "";
- assertEquals("", s.serialize(t));
- assertEquals("", ss.serialize(t));
- assertEquals("", su.serialize(t));
- assertEquals("", ssu.serialize(t));
- assertEquals("", sr.serialize(t));
-
- // 2nd level
- t = new ObjectMap("{'':''}");
- assertEquals("$o(=)", s.serialize(t));
- assertEquals("(=)", ss.serialize(t));
- assertEquals("$o(=)", su.serialize(t));
- assertEquals("(=)", ssu.serialize(t));
- assertEquals("$o(\n\t()=()\n)", sr.serialize(t));
-
- // 3rd level
- t = new ObjectMap("{'':{'':''}}");
- assertEquals("$o(=$o(=))", s.serialize(t));
- assertEquals("(=(=))", ss.serialize(t));
- assertEquals("$o(=$o(=))", su.serialize(t));
- assertEquals("(=(=))", ssu.serialize(t));
- assertEquals("$o(\n\t()=$o(\n\t\t()=()\n\t)\n)", sr.serialize(t));
-
- // Newline character
- // Top level
- t = "\n";
- assertEquals("%0A", s.serialize(t));
- assertEquals("%0A", ss.serialize(t));
- assertEquals("\n", su.serialize(t));
- assertEquals("\n", ssu.serialize(t));
- assertEquals("(\n)", sr.serialize(t));
-
- // 2nd level
- t = new ObjectMap("{'\n':'\n'}");
- assertEquals("$o(%0A=%0A)", s.serialize(t));
- assertEquals("(%0A=%0A)", ss.serialize(t));
- assertEquals("$o(\n=\n)", su.serialize(t));
- assertEquals("(\n=\n)", ssu.serialize(t));
- assertEquals("$o(\n\t(\n)=(\n)\n)", sr.serialize(t));
-
- // 3rd level
- t = new ObjectMap("{'\n':{'\n':'\n'}}");
- assertEquals("$o(%0A=$o(%0A=%0A))", s.serialize(t));
- assertEquals("(%0A=(%0A=%0A))", ss.serialize(t));
- assertEquals("$o(\n=$o(\n=\n))", su.serialize(t));
- assertEquals("(\n=(\n=\n))", ssu.serialize(t));
- assertEquals("$o(\n\t(\n)=$o(\n\t\t(\n)=(\n)\n\t)\n)", sr.serialize(t));
- }
-
- //====================================================================================================
- // Unicode characters test
- //====================================================================================================
- @Test
- public void testUnicodeChars() throws Exception {
- Object t;
-
- // 2-byte UTF-8 character
- // Top level
- t = "�";
- assertEquals("%C2%A2", s.serialize(t));
- assertEquals("%C2%A2", ss.serialize(t));
- assertEquals("�", su.serialize(t));
- assertEquals("�", ssu.serialize(t));
- assertEquals("�", sr.serialize(t));
-
- // 2nd level
- t = new ObjectMap("{'�':'�'}");
- assertEquals("$o(%C2%A2=%C2%A2)", s.serialize(t));
- assertEquals("(%C2%A2=%C2%A2)", ss.serialize(t));
- assertEquals("$o(�=�)", su.serialize(t));
- assertEquals("(�=�)", ssu.serialize(t));
- assertEquals("$o(\n\t�=�\n)", sr.serialize(t));
-
- // 3rd level
- t = new ObjectMap("{'�':{'�':'�'}}");
- assertEquals("$o(%C2%A2=$o(%C2%A2=%C2%A2))", s.serialize(t));
- assertEquals("(%C2%A2=(%C2%A2=%C2%A2))", ss.serialize(t));
- assertEquals("$o(�=$o(�=�))", su.serialize(t));
- assertEquals("(�=(�=�))", ssu.serialize(t));
- assertEquals("$o(\n\t�=$o(\n\t\t�=�\n\t)\n)", sr.serialize(t));
-
- // 3-byte UTF-8 character
- // Top level
- t = "\u20ac";
- assertEquals("%E2%82%AC", s.serialize(t));
- assertEquals("%E2%82%AC", ss.serialize(t));
- assertEquals("\u20ac", su.serialize(t));
- assertEquals("\u20ac", ssu.serialize(t));
- assertEquals("\u20ac", sr.serialize(t));
-
- // 2nd level
- t = new ObjectMap("{'\u20ac':'\u20ac'}");
- assertEquals("$o(%E2%82%AC=%E2%82%AC)", s.serialize(t));
- assertEquals("(%E2%82%AC=%E2%82%AC)", ss.serialize(t));
- assertEquals("$o(\u20ac=\u20ac)", su.serialize(t));
- assertEquals("(\u20ac=\u20ac)", ssu.serialize(t));
- assertEquals("$o(\n\t\u20ac=\u20ac\n)", sr.serialize(t));
-
- // 3rd level
- t = new ObjectMap("{'\u20ac':{'\u20ac':'\u20ac'}}");
- assertEquals("$o(%E2%82%AC=$o(%E2%82%AC=%E2%82%AC))", s.serialize(t));
- assertEquals("(%E2%82%AC=(%E2%82%AC=%E2%82%AC))", ss.serialize(t));
- assertEquals("$o(\u20ac=$o(\u20ac=\u20ac))", su.serialize(t));
- assertEquals("(\u20ac=(\u20ac=\u20ac))", ssu.serialize(t));
- assertEquals("$o(\n\t\u20ac=$o(\n\t\t\u20ac=\u20ac\n\t)\n)", sr.serialize(t));
-
- // 4-byte UTF-8 character
- // Top level
- t = "\U00024b62";
- assertEquals("%F0%A4%AD%A2", s.serialize(t));
- assertEquals("%F0%A4%AD%A2", ss.serialize(t));
- assertEquals("\U00024b62", su.serialize(t));
- assertEquals("\U00024b62", ssu.serialize(t));
- assertEquals("\U00024b62", sr.serialize(t));
-
- // 2nd level
- t = new ObjectMap("{'\U00024b62':'\U00024b62'}");
- assertEquals("$o(%F0%A4%AD%A2=%F0%A4%AD%A2)", s.serialize(t));
- assertEquals("(%F0%A4%AD%A2=%F0%A4%AD%A2)", ss.serialize(t));
- assertEquals("$o(\U00024b62=\U00024b62)", su.serialize(t));
- assertEquals("(\U00024b62=\U00024b62)", ssu.serialize(t));
- assertEquals("$o(\n\t\U00024b62=\U00024b62\n)", sr.serialize(t));
-
- // 3rd level
- t = new ObjectMap("{'\U00024b62':{'\U00024b62':'\U00024b62'}}");
- assertEquals("$o(%F0%A4%AD%A2=$o(%F0%A4%AD%A2=%F0%A4%AD%A2))", s.serialize(t));
- assertEquals("(%F0%A4%AD%A2=(%F0%A4%AD%A2=%F0%A4%AD%A2))", ss.serialize(t));
- assertEquals("$o(\U00024b62=$o(\U00024b62=\U00024b62))", su.serialize(t));
- assertEquals("(\U00024b62=(\U00024b62=\U00024b62))", ssu.serialize(t));
- assertEquals("$o(\n\t\U00024b62=$o(\n\t\t\U00024b62=\U00024b62\n\t)\n)", sr.serialize(t));
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/urlencoding/CT_UrlEncodingParser.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/urlencoding/CT_UrlEncodingParser.java b/org.apache.juneau/src/test/java/org/apache/juneau/urlencoding/CT_UrlEncodingParser.java
deleted file mode 100755
index c929bab..0000000
--- a/org.apache.juneau/src/test/java/org/apache/juneau/urlencoding/CT_UrlEncodingParser.java
+++ /dev/null
@@ -1,1000 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.urlencoding;
-
-import static org.apache.juneau.TestUtils.*;
-import static org.junit.Assert.*;
-
-import java.util.*;
-
-import org.apache.juneau.*;
-import org.apache.juneau.parser.*;
-import org.junit.*;
-
-@SuppressWarnings({"rawtypes","unchecked","hiding"})
-public class CT_UrlEncodingParser {
-
- static UrlEncodingParser p = UrlEncodingParser.DEFAULT;
-
- //====================================================================================================
- // Basic test
- //====================================================================================================
- @Test
- public void testBasic() throws Exception {
-
- String t;
- Map m;
- List l;
-
- // Simple string
- // Top level
- t = "_value=a";
- assertEquals("a", p.parse(t, Object.class));
- assertEquals("a", p.parse(t, String.class));
- t = "_value=(a)";
- assertEquals("a", p.parse(t, String.class));
- assertEquals("a", p.parse(t, Object.class));
- t = "_value=$s(a)";
- assertEquals("a", p.parse(t, String.class));
-
- t = "a";
- assertEquals("a", p.parseParameter(t, Object.class));
- assertEquals("a", p.parseParameter(t, String.class));
- t = "(a)";
- assertEquals("a", p.parseParameter(t, String.class));
- assertEquals("a", p.parseParameter(t, Object.class));
- t = "$s(a)";
- assertEquals("a", p.parseParameter(t, String.class));
-
- // 2nd level
- t = "?a=a";
- assertEquals("a", p.parse(t, Map.class).get("a"));
-
- // Simple map
- // Top level
- t = "?a=b&c=$n(123)&d=$b(false)&e=$b(true)&f=%00";
- m = p.parse(t, Map.class);
- assertEquals("b", m.get("a"));
- assertTrue(m.get("c") instanceof Number);
- assertEquals(123, m.get("c"));
- assertTrue(m.get("d") instanceof Boolean);
- assertEquals(Boolean.FALSE, m.get("d"));
- assertTrue(m.get("e") instanceof Boolean);
- assertEquals(Boolean.TRUE, m.get("e"));
- assertNull(m.get("f"));
-
- t = "$o(a=b,c=$n(123),d=$b(false),e=$b(true),f=%00)";
- m = p.parseParameter(t, Map.class);
- assertEquals("b", m.get("a"));
- assertTrue(m.get("c") instanceof Number);
- assertEquals(123, m.get("c"));
- assertTrue(m.get("d") instanceof Boolean);
- assertEquals(Boolean.FALSE, m.get("d"));
- assertTrue(m.get("e") instanceof Boolean);
- assertEquals(Boolean.TRUE, m.get("e"));
- assertEquals("%00", m.get("f"));
-
- t = "$o(a=b,c=$n(123),d=$b(false),e=$b(true),f=\u0000)";
- m = p.parseParameter(t, Map.class);
- assertTrue(m.containsKey("f"));
- assertNull(m.get("f"));
-
- t = "?a=true";
- m = p.parseMap(t, HashMap.class, String.class, Boolean.class);
- assertTrue(m.get("a") instanceof Boolean);
- assertEquals("true", m.get("a").toString());
-
- // null
- // Top level
- t = "_value=%00";
- assertNull(p.parse(t, Object.class));
- t = "\u0000";
- assertNull(p.parseParameter(t, Object.class));
- t = "%00";
- assertEquals("%00", p.parseParameter(t, Object.class));
-
- // 2nd level
- t = "?%00=%00";
- m = p.parse(t, Map.class);
- assertTrue(m.containsKey(null));
- assertNull(m.get(null));
-
- t = "?\u0000=\u0000";
- m = p.parse(t, Map.class);
- assertTrue(m.containsKey(null));
- assertNull(m.get(null));
-
- // 3rd level
- t = "?%00=$o(%00=%00)";
- m = p.parse(t, Map.class);
- assertTrue(((Map)m.get(null)).containsKey(null));
- assertNull(((Map)m.get(null)).get(null));
-
- // Empty array
- // Top level
- t = "_value=$a()";
- l = (List)p.parse(t, Object.class);
- assertTrue(l.isEmpty());
- t = "_value=()";
- l = p.parse(t, List.class);
- assertTrue(l.isEmpty());
- t = "$a()";
- l = (List)p.parseParameter(t, Object.class);
- assertTrue(l.isEmpty());
- t = "()";
- l = p.parseParameter(t, List.class);
- assertTrue(l.isEmpty());
-
- // 2nd level in map
- t = "?x=$a()";
- m = p.parseMap(t, HashMap.class, String.class, List.class);
- assertTrue(m.containsKey("x"));
- assertTrue(((List)m.get("x")).isEmpty());
- m = (Map)p.parse(t, Object.class);
- assertTrue(m.containsKey("x"));
- assertTrue(((List)m.get("x")).isEmpty());
- t = "?x=()";
- m = p.parseMap(t, HashMap.class, String.class, List.class);
- assertTrue(m.containsKey("x"));
- assertTrue(((List)m.get("x")).isEmpty());
-
- // Empty 2 dimensional array
- t = "_value=$a($a())";
- l = (List)p.parse(t, Object.class);
- assertTrue(l.size() == 1);
- l = (List)l.get(0);
- assertTrue(l.isEmpty());
- t = "0=()";
- l = p.parseCollection(t, LinkedList.class, List.class);
- assertTrue(l.size() == 1);
- l = (List)l.get(0);
- assertTrue(l.isEmpty());
- t = "$a($a())";
- l = (List)p.parseParameter(t, Object.class);
- assertTrue(l.size() == 1);
- l = (List)l.get(0);
- assertTrue(l.isEmpty());
- t = "(())";
- l = (List)p.parseParameter(t, p.getBeanContext().getCollectionClassMeta(LinkedList.class, List.class));
- assertTrue(l.size() == 1);
- l = (List)l.get(0);
- assertTrue(l.isEmpty());
-
- // Array containing empty string
- // Top level
- t = "_value=$a(())";
- l = (List)p.parse(t, Object.class);
- assertTrue(l.size() == 1);
- assertEquals("", l.get(0));
- t = "0=()";
- l = p.parseCollection(t, List.class, String.class);
- assertTrue(l.size() == 1);
- assertEquals("", l.get(0));
- t = "$a(())";
- l = (List)p.parseParameter(t, Object.class);
- assertTrue(l.size() == 1);
- assertEquals("", l.get(0));
- t = "(())";
- l = (List)p.parseParameter(t, p.getBeanContext().getCollectionClassMeta(List.class, String.class));
- assertTrue(l.size() == 1);
- assertEquals("", l.get(0));
-
- // 2nd level
- t = "?()=$a(())";
- m = (Map)p.parse(t, Object.class);
- assertEquals("", ((List)m.get("")).get(0));
- t = "?()=(())";
- m = p.parseMap(t, HashMap.class, String.class, List.class);
- assertEquals("", ((List)m.get("")).get(0));
-
- // Array containing 3 empty strings
- t = "_value=$a(,,)";
- l = (List)p.parse(t, Object.class);
- assertTrue(l.size() == 3);
- assertEquals("", l.get(0));
- assertEquals("", l.get(1));
- assertEquals("", l.get(2));
- t = "0=&1=&2=";
- l = p.parseCollection(t, List.class, Object.class);
- assertTrue(l.size() == 3);
- assertEquals("", l.get(0));
- assertEquals("", l.get(1));
- assertEquals("", l.get(2));
- t = "$a(,,)";
- l = (List)p.parseParameter(t, Object.class);
- assertTrue(l.size() == 3);
- assertEquals("", l.get(0));
- assertEquals("", l.get(1));
- assertEquals("", l.get(2));
- t = "(,,)";
- l = (List)p.parseParameter(t, p.getBeanContext().getCollectionClassMeta(List.class, Object.class));
- assertTrue(l.size() == 3);
- assertEquals("", l.get(0));
- assertEquals("", l.get(1));
- assertEquals("", l.get(2));
-
- // String containing \u0000
- // Top level
- t = "_value=$s(\u0000)";
- assertEquals("\u0000", p.parse(t, Object.class));
- t = "_value=(\u0000)";
- assertEquals("\u0000", p.parse(t, String.class));
- assertEquals("\u0000", p.parse(t, Object.class));
- t = "$s(\u0000)";
- assertEquals("\u0000", p.parseParameter(t, Object.class));
- t = "(\u0000)";
- assertEquals("\u0000", p.parseParameter(t, String.class));
- assertEquals("\u0000", p.parseParameter(t, Object.class));
-
- // 2nd level
- t = "?(\u0000)=(\u0000)";
- m = (Map)p.parse(t, Object.class);
- assertTrue(m.size() == 1);
- assertEquals("\u0000", m.get("\u0000"));
- m = p.parseMap(t, HashMap.class, String.class, Object.class);
- assertTrue(m.size() == 1);
- assertEquals("\u0000", m.get("\u0000"));
-
- // Boolean
- // Top level
- t = "_value=$b(false)";
- Boolean b = (Boolean)p.parse(t, Object.class);
- assertEquals(Boolean.FALSE, b);
- b = p.parse(t, Boolean.class);
- assertEquals(Boolean.FALSE, b);
- t = "_value=false";
- b = p.parse(t, Boolean.class);
- assertEquals(Boolean.FALSE, b);
- t = "$b(false)";
- b = (Boolean)p.parseParameter(t, Object.class);
- assertEquals(Boolean.FALSE, b);
- b = p.parseParameter(t, Boolean.class);
- assertEquals(Boolean.FALSE, b);
- t = "false";
- b = p.parseParameter(t, Boolean.class);
- assertEquals(Boolean.FALSE, b);
-
- // 2nd level
- t = "?x=$b(false)";
- m = (Map)p.parse(t, Object.class);
- assertEquals(Boolean.FALSE, m.get("x"));
- t = "?x=false";
- m = p.parseMap(t, HashMap.class, String.class, Boolean.class);
- assertEquals(Boolean.FALSE, m.get("x"));
-
- // Number
- // Top level
- t = "_value=$n(123)";
- Integer i = (Integer)p.parse(t, Object.class);
- assertEquals(123, i.intValue());
- i = p.parse(t, Integer.class);
- assertEquals(123, i.intValue());
- Double d = p.parse(t, Double.class);
- assertEquals(123, d.intValue());
- Float f = p.parse(t, Float.class);
- assertEquals(123, f.intValue());
- t = "_value=123";
- i = p.parse(t, Integer.class);
- assertEquals(123, i.intValue());
- t = "$n(123)";
- i = (Integer)p.parseParameter(t, Object.class);
- assertEquals(123, i.intValue());
- i = p.parseParameter(t, Integer.class);
- assertEquals(123, i.intValue());
- d = p.parseParameter(t, Double.class);
- assertEquals(123, d.intValue());
- f = p.parseParameter(t, Float.class);
- assertEquals(123, f.intValue());
- t = "123";
- i = p.parseParameter(t, Integer.class);
- assertEquals(123, i.intValue());
-
- // 2nd level
- t = "?x=$n(123)";
- m = (Map)p.parse(t, Object.class);
- assertEquals(123, ((Integer)m.get("x")).intValue());
- m = p.parseMap(t, HashMap.class, String.class, Double.class);
- assertEquals(123, ((Double)m.get("x")).intValue());
-
- // Unencoded chars
- // Top level
- t = "_value=x;/?:@-_.!*'";
- assertEquals("x;/?:@-_.!*'", p.parse(t, Object.class));
- t = "x;/?:@-_.!*'";
- assertEquals("x;/?:@-_.!*'", p.parseParameter(t, Object.class));
-
- // 2nd level
- t = "?x;/?:@-_.!*'=x;/?:@-_.!*'";
- m = (Map)p.parse(t, Object.class);
- assertEquals("x;/?:@-_.!*'", m.get("x;/?:@-_.!*'"));
- m = p.parseMap(t, HashMap.class, String.class, Object.class);
- assertEquals("x;/?:@-_.!*'", m.get("x;/?:@-_.!*'"));
- m = p.parseMap(t, HashMap.class, String.class, String.class);
- assertEquals("x;/?:@-_.!*'", m.get("x;/?:@-_.!*'"));
-
- // Encoded chars
- // Top level
- t = "_value=x{}|\\^[]`<>#%\"&+";
- try {
- assertEquals("x{}|\\^[]`<>#%\"&+", p.parse(t, Object.class));
- fail("Expected parse exception from invalid hex sequence.");
- } catch (ParseException e) {
- // Good.
- }
- t = "_value=x%7B%7D%7C%5C%5E%5B%5D%60%3C%3E%23%25%22%26%2B";
- assertEquals("x{}|\\^[]`<>#%\"&+", p.parse(t, Object.class));
- assertEquals("x{}|\\^[]`<>#%\"&+", p.parse(t, String.class));
- t = "x{}|\\^[]`<>#%\"&+";
- assertEquals("x{}|\\^[]`<>#%\"&+", p.parseParameter(t, Object.class));
- t = "x%7B%7D%7C%5C%5E%5B%5D%60%3C%3E%23%25%22%26%2B";
- assertEquals("x%7B%7D%7C%5C%5E%5B%5D%60%3C%3E%23%25%22%26%2B", p.parseParameter(t, Object.class));
- assertEquals("x%7B%7D%7C%5C%5E%5B%5D%60%3C%3E%23%25%22%26%2B", p.parseParameter(t, String.class));
-
- // 2nd level
- t = "?x{}|\\^[]`<>#%\"&+=x{}|\\^[]`<>#%\"&+";
- try {
- m = (Map)p.parse(t, Object.class);
- fail("Expected parse exception from invalid hex sequence.");
- } catch (ParseException e) {
- // Good.
- }
- t = "?x%7B%7D%7C%5C%5E%5B%5D%60%3C%3E%23%25%22%26%2B=x%7B%7D%7C%5C%5E%5B%5D%60%3C%3E%23%25%22%26%2B";
- m = (Map)p.parse(t, Object.class);
- assertEquals("x{}|\\^[]`<>#%\"&+", m.get("x{}|\\^[]`<>#%\"&+"));
-
- // Special chars
- // These characters are escaped and not encoded.
- // Top level
- t = "_value=x~$~,~(~)";
- assertEquals("x$,()", p.parse(t, Object.class));
- t = "x~$~,~(~)";
- assertEquals("x$,()", p.parseParameter(t, Object.class));
- t = "_value=x~~$~~,~~(~~)";
- assertEquals("x~$~,~(~)", p.parse(t, Object.class));
- t = "x~~$~~,~~(~~)";
- assertEquals("x~$~,~(~)", p.parseParameter(t, Object.class));
-
- // At secondary levels, these characters are escaped and not encoded.
- // 2nd level
- t = "?x~$~,~(~)=x~$~,~(~)";
- m = (Map)p.parse(t, Object.class);
- assertEquals("x$,()", m.get("x$,()"));
- t = "?x~~$~~,~~(~~)=x~~$~~,~~(~~)";
- m = (Map)p.parse(t, Object.class);
- assertEquals("x~$~,~(~)", m.get("x~$~,~(~)"));
-
- // Equals sign
- // Gets encoded at top level, and encoded+escaped at 2nd level.
- // Top level
- t = "_value=x=";
- assertEquals("x=", p.parse(t, Object.class));
- t = "_value=x%3D";
- assertEquals("x=", p.parse(t, Object.class));
- t = "x=";
- assertEquals("x=", p.parseParameter(t, Object.class));
- t = "x%3D";
- assertEquals("x%3D", p.parseParameter(t, Object.class));
-
- // 2nd level
- t = "?x~%3D=x~%3D";
- m = (Map)p.parse(t, Object.class);
- assertEquals("x=", m.get("x="));
- t = "?x~~%3D=x~~%3D";
- m = (Map)p.parse(t, Object.class);
- assertEquals("x~=", m.get("x~="));
-
- // String starting with parenthesis
- // Top level
- t = "_value=~(~)";
- assertEquals("()", p.parse(t, Object.class));
- assertEquals("()", p.parse(t, String.class));
- t = "_value=(~(~))";
- assertEquals("()", p.parse(t, Object.class));
- assertEquals("()", p.parse(t, String.class));
- t = "_value=(~(~))";
- assertEquals("()", p.parse(t, Object.class));
- assertEquals("()", p.parse(t, String.class));
- t = "~(~)";
- assertEquals("()", p.parseParameter(t, Object.class));
- assertEquals("()", p.parseParameter(t, String.class));
- t = "(~(~))";
- assertEquals("()", p.parseParameter(t, Object.class));
- assertEquals("()", p.parseParameter(t, String.class));
- t = "(~(~))";
- assertEquals("()", p.parseParameter(t, Object.class));
- assertEquals("()", p.parseParameter(t, String.class));
-
- // 2nd level
- t = "?(~(~))=(~(~))";
- m = (Map)p.parse(t, Object.class);
- assertEquals("()", m.get("()"));
- t = "?(~(~))=(~(~))";
- m = p.parseMap(t, HashMap.class, String.class, Object.class);
- assertEquals("()", m.get("()"));
-
- // String starting with $
- // Top level
- t = "_value=(~$a)";
- assertEquals("$a", p.parse(t, Object.class));
- t = "_value=(~$a)";
- assertEquals("$a", p.parse(t, Object.class));
- t = "(~$a)";
- assertEquals("$a", p.parseParameter(t, Object.class));
- t = "(~$a)";
- assertEquals("$a", p.parseParameter(t, Object.class));
-
- // 2nd level
- t = "?(~$a)=(~$a)";
- m = (Map)p.parse(t, Object.class);
- assertEquals("$a", m.get("$a"));
- m = p.parseMap(t, HashMap.class, String.class, Object.class);
- assertEquals("$a", m.get("$a"));
-
- // Blank string
- // Top level
- t = "_value=";
- assertEquals("", p.parse(t, Object.class));
- t = "";
- assertEquals("", p.parseParameter(t, Object.class));
-
- // 2nd level
- t = "?=";
- m = (Map)p.parse(t, Object.class);
- assertEquals("", m.get(""));
- m = p.parseMap(t, HashMap.class, String.class, Object.class);
- assertEquals("", m.get(""));
-
- // 3rd level
- t = "?=$o(=)";
- m = (Map)p.parse(t, Object.class);
- assertEquals("", ((Map)m.get("")).get(""));
- t = "?=(=)";
- m = p.parseMap(t, HashMap.class, String.class, HashMap.class);
- assertEquals("", ((Map)m.get("")).get(""));
-
- // Newline character
- // Top level
- t = "_value=(%0A)";
- assertEquals("\n", p.parse(t, Object.class));
- t = "(%0A)";
- assertEquals("%0A", p.parseParameter(t, Object.class));
- t = "(\n)";
- assertEquals("\n", p.parseParameter(t, Object.class));
-
- // 2nd level
- t = "?%0A=(%0A)";
- m = (Map)p.parse(t, Object.class);
- assertEquals("\n", m.get("\n"));
-
- // 3rd level
- t = "?%0A=$o((%0A)=(%0A))";
- m = (Map)p.parse(t, Object.class);
- assertEquals("\n", ((Map)m.get("\n")).get("\n"));
- }
-
- //====================================================================================================
- // Unicode character test
- //====================================================================================================
- @Test
- public void testUnicodeChars() throws Exception {
- String t;
- Map m;
-
- // 2-byte UTF-8 character
- // Top level
- t = "_value=�";
- assertEquals("�", p.parse(t, Object.class));
- assertEquals("�", p.parse(t, String.class));
- t = "_value=%C2%A2";
- assertEquals("�", p.parse(t, Object.class));
- assertEquals("�", p.parse(t, String.class));
- t = "�";
- assertEquals("�", p.parseParameter(t, Object.class));
- assertEquals("�", p.parseParameter(t, String.class));
- t = "%C2%A2";
- assertEquals("%C2%A2", p.parseParameter(t, Object.class));
- assertEquals("%C2%A2", p.parseParameter(t, String.class));
-
- // 2nd level
- t = "?%C2%A2=%C2%A2";
- m = (Map)p.parse(t, Object.class);
- assertEquals("�", m.get("�"));
-
- // 3rd level
- t = "?%C2%A2=$o(%C2%A2=%C2%A2)";
- m = (Map)p.parse(t, Object.class);
- assertEquals("�", ((Map)m.get("�")).get("�"));
-
- // 3-byte UTF-8 character
- // Top level
- t = "_value=\u20ac";
- assertEquals("\u20ac", p.parse(t, Object.class));
- assertEquals("\u20ac", p.parse(t, String.class));
- t = "_value=%E2%82%AC";
- assertEquals("\u20ac", p.parse(t, Object.class));
- assertEquals("\u20ac", p.parse(t, String.class));
- t = "\u20ac";
- assertEquals("\u20ac", p.parseParameter(t, Object.class));
- assertEquals("\u20ac", p.parseParameter(t, String.class));
- t = "%E2%82%AC";
- assertEquals("%E2%82%AC", p.parseParameter(t, Object.class));
- assertEquals("%E2%82%AC", p.parseParameter(t, String.class));
-
- // 2nd level
- t = "?%E2%82%AC=%E2%82%AC";
- m = (Map)p.parse(t, Object.class);
- assertEquals("\u20ac", m.get("\u20ac"));
-
- // 3rd level
- t = "?%E2%82%AC=$o(%E2%82%AC=%E2%82%AC)";
- m = (Map)p.parse(t, Object.class);
- assertEquals("\u20ac", ((Map)m.get("\u20ac")).get("\u20ac"));
-
- // 4-byte UTF-8 character
- // Top level
- t = "_value=\U00024b62";
- assertEquals("\U00024b62", p.parse(t, Object.class));
- assertEquals("\U00024b62", p.parse(t, String.class));
- t = "_value=%F0%A4%AD%A2";
- assertEquals("\U00024b62", p.parse(t, Object.class));
- assertEquals("\U00024b62", p.parse(t, String.class));
- t = "\U00024b62";
- assertEquals("\U00024b62", p.parseParameter(t, Object.class));
- assertEquals("\U00024b62", p.parseParameter(t, String.class));
- t = "%F0%A4%AD%A2";
- assertEquals("%F0%A4%AD%A2", p.parseParameter(t, Object.class));
- assertEquals("%F0%A4%AD%A2", p.parseParameter(t, String.class));
-
- // 2nd level
- t = "?%F0%A4%AD%A2=%F0%A4%AD%A2";
- m = (Map)p.parse(t, Object.class);
- assertEquals("\U00024b62", m.get("\U00024b62"));
-
- // 3rd level
- t = "?%F0%A4%AD%A2=$o(%F0%A4%AD%A2=%F0%A4%AD%A2)";
- m = (Map)p.parse(t, Object.class);
- assertEquals("\U00024b62", ((Map)m.get("\U00024b62")).get("\U00024b62"));
- }
-
- //====================================================================================================
- // Test simple bean
- //====================================================================================================
- @Test
- public void testSimpleBean() throws Exception {
- UrlEncodingParser p = UrlEncodingParser.DEFAULT;
- A t;
-
- String s = "?f1=foo&f2=123";
- t = p.parse(s, A.class);
- assertEquals("foo", t.f1);
- assertEquals(123, t.f2);
-
- s = "(f1=foo,f2=123)";
- t = p.parseParameter(s, A.class);
- assertEquals("foo", t.f1);
- assertEquals(123, t.f2);
-
- s = "$o(f1=foo,f2=123)";
- t = p.parseParameter(s, A.class);
- assertEquals("foo", t.f1);
- assertEquals(123, t.f2);
- }
-
- public static class A {
- public String f1;
- public int f2;
- }
-
- //====================================================================================================
- // Test URL-encoded strings with no-value parameters.
- //====================================================================================================
- @Test
- public void testNoValues() throws Exception {
- UrlEncodingParser p = UrlEncodingParser.DEFAULT;
- ObjectMap m;
-
- String s = "?f1";
- m = p.parse(s, ObjectMap.class);
- assertTrue(m.containsKey("f1"));
- assertNull(m.get("f1"));
- s = "?f1=f2&f3";
- m = p.parse(s, ObjectMap.class);
- assertEquals("f2", m.get("f1"));
- assertTrue(m.containsKey("f3"));
- assertNull(m.get("f3"));
- }
-
- //====================================================================================================
- // Test URL-encoded strings parsed into plain-text values using UrlEncodingParser.parseIntoSimpleMap().
- //====================================================================================================
- @Test
- public void testParseIntoSimpleMap() throws Exception {
- UrlEncodingParser p = UrlEncodingParser.DEFAULT;
- Map<String,String[]> m;
-
- String s = "?f1=,()=&f2a=$b(true)&f2b=true&f3a=$n(123)&f3b=123&f4=$s(foo)";
- m = p.parseIntoSimpleMap(s);
- assertEquals(",()=", m.get("f1")[0]);
- assertEquals("$b(true)", m.get("f2a")[0]);
- assertEquals("true", m.get("f2b")[0]);
- assertEquals("$n(123)", m.get("f3a")[0]);
- assertEquals("123", m.get("f3b")[0]);
- assertEquals("$s(foo)", m.get("f4")[0]);
-
- s = "f1=v1&=";
- m = p.parseIntoSimpleMap(s);
- assertEquals("v1", m.get("f1")[0]);
- assertEquals("", m.get("")[0]);
-
- s = "f1=v1&f2&f3";
- m = p.parseIntoSimpleMap(s);
- assertEquals("v1", m.get("f1")[0]);
- assertTrue(m.containsKey("f2"));
- assertTrue(m.containsKey("f3"));
- assertNull(m.get("f2"));
- assertNull(m.get("f3"));
- }
-
- //====================================================================================================
- // Test parsing URL-encoded strings with multiple values.
- //====================================================================================================
- @Test
- public void testParseIntoSimpleMapMultiValues() throws Exception {
- UrlEncodingParser p = UrlEncodingParser.DEFAULT;
- Map<String,String[]> m;
-
- String s = "?f1&f1&f2&f2=abc&f2=def&f2";
- m = p.parseIntoSimpleMap(s);
- assertObjectEquals("{f1:null,f2:['abc','def']}", m);
- }
-
- @Test
- public void testEmptyString() throws Exception {
- UrlEncodingParser p = UrlEncodingParser.DEFAULT;
-
- String s = "";
- B b = p.parse(s, B.class);
- assertEquals("f1", b.f1);
- }
-
- public static class B {
- public String f1 = "f1";
- }
-
- //====================================================================================================
- // Test comma-delimited list parameters.
- //====================================================================================================
- @Test
- public void testCommaDelimitedLists() throws Exception {
- UrlEncodingParser p = UrlEncodingParser.DEFAULT;
-
- String s = "?f1=1,2,3&f2=a,b,c&f3=true,false&f4=&f5";
- C c = p.parse(s, C.class);
- assertObjectEquals("{f1:[1,2,3],f2:['a','b','c'],f3:[true,false],f4:[]}", c);
- }
-
- public static class C {
- public int[] f1;
- public String[] f2;
- public boolean[] f3;
- public String[] f4;
- public String[] f5;
- }
-
- //====================================================================================================
- // Test comma-delimited list parameters with special characters.
- //====================================================================================================
- @Test
- public void testCommaDelimitedListsWithSpecialChars() throws Exception {
- UrlEncodingParser p = UrlEncodingParser.DEFAULT;
- String s;
- C1 c;
-
- // In the string below, the ~ character should not be interpreted as an escape.
- s = "?f1=a~b,a~b";
- c = p.parse(s, C1.class);
- assertObjectEquals("{f1:['a~b','a~b']}", c);
-
- s = "?f1=(a~b,a~b)";
- c = p.parse(s, C1.class);
- assertObjectEquals("{f1:['a~b','a~b']}", c);
-
- s = "?f1=((a~b),(a~b))";
- c = p.parse(s, C1.class);
- assertObjectEquals("{f1:['a~b','a~b']}", c);
-
- s = "?f1=($s(a~b),$s(a~b))";
- c = p.parse(s, C1.class);
- assertObjectEquals("{f1:['a~b','a~b']}", c);
-
- s = "?f1=$a($s(a~b),$s(a~b))";
- c = p.parse(s, C1.class);
- assertObjectEquals("{f1:['a~b','a~b']}", c);
-
- s = "?f1=~~,~~";
- c = p.parse(s, C1.class);
- assertObjectEquals("{f1:['~','~']}", c);
-
- s = "?f1=(~~,~~)";
- c = p.parse(s, C1.class);
- assertObjectEquals("{f1:['~','~']}", c);
-
- s = "?f1=(~~~~~~,~~~~~~)";
- c = p.parse(s, C1.class);
- assertObjectEquals("{f1:['~~~','~~~']}", c);
-
- s = "?f1=((~~~~~~),(~~~~~~))";
- c = p.parse(s, C1.class);
- assertObjectEquals("{f1:['~~~','~~~']}", c);
-
- // The ~ should be treated as an escape if followed by any of the following characters: ,()~=
- s = "?f1=~,~(~)~~~=~$,~,~(~)~~~=~$";
- c = p.parse(s, C1.class);
- assertObjectEquals("{f1:[',()~=$',',()~=$']}", c);
-
- s = "?f1=(~,~(~)~~~=~$,~,~(~)~~~=~$)";
- c = p.parse(s, C1.class);
- assertObjectEquals("{f1:[',()~=$',',()~=$']}", c);
-
- s = "?f1=((~,~(~)~~~=~$),(~,~(~)~~~=~$))";
- c = p.parse(s, C1.class);
- assertObjectEquals("{f1:[',()~=$',',()~=$']}", c);
-
- s = "?a~b=a~b";
- ObjectMap m = p.parse(s, ObjectMap.class);
- assertEquals("{'a~b':'a~b'}", m.toString());
-
- s = "?(a~b)=(a~b)";
- m = p.parse(s, ObjectMap.class);
- assertEquals("{'a~b':'a~b'}", m.toString());
-
- s = "?$s(a~b)=$s(a~b)";
- m = p.parse(s, ObjectMap.class);
- assertEquals("{'a~b':'a~b'}", m.toString());
-
- s = "?~~=~~";
- m = p.parse(s, ObjectMap.class);
- assertEquals("{'~':'~'}", m.toString());
-
- s = "?(~~)=(~~)";
- m = p.parse(s, ObjectMap.class);
- assertEquals("{'~':'~'}", m.toString());
-
- s = "?~~~~~~=~~~~~~";
- m = p.parse(s, ObjectMap.class);
- assertEquals("{'~~~':'~~~'}", m.toString());
-
- s = "?(~~~~~~)=(~~~~~~)";
- m = p.parse(s, ObjectMap.class);
- assertEquals("{'~~~':'~~~'}", m.toString());
-
- s = "?$s(~~~~~~)=$s(~~~~~~)";
- m = p.parse(s, ObjectMap.class);
- assertEquals("{'~~~':'~~~'}", m.toString());
-
- s = "?~,~(~)~~~=~$=~,~(~)~~~=~$";
- m = p.parse(s, ObjectMap.class);
- assertEquals("{',()~=$':',()~=$'}", m.toString());
-
- s = "?(~,~(~)~~~=~$)=(~,~(~)~~~=~$)";
- m = p.parse(s, ObjectMap.class);
- assertEquals("{',()~=$':',()~=$'}", m.toString());
-
- s = "?$s(~,~(~)~~~=~$)=$s(~,~(~)~~~=~$)";
- m = p.parse(s, ObjectMap.class);
- assertEquals("{',()~=$':',()~=$'}", m.toString());
-
- s = "?%7E%2C%7E%28%7E%29%7E%7E%7E%3D%7E%24=%7E%2C%7E%28%7E%29%7E%7E%7E%3D%7E%24";
- m = p.parse(s, ObjectMap.class);
- assertEquals("{',()~=$':',()~=$'}", m.toString());
-
- s = "?(%7E%2C%7E%28%7E%29%7E%7E%7E%3D%7E%24)=(%7E%2C%7E%28%7E%29%7E%7E%7E%3D%7E%24)";
- m = p.parse(s, ObjectMap.class);
- assertEquals("{',()~=$':',()~=$'}", m.toString());
-
- s = "?$s(%7E%2C%7E%28%7E%29%7E%7E%7E%3D%7E%24)=$s(%7E%2C%7E%28%7E%29%7E%7E%7E%3D%7E%24)";
- m = p.parse(s, ObjectMap.class);
- assertEquals("{',()~=$':',()~=$'}", m.toString());
- }
-
- public static class C1 {
- public String[] f1;
- }
-
- //====================================================================================================
- // Test comma-delimited list parameters.
- //====================================================================================================
- @Test
- public void testWhitespace() throws Exception {
- UrlEncodingParser p = UrlEncodingParser.DEFAULT_WS_AWARE;
- String s;
- ObjectMap m;
-
- s = "?f1=foo\n\t&f2=bar\n\t";
- m = p.parse(s, ObjectMap.class);
- assertEquals("{f1:'foo',f2:'bar'}", m.toString());
-
- s = "?f1=(\n\t)&f2=(\n\t)";
- m = p.parse(s, ObjectMap.class);
- assertEquals("\n\t", m.getString("f1"));
- assertEquals("\n\t", m.getString("f2"));
-
- s = "?f1=(\n\t)\n\t&f2=(\n\t)\n\t";
- m = p.parse(s, ObjectMap.class);
- assertEquals("\n\t", m.getString("f1"));
- assertEquals("\n\t", m.getString("f2"));
- assertEquals("{f1:'\\n\\t',f2:'\\n\\t'}", m.toString()); // Note that JsonSerializer escapes newlines and tabs.
-
- s = "?f1=$s(\n\t)\n\t&f2=$s(\n\t)\n\t";
- m = p.parse(s, ObjectMap.class);
- assertEquals("\n\t", m.getString("f1"));
- assertEquals("\n\t", m.getString("f2"));
- assertEquals("{f1:'\\n\\t',f2:'\\n\\t'}", m.toString()); // Note that JsonSerializer escapes newlines and tabs.
-
- s = "?f1=$o(\n\tf1a=a,\n\tf1b=b\n\t)\n\t&f2=$o(\n\tf2a=a,\n\tf2b=b\n\t)\n\t";
- m = p.parse(s, ObjectMap.class);
- assertEquals("{f1:{f1a:'a',f1b:'b'},f2:{f2a:'a',f2b:'b'}}", m.toString()); // Note that JsonSerializer escapes newlines and tabs.
- D d = p.parse(s, D.class);
- assertObjectEquals("{f1:{f1a:'a',f1b:'b'},f2:{f2a:'a',f2b:'b'}}", d); // Note that JsonSerializer escapes newlines and tabs.
-
- s = "?f1=$o(\n\tf1a=(\n\t),\n\tf1b=(\n\t)\n\t)\n\t&f2=$o(\n\tf2a=(\n\t),\n\tf2b=(\n\t)\n\t)\n\t";
- m = p.parse(s, ObjectMap.class);
- assertEquals("{f1:{f1a:'\\n\\t',f1b:'\\n\\t'},f2:{f2a:'\\n\\t',f2b:'\\n\\t'}}", m.toString()); // Note that JsonSerializer escapes newlines and tabs.
- d = p.parse(s, D.class);
- assertObjectEquals("{f1:{f1a:'\\n\\t',f1b:'\\n\\t'},f2:{f2a:'\\n\\t',f2b:'\\n\\t'}}", d); // Note that JsonSerializer escapes newlines and tabs.
-
- s = "?f1=$a(\n\tfoo,\n\tbar\n\t)\n\t&f2=$a(\n\tfoo,\n\tbar\n\t)\n\t";
- m = p.parse(s, ObjectMap.class);
- assertEquals("{f1:['foo','bar'],f2:['foo','bar']}", m.toString()); // Note that JsonSerializer escapes newlines and tabs.
-
- s = "f1=a,\n\tb,\n\tc\n\t&f2=1,\n\t2,\n\t3\n\t&f3=true,\n\tfalse\n\t";
- E e = p.parse(s, E.class);
- assertObjectEquals("{f1:['a','b','c'],f2:[1,2,3],f3:[true,false]}", e);
-
- s = "f1=a%2C%0D%0Ab%2C%0D%0Ac%0D%0A&f2=1%2C%0D%0A2%2C%0D%0A3%0D%0A&f3=true%2C%0D%0Afalse%0D%0A";
- e = p.parse(s, E.class);
- assertObjectEquals("{f1:['a','b','c'],f2:[1,2,3],f3:[true,false]}", e);
- }
-
- public static class D {
- public D1 f1;
- public D2 f2;
- }
-
- public static class D1 {
- public String f1a, f1b;
- }
-
- public static class D2 {
- public String f2a, f2b;
- }
-
- public static class E {
- public String[] f1;
- public int[] f2;
- public boolean[] f3;
- }
-
- //====================================================================================================
- // Multi-part parameters on beans via URLENC_expandedParams
- //====================================================================================================
- @Test
- public void testMultiPartParametersOnBeansViaProperty() throws Exception {
- UrlEncodingParser p;
- String in;
-
- p = UrlEncodingParser.DEFAULT.clone().setProperty(UrlEncodingContext.URLENC_expandedParams, true);
- in = ""
- + "f01=a&f01=b"
- + "&f02=c&f02=d"
- + "&f03=1&f03=2"
- + "&f04=3&f04=4"
- + "&f05=(e,f)&f05=(g,h)"
- + "&f06=(i,j)&f06=(k,l)"
- + "&f07=(a=a,b=1,c=true)&f07=(a=b,b=2,c=false)"
- + "&f08=(a=a,b=1,c=true)&f08=(a=b,b=2,c=false)"
- + "&f09=((a=a,b=1,c=true))&f09=((a=b,b=2,c=false))"
- + "&f10=((a=a,b=1,c=true))&f10=((a=b,b=2,c=false))"
- + "&f11=a&f11=b"
- + "&f12=c&f12=d"
- + "&f13=1&f13=2"
- + "&f14=3&f14=4"
- + "&f15=(e,f)&f15=(g,h)"
- + "&f16=(i,j)&f16=(k,l)"
- + "&f17=(a=a,b=1,c=true)&f17=(a=b,b=2,c=false)"
- + "&f18=(a=a,b=1,c=true)&f18=(a=b,b=2,c=false)"
- + "&f19=((a=a,b=1,c=true))&f19=((a=b,b=2,c=false))"
- + "&f20=((a=a,b=1,c=true))&f20=((a=b,b=2,c=false))";
-
- DTOs.B t = p.parse(in, DTOs.B.class);
- String e = "{"
- + "f01:['a','b'],"
- + "f02:['c','d'],"
- + "f03:[1,2],"
- + "f04:[3,4],"
- + "f05:[['e','f'],['g','h']],"
- + "f06:[['i','j'],['k','l']],"
- + "f07:[{a:'a',b:1,c:true},{a:'b',b:2,c:false}],"
- + "f08:[{a:'a',b:1,c:true},{a:'b',b:2,c:false}],"
- + "f09:[[{a:'a',b:1,c:true}],[{a:'b',b:2,c:false}]],"
- + "f10:[[{a:'a',b:1,c:true}],[{a:'b',b:2,c:false}]],"
- + "f11:['a','b'],"
- + "f12:['c','d'],"
- + "f13:[1,2],"
- + "f14:[3,4],"
- + "f15:[['e','f'],['g','h']],"
- + "f16:[['i','j'],['k','l']],"
- + "f17:[{a:'a',b:1,c:true},{a:'b',b:2,c:false}],"
- + "f18:[{a:'a',b:1,c:true},{a:'b',b:2,c:false}],"
- + "f19:[[{a:'a',b:1,c:true}],[{a:'b',b:2,c:false}]],"
- + "f20:[[{a:'a',b:1,c:true}],[{a:'b',b:2,c:false}]]"
- +"}";
- assertSortedObjectEquals(e, t);
- }
-
- //====================================================================================================
- // Multi-part parameters on beans via @UrlEncoding.expandedParams on class
- //====================================================================================================
- @Test
- public void testMultiPartParametersOnBeansViaAnnotationOnClass() throws Exception {
- UrlEncodingParser p;
- String in;
- p = UrlEncodingParser.DEFAULT;
- in = ""
- + "f01=a&f01=b"
- + "&f02=c&f02=d"
- + "&f03=1&f03=2"
- + "&f04=3&f04=4"
- + "&f05=(e,f)&f05=(g,h)"
- + "&f06=(i,j)&f06=(k,l)"
- + "&f07=(a=a,b=1,c=true)&f07=(a=b,b=2,c=false)"
- + "&f08=(a=a,b=1,c=true)&f08=(a=b,b=2,c=false)"
- + "&f09=((a=a,b=1,c=true))&f09=((a=b,b=2,c=false))"
- + "&f10=((a=a,b=1,c=true))&f10=((a=b,b=2,c=false))"
- + "&f11=a&f11=b"
- + "&f12=c&f12=d"
- + "&f13=1&f13=2"
- + "&f14=3&f14=4"
- + "&f15=(e,f)&f15=(g,h)"
- + "&f16=(i,j)&f16=(k,l)"
- + "&f17=(a=a,b=1,c=true)&f17=(a=b,b=2,c=false)"
- + "&f18=(a=a,b=1,c=true)&f18=(a=b,b=2,c=false)"
- + "&f19=((a=a,b=1,c=true))&f19=((a=b,b=2,c=false))"
- + "&f20=((a=a,b=1,c=true))&f20=((a=b,b=2,c=false))";
-
- DTOs.C t = p.parse(in, DTOs.C.class);
- String e = "{"
- + "f01:['a','b'],"
- + "f02:['c','d'],"
- + "f03:[1,2],"
- + "f04:[3,4],"
- + "f05:[['e','f'],['g','h']],"
- + "f06:[['i','j'],['k','l']],"
- + "f07:[{a:'a',b:1,c:true},{a:'b',b:2,c:false}],"
- + "f08:[{a:'a',b:1,c:true},{a:'b',b:2,c:false}],"
- + "f09:[[{a:'a',b:1,c:true}],[{a:'b',b:2,c:false}]],"
- + "f10:[[{a:'a',b:1,c:true}],[{a:'b',b:2,c:false}]],"
- + "f11:['a','b'],"
- + "f12:['c','d'],"
- + "f13:[1,2],"
- + "f14:[3,4],"
- + "f15:[['e','f'],['g','h']],"
- + "f16:[['i','j'],['k','l']],"
- + "f17:[{a:'a',b:1,c:true},{a:'b',b:2,c:false}],"
- + "f18:[{a:'a',b:1,c:true},{a:'b',b:2,c:false}],"
- + "f19:[[{a:'a',b:1,c:true}],[{a:'b',b:2,c:false}]],"
- + "f20:[[{a:'a',b:1,c:true}],[{a:'b',b:2,c:false}]]"
- +"}";
- assertSortedObjectEquals(e, t);
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/urlencoding/CT_UrlEncodingSerializer.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/urlencoding/CT_UrlEncodingSerializer.java b/org.apache.juneau/src/test/java/org/apache/juneau/urlencoding/CT_UrlEncodingSerializer.java
deleted file mode 100755
index 33d6ed1..0000000
--- a/org.apache.juneau/src/test/java/org/apache/juneau/urlencoding/CT_UrlEncodingSerializer.java
+++ /dev/null
@@ -1,497 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.urlencoding;
-
-import static org.junit.Assert.*;
-
-import java.util.*;
-
-import org.apache.juneau.*;
-import org.junit.*;
-
-public class CT_UrlEncodingSerializer {
-
- static UrlEncodingSerializer s = UrlEncodingSerializer.DEFAULT;
- static UrlEncodingSerializer ss = UrlEncodingSerializer.DEFAULT_SIMPLE;
- static UrlEncodingSerializer sr = UrlEncodingSerializer.DEFAULT_READABLE;
-
-
- //====================================================================================================
- // Basic test
- //====================================================================================================
- @Test
- public void testBasic() throws Exception {
-
- Object t;
-
- // Simple string
- // Top level
- t = "a";
- assertEquals("_value=a", s.serialize(t));
-
- // 2nd level
- t = new ObjectMap("{a:'a'}");
- assertEquals("a=a", s.serialize(t));
- assertEquals("a=a", ss.serialize(t));
- assertEquals("a=a", sr.serialize(t));
-
- // Simple map
- // Top level
- t = new ObjectMap("{a:'b',c:123,d:false,e:true,f:null}");
- assertEquals("a=b&c=$n(123)&d=$b(false)&e=$b(true)&f=%00", s.serialize(t));
- assertEquals("a=b&c=123&d=false&e=true&f=%00", ss.serialize(t));
- assertEquals("a=b\n&c=$n(123)\n&d=$b(false)\n&e=$b(true)\n&f=%00", sr.serialize(t));
-
- // 2nd level
- t = new ObjectMap("{a:{a:'b',c:123,d:false,e:true,f:null}}");
- assertEquals("a=$o(a=b,c=$n(123),d=$b(false),e=$b(true),f=%00)", s.serialize(t));
- assertEquals("a=(a=b,c=123,d=false,e=true,f=%00)", ss.serialize(t));
- assertEquals("a=$o(\n\ta=b,\n\tc=$n(123),\n\td=$b(false),\n\te=$b(true),\n\tf=%00\n)", sr.serialize(t));
-
- // Simple map with primitives as literals
- t = new ObjectMap("{a:'b',c:'123',d:'false',e:'true',f:'null'}");
- assertEquals("a=b&c=123&d=false&e=true&f=null", s.serialize(t));
- assertEquals("a=b&c=123&d=false&e=true&f=null", ss.serialize(t));
- assertEquals("a=b\n&c=123\n&d=false\n&e=true\n&f=null", sr.serialize(t));
-
- // null
- // Note that serializeParams is always encoded.
- // Top level
- t = null;
- assertEquals("_value=%00", s.serialize(t));
- assertEquals("_value=%00", ss.serialize(t));
- assertEquals("_value=%00", sr.serialize(t));
-
- // 2nd level
- t = new ObjectMap("{null:null}");
- assertEquals("%00=%00", s.serialize(t));
- assertEquals("%00=%00", ss.serialize(t));
- assertEquals("%00=%00", sr.serialize(t));
-
- // 3rd level
- t = new ObjectMap("{null:{null:null}}");
- assertEquals("%00=$o(%00=%00)", s.serialize(t));
- assertEquals("%00=(%00=%00)", ss.serialize(t));
- assertEquals("%00=$o(\n\t%00=%00\n)", sr.serialize(t));
-
- // Empty array
- // Top level
- t = new String[0];
- assertEquals("_value=$a()", s.serialize(t));
- assertEquals("_value=()", ss.serialize(t));
- assertEquals("_value=$a()", sr.serialize(t));
-
- // 2nd level in map
- t = new ObjectMap("{x:[]}");
- assertEquals("x=$a()", s.serialize(t));
- assertEquals("x=()", ss.serialize(t));
- assertEquals("x=$a()", sr.serialize(t));
-
- // Empty 2 dimensional array
- t = new String[1][0];
- assertEquals("_value=$a($a())", s.serialize(t));
- assertEquals("_value=(())", ss.serialize(t));
- assertEquals("_value=$a(\n\t$a()\n)", sr.serialize(t));
-
- // Array containing empty string
- // Top level
- t = new String[]{""};
- assertEquals("_value=$a(())", s.serialize(t));
- assertEquals("_value=(())", ss.serialize(t));
- assertEquals("_value=$a(\n\t()\n)", sr.serialize(t));
-
- // 2nd level
- t = new ObjectMap("{x:['']}");
- assertEquals("x=$a(())", s.serialize(t));
- assertEquals("x=(())", ss.serialize(t));
- assertEquals("x=$a(\n\t()\n)", sr.serialize(t));
-
- // Array containing 3 empty strings
- t = new String[]{"","",""};
- assertEquals("_value=$a(,,)", s.serialize(t));
- assertEquals("_value=(,,)", ss.serialize(t));
- assertEquals("_value=$a(\n\t(),\n\t(),\n\t()\n)", sr.serialize(t));
-
- // String containing \u0000
- // Top level
- t = "\u0000";
- assertEquals("_value=(%00)", s.serialize(t));
- assertEquals("_value=(%00)", ss.serialize(t));
- assertEquals("_value=(%00)", sr.serialize(t));
-
- // 2nd level
- t = new ObjectMap("{'\u0000':'\u0000'}");
- assertEquals("(%00)=(%00)", s.serialize(t));
- assertEquals("(%00)=(%00)", ss.serialize(t));
- assertEquals("(%00)=(%00)", sr.serialize(t));
-
- // Boolean
- // Top level
- t = false;
- assertEquals("_value=$b(false)", s.serialize(t));
- assertEquals("_value=false", ss.serialize(t));
- assertEquals("_value=$b(false)", sr.serialize(t));
-
- // 2nd level
- t = new ObjectMap("{x:false}");
- assertEquals("x=$b(false)", s.serialize(t));
- assertEquals("x=false", ss.serialize(t));
- assertEquals("x=$b(false)", sr.serialize(t));
-
- // Number
- // Top level
- t = 123;
- assertEquals("_value=$n(123)", s.serialize(t));
- assertEquals("_value=123", ss.serialize(t));
- assertEquals("_value=$n(123)", sr.serialize(t));
-
- // 2nd level
- t = new ObjectMap("{x:123}");
- assertEquals("x=$n(123)", s.serialize(t));
- assertEquals("x=123", ss.serialize(t));
- assertEquals("x=$n(123)", sr.serialize(t));
-
- // Unencoded chars
- // Top level
- t = "x;/?:@-_.!*'";
- assertEquals("_value=x;/?:@-_.!*'", s.serialize(t));
- assertEquals("_value=x;/?:@-_.!*'", ss.serialize(t));
- assertEquals("_value=x;/?:@-_.!*'", sr.serialize(t));
-
- // 2nd level
- t = new ObjectMap("{x:'x;/?:@-_.!*\\''}");
- assertEquals("x=x;/?:@-_.!*'", s.serialize(t));
- assertEquals("x=x;/?:@-_.!*'", ss.serialize(t));
- assertEquals("x=x;/?:@-_.!*'", sr.serialize(t));
-
- // Encoded chars
- // Top level
- t = "x{}|\\^[]`<>#%\"&+";
- assertEquals("_value=x%7B%7D%7C%5C%5E%5B%5D%60%3C%3E%23%25%22%26%2B", s.serialize(t));
- assertEquals("_value=x%7B%7D%7C%5C%5E%5B%5D%60%3C%3E%23%25%22%26%2B", ss.serialize(t));
- assertEquals("_value=x%7B%7D%7C%5C%5E%5B%5D%60%3C%3E%23%25%22%26%2B", sr.serialize(t));
-
- // 2nd level
- t = new ObjectMap("{'x{}|\\\\^[]`<>#%\"&+':'x{}|\\\\^[]`<>#%\"&+'}");
- assertEquals("x%7B%7D%7C%5C%5E%5B%5D%60%3C%3E%23%25%22%26%2B=x%7B%7D%7C%5C%5E%5B%5D%60%3C%3E%23%25%22%26%2B", s.serialize(t));
- assertEquals("x%7B%7D%7C%5C%5E%5B%5D%60%3C%3E%23%25%22%26%2B=x%7B%7D%7C%5C%5E%5B%5D%60%3C%3E%23%25%22%26%2B", ss.serialize(t));
- assertEquals("x%7B%7D%7C%5C%5E%5B%5D%60%3C%3E%23%25%22%26%2B=x%7B%7D%7C%5C%5E%5B%5D%60%3C%3E%23%25%22%26%2B", sr.serialize(t));
-
- // Escaped chars
- // Top level
- t = "x$,()~";
- assertEquals("_value=x$,()~", s.serialize(t));
- assertEquals("_value=x$,()~", ss.serialize(t));
- assertEquals("_value=x$,()~", sr.serialize(t));
-
- // 2nd level
- t = new ObjectMap("{'x$,()~':'x$,()~'}");
- assertEquals("x$,()~=x$,()~", s.serialize(t));
- assertEquals("x$,()~=x$,()~", ss.serialize(t));
- assertEquals("x$,()~=x$,()~", sr.serialize(t));
-
- // 3rd level
- t = new ObjectMap("{'x$,()~':{'x$,()~':'x$,()~'}}");
- assertEquals("x$,()~=$o(x$~,~(~)~~=x$~,~(~)~~)", s.serialize(t));
- assertEquals("x$,()~=(x$~,~(~)~~=x$~,~(~)~~)", ss.serialize(t));
- assertEquals("x$,()~=$o(\n\tx$~,~(~)~~=x$~,~(~)~~\n)", sr.serialize(t));
-
- // Equals sign
- // Gets encoded at top level, and encoded+escaped at 2nd level.
- // Top level
- t = "x=";
- assertEquals("_value=x=", s.serialize(t));
- assertEquals("_value=x=", ss.serialize(t));
- assertEquals("_value=x=", sr.serialize(t));
-
- // 2nd level
- t = new ObjectMap("{'x=':'x='}");
- assertEquals("x%3D=x=", s.serialize(t));
- assertEquals("x%3D=x=", ss.serialize(t));
- assertEquals("x%3D=x=", sr.serialize(t));
-
- // 3rd level
- t = new ObjectMap("{'x=':{'x=':'x='}}");
- assertEquals("x%3D=$o(x~==x~=)", s.serialize(t));
- assertEquals("x%3D=(x~==x~=)", ss.serialize(t));
- assertEquals("x%3D=$o(\n\tx~==x~=\n)", sr.serialize(t));
-
- // String starting with parenthesis
- // Top level
- t = "()";
- assertEquals("_value=(~(~))", s.serialize(t));
- assertEquals("_value=(~(~))", ss.serialize(t));
- assertEquals("_value=(~(~))", sr.serialize(t));
-
- // 2nd level
- t = new ObjectMap("{'()':'()'}");
- assertEquals("(~(~))=(~(~))", s.serialize(t));
- assertEquals("(~(~))=(~(~))", ss.serialize(t));
- assertEquals("(~(~))=(~(~))", sr.serialize(t));
-
- // String starting with $
- // Top level
- t = "$a";
- assertEquals("_value=($a)", s.serialize(t));
- assertEquals("_value=($a)", ss.serialize(t));
- assertEquals("_value=($a)", sr.serialize(t));
-
- // 2nd level
- t = new ObjectMap("{$a:'$a'}");
- assertEquals("($a)=($a)", s.serialize(t));
- assertEquals("($a)=($a)", ss.serialize(t));
- assertEquals("($a)=($a)", sr.serialize(t));
-
- // Blank string
- // Top level
- t = "";
- assertEquals("_value=", s.serialize(t));
- assertEquals("_value=", ss.serialize(t));
- assertEquals("_value=", sr.serialize(t));
-
- // 2nd level
- t = new ObjectMap("{'':''}");
- assertEquals("=", s.serialize(t));
- assertEquals("=", ss.serialize(t));
- assertEquals("=", sr.serialize(t));
-
- // 3rd level
- t = new ObjectMap("{'':{'':''}}");
- assertEquals("=$o(=)", s.serialize(t));
- assertEquals("=(=)", ss.serialize(t));
- assertEquals("=$o(\n\t()=()\n)", sr.serialize(t));
-
- // Newline character
- // Top level
- t = "\n";
- assertEquals("_value=%0A", s.serialize(t));
- assertEquals("_value=%0A", ss.serialize(t));
- assertEquals("_value=(%0A)", sr.serialize(t));
-
- // 2nd level
- t = new ObjectMap("{'\n':'\n'}");
- assertEquals("%0A=%0A", s.serialize(t));
- assertEquals("%0A=%0A", ss.serialize(t));
- assertEquals("(%0A)=(%0A)", sr.serialize(t));
-
- // 3rd level
- t = new ObjectMap("{'\n':{'\n':'\n'}}");
- assertEquals("%0A=$o(%0A=%0A)", s.serialize(t));
- assertEquals("%0A=(%0A=%0A)", ss.serialize(t));
- assertEquals("(%0A)=$o(\n\t(%0A)=(%0A)\n)", sr.serialize(t));
- }
-
- //====================================================================================================
- // Unicode characters test
- //====================================================================================================
- @Test
- public void testUnicodeChars() throws Exception {
- Object t;
-
- // 2-byte UTF-8 character
- // Top level
- t = "�";
- assertEquals("_value=%C2%A2", s.serialize(t));
- assertEquals("_value=%C2%A2", ss.serialize(t));
- assertEquals("_value=%C2%A2", sr.serialize(t));
-
- // 2nd level
- t = new ObjectMap("{'�':'�'}");
- assertEquals("%C2%A2=%C2%A2", s.serialize(t));
- assertEquals("%C2%A2=%C2%A2", ss.serialize(t));
- assertEquals("%C2%A2=%C2%A2", sr.serialize(t));
-
- // 3rd level
- t = new ObjectMap("{'�':{'�':'�'}}");
- assertEquals("%C2%A2=$o(%C2%A2=%C2%A2)", s.serialize(t));
- assertEquals("%C2%A2=(%C2%A2=%C2%A2)", ss.serialize(t));
- assertEquals("%C2%A2=$o(\n\t%C2%A2=%C2%A2\n)", sr.serialize(t));
-
- // 3-byte UTF-8 character
- // Top level
- t = "\u20ac";
- assertEquals("_value=%E2%82%AC", s.serialize(t));
- assertEquals("_value=%E2%82%AC", ss.serialize(t));
- assertEquals("_value=%E2%82%AC", sr.serialize(t));
-
- // 2nd level
- t = new ObjectMap("{'\u20ac':'\u20ac'}");
- assertEquals("%E2%82%AC=%E2%82%AC", s.serialize(t));
- assertEquals("%E2%82%AC=%E2%82%AC", ss.serialize(t));
- assertEquals("%E2%82%AC=%E2%82%AC", sr.serialize(t));
-
- // 3rd level
- t = new ObjectMap("{'\u20ac':{'\u20ac':'\u20ac'}}");
- assertEquals("%E2%82%AC=$o(%E2%82%AC=%E2%82%AC)", s.serialize(t));
- assertEquals("%E2%82%AC=(%E2%82%AC=%E2%82%AC)", ss.serialize(t));
- assertEquals("%E2%82%AC=$o(\n\t%E2%82%AC=%E2%82%AC\n)", sr.serialize(t));
-
- // 4-byte UTF-8 character
- // Top level
- t = "\U00024b62";
- assertEquals("_value=%F0%A4%AD%A2", s.serialize(t));
- assertEquals("_value=%F0%A4%AD%A2", ss.serialize(t));
- assertEquals("_value=%F0%A4%AD%A2", sr.serialize(t));
-
- // 2nd level
- t = new ObjectMap("{'\U00024b62':'\U00024b62'}");
- assertEquals("%F0%A4%AD%A2=%F0%A4%AD%A2", s.serialize(t));
- assertEquals("%F0%A4%AD%A2=%F0%A4%AD%A2", ss.serialize(t));
- assertEquals("%F0%A4%AD%A2=%F0%A4%AD%A2", sr.serialize(t));
-
- // 3rd level
- t = new ObjectMap("{'\U00024b62':{'\U00024b62':'\U00024b62'}}");
- assertEquals("%F0%A4%AD%A2=$o(%F0%A4%AD%A2=%F0%A4%AD%A2)", s.serialize(t));
- assertEquals("%F0%A4%AD%A2=(%F0%A4%AD%A2=%F0%A4%AD%A2)", ss.serialize(t));
- assertEquals("%F0%A4%AD%A2=$o(\n\t%F0%A4%AD%A2=%F0%A4%AD%A2\n)", sr.serialize(t));
- }
-
- //====================================================================================================
- // Multi-part parameters on beans via URLENC_expandedParams
- //====================================================================================================
- @Test
- @SuppressWarnings("hiding")
- public void testMultiPartParametersOnBeansViaProperty() throws Exception {
- UrlEncodingSerializer s;
- DTOs.B t = DTOs.B.create();
- String r;
-
- s = UrlEncodingSerializer.DEFAULT_SIMPLE;
- r = s.serialize(t);
- String e = ""
- + "f01=(a,b)"
- + "&f02=(c,d)"
- + "&f03=(1,2)"
- + "&f04=(3,4)"
- + "&f05=((e,f),(g,h))"
- + "&f06=((i,j),(k,l))"
- + "&f07=((a=a,b=1,c=true),(a=a,b=1,c=true))"
- + "&f08=((a=a,b=1,c=true),(a=a,b=1,c=true))"
- + "&f09=(((a=a,b=1,c=true)),((a=a,b=1,c=true)))"
- + "&f10=(((a=a,b=1,c=true)),((a=a,b=1,c=true)))"
- + "&f11=(a,b)"
- + "&f12=(c,d)"
- + "&f13=(1,2)"
- + "&f14=(3,4)"
- + "&f15=((e,f),(g,h))"
- + "&f16=((i,j),(k,l))"
- + "&f17=((a=a,b=1,c=true),(a=a,b=1,c=true))"
- + "&f18=((a=a,b=1,c=true),(a=a,b=1,c=true))"
- + "&f19=(((a=a,b=1,c=true)),((a=a,b=1,c=true)))"
- + "&f20=(((a=a,b=1,c=true)),((a=a,b=1,c=true)))";
- assertEquals(e, r);
-
- s = UrlEncodingSerializer.DEFAULT_SIMPLE.clone().setProperty(UrlEncodingContext.URLENC_expandedParams, true);
- r = s.serialize(t);
- e = ""
- + "f01=a&f01=b"
- + "&f02=c&f02=d"
- + "&f03=1&f03=2"
- + "&f04=3&f04=4"
- + "&f05=(e,f)&f05=(g,h)"
- + "&f06=(i,j)&f06=(k,l)"
- + "&f07=(a=a,b=1,c=true)&f07=(a=a,b=1,c=true)"
- + "&f08=(a=a,b=1,c=true)&f08=(a=a,b=1,c=true)"
- + "&f09=((a=a,b=1,c=true))&f09=((a=a,b=1,c=true))"
- + "&f10=((a=a,b=1,c=true))&f10=((a=a,b=1,c=true))"
- + "&f11=a&f11=b"
- + "&f12=c&f12=d"
- + "&f13=1&f13=2"
- + "&f14=3&f14=4"
- + "&f15=(e,f)&f15=(g,h)"
- + "&f16=(i,j)&f16=(k,l)"
- + "&f17=(a=a,b=1,c=true)&f17=(a=a,b=1,c=true)"
- + "&f18=(a=a,b=1,c=true)&f18=(a=a,b=1,c=true)"
- + "&f19=((a=a,b=1,c=true))&f19=((a=a,b=1,c=true))"
- + "&f20=((a=a,b=1,c=true))&f20=((a=a,b=1,c=true))";
- assertEquals(e, r);
- }
-
-
- //====================================================================================================
- // Multi-part parameters on beans via @UrlEncoding.expandedParams on class
- //====================================================================================================
- @Test
- @SuppressWarnings("hiding")
- public void testMultiPartParametersOnBeansViaAnnotationOnClass() throws Exception {
- UrlEncodingSerializer s;
- DTOs.C t = DTOs.C.create();
- String r;
-
- s = UrlEncodingSerializer.DEFAULT_SIMPLE;
- r = s.serialize(t);
- String e = ""
- + "f01=a&f01=b"
- + "&f02=c&f02=d"
- + "&f03=1&f03=2"
- + "&f04=3&f04=4"
- + "&f05=(e,f)&f05=(g,h)"
- + "&f06=(i,j)&f06=(k,l)"
- + "&f07=(a=a,b=1,c=true)&f07=(a=a,b=1,c=true)"
- + "&f08=(a=a,b=1,c=true)&f08=(a=a,b=1,c=true)"
- + "&f09=((a=a,b=1,c=true))&f09=((a=a,b=1,c=true))"
- + "&f10=((a=a,b=1,c=true))&f10=((a=a,b=1,c=true))"
- + "&f11=a&f11=b"
- + "&f12=c&f12=d"
- + "&f13=1&f13=2"
- + "&f14=3&f14=4"
- + "&f15=(e,f)&f15=(g,h)"
- + "&f16=(i,j)&f16=(k,l)"
- + "&f17=(a=a,b=1,c=true)&f17=(a=a,b=1,c=true)"
- + "&f18=(a=a,b=1,c=true)&f18=(a=a,b=1,c=true)"
- + "&f19=((a=a,b=1,c=true))&f19=((a=a,b=1,c=true))"
- + "&f20=((a=a,b=1,c=true))&f20=((a=a,b=1,c=true))";
- assertEquals(e, r);
-
- s = UrlEncodingSerializer.DEFAULT_SIMPLE.clone().setProperty(UrlEncodingContext.URLENC_expandedParams, true);
- r = s.serialize(t);
- e = ""
- + "f01=a&f01=b"
- + "&f02=c&f02=d"
- + "&f03=1&f03=2"
- + "&f04=3&f04=4"
- + "&f05=(e,f)&f05=(g,h)"
- + "&f06=(i,j)&f06=(k,l)"
- + "&f07=(a=a,b=1,c=true)&f07=(a=a,b=1,c=true)"
- + "&f08=(a=a,b=1,c=true)&f08=(a=a,b=1,c=true)"
- + "&f09=((a=a,b=1,c=true))&f09=((a=a,b=1,c=true))"
- + "&f10=((a=a,b=1,c=true))&f10=((a=a,b=1,c=true))"
- + "&f11=a&f11=b"
- + "&f12=c&f12=d"
- + "&f13=1&f13=2"
- + "&f14=3&f14=4"
- + "&f15=(e,f)&f15=(g,h)"
- + "&f16=(i,j)&f16=(k,l)"
- + "&f17=(a=a,b=1,c=true)&f17=(a=a,b=1,c=true)"
- + "&f18=(a=a,b=1,c=true)&f18=(a=a,b=1,c=true)"
- + "&f19=((a=a,b=1,c=true))&f19=((a=a,b=1,c=true))"
- + "&f20=((a=a,b=1,c=true))&f20=((a=a,b=1,c=true))";
- assertEquals(e, r);
- }
-
- @Test
- @SuppressWarnings("hiding")
- public void testMultiPartParametersOnMapOfStringArrays() throws Exception {
- UrlEncodingSerializer s;
- String r;
-
- Map<String,String[]> t = new LinkedHashMap<String,String[]>();
- t.put("f1", new String[]{"bar"});
- t.put("f2", new String[]{"bar","baz"});
- t.put("f3", new String[]{});
- s = UrlEncodingSerializer.DEFAULT_SIMPLE_EXPANDED;
- r = s.serialize(t);
- String e = "f1=bar&f2=bar&f2=baz";
- assertEquals(e, r);
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/urlencoding/CommonParser_UonTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/urlencoding/CommonParser_UonTest.java b/org.apache.juneau/src/test/java/org/apache/juneau/urlencoding/CommonParser_UonTest.java
new file mode 100755
index 0000000..b84aca9
--- /dev/null
+++ b/org.apache.juneau/src/test/java/org/apache/juneau/urlencoding/CommonParser_UonTest.java
@@ -0,0 +1,168 @@
+/***************************************************************************************************************************
+ * 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.juneau.urlencoding;
+
+import static org.apache.juneau.BeanContext.*;
+import static org.apache.juneau.serializer.SerializerContext.*;
+import static org.junit.Assert.*;
+
+import java.util.*;
+
+import org.apache.juneau.*;
+import org.apache.juneau.parser.*;
+import org.junit.*;
+
+@SuppressWarnings({"rawtypes","hiding","serial"})
+public class CommonParser_UonTest {
+
+ ReaderParser p = UonParser.DEFAULT.clone().setClassLoader(getClass().getClassLoader());
+ ReaderParser pe = UonParser.DEFAULT_DECODING.clone().setClassLoader(getClass().getClassLoader());
+
+ //====================================================================================================
+ // testFromSerializer
+ //====================================================================================================
+ @Test
+ public void testFromSerializer() throws Exception {
+ Map m = null;
+ String in;
+
+ in = "$o(a=$n(1))";
+ m = (Map)p.parse(in, Object.class);
+ assertEquals(1, m.get("a"));
+
+ in = "$o(a=$n(1),b=foo+bar)";
+ m = (Map)p.parse(in, Object.class);
+ assertEquals(1, m.get("a"));
+ assertEquals("foo+bar", m.get("b"));
+ m = (Map)pe.parse(in, Object.class);
+ assertEquals(1, m.get("a"));
+ assertEquals("foo bar", m.get("b"));
+
+ in = "$o(a=$n(1),b=foo+bar,c=$b(false))";
+ m = (Map)pe.parse(in, Object.class);
+ assertEquals(1, m.get("a"));
+ assertEquals("foo bar", m.get("b"));
+ assertEquals(false, m.get("c"));
+
+ in = "$o(a=$n(1),b=foo%20bar,c=$b(false))";
+ m = (Map)pe.parse(in, Object.class);
+ assertEquals(1, m.get("a"));
+ assertEquals("foo bar", m.get("b"));
+ assertEquals(false, m.get("c"));
+
+ ObjectList jl = (ObjectList)p.parse("$a($o(attribute=value),$o(attribute='value'))", Object.class);
+ assertEquals("value", jl.getObjectMap(0).getString("attribute"));
+ assertEquals("'value'", jl.getObjectMap(1).getString("attribute"));
+
+ A1 b = new A1();
+ A2 tl = new A2();
+ tl.add(new A3("name0","value0"));
+ tl.add(new A3("name1","value1"));
+ b.list = tl;
+
+ in = new UonSerializer().setProperty(SERIALIZER_addClassAttrs, true).serialize(b);
+ b = (A1)p.parse(in, Object.class);
+ assertEquals("value1", b.list.get(1).value);
+
+ in = UonSerializer.DEFAULT.serialize(b);
+ b = p.parse(in, A1.class);
+ assertEquals("value1", b.list.get(1).value);
+ }
+
+ public static class A1 {
+ public A2 list;
+ }
+
+ public static class A2 extends LinkedList<A3> {
+ }
+
+ public static class A3 {
+ public String name, value;
+ public A3(){}
+ public A3(String name, String value) {
+ this.name = name;
+ this.value = value;
+ }
+ }
+
+ //====================================================================================================
+ // Correct handling of unknown properties.
+ //====================================================================================================
+ @Test
+ public void testCorrectHandlingOfUnknownProperties() throws Exception {
+ ReaderParser p = new UonParser().setProperty(BEAN_ignoreUnknownBeanProperties, true);
+ B t;
+
+ String in = "(a=1,unknown=3,b=2)";
+ t = p.parse(in, B.class);
+ assertEquals(t.a, 1);
+ assertEquals(t.b, 2);
+
+ try {
+ p = new UonParser();
+ p.parse(in, B.class);
+ fail("Exception expected");
+ } catch (ParseException e) {}
+ }
+
+ public static class B {
+ public int a, b;
+ }
+
+ //====================================================================================================
+ // Writing to Collection properties with no setters.
+ //====================================================================================================
+ @Test
+ public void testCollectionPropertiesWithNoSetters() throws Exception {
+
+ ReaderParser p = UonParser.DEFAULT;
+
+ String json = "(ints=(1,2,3),beans=((a=1,b=2)))";
+ C t = p.parse(json, C.class);
+ assertEquals(t.getInts().size(), 3);
+ assertEquals(t.getBeans().get(0).b, 2);
+ }
+
+ public static class C {
+ private Collection<Integer> ints = new LinkedList<Integer>();
+ private List<B> beans = new LinkedList<B>();
+ public Collection<Integer> getInts() {
+ return ints;
+ }
+ public List<B> getBeans() {
+ return beans;
+ }
+ }
+
+ //====================================================================================================
+ // Parser listeners.
+ //====================================================================================================
+ @Test
+ public void testParserListeners() throws Exception {
+ final List<String> events = new LinkedList<String>();
+ UonParser p = new UonParser().setProperty(BEAN_ignoreUnknownBeanProperties, true);
+ p.addListener(
+ new ParserListener() {
+ @Override /* ParserListener */
+ public <T> void onUnknownProperty(String propertyName, Class<T> beanClass, T bean, int line, int col) {
+ events.add(propertyName + "," + line + "," + col);
+ }
+ }
+ );
+
+ String in = "(a=1,unknownProperty=foo,b=2)";
+ p.parse(in, B.class);
+ assertEquals(1, events.size());
+ assertEquals("unknownProperty,1,5", events.get(0));
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/urlencoding/CommonParser_UrlEncodingTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/urlencoding/CommonParser_UrlEncodingTest.java b/org.apache.juneau/src/test/java/org/apache/juneau/urlencoding/CommonParser_UrlEncodingTest.java
new file mode 100755
index 0000000..0efafa5
--- /dev/null
+++ b/org.apache.juneau/src/test/java/org/apache/juneau/urlencoding/CommonParser_UrlEncodingTest.java
@@ -0,0 +1,185 @@
+/***************************************************************************************************************************
+ * 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.juneau.urlencoding;
+
+import static org.apache.juneau.BeanContext.*;
+import static org.apache.juneau.TestUtils.*;
+import static org.apache.juneau.serializer.SerializerContext.*;
+import static org.junit.Assert.*;
+
+import java.util.*;
+
+import org.apache.juneau.*;
+import org.apache.juneau.parser.*;
+import org.apache.juneau.serializer.*;
+import org.junit.*;
+
+@SuppressWarnings({"rawtypes","hiding","serial"})
+public class CommonParser_UrlEncodingTest {
+
+ ReaderParser p = UrlEncodingParser.DEFAULT.clone().setClassLoader(getClass().getClassLoader());
+
+ //====================================================================================================
+ // testFromSerializer
+ //====================================================================================================
+ @Test
+ public void testFromSerializer() throws Exception {
+ Map m = null;
+ String in;
+
+ in = "a=$n(1)";
+ m = (Map)p.parse(in, Object.class);
+ assertEquals(1, m.get("a"));
+
+ in = "a=$n(1)&b=foo+bar";
+ m = (Map)p.parse(in, Object.class);
+ assertEquals(1, m.get("a"));
+ assertEquals("foo bar", m.get("b"));
+
+ in = "a=$n(1)&b=foo+bar&c=$b(false)";
+ m = (Map)p.parse(in, Object.class);
+ assertEquals(1, m.get("a"));
+ assertEquals("foo bar", m.get("b"));
+ assertEquals(false, m.get("c"));
+
+ in = "a=$n(1)&b=foo%20bar&c=$b(false)";
+ m = (Map)p.parse(in, Object.class);
+ assertEquals(1, m.get("a"));
+ assertEquals("foo bar", m.get("b"));
+ assertEquals(false, m.get("c"));
+
+ ObjectMap jm = (ObjectMap)p.parse("x=$a($o(attribute=value),$o(attribute='value'))", Object.class);
+ assertEquals("value", jm.getObjectList("x").getObjectMap(0).getString("attribute"));
+ assertEquals("'value'", jm.getObjectList("x").getObjectMap(1).getString("attribute"));
+
+ ObjectList jl = (ObjectList)p.parse("_value=$a($o(attribute=value),$o(attribute='value'))", Object.class);
+ assertEquals("value", jl.getObjectMap(0).getString("attribute"));
+ assertEquals("'value'", jl.getObjectMap(1).getString("attribute"));
+
+ A1 b = new A1();
+ A2 tl = new A2();
+ tl.add(new A3("name0","value0"));
+ tl.add(new A3("name1","value1"));
+ b.list = tl;
+
+ in = new UrlEncodingSerializer().setProperty(SERIALIZER_addClassAttrs, true).serialize(b);
+ b = (A1)p.parse(in, Object.class);
+ assertEquals("value1", b.list.get(1).value);
+
+ in = UrlEncodingSerializer.DEFAULT.serialize(b);
+ b = p.parse(in, A1.class);
+ assertEquals("value1", b.list.get(1).value);
+ }
+
+ public static class A1 {
+ public A2 list;
+ }
+
+ public static class A2 extends LinkedList<A3> {
+ }
+
+ public static class A3 {
+ public String name, value;
+ public A3(){}
+ public A3(String name, String value) {
+ this.name = name;
+ this.value = value;
+ }
+ }
+
+ //====================================================================================================
+ // Correct handling of unknown properties.
+ //====================================================================================================
+ @Test
+ public void testCorrectHandlingOfUnknownProperties() throws Exception {
+ ReaderParser p = new UrlEncodingParser().setProperty(BEAN_ignoreUnknownBeanProperties, true);
+ B t;
+
+ String in = "a=1&unknown=3&b=2";
+ t = p.parse(in, B.class);
+ assertEquals(t.a, 1);
+ assertEquals(t.b, 2);
+
+ try {
+ p = new UrlEncodingParser();
+ p.parse(in, B.class);
+ fail("Exception expected");
+ } catch (ParseException e) {}
+ }
+
+ public static class B {
+ public int a, b;
+ }
+
+ //====================================================================================================
+ // Writing to Collection properties with no setters.
+ //====================================================================================================
+ @Test
+ public void testCollectionPropertiesWithNoSetters() throws Exception {
+
+ ReaderParser p = UrlEncodingParser.DEFAULT;
+
+ String json = "ints=(1,2,3)&beans=((a=1,b=2))";
+ C t = p.parse(json, C.class);
+ assertEquals(t.getInts().size(), 3);
+ assertEquals(t.getBeans().get(0).b, 2);
+ }
+
+ public static class C {
+ private Collection<Integer> ints = new LinkedList<Integer>();
+ private List<B> beans = new LinkedList<B>();
+ public Collection<Integer> getInts() {
+ return ints;
+ }
+ public List<B> getBeans() {
+ return beans;
+ }
+ }
+
+ //====================================================================================================
+ // Parser listeners.
+ //====================================================================================================
+ @Test
+ public void testParserListeners() throws Exception {
+ final List<String> events = new LinkedList<String>();
+ UonParser p = new UrlEncodingParser().setProperty(BEAN_ignoreUnknownBeanProperties, true);
+ p.addListener(
+ new ParserListener() {
+ @Override /* ParserListener */
+ public <T> void onUnknownProperty(String propertyName, Class<T> beanClass, T bean, int line, int col) {
+ events.add(propertyName + "," + line + "," + col);
+ }
+ }
+ );
+
+ String in = "a=1&unknownProperty=foo&b=2";
+ p.parse(in, B.class);
+ assertEquals(1, events.size());
+ assertEquals("unknownProperty,1,4", events.get(0));
+ }
+
+ @SuppressWarnings("unchecked")
+ @Test
+ public void testCollections() throws Exception {
+ WriterSerializer s = new UrlEncodingSerializer().setProperty(UonSerializerContext.UON_simpleMode, true);
+ ReaderParser p = new UrlEncodingParser();
+
+ List l = new ObjectList("foo","bar");
+ assertEquals("0=foo&1=bar", s.serialize(l));
+
+ String in = "0=foo&1=bar";
+ ClassMeta<LinkedList<String>> cm = p.getBeanContext().getCollectionClassMeta(LinkedList.class, String.class);
+ l = p.parse(in, cm);
+ assertObjectEquals("['foo','bar']",l);
+ }
+}
[11/44] incubator-juneau git commit: Rename CT_* testcases.
Posted by ja...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/transforms/DateFilterTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/transforms/DateFilterTest.java b/org.apache.juneau/src/test/java/org/apache/juneau/transforms/DateFilterTest.java
new file mode 100755
index 0000000..41d4329
--- /dev/null
+++ b/org.apache.juneau/src/test/java/org/apache/juneau/transforms/DateFilterTest.java
@@ -0,0 +1,170 @@
+/***************************************************************************************************************************
+ * 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.juneau.transforms;
+
+import static org.junit.Assert.*;
+
+import java.text.*;
+import java.util.*;
+
+import org.apache.juneau.*;
+import org.apache.juneau.json.*;
+import org.apache.juneau.parser.*;
+import org.apache.juneau.serializer.*;
+import org.junit.*;
+
+@SuppressWarnings("deprecation")
+public class DateFilterTest {
+
+ private static TimeZone tz;
+
+ @BeforeClass
+ public static void beforeClass() {
+ tz = TimeZone.getDefault();
+ TimeZone.setDefault(TimeZone.getTimeZone("GMT-5"));
+ }
+
+ @AfterClass
+ public static void afterClass() {
+ TimeZone.setDefault(tz);
+ }
+
+ private Date testDate = new Date(1, 2, 3, 4, 5, 6);
+ private String tz1 = new SimpleDateFormat("zzz").format(testDate);
+
+ //====================================================================================================
+ // testString - DEFAULT_STRING
+ //====================================================================================================
+ @Test
+ public void testString() throws Exception {
+ Class<?> f = DateTransform.ToString.class;
+ WriterSerializer s = new JsonSerializer.Simple().addTransforms(f);
+ ReaderParser p = new JsonParser().addTransforms(f);
+ doTest(s, p, "'Sun Mar 03 04:05:06 "+tz1+" 1901'");
+ }
+
+ //====================================================================================================
+ // testISO8601DTZ - DEFAULT_ISO8601DTZ
+ //====================================================================================================
+ @Test
+ public void testISO8601DTZ() throws Exception {
+ Class<?> f = DateTransform.ISO8601DTZ.class;
+ WriterSerializer s = new JsonSerializer.Simple().addTransforms(f);
+ ReaderParser p = new JsonParser().addTransforms(f);
+ doTest(s, p, "'1901-03-03T09:05:06Z'");
+ }
+
+ //====================================================================================================
+ // testRFC2822DT - DEFAULT_RFC2822DT
+ //====================================================================================================
+ @Test
+ public void testRFC2822DT() throws Exception {
+ Class<?> f = DateTransform.RFC2822DT.class;
+ WriterSerializer s = new JsonSerializer.Simple().addTransforms(f);
+ ReaderParser p = new JsonParser().addTransforms(f);
+ doTest(s, p, "'Sun, 03 Mar 1901 04:05:06 "+tz1+"'");
+ }
+
+ //====================================================================================================
+ // testLong - DEFAULT_LONG
+ //====================================================================================================
+ @Test
+ public void testLong() throws Exception {
+ Class<?> f = DateLongTransform.class;
+ WriterSerializer s = new JsonSerializer.Simple().addTransforms(f);
+ ReaderParser p = new JsonParser().addTransforms(f);
+ doTest(s, p, "-2172149694000");
+ }
+
+ //====================================================================================================
+ // testMap - DEFAULT_MAP
+ //====================================================================================================
+ @Test
+ public void testMap() throws Exception {
+ Class<?> f = DateMapTransform.class;
+ WriterSerializer s = new JsonSerializer.Simple().addTransforms(f);
+ ReaderParser p = new JsonParser().addTransforms(f);
+ doTest(s, p, "{time:-2172149694000}");
+ }
+
+ public void doTest(WriterSerializer s, ReaderParser p, String expected) throws Exception {
+ Date d;
+ String actual;
+
+ d = testDate;
+ actual = s.serialize(d);
+ assertEquals(expected, actual);
+ d = p.parse(actual, Date.class);
+ assertEquals(1, d.getYear());
+ assertEquals(2, d.getMonth());
+ assertEquals(3, d.getDate());
+ assertEquals(4, d.getHours());
+ assertEquals(5, d.getMinutes());
+ assertEquals(6, d.getSeconds());
+
+ d = new java.sql.Date(testDate.getTime());
+ actual = s.serialize(d);
+ assertEquals(expected, actual);
+ d = p.parse(actual, java.sql.Date.class);
+ assertEquals(1, d.getYear());
+ assertEquals(2, d.getMonth());
+ assertEquals(3, d.getDate());
+
+ d = new java.sql.Time(testDate.getTime());
+ actual = s.serialize(d);
+ assertEquals(expected, actual);
+ d = p.parse(actual, java.sql.Time.class);
+ assertEquals(4, d.getHours());
+ assertEquals(5, d.getMinutes());
+ assertEquals(6, d.getSeconds());
+
+ d = new java.sql.Timestamp(testDate.getTime());
+ actual = s.serialize(d);
+ assertEquals(expected, actual);
+ d = p.parse(actual, java.sql.Timestamp.class);
+ assertEquals(1, d.getYear());
+ assertEquals(2, d.getMonth());
+ assertEquals(3, d.getDate());
+ assertEquals(4, d.getHours());
+ assertEquals(5, d.getMinutes());
+ assertEquals(6, d.getSeconds());
+ }
+
+ //====================================================================================================
+ //====================================================================================================
+ @Test
+ public void testBeanWithDate() throws Exception {
+ A testBeanA = new A().init();
+
+ final String jsonData = new JsonSerializer().addTransforms(
+ DateTransform.ISO8601DT.class).serialize(testBeanA);
+ final ObjectMap data = new JsonParser().addTransforms(
+ DateTransform.ISO8601DT.class).parse(jsonData, ObjectMap.class);
+
+ final DateTransform.ISO8601DT dateTransform = new DateTransform.ISO8601DT();
+ // this works
+ final String sValue = data.getString("birthday"); //$NON-NLS-1$
+ dateTransform.normalize(sValue, data.getBeanContext().getClassMeta(Date.class));
+ // this does not work
+ data.get(dateTransform, "birthday"); //$NON-NLS-1$
+ }
+
+ public static class A {
+ public Date birthday;
+
+ public A init() {
+ birthday = new Date();
+ return this;
+ }
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/transforms/EnumerationTransformTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/transforms/EnumerationTransformTest.java b/org.apache.juneau/src/test/java/org/apache/juneau/transforms/EnumerationTransformTest.java
new file mode 100755
index 0000000..064249a
--- /dev/null
+++ b/org.apache.juneau/src/test/java/org/apache/juneau/transforms/EnumerationTransformTest.java
@@ -0,0 +1,35 @@
+/***************************************************************************************************************************
+ * 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.juneau.transforms;
+
+import static org.junit.Assert.*;
+
+import java.util.*;
+
+import org.apache.juneau.json.*;
+import org.apache.juneau.serializer.*;
+import org.junit.*;
+
+public class EnumerationTransformTest {
+
+ //====================================================================================================
+ // test
+ //====================================================================================================
+ @Test
+ public void test() throws Exception {
+ WriterSerializer s = new JsonSerializer.Simple().addTransforms(EnumerationTransform.class);
+ Vector<String> v = new Vector<String>(Arrays.asList(new String[]{"foo","bar","baz"}));
+ Enumeration<String> e = v.elements();
+ assertEquals("['foo','bar','baz']", s.serialize(e));
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/transforms/IteratorTransformTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/transforms/IteratorTransformTest.java b/org.apache.juneau/src/test/java/org/apache/juneau/transforms/IteratorTransformTest.java
new file mode 100755
index 0000000..be1b76a
--- /dev/null
+++ b/org.apache.juneau/src/test/java/org/apache/juneau/transforms/IteratorTransformTest.java
@@ -0,0 +1,37 @@
+/***************************************************************************************************************************
+ * 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.juneau.transforms;
+
+import static org.junit.Assert.*;
+
+import java.util.*;
+
+import org.apache.juneau.json.*;
+import org.apache.juneau.serializer.*;
+import org.junit.*;
+
+public class IteratorTransformTest {
+
+ //====================================================================================================
+ // test
+ //====================================================================================================
+ @Test
+ public void test() throws Exception {
+ WriterSerializer s = new JsonSerializer.Simple().addTransforms(IteratorTransform.class);
+
+ // Iterators
+ List<String> l = new ArrayList<String>(Arrays.asList(new String[]{"foo","bar","baz"}));
+ Iterator<String> i = l.iterator();
+ assertEquals("['foo','bar','baz']", s.serialize(i));
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/transforms/ReaderFilterTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/transforms/ReaderFilterTest.java b/org.apache.juneau/src/test/java/org/apache/juneau/transforms/ReaderFilterTest.java
new file mode 100755
index 0000000..6157895
--- /dev/null
+++ b/org.apache.juneau/src/test/java/org/apache/juneau/transforms/ReaderFilterTest.java
@@ -0,0 +1,47 @@
+/***************************************************************************************************************************
+ * 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.juneau.transforms;
+
+import static org.junit.Assert.*;
+
+import java.io.*;
+import java.util.*;
+
+import org.apache.juneau.json.*;
+import org.apache.juneau.serializer.*;
+import org.junit.*;
+
+public class ReaderFilterTest {
+
+ //====================================================================================================
+ // test
+ //====================================================================================================
+ @Test
+ public void test() throws Exception {
+ WriterSerializer s = new JsonSerializer.Simple().addTransforms(ReaderTransform.Json.class);
+
+ Reader r;
+ Map<String,Object> m;
+
+ r = new StringReader("{foo:'bar',baz:'quz'}");
+ m = new HashMap<String,Object>();
+ m.put("X", r);
+ assertEquals("{X:{foo:'bar',baz:'quz'}}", s.serialize(m));
+
+ s.addTransforms(ReaderTransform.Xml.class);
+ r = new StringReader("<object><foo type='string'>bar</foo><baz type='string'>quz</baz></object>");
+ m = new HashMap<String,Object>();
+ m.put("X", r);
+ assertEquals("{X:{foo:'bar',baz:'quz'}}", s.serialize(m));
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/urlencoding/CT_CommonParser_Uon.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/urlencoding/CT_CommonParser_Uon.java b/org.apache.juneau/src/test/java/org/apache/juneau/urlencoding/CT_CommonParser_Uon.java
deleted file mode 100755
index 6ef0429..0000000
--- a/org.apache.juneau/src/test/java/org/apache/juneau/urlencoding/CT_CommonParser_Uon.java
+++ /dev/null
@@ -1,168 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.urlencoding;
-
-import static org.apache.juneau.BeanContext.*;
-import static org.apache.juneau.serializer.SerializerContext.*;
-import static org.junit.Assert.*;
-
-import java.util.*;
-
-import org.apache.juneau.*;
-import org.apache.juneau.parser.*;
-import org.junit.*;
-
-@SuppressWarnings({"rawtypes","hiding","serial"})
-public class CT_CommonParser_Uon {
-
- ReaderParser p = UonParser.DEFAULT.clone().setClassLoader(getClass().getClassLoader());
- ReaderParser pe = UonParser.DEFAULT_DECODING.clone().setClassLoader(getClass().getClassLoader());
-
- //====================================================================================================
- // testFromSerializer
- //====================================================================================================
- @Test
- public void testFromSerializer() throws Exception {
- Map m = null;
- String in;
-
- in = "$o(a=$n(1))";
- m = (Map)p.parse(in, Object.class);
- assertEquals(1, m.get("a"));
-
- in = "$o(a=$n(1),b=foo+bar)";
- m = (Map)p.parse(in, Object.class);
- assertEquals(1, m.get("a"));
- assertEquals("foo+bar", m.get("b"));
- m = (Map)pe.parse(in, Object.class);
- assertEquals(1, m.get("a"));
- assertEquals("foo bar", m.get("b"));
-
- in = "$o(a=$n(1),b=foo+bar,c=$b(false))";
- m = (Map)pe.parse(in, Object.class);
- assertEquals(1, m.get("a"));
- assertEquals("foo bar", m.get("b"));
- assertEquals(false, m.get("c"));
-
- in = "$o(a=$n(1),b=foo%20bar,c=$b(false))";
- m = (Map)pe.parse(in, Object.class);
- assertEquals(1, m.get("a"));
- assertEquals("foo bar", m.get("b"));
- assertEquals(false, m.get("c"));
-
- ObjectList jl = (ObjectList)p.parse("$a($o(attribute=value),$o(attribute='value'))", Object.class);
- assertEquals("value", jl.getObjectMap(0).getString("attribute"));
- assertEquals("'value'", jl.getObjectMap(1).getString("attribute"));
-
- A1 b = new A1();
- A2 tl = new A2();
- tl.add(new A3("name0","value0"));
- tl.add(new A3("name1","value1"));
- b.list = tl;
-
- in = new UonSerializer().setProperty(SERIALIZER_addClassAttrs, true).serialize(b);
- b = (A1)p.parse(in, Object.class);
- assertEquals("value1", b.list.get(1).value);
-
- in = UonSerializer.DEFAULT.serialize(b);
- b = p.parse(in, A1.class);
- assertEquals("value1", b.list.get(1).value);
- }
-
- public static class A1 {
- public A2 list;
- }
-
- public static class A2 extends LinkedList<A3> {
- }
-
- public static class A3 {
- public String name, value;
- public A3(){}
- public A3(String name, String value) {
- this.name = name;
- this.value = value;
- }
- }
-
- //====================================================================================================
- // Correct handling of unknown properties.
- //====================================================================================================
- @Test
- public void testCorrectHandlingOfUnknownProperties() throws Exception {
- ReaderParser p = new UonParser().setProperty(BEAN_ignoreUnknownBeanProperties, true);
- B t;
-
- String in = "(a=1,unknown=3,b=2)";
- t = p.parse(in, B.class);
- assertEquals(t.a, 1);
- assertEquals(t.b, 2);
-
- try {
- p = new UonParser();
- p.parse(in, B.class);
- fail("Exception expected");
- } catch (ParseException e) {}
- }
-
- public static class B {
- public int a, b;
- }
-
- //====================================================================================================
- // Writing to Collection properties with no setters.
- //====================================================================================================
- @Test
- public void testCollectionPropertiesWithNoSetters() throws Exception {
-
- ReaderParser p = UonParser.DEFAULT;
-
- String json = "(ints=(1,2,3),beans=((a=1,b=2)))";
- C t = p.parse(json, C.class);
- assertEquals(t.getInts().size(), 3);
- assertEquals(t.getBeans().get(0).b, 2);
- }
-
- public static class C {
- private Collection<Integer> ints = new LinkedList<Integer>();
- private List<B> beans = new LinkedList<B>();
- public Collection<Integer> getInts() {
- return ints;
- }
- public List<B> getBeans() {
- return beans;
- }
- }
-
- //====================================================================================================
- // Parser listeners.
- //====================================================================================================
- @Test
- public void testParserListeners() throws Exception {
- final List<String> events = new LinkedList<String>();
- UonParser p = new UonParser().setProperty(BEAN_ignoreUnknownBeanProperties, true);
- p.addListener(
- new ParserListener() {
- @Override /* ParserListener */
- public <T> void onUnknownProperty(String propertyName, Class<T> beanClass, T bean, int line, int col) {
- events.add(propertyName + "," + line + "," + col);
- }
- }
- );
-
- String in = "(a=1,unknownProperty=foo,b=2)";
- p.parse(in, B.class);
- assertEquals(1, events.size());
- assertEquals("unknownProperty,1,5", events.get(0));
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/urlencoding/CT_CommonParser_UrlEncoding.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/urlencoding/CT_CommonParser_UrlEncoding.java b/org.apache.juneau/src/test/java/org/apache/juneau/urlencoding/CT_CommonParser_UrlEncoding.java
deleted file mode 100755
index 4256402..0000000
--- a/org.apache.juneau/src/test/java/org/apache/juneau/urlencoding/CT_CommonParser_UrlEncoding.java
+++ /dev/null
@@ -1,185 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.urlencoding;
-
-import static org.apache.juneau.BeanContext.*;
-import static org.apache.juneau.TestUtils.*;
-import static org.apache.juneau.serializer.SerializerContext.*;
-import static org.junit.Assert.*;
-
-import java.util.*;
-
-import org.apache.juneau.*;
-import org.apache.juneau.parser.*;
-import org.apache.juneau.serializer.*;
-import org.junit.*;
-
-@SuppressWarnings({"rawtypes","hiding","serial"})
-public class CT_CommonParser_UrlEncoding {
-
- ReaderParser p = UrlEncodingParser.DEFAULT.clone().setClassLoader(getClass().getClassLoader());
-
- //====================================================================================================
- // testFromSerializer
- //====================================================================================================
- @Test
- public void testFromSerializer() throws Exception {
- Map m = null;
- String in;
-
- in = "a=$n(1)";
- m = (Map)p.parse(in, Object.class);
- assertEquals(1, m.get("a"));
-
- in = "a=$n(1)&b=foo+bar";
- m = (Map)p.parse(in, Object.class);
- assertEquals(1, m.get("a"));
- assertEquals("foo bar", m.get("b"));
-
- in = "a=$n(1)&b=foo+bar&c=$b(false)";
- m = (Map)p.parse(in, Object.class);
- assertEquals(1, m.get("a"));
- assertEquals("foo bar", m.get("b"));
- assertEquals(false, m.get("c"));
-
- in = "a=$n(1)&b=foo%20bar&c=$b(false)";
- m = (Map)p.parse(in, Object.class);
- assertEquals(1, m.get("a"));
- assertEquals("foo bar", m.get("b"));
- assertEquals(false, m.get("c"));
-
- ObjectMap jm = (ObjectMap)p.parse("x=$a($o(attribute=value),$o(attribute='value'))", Object.class);
- assertEquals("value", jm.getObjectList("x").getObjectMap(0).getString("attribute"));
- assertEquals("'value'", jm.getObjectList("x").getObjectMap(1).getString("attribute"));
-
- ObjectList jl = (ObjectList)p.parse("_value=$a($o(attribute=value),$o(attribute='value'))", Object.class);
- assertEquals("value", jl.getObjectMap(0).getString("attribute"));
- assertEquals("'value'", jl.getObjectMap(1).getString("attribute"));
-
- A1 b = new A1();
- A2 tl = new A2();
- tl.add(new A3("name0","value0"));
- tl.add(new A3("name1","value1"));
- b.list = tl;
-
- in = new UrlEncodingSerializer().setProperty(SERIALIZER_addClassAttrs, true).serialize(b);
- b = (A1)p.parse(in, Object.class);
- assertEquals("value1", b.list.get(1).value);
-
- in = UrlEncodingSerializer.DEFAULT.serialize(b);
- b = p.parse(in, A1.class);
- assertEquals("value1", b.list.get(1).value);
- }
-
- public static class A1 {
- public A2 list;
- }
-
- public static class A2 extends LinkedList<A3> {
- }
-
- public static class A3 {
- public String name, value;
- public A3(){}
- public A3(String name, String value) {
- this.name = name;
- this.value = value;
- }
- }
-
- //====================================================================================================
- // Correct handling of unknown properties.
- //====================================================================================================
- @Test
- public void testCorrectHandlingOfUnknownProperties() throws Exception {
- ReaderParser p = new UrlEncodingParser().setProperty(BEAN_ignoreUnknownBeanProperties, true);
- B t;
-
- String in = "a=1&unknown=3&b=2";
- t = p.parse(in, B.class);
- assertEquals(t.a, 1);
- assertEquals(t.b, 2);
-
- try {
- p = new UrlEncodingParser();
- p.parse(in, B.class);
- fail("Exception expected");
- } catch (ParseException e) {}
- }
-
- public static class B {
- public int a, b;
- }
-
- //====================================================================================================
- // Writing to Collection properties with no setters.
- //====================================================================================================
- @Test
- public void testCollectionPropertiesWithNoSetters() throws Exception {
-
- ReaderParser p = UrlEncodingParser.DEFAULT;
-
- String json = "ints=(1,2,3)&beans=((a=1,b=2))";
- C t = p.parse(json, C.class);
- assertEquals(t.getInts().size(), 3);
- assertEquals(t.getBeans().get(0).b, 2);
- }
-
- public static class C {
- private Collection<Integer> ints = new LinkedList<Integer>();
- private List<B> beans = new LinkedList<B>();
- public Collection<Integer> getInts() {
- return ints;
- }
- public List<B> getBeans() {
- return beans;
- }
- }
-
- //====================================================================================================
- // Parser listeners.
- //====================================================================================================
- @Test
- public void testParserListeners() throws Exception {
- final List<String> events = new LinkedList<String>();
- UonParser p = new UrlEncodingParser().setProperty(BEAN_ignoreUnknownBeanProperties, true);
- p.addListener(
- new ParserListener() {
- @Override /* ParserListener */
- public <T> void onUnknownProperty(String propertyName, Class<T> beanClass, T bean, int line, int col) {
- events.add(propertyName + "," + line + "," + col);
- }
- }
- );
-
- String in = "a=1&unknownProperty=foo&b=2";
- p.parse(in, B.class);
- assertEquals(1, events.size());
- assertEquals("unknownProperty,1,4", events.get(0));
- }
-
- @SuppressWarnings("unchecked")
- @Test
- public void testCollections() throws Exception {
- WriterSerializer s = new UrlEncodingSerializer().setProperty(UonSerializerContext.UON_simpleMode, true);
- ReaderParser p = new UrlEncodingParser();
-
- List l = new ObjectList("foo","bar");
- assertEquals("0=foo&1=bar", s.serialize(l));
-
- String in = "0=foo&1=bar";
- ClassMeta<LinkedList<String>> cm = p.getBeanContext().getCollectionClassMeta(LinkedList.class, String.class);
- l = p.parse(in, cm);
- assertObjectEquals("['foo','bar']",l);
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/urlencoding/CT_Common_Uon.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/urlencoding/CT_Common_Uon.java b/org.apache.juneau/src/test/java/org/apache/juneau/urlencoding/CT_Common_Uon.java
deleted file mode 100755
index a1c0c0d..0000000
--- a/org.apache.juneau/src/test/java/org/apache/juneau/urlencoding/CT_Common_Uon.java
+++ /dev/null
@@ -1,450 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.urlencoding;
-
-import static org.apache.juneau.TestUtils.*;
-import static org.apache.juneau.serializer.SerializerContext.*;
-import static org.junit.Assert.*;
-
-import java.net.*;
-import java.net.URI;
-import java.util.*;
-
-import org.apache.juneau.*;
-import org.apache.juneau.annotation.*;
-import org.apache.juneau.json.*;
-import org.apache.juneau.serializer.*;
-import org.apache.juneau.testbeans.*;
-import org.junit.*;
-
-@SuppressWarnings({"hiding","serial"})
-public class CT_Common_Uon {
- UonParser p = UonParser.DEFAULT;
- UonParser pe = UonParser.DEFAULT_DECODING;
-
- //====================================================================================================
- // Trim nulls from beans
- //====================================================================================================
- @Test
- public void testTrimNullsFromBeans() throws Exception {
- UonSerializer s = new UonSerializer.Encoding();
- A t1 = A.create(), t2;
-
- s.setProperty(SERIALIZER_trimNullProperties, false);
- String r = s.serialize(t1);
- assertEquals("$o(s1=%00,s2=s2)", r);
- t2 = pe.parse(r, A.class);
- assertEqualObjects(t1, t2);
-
- s.setProperty(SERIALIZER_trimNullProperties, true);
- r = s.serialize(t1);
- assertEquals("$o(s2=s2)", r);
- t2 = p.parse(r, A.class);
- assertEqualObjects(t1, t2);
- }
-
- public static class A {
- public String s1, s2;
-
- public static A create() {
- A t = new A();
- t.s2 = "s2";
- return t;
- }
- }
-
- //====================================================================================================
- // Trim empty maps
- //====================================================================================================
- @Test
- public void testTrimEmptyMaps() throws Exception {
- UonSerializer s = UonSerializer.DEFAULT_SIMPLE_ENCODING.clone();
- B t1 = B.create(), t2;
- String r;
-
- s.setProperty(SERIALIZER_trimEmptyMaps, false);
- r = s.serialize(t1);
- assertEquals("(f1=(),f2=(f2a=%00,f2b=(s2=s2)))", r);
- t2 = pe.parse(r, B.class);
- assertEqualObjects(t1, t2);
-
- s.setProperty(SERIALIZER_trimEmptyMaps, true);
- r = s.serialize(t1);
- assertEquals("(f2=(f2a=%00,f2b=(s2=s2)))", r);
- t2 = pe.parse(r, B.class);
- assertNull(t2.f1);
- }
-
- public static class B {
- public TreeMap<String,A> f1, f2;
-
- public static B create() {
- B t = new B();
- t.f1 = new TreeMap<String,A>();
- t.f2 = new TreeMap<String,A>(){{put("f2a",null);put("f2b",A.create());}};
- return t;
- }
- }
-
- //====================================================================================================
- // Trim empty lists
- //====================================================================================================
- @Test
- public void testTrimEmptyLists() throws Exception {
- UonSerializer s = new UonSerializer.Encoding();
- C t1 = C.create(), t2;
- String r;
-
- s.setProperty(SERIALIZER_trimEmptyLists, false);
- r = s.serialize(t1);
- assertEquals("$o(f1=$a(),f2=$a(%00,$o(s2=s2)))", r);
- t2 = pe.parse(r, C.class);
- assertEqualObjects(t1, t2);
-
- s.setProperty(SERIALIZER_trimEmptyLists, true);
- r = s.serialize(t1);
- assertEquals("$o(f2=$a(%00,$o(s2=s2)))", r);
- t2 = pe.parse(r, C.class);
- assertNull(t2.f1);
- }
-
- public static class C {
- public List<A> f1, f2;
-
- public static C create() {
- C t = new C();
- t.f1 = new LinkedList<A>();
- t.f2 = new LinkedList<A>(){{add(null);add(A.create());}};
- return t;
- }
- }
-
- //====================================================================================================
- // Trim empty arrays
- //====================================================================================================
- @Test
- public void testTrimEmptyArrays() throws Exception {
- UonSerializer s = new UonSerializer.Encoding();
- D t1 = D.create(), t2;
- String r;
-
- s.setProperty(SERIALIZER_trimEmptyLists, false);
- r = s.serialize(t1);
- assertEquals("$o(f1=$a(),f2=$a(%00,$o(s2=s2)))", r);
- t2 = pe.parse(r, D.class);
- assertEqualObjects(t1, t2);
-
- s.setProperty(SERIALIZER_trimEmptyLists, true);
- r = s.serialize(t1);
- assertEquals("$o(f2=$a(%00,$o(s2=s2)))", r);
- t2 = pe.parse(r, D.class);
- assertNull(t2.f1);
- }
-
- public static class D {
- public A[] f1, f2;
-
- public static D create() {
- D t = new D();
- t.f1 = new A[]{};
- t.f2 = new A[]{null, A.create()};
- return t;
- }
- }
-
- //====================================================================================================
- // @BeanProperty.properties annotation.
- //====================================================================================================
- @Test
- public void testBeanPropertyProperies() throws Exception {
- UonSerializer s = UonSerializer.DEFAULT;
- UonSerializer ss = UonSerializer.DEFAULT_SIMPLE;
- String ue = ss.serialize(new E1());
- assertEquals("(x1=(f1=1),x2=(f1=1),x3=((f1=1)),x4=((f1=1)),x5=((f1=1)),x6=((f1=1)))", ue);
- ue = s.serialize(new E1());
- assertEquals("$o(x1=$o(f1=$n(1)),x2=$o(f1=$n(1)),x3=$a($o(f1=$n(1))),x4=$a($o(f1=$n(1))),x5=$a($o(f1=$n(1))),x6=$a($o(f1=$n(1))))", ue);
- }
-
- public static class E1 {
- @BeanProperty(properties={"f1"}) public E2 x1 = new E2();
- @BeanProperty(properties={"f1"}) public Map<String,Integer> x2 = new LinkedHashMap<String,Integer>() {{
- put("f1",1); put("f2",2);
- }};
- @BeanProperty(properties={"f1"}) public E2[] x3 = {new E2()};
- @BeanProperty(properties={"f1"}) public List<E2> x4 = new LinkedList<E2>() {{
- add(new E2());
- }};
- @BeanProperty(properties={"f1"}) public ObjectMap[] x5 = {new ObjectMap().append("f1",1).append("f2",2)};
- @BeanProperty(properties={"f1"}) public List<ObjectMap> x6 = new LinkedList<ObjectMap>() {{
- add(new ObjectMap().append("f1",1).append("f2",2));
- }};
- }
-
- public static class E2 {
- public int f1 = 1;
- public int f2 = 2;
- }
-
- //====================================================================================================
- // @BeanProperty.properties annotation on list of beans.
- //====================================================================================================
- @Test
- public void testBeanPropertyPropertiesOnListOfBeans() throws Exception {
- UonSerializer s = UonSerializer.DEFAULT;
- List<F> l = new LinkedList<F>();
- F t = new F();
- t.x1.add(new F());
- l.add(t);
- String xml = s.serialize(l);
- assertEquals("$a($o(x1=$a($o(x2=$n(2))),x2=$n(2)))", xml);
- }
-
- public static class F {
- @BeanProperty(properties={"x2"}) public List<F> x1 = new LinkedList<F>();
- public int x2 = 2;
- }
-
- //====================================================================================================
- // Test URIAttr - Test that URLs and URIs are serialized and parsed correctly.
- //====================================================================================================
- @Test
- public void testURIAttr() throws Exception {
- UonSerializer s = UonSerializer.DEFAULT;
- UonParser p = UonParser.DEFAULT;
-
- G t = new G();
- t.uri = new URI("http://uri");
- t.f1 = new URI("http://f1");
- t.f2 = new URL("http://f2");
-
- String r = s.serialize(t);
- t = p.parse(r, G.class);
- assertEquals("http://uri", t.uri.toString());
- assertEquals("http://f1", t.f1.toString());
- assertEquals("http://f2", t.f2.toString());
- }
-
- public static class G {
- @BeanProperty(beanUri=true) public URI uri;
- public URI f1;
- public URL f2;
- }
-
- //====================================================================================================
- // Test URIs with URI_CONTEXT and URI_AUTHORITY
- //====================================================================================================
- @Test
- public void testUris() throws Exception {
- WriterSerializer s = new UonSerializer();
- TestURI t = new TestURI();
- String r;
- String expected;
-
- s.setProperty(SERIALIZER_relativeUriBase, null);
- r = s.serialize(t);
- expected = ""
- +"$o("
- +"f0=f0/x0,"
- +"f1=f1/x1,"
- +"f2=/f2/x2,"
- +"f3=http://www.ibm.com/f3/x3,"
- +"f4=f4/x4,"
- +"f5=/f5/x5,"
- +"f6=http://www.ibm.com/f6/x6,"
- +"f7=http://www.ibm.com/f7/x7,"
- +"f8=f8/x8,"
- +"f9=f9/x9,"
- +"fa=http://www.ibm.com/fa/xa#MY_LABEL,"
- +"fb=http://www.ibm.com/fb/xb?label~=MY_LABEL&foo~=bar,"
- +"fc=http://www.ibm.com/fc/xc?foo~=bar&label~=MY_LABEL,"
- +"fd=http://www.ibm.com/fd/xd?label2~=MY_LABEL&foo~=bar,"
- +"fe=http://www.ibm.com/fe/xe?foo~=bar&label2~=MY_LABEL"
- +")";
- assertEquals(expected, r);
-
- s.setProperty(SERIALIZER_relativeUriBase, ""); // Same as null.
- r = s.serialize(t);
- assertEquals(expected, r);
-
- s.setProperty(SERIALIZER_relativeUriBase, "/cr");
- r = s.serialize(t);
- expected = ""
- +"$o("
- +"f0=/cr/f0/x0,"
- +"f1=/cr/f1/x1,"
- +"f2=/f2/x2,"
- +"f3=http://www.ibm.com/f3/x3,"
- +"f4=/cr/f4/x4,"
- +"f5=/f5/x5,"
- +"f6=http://www.ibm.com/f6/x6,"
- +"f7=http://www.ibm.com/f7/x7,"
- +"f8=/cr/f8/x8,"
- +"f9=/cr/f9/x9,"
- +"fa=http://www.ibm.com/fa/xa#MY_LABEL,"
- +"fb=http://www.ibm.com/fb/xb?label~=MY_LABEL&foo~=bar,"
- +"fc=http://www.ibm.com/fc/xc?foo~=bar&label~=MY_LABEL,"
- +"fd=http://www.ibm.com/fd/xd?label2~=MY_LABEL&foo~=bar,"
- +"fe=http://www.ibm.com/fe/xe?foo~=bar&label2~=MY_LABEL"
- +")";
- assertEquals(expected, r);
-
- s.setProperty(SERIALIZER_relativeUriBase, "/cr/"); // Same as above
- r = s.serialize(t);
- assertEquals(expected, r);
-
- s.setProperty(SERIALIZER_relativeUriBase, "/");
- r = s.serialize(t);
- expected = ""
- +"$o("
- +"f0=/f0/x0,"
- +"f1=/f1/x1,"
- +"f2=/f2/x2,"
- +"f3=http://www.ibm.com/f3/x3,"
- +"f4=/f4/x4,"
- +"f5=/f5/x5,"
- +"f6=http://www.ibm.com/f6/x6,"
- +"f7=http://www.ibm.com/f7/x7,"
- +"f8=/f8/x8,"
- +"f9=/f9/x9,"
- +"fa=http://www.ibm.com/fa/xa#MY_LABEL,"
- +"fb=http://www.ibm.com/fb/xb?label~=MY_LABEL&foo~=bar,"
- +"fc=http://www.ibm.com/fc/xc?foo~=bar&label~=MY_LABEL,"
- +"fd=http://www.ibm.com/fd/xd?label2~=MY_LABEL&foo~=bar,"
- +"fe=http://www.ibm.com/fe/xe?foo~=bar&label2~=MY_LABEL"
- +")";
- assertEquals(expected, r);
-
- s.setProperty(SERIALIZER_relativeUriBase, null);
-
- s.setProperty(SERIALIZER_absolutePathUriBase, "http://foo");
- r = s.serialize(t);
- expected = ""
- +"$o("
- +"f0=f0/x0,"
- +"f1=f1/x1,"
- +"f2=http://foo/f2/x2,"
- +"f3=http://www.ibm.com/f3/x3,"
- +"f4=f4/x4,"
- +"f5=http://foo/f5/x5,"
- +"f6=http://www.ibm.com/f6/x6,"
- +"f7=http://www.ibm.com/f7/x7,"
- +"f8=f8/x8,"
- +"f9=f9/x9,"
- +"fa=http://www.ibm.com/fa/xa#MY_LABEL,"
- +"fb=http://www.ibm.com/fb/xb?label~=MY_LABEL&foo~=bar,"
- +"fc=http://www.ibm.com/fc/xc?foo~=bar&label~=MY_LABEL,"
- +"fd=http://www.ibm.com/fd/xd?label2~=MY_LABEL&foo~=bar,"
- +"fe=http://www.ibm.com/fe/xe?foo~=bar&label2~=MY_LABEL"
- +")";
- assertEquals(expected, r);
-
- s.setProperty(SERIALIZER_absolutePathUriBase, "http://foo/");
- r = s.serialize(t);
- assertEquals(expected, r);
-
- s.setProperty(SERIALIZER_absolutePathUriBase, ""); // Same as null.
- r = s.serialize(t);
- expected = ""
- +"$o("
- +"f0=f0/x0,"
- +"f1=f1/x1,"
- +"f2=/f2/x2,"
- +"f3=http://www.ibm.com/f3/x3,"
- +"f4=f4/x4,"
- +"f5=/f5/x5,"
- +"f6=http://www.ibm.com/f6/x6,"
- +"f7=http://www.ibm.com/f7/x7,"
- +"f8=f8/x8,"
- +"f9=f9/x9,"
- +"fa=http://www.ibm.com/fa/xa#MY_LABEL,"
- +"fb=http://www.ibm.com/fb/xb?label~=MY_LABEL&foo~=bar,"
- +"fc=http://www.ibm.com/fc/xc?foo~=bar&label~=MY_LABEL,"
- +"fd=http://www.ibm.com/fd/xd?label2~=MY_LABEL&foo~=bar,"
- +"fe=http://www.ibm.com/fe/xe?foo~=bar&label2~=MY_LABEL"
- +")";
- assertEquals(expected, r);
- }
-
- //====================================================================================================
- // Validate that you cannot update properties on locked serializer.
- //====================================================================================================
- @Test
- public void testLockedSerializer() throws Exception {
- UonSerializer s = new UonSerializer().lock();
- try {
- s.setProperty(JsonSerializerContext.JSON_simpleMode, true);
- fail("Locked exception not thrown");
- } catch (LockedException e) {}
- try {
- s.setProperty(SerializerContext.SERIALIZER_addClassAttrs, true);
- fail("Locked exception not thrown");
- } catch (LockedException e) {}
- try {
- s.setProperty(BeanContext.BEAN_beanMapPutReturnsOldValue, true);
- fail("Locked exception not thrown");
- } catch (LockedException e) {}
- }
-
- //====================================================================================================
- // Recursion
- //====================================================================================================
- @Test
- public void testRecursion() throws Exception {
- WriterSerializer s = new UonSerializer();
-
- R1 r1 = new R1();
- R2 r2 = new R2();
- R3 r3 = new R3();
- r1.r2 = r2;
- r2.r3 = r3;
- r3.r1 = r1;
-
- // No recursion detection
- try {
- s.serialize(r1);
- fail("Exception expected!");
- } catch (Exception e) {
- String msg = e.getLocalizedMessage();
- assertTrue(msg.contains("It's recommended you use the SerializerContext.SERIALIZER_detectRecursions setting to help locate the loop."));
- }
-
- // Recursion detection, no ignore
- s.setProperty(SERIALIZER_detectRecursions, true);
- try {
- s.serialize(r1);
- fail("Exception expected!");
- } catch (Exception e) {
- String msg = e.getLocalizedMessage();
- assertTrue(msg.contains("[0]root:org.apache.juneau.urlencoding.CT_Common_Uon$R1"));
- assertTrue(msg.contains("->[1]r2:org.apache.juneau.urlencoding.CT_Common_Uon$R2"));
- assertTrue(msg.contains("->[2]r3:org.apache.juneau.urlencoding.CT_Common_Uon$R3"));
- assertTrue(msg.contains("->[3]r1:org.apache.juneau.urlencoding.CT_Common_Uon$R1"));
- }
-
- s.setProperty(SERIALIZER_ignoreRecursions, true);
- assertEquals("$o(name=foo,r2=$o(name=bar,r3=$o(name=baz)))", s.serialize(r1));
- }
-
- public static class R1 {
- public String name = "foo";
- public R2 r2;
- }
- public static class R2 {
- public String name = "bar";
- public R3 r3;
- }
- public static class R3 {
- public String name = "baz";
- public R1 r1;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/urlencoding/CT_Common_UrlEncoding.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/urlencoding/CT_Common_UrlEncoding.java b/org.apache.juneau/src/test/java/org/apache/juneau/urlencoding/CT_Common_UrlEncoding.java
deleted file mode 100755
index fe499fc..0000000
--- a/org.apache.juneau/src/test/java/org/apache/juneau/urlencoding/CT_Common_UrlEncoding.java
+++ /dev/null
@@ -1,442 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.urlencoding;
-
-import static org.apache.juneau.TestUtils.*;
-import static org.apache.juneau.serializer.SerializerContext.*;
-import static org.junit.Assert.*;
-
-import java.net.*;
-import java.net.URI;
-import java.util.*;
-
-import org.apache.juneau.*;
-import org.apache.juneau.annotation.*;
-import org.apache.juneau.json.*;
-import org.apache.juneau.serializer.*;
-import org.apache.juneau.testbeans.*;
-import org.junit.*;
-
-@SuppressWarnings({"hiding","serial"})
-public class CT_Common_UrlEncoding {
- UrlEncodingParser p = UrlEncodingParser.DEFAULT;
-
- //====================================================================================================
- // Trim nulls from beans
- //====================================================================================================
- @Test
- public void testTrimNullsFromBeans() throws Exception {
- UrlEncodingSerializer s = new UrlEncodingSerializer();
- A t1 = A.create(), t2;
-
- s.setProperty(SERIALIZER_trimNullProperties, false);
- String r = s.serialize(t1);
- assertEquals("s1=%00&s2=s2", r);
- t2 = p.parse(r, A.class);
- assertEqualObjects(t1, t2);
-
- s.setProperty(SERIALIZER_trimNullProperties, true);
- r = s.serialize(t1);
- assertEquals("s2=s2", r);
- t2 = p.parse(r, A.class);
- assertEqualObjects(t1, t2);
- }
-
- public static class A {
- public String s1, s2;
-
- public static A create() {
- A t = new A();
- t.s2 = "s2";
- return t;
- }
- }
-
- //====================================================================================================
- // Trim empty maps
- //====================================================================================================
- @Test
- public void testTrimEmptyMaps() throws Exception {
- UrlEncodingSerializer s = UrlEncodingSerializer.DEFAULT_SIMPLE.clone();
- B t1 = B.create(), t2;
- String r;
-
- s.setProperty(SERIALIZER_trimEmptyMaps, false);
- r = s.serialize(t1);
- assertEquals("f1=()&f2=(f2a=%00,f2b=(s2=s2))", r);
- t2 = p.parse(r, B.class);
- assertEqualObjects(t1, t2);
-
- s.setProperty(SERIALIZER_trimEmptyMaps, true);
- r = s.serialize(t1);
- assertEquals("f2=(f2a=%00,f2b=(s2=s2))", r);
- t2 = p.parse(r, B.class);
- assertNull(t2.f1);
- }
-
- public static class B {
- public TreeMap<String,A> f1, f2;
-
- public static B create() {
- B t = new B();
- t.f1 = new TreeMap<String,A>();
- t.f2 = new TreeMap<String,A>(){{put("f2a",null);put("f2b",A.create());}};
- return t;
- }
- }
-
- //====================================================================================================
- // Trim empty lists
- //====================================================================================================
- @Test
- public void testTrimEmptyLists() throws Exception {
- UrlEncodingSerializer s = new UrlEncodingSerializer();
- C t1 = C.create(), t2;
- String r;
-
- s.setProperty(SERIALIZER_trimEmptyLists, false);
- r = s.serialize(t1);
- assertEquals("f1=$a()&f2=$a(%00,$o(s2=s2))", r);
- t2 = p.parse(r, C.class);
- assertEqualObjects(t1, t2);
-
- s.setProperty(SERIALIZER_trimEmptyLists, true);
- r = s.serialize(t1);
- assertEquals("f2=$a(%00,$o(s2=s2))", r);
- t2 = p.parse(r, C.class);
- assertNull(t2.f1);
- }
-
- public static class C {
- public List<A> f1, f2;
-
- public static C create() {
- C t = new C();
- t.f1 = new LinkedList<A>();
- t.f2 = new LinkedList<A>(){{add(null);add(A.create());}};
- return t;
- }
- }
-
- //====================================================================================================
- // Trim empty arrays
- //====================================================================================================
- @Test
- public void testTrimEmptyArrays() throws Exception {
- UrlEncodingSerializer s = new UrlEncodingSerializer();
- D t1 = D.create(), t2;
- String r;
-
- s.setProperty(SERIALIZER_trimEmptyLists, false);
- r = s.serialize(t1);
- assertEquals("f1=$a()&f2=$a(%00,$o(s2=s2))", r);
- t2 = p.parse(r, D.class);
- assertEqualObjects(t1, t2);
-
- s.setProperty(SERIALIZER_trimEmptyLists, true);
- r = s.serialize(t1);
- assertEquals("f2=$a(%00,$o(s2=s2))", r);
- t2 = p.parse(r, D.class);
- assertNull(t2.f1);
- }
-
- public static class D {
- public A[] f1, f2;
-
- public static D create() {
- D t = new D();
- t.f1 = new A[]{};
- t.f2 = new A[]{null, A.create()};
- return t;
- }
- }
-
- //====================================================================================================
- // @BeanProperty.properties annotation.
- //====================================================================================================
- @Test
- public void testBeanPropertyProperies() throws Exception {
- UrlEncodingSerializer s = UrlEncodingSerializer.DEFAULT;
- UrlEncodingSerializer ss = UrlEncodingSerializer.DEFAULT_SIMPLE;
- String ue = ss.serialize(new E1());
- assertEquals("x1=(f1=1)&x2=(f1=1)&x3=((f1=1))&x4=((f1=1))&x5=((f1=1))&x6=((f1=1))", ue);
- ue = s.serialize(new E1());
- assertEquals("x1=$o(f1=$n(1))&x2=$o(f1=$n(1))&x3=$a($o(f1=$n(1)))&x4=$a($o(f1=$n(1)))&x5=$a($o(f1=$n(1)))&x6=$a($o(f1=$n(1)))", ue);
- }
-
- public static class E1 {
- @BeanProperty(properties={"f1"}) public E2 x1 = new E2();
- @BeanProperty(properties={"f1"}) public Map<String,Integer> x2 = new LinkedHashMap<String,Integer>() {{
- put("f1",1); put("f2",2);
- }};
- @BeanProperty(properties={"f1"}) public E2[] x3 = {new E2()};
- @BeanProperty(properties={"f1"}) public List<E2> x4 = new LinkedList<E2>() {{
- add(new E2());
- }};
- @BeanProperty(properties={"f1"}) public ObjectMap[] x5 = {new ObjectMap().append("f1",1).append("f2",2)};
- @BeanProperty(properties={"f1"}) public List<ObjectMap> x6 = new LinkedList<ObjectMap>() {{
- add(new ObjectMap().append("f1",1).append("f2",2));
- }};
- }
-
- public static class E2 {
- public int f1 = 1;
- public int f2 = 2;
- }
-
- //====================================================================================================
- // @BeanProperty.properties annotation on list of beans.
- //====================================================================================================
- @Test
- public void testBeanPropertyPropertiesOnListOfBeans() throws Exception {
- UrlEncodingSerializer s = UrlEncodingSerializer.DEFAULT;
- List<F> l = new LinkedList<F>();
- F t = new F();
- t.x1.add(new F());
- l.add(t);
- ObjectMap m = new ObjectMap().append("t", l);
- String xml = s.serialize(m);
- assertEquals("t=$a($o(x1=$a($o(x2=$n(2))),x2=$n(2)))", xml);
- xml = s.serialize(l);
- assertEquals("$n(0)=$o(x1=$a($o(x2=$n(2))),x2=$n(2))", xml);
- }
-
- public static class F {
- @BeanProperty(properties={"x2"}) public List<F> x1 = new LinkedList<F>();
- public int x2 = 2;
- }
-
- //====================================================================================================
- // Test URIAttr - Test that URLs and URIs are serialized and parsed correctly.
- //====================================================================================================
- @Test
- public void testURIAttr() throws Exception {
- UrlEncodingSerializer s = UrlEncodingSerializer.DEFAULT;
- UrlEncodingParser p = UrlEncodingParser.DEFAULT;
-
- G t = new G();
- t.uri = new URI("http://uri");
- t.f1 = new URI("http://f1");
- t.f2 = new URL("http://f2");
-
- String r = s.serialize(t);
- t = p.parse(r, G.class);
- assertEquals("http://uri", t.uri.toString());
- assertEquals("http://f1", t.f1.toString());
- assertEquals("http://f2", t.f2.toString());
- }
-
- public static class G {
- @BeanProperty(beanUri=true) public URI uri;
- public URI f1;
- public URL f2;
- }
-
- //====================================================================================================
- // Test URIs with URI_CONTEXT and URI_AUTHORITY
- //====================================================================================================
- @Test
- public void testUris() throws Exception {
- WriterSerializer s = new UrlEncodingSerializer();
- TestURI t = new TestURI();
- String r;
- String expected = "";
-
- s.setProperty(SERIALIZER_relativeUriBase, null);
- r = s.serialize(t);
- expected = ""
- +"f0=f0/x0"
- +"&f1=f1/x1"
- +"&f2=/f2/x2"
- +"&f3=http://www.ibm.com/f3/x3"
- +"&f4=f4/x4"
- +"&f5=/f5/x5"
- +"&f6=http://www.ibm.com/f6/x6"
- +"&f7=http://www.ibm.com/f7/x7"
- +"&f8=f8/x8"
- +"&f9=f9/x9"
- +"&fa=http://www.ibm.com/fa/xa%23MY_LABEL"
- +"&fb=http://www.ibm.com/fb/xb?label=MY_LABEL%26foo=bar"
- +"&fc=http://www.ibm.com/fc/xc?foo=bar%26label=MY_LABEL"
- +"&fd=http://www.ibm.com/fd/xd?label2=MY_LABEL%26foo=bar"
- +"&fe=http://www.ibm.com/fe/xe?foo=bar%26label2=MY_LABEL";
- assertEquals(expected, r);
-
- s.setProperty(SERIALIZER_relativeUriBase, ""); // Same as null.
- r = s.serialize(t);
- assertEquals(expected, r);
-
- s.setProperty(SERIALIZER_relativeUriBase, "/cr");
- r = s.serialize(t);
- expected = ""
- +"f0=/cr/f0/x0"
- +"&f1=/cr/f1/x1"
- +"&f2=/f2/x2"
- +"&f3=http://www.ibm.com/f3/x3"
- +"&f4=/cr/f4/x4"
- +"&f5=/f5/x5"
- +"&f6=http://www.ibm.com/f6/x6"
- +"&f7=http://www.ibm.com/f7/x7"
- +"&f8=/cr/f8/x8"
- +"&f9=/cr/f9/x9"
- +"&fa=http://www.ibm.com/fa/xa%23MY_LABEL"
- +"&fb=http://www.ibm.com/fb/xb?label=MY_LABEL%26foo=bar"
- +"&fc=http://www.ibm.com/fc/xc?foo=bar%26label=MY_LABEL"
- +"&fd=http://www.ibm.com/fd/xd?label2=MY_LABEL%26foo=bar"
- +"&fe=http://www.ibm.com/fe/xe?foo=bar%26label2=MY_LABEL";
- assertEquals(expected, r);
-
- s.setProperty(SERIALIZER_relativeUriBase, "/cr/"); // Same as above
- r = s.serialize(t);
- assertEquals(expected, r);
-
- s.setProperty(SERIALIZER_relativeUriBase, "/");
- r = s.serialize(t);
- expected = ""
- +"f0=/f0/x0"
- +"&f1=/f1/x1"
- +"&f2=/f2/x2"
- +"&f3=http://www.ibm.com/f3/x3"
- +"&f4=/f4/x4"
- +"&f5=/f5/x5"
- +"&f6=http://www.ibm.com/f6/x6"
- +"&f7=http://www.ibm.com/f7/x7"
- +"&f8=/f8/x8"
- +"&f9=/f9/x9"
- +"&fa=http://www.ibm.com/fa/xa%23MY_LABEL"
- +"&fb=http://www.ibm.com/fb/xb?label=MY_LABEL%26foo=bar"
- +"&fc=http://www.ibm.com/fc/xc?foo=bar%26label=MY_LABEL"
- +"&fd=http://www.ibm.com/fd/xd?label2=MY_LABEL%26foo=bar"
- +"&fe=http://www.ibm.com/fe/xe?foo=bar%26label2=MY_LABEL";
- assertEquals(expected, r);
-
- s.setProperty(SERIALIZER_relativeUriBase, null);
-
- s.setProperty(SERIALIZER_absolutePathUriBase, "http://foo");
- r = s.serialize(t);
- expected = ""
- +"f0=f0/x0"
- +"&f1=f1/x1"
- +"&f2=http://foo/f2/x2"
- +"&f3=http://www.ibm.com/f3/x3"
- +"&f4=f4/x4"
- +"&f5=http://foo/f5/x5"
- +"&f6=http://www.ibm.com/f6/x6"
- +"&f7=http://www.ibm.com/f7/x7"
- +"&f8=f8/x8"
- +"&f9=f9/x9"
- +"&fa=http://www.ibm.com/fa/xa%23MY_LABEL"
- +"&fb=http://www.ibm.com/fb/xb?label=MY_LABEL%26foo=bar"
- +"&fc=http://www.ibm.com/fc/xc?foo=bar%26label=MY_LABEL"
- +"&fd=http://www.ibm.com/fd/xd?label2=MY_LABEL%26foo=bar"
- +"&fe=http://www.ibm.com/fe/xe?foo=bar%26label2=MY_LABEL";
- assertEquals(expected, r);
-
- s.setProperty(SERIALIZER_absolutePathUriBase, "http://foo/");
- r = s.serialize(t);
- assertEquals(expected, r);
-
- s.setProperty(SERIALIZER_absolutePathUriBase, ""); // Same as null.
- r = s.serialize(t);
- expected = ""
- +"f0=f0/x0"
- +"&f1=f1/x1"
- +"&f2=/f2/x2"
- +"&f3=http://www.ibm.com/f3/x3"
- +"&f4=f4/x4"
- +"&f5=/f5/x5"
- +"&f6=http://www.ibm.com/f6/x6"
- +"&f7=http://www.ibm.com/f7/x7"
- +"&f8=f8/x8"
- +"&f9=f9/x9"
- +"&fa=http://www.ibm.com/fa/xa%23MY_LABEL"
- +"&fb=http://www.ibm.com/fb/xb?label=MY_LABEL%26foo=bar"
- +"&fc=http://www.ibm.com/fc/xc?foo=bar%26label=MY_LABEL"
- +"&fd=http://www.ibm.com/fd/xd?label2=MY_LABEL%26foo=bar"
- +"&fe=http://www.ibm.com/fe/xe?foo=bar%26label2=MY_LABEL";
- assertEquals(expected, r);
- }
-
- //====================================================================================================
- // Validate that you cannot update properties on locked serializer.
- //====================================================================================================
- @Test
- public void testLockedSerializer() throws Exception {
- UrlEncodingSerializer s = new UrlEncodingSerializer().lock();
- try {
- s.setProperty(JsonSerializerContext.JSON_simpleMode, true);
- fail("Locked exception not thrown");
- } catch (LockedException e) {}
- try {
- s.setProperty(SerializerContext.SERIALIZER_addClassAttrs, true);
- fail("Locked exception not thrown");
- } catch (LockedException e) {}
- try {
- s.setProperty(BeanContext.BEAN_beanMapPutReturnsOldValue, true);
- fail("Locked exception not thrown");
- } catch (LockedException e) {}
- }
-
- //====================================================================================================
- // Recursion
- //====================================================================================================
- @Test
- public void testRecursion() throws Exception {
- WriterSerializer s = new UrlEncodingSerializer();
-
- R1 r1 = new R1();
- R2 r2 = new R2();
- R3 r3 = new R3();
- r1.r2 = r2;
- r2.r3 = r3;
- r3.r1 = r1;
-
- // No recursion detection
- try {
- s.serialize(r1);
- fail("Exception expected!");
- } catch (Exception e) {
- String msg = e.getLocalizedMessage();
- assertTrue(msg.contains("It's recommended you use the SerializerContext.SERIALIZER_detectRecursions setting to help locate the loop."));
- }
-
- // Recursion detection, no ignore
- s.setProperty(SERIALIZER_detectRecursions, true);
- try {
- s.serialize(r1);
- fail("Exception expected!");
- } catch (Exception e) {
- String msg = e.getLocalizedMessage();
- assertTrue(msg.contains("[0]root:org.apache.juneau.urlencoding.CT_Common_UrlEncoding$R1"));
- assertTrue(msg.contains("->[1]r2:org.apache.juneau.urlencoding.CT_Common_UrlEncoding$R2"));
- assertTrue(msg.contains("->[2]r3:org.apache.juneau.urlencoding.CT_Common_UrlEncoding$R3"));
- assertTrue(msg.contains("->[3]r1:org.apache.juneau.urlencoding.CT_Common_UrlEncoding$R1"));
- }
-
- s.setProperty(SERIALIZER_ignoreRecursions, true);
- assertEquals("name=foo&r2=$o(name=bar,r3=$o(name=baz))", s.serialize(r1));
- }
-
- public static class R1 {
- public String name = "foo";
- public R2 r2;
- }
- public static class R2 {
- public String name = "bar";
- public R3 r3;
- }
- public static class R3 {
- public String name = "baz";
- public R1 r1;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/urlencoding/CT_UonParser.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/urlencoding/CT_UonParser.java b/org.apache.juneau/src/test/java/org/apache/juneau/urlencoding/CT_UonParser.java
deleted file mode 100755
index 49d37de..0000000
--- a/org.apache.juneau/src/test/java/org/apache/juneau/urlencoding/CT_UonParser.java
+++ /dev/null
@@ -1,542 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.urlencoding;
-
-import static org.junit.Assert.*;
-
-import java.util.*;
-
-import org.apache.juneau.parser.*;
-import org.junit.*;
-
-@SuppressWarnings({"rawtypes","unchecked","hiding"})
-public class CT_UonParser {
-
- static UonParser p = UonParser.DEFAULT;
- static UonParser pe = UonParser.DEFAULT_DECODING;
-
- //====================================================================================================
- // Basic test
- //====================================================================================================
- @Test
- public void testBasic() throws Exception {
-
- String t;
- Map m;
-
- // Simple string
- // Top level
- t = "a";
- assertEquals("a", p.parse(t, String.class));
- assertEquals("a", p.parse(t, Object.class));
- assertEquals("a", pe.parse(t, String.class));
- t = "(a)";
- assertEquals("a", p.parse(t, String.class));
- assertEquals("a", p.parse(t, Object.class));
- t = "$s(a)";
- assertEquals("a", p.parse(t, String.class));
-
- // 2nd level
- t = "$o(a=a)";
- assertEquals("a", p.parse(t, Map.class).get("a"));
- assertEquals("a", pe.parse(t, Map.class).get("a"));
-
- t = "(a=a)";
- assertEquals("a", p.parse(t, Map.class).get("a"));
- assertEquals("a", pe.parse(t, Map.class).get("a"));
-
- // Simple map
- // Top level
- t = "$o(a=b,c=$n(123),d=$b(false),e=$b(true),f=%00)";
- m = p.parse(t, Map.class);
- assertEquals("b", m.get("a"));
- assertTrue(m.get("c") instanceof Number);
- assertEquals(123, m.get("c"));
- assertTrue(m.get("d") instanceof Boolean);
- assertEquals(Boolean.FALSE, m.get("d"));
- assertTrue(m.get("e") instanceof Boolean);
- assertEquals(Boolean.TRUE, m.get("e"));
- m = pe.parse(t, Map.class);
- assertNull(m.get("f"));
-
- t = "(a=true)";
- m = p.parseMap(t, HashMap.class, String.class, Boolean.class);
- assertTrue(m.get("a") instanceof Boolean);
- assertEquals("true", m.get("a").toString());
-
- // null
- // Top level
- t = "%00";
- assertEquals("%00", p.parse(t, Object.class));
- assertNull(pe.parse(t, Object.class));
-
- // 2nd level
- t = "$o(%00=%00)";
- m = p.parse(t, Map.class);
- assertEquals("%00", m.get("%00"));
- m = pe.parse(t, Map.class);
- assertTrue(m.containsKey(null));
- assertNull(m.get(null));
-
- t = "(%00=%00)";
- m = p.parse(t, Map.class);
- assertEquals("%00", m.get("%00"));
- m = pe.parse(t, Map.class);
- assertTrue(m.containsKey(null));
- assertNull(m.get(null));
-
- t = "(\u0000=\u0000)";
- m = p.parse(t, Map.class);
- assertTrue(m.containsKey(null));
- assertNull(m.get(null));
- m = pe.parse(t, Map.class);
- assertTrue(m.containsKey(null));
- assertNull(m.get(null));
-
- // 3rd level
- t = "$o(%00=$o(%00=%00))";
- m = p.parse(t, Map.class);
- assertEquals("%00", ((Map)m.get("%00")).get("%00"));
- m = pe.parse(t, Map.class);
- assertTrue(((Map)m.get(null)).containsKey(null));
- assertNull(((Map)m.get(null)).get(null));
-
- // Empty array
- // Top level
- t = "$a()";
- List l = (List)p.parse(t, Object.class);
- assertTrue(l.isEmpty());
- t = "()";
- l = p.parse(t, List.class);
- assertTrue(l.isEmpty());
-
- // 2nd level in map
- t = "$o(x=$a())";
- m = p.parseMap(t, HashMap.class, String.class, List.class);
- assertTrue(m.containsKey("x"));
- assertTrue(((List)m.get("x")).isEmpty());
- m = (Map)p.parse(t, Object.class);
- assertTrue(m.containsKey("x"));
- assertTrue(((List)m.get("x")).isEmpty());
- t = "(x=())";
- m = p.parseMap(t, HashMap.class, String.class, List.class);
- assertTrue(m.containsKey("x"));
- assertTrue(((List)m.get("x")).isEmpty());
-
- // Empty 2 dimensional array
- t = "$a($a())";
- l = (List)p.parse(t, Object.class);
- assertTrue(l.size() == 1);
- l = (List)l.get(0);
- assertTrue(l.isEmpty());
- t = "(())";
- l = p.parseCollection(t, LinkedList.class, List.class);
- assertTrue(l.size() == 1);
- l = (List)l.get(0);
- assertTrue(l.isEmpty());
-
- // Array containing empty string
- // Top level
- t = "$a(())";
- l = (List)p.parse(t, Object.class);
- assertTrue(l.size() == 1);
- assertEquals("", l.get(0));
- t = "(())";
- l = p.parseCollection(t, List.class, String.class);
- assertTrue(l.size() == 1);
- assertEquals("", l.get(0));
-
- // 2nd level
- t = "$o(()=$a(()))";
- m = (Map)p.parse(t, Object.class);
- assertEquals("", ((List)m.get("")).get(0));
- t = "(=(()))";
- m = p.parseMap(t, HashMap.class, String.class, List.class);
- assertEquals("", ((List)m.get("")).get(0));
-
- // Array containing 3 empty strings
- t = "$a(,,)";
- l = (List)p.parse(t, Object.class);
- assertTrue(l.size() == 3);
- assertEquals("", l.get(0));
- assertEquals("", l.get(1));
- assertEquals("", l.get(2));
- t = "(,,)";
- l = p.parseCollection(t, List.class, Object.class);
- assertTrue(l.size() == 3);
- assertEquals("", l.get(0));
- assertEquals("", l.get(1));
- assertEquals("", l.get(2));
-
- // String containing \u0000
- // Top level
- t = "$s(\u0000)";
- assertEquals("\u0000", p.parse(t, Object.class));
- t = "(\u0000)";
- assertEquals("\u0000", p.parse(t, String.class));
- assertEquals("\u0000", p.parse(t, Object.class));
-
- // 2nd level
- t = "$o((\u0000)=(\u0000))";
- m = (Map)p.parse(t, Object.class);
- assertTrue(m.size() == 1);
- assertEquals("\u0000", m.get("\u0000"));
- t = "((\u0000)=(\u0000))";
- m = p.parseMap(t, HashMap.class, String.class, String.class);
- assertTrue(m.size() == 1);
- assertEquals("\u0000", m.get("\u0000"));
- m = p.parseMap(t, HashMap.class, String.class, Object.class);
- assertTrue(m.size() == 1);
- assertEquals("\u0000", m.get("\u0000"));
-
- // Boolean
- // Top level
- t = "$b(false)";
- Boolean b = (Boolean)p.parse(t, Object.class);
- assertEquals(Boolean.FALSE, b);
- b = p.parse(t, Boolean.class);
- assertEquals(Boolean.FALSE, b);
- t = "false";
- b = p.parse(t, Boolean.class);
- assertEquals(Boolean.FALSE, b);
-
- // 2nd level
- t = "$o(x=$b(false))";
- m = (Map)p.parse(t, Object.class);
- assertEquals(Boolean.FALSE, m.get("x"));
- t = "(x=$b(false))";
- m = p.parseMap(t, HashMap.class, String.class, Object.class);
- assertEquals(Boolean.FALSE, m.get("x"));
- t = "(x=false)";
- m = p.parseMap(t, HashMap.class, String.class, Boolean.class);
- assertEquals(Boolean.FALSE, m.get("x"));
-
- // Number
- // Top level
- t = "$n(123)";
- Integer i = (Integer)p.parse(t, Object.class);
- assertEquals(123, i.intValue());
- i = p.parse(t, Integer.class);
- assertEquals(123, i.intValue());
- Double d = p.parse(t, Double.class);
- assertEquals(123, d.intValue());
- Float f = p.parse(t, Float.class);
- assertEquals(123, f.intValue());
- t = "123";
- i = p.parse(t, Integer.class);
- assertEquals(123, i.intValue());
-
- // 2nd level
- t = "$o(x=$n(123))";
- m = (Map)p.parse(t, Object.class);
- assertEquals(123, ((Integer)m.get("x")).intValue());
- t = "(x=123)";
- m = p.parseMap(t, HashMap.class, String.class, Number.class);
- assertEquals(123, ((Integer)m.get("x")).intValue());
- m = p.parseMap(t, HashMap.class, String.class, Double.class);
- assertEquals(123, ((Double)m.get("x")).intValue());
-
- // Unencoded chars
- // Top level
- t = "x;/?:@-_.!*'";
- assertEquals("x;/?:@-_.!*'", p.parse(t, Object.class));
- assertEquals("x;/?:@-_.!*'", pe.parse(t, Object.class));
-
- // 2nd level
- t = "$o(x;/?:@-_.!*'=x;/?:@-_.!*')";
- m = (Map)p.parse(t, Object.class);
- assertEquals("x;/?:@-_.!*'", m.get("x;/?:@-_.!*'"));
- m = p.parseMap(t, HashMap.class, String.class, Object.class);
- assertEquals("x;/?:@-_.!*'", m.get("x;/?:@-_.!*'"));
- m = p.parseMap(t, HashMap.class, String.class, String.class);
- assertEquals("x;/?:@-_.!*'", m.get("x;/?:@-_.!*'"));
-
- // Encoded chars
- // Top level
- t = "x{}|\\^[]`<>#%\"&+";
- assertEquals("x{}|\\^[]`<>#%\"&+", p.parse(t, Object.class));
- assertEquals("x{}|\\^[]`<>#%\"&+", p.parse(t, String.class));
- try {
- assertEquals("x{}|\\^[]`<>#%\"&+", pe.parse(t, Object.class));
- fail("Expected parse exception from invalid hex sequence.");
- } catch (ParseException e) {
- // Good.
- }
- t = "x%7B%7D%7C%5C%5E%5B%5D%60%3C%3E%23%25%22%26%2B";
- assertEquals("x{}|\\^[]`<>#%\"&+", pe.parse(t, Object.class));
- assertEquals("x{}|\\^[]`<>#%\"&+", pe.parse(t, String.class));
-
- // 2nd level
- t = "$o(x{}|\\^[]`<>#%\"&+=x{}|\\^[]`<>#%\"&+)";
- m = (Map)p.parse(t, Object.class);
- assertEquals("x{}|\\^[]`<>#%\"&+", m.get("x{}|\\^[]`<>#%\"&+"));
- try {
- m = (Map)pe.parse(t, Object.class);
- fail("Expected parse exception from invalid hex sequence.");
- } catch (ParseException e) {
- // Good.
- }
- t = "$o(x%7B%7D%7C%5C%5E%5B%5D%60%3C%3E%23%25%22%26%2B=x%7B%7D%7C%5C%5E%5B%5D%60%3C%3E%23%25%22%26%2B)";
- m = (Map)pe.parse(t, Object.class);
- assertEquals("x{}|\\^[]`<>#%\"&+", m.get("x{}|\\^[]`<>#%\"&+"));
-
- // Special chars
- // Top level
- t = "x~$~,~(~)";
- assertEquals("x$,()", p.parse(t, Object.class));
- t = "(x~$~,~(~))";
- assertEquals("x$,()", p.parse(t, Object.class));
- t = "$s(x~$~,~(~))";
- assertEquals("x$,()", p.parse(t, Object.class));
-
- // 2nd level
- // Note behavior on serializeParams() is different since 2nd-level is top level.
- t = "$o(x~$~,~(~)=x~$~,~(~))";
- m = (Map)p.parse(t, Object.class);
- assertEquals("x$,()", m.get("x$,()"));
- t = "$o((x~$~,~(~))=(x~$~,~(~)))";
- m = (Map)p.parse(t, Object.class);
- assertEquals("x$,()", m.get("x$,()"));
- t = "$o($s(x~$~,~(~))=$s(x~$~,~(~)))";
- m = (Map)p.parse(t, Object.class);
- assertEquals("x$,()", m.get("x$,()"));
-
- // Equals sign
- // Gets encoded at top level, and encoded+escaped at 2nd level.
- // Top level
- t = "x=";
- assertEquals("x=", p.parse(t, Object.class));
- t = "x%3D";
- assertEquals("x=", pe.parse(t, Object.class));
-
- // 2nd level
- t = "$o(x~==x~=)";
- m = (Map)p.parse(t, Object.class);
- assertEquals("x=", m.get("x="));
- t = "$o((x~=)=(x~=))";
- m = (Map)p.parse(t, Object.class);
- assertEquals("x=", m.get("x="));
- t = "$o($s(x~=)=$s(x~=))";
- m = (Map)p.parse(t, Object.class);
- assertEquals("x=", m.get("x="));
- t = "(x~==x~=)";
- m = p.parseMap(t, HashMap.class, String.class, Object.class);
- assertEquals("x=", m.get("x="));
- t = "((x~=)=(x~=))";
- m = p.parseMap(t, HashMap.class, String.class, Object.class);
- assertEquals("x=", m.get("x="));
- t = "($s(x~=)=$s(x~=))";
- m = p.parseMap(t, HashMap.class, String.class, Object.class);
- assertEquals("x=", m.get("x="));
- t = "$o(x~%3D=x~%3D)";
- m = (Map)pe.parse(t, Object.class);
- assertEquals("x=", m.get("x="));
- t = "$o((x~%3D)=(x~%3D))";
- m = (Map)pe.parse(t, Object.class);
- assertEquals("x=", m.get("x="));
- t = "$o($s(x~%3D)=$s(x~%3D))";
- m = (Map)pe.parse(t, Object.class);
- assertEquals("x=", m.get("x="));
- t = "(x~%3D=x~%3D)";
- m = pe.parseMap(t, HashMap.class, String.class, Object.class);
- assertEquals("x=", m.get("x="));
- t = "((x~%3D)=(x~%3D))";
- m = pe.parseMap(t, HashMap.class, String.class, Object.class);
- assertEquals("x=", m.get("x="));
- t = "($s(x~%3D)=$s(x~%3D))";
- m = pe.parseMap(t, HashMap.class, String.class, Object.class);
- assertEquals("x=", m.get("x="));
-
- // String starting with parenthesis
- // Top level
- t = "~(~)";
- assertEquals("()", p.parse(t, Object.class));
- assertEquals("()", p.parse(t, String.class));
-
- t = "(~(~))";
- assertEquals("()", p.parse(t, Object.class));
- assertEquals("()", p.parse(t, String.class));
- t = "$s(~(~))";
- assertEquals("()", p.parse(t, Object.class));
- assertEquals("()", p.parse(t, String.class));
-
- // 2nd level
- t = "$o((~(~))=(~(~)))";
- m = (Map)p.parse(t, Object.class);
- assertEquals("()", m.get("()"));
- t = "((~(~))=(~(~)))";
- m = p.parseMap(t, HashMap.class, String.class, Object.class);
- assertEquals("()", m.get("()"));
- t = "($s(~(~))=$s(~(~)))";
- m = p.parseMap(t, HashMap.class, String.class, Object.class);
- assertEquals("()", m.get("()"));
-
- // String starting with $
- // Top level
- t = "($a)";
- assertEquals("$a", p.parse(t, Object.class));
- t = "($a)";
- assertEquals("$a", p.parse(t, Object.class));
-
- // 2nd level
- t = "$o(($a)=($a))";
- m = (Map)p.parse(t, Object.class);
- assertEquals("$a", m.get("$a"));
- t = "(($a)=($a))";
- m = p.parseMap(t, HashMap.class, String.class, Object.class);
- assertEquals("$a", m.get("$a"));
-
- // Blank string
- // Top level
- t = "";
- assertEquals("", p.parse(t, Object.class));
- assertEquals("", pe.parse(t, Object.class));
-
- // 2nd level
- t = "$o(=)";
- m = (Map)p.parse(t, Object.class);
- assertEquals("", m.get(""));
- t = "(=)";
- m = p.parseMap(t, HashMap.class, String.class, Object.class);
- assertEquals("", m.get(""));
-
- // 3rd level
- t = "$o(=$o(=))";
- m = (Map)p.parse(t, Object.class);
- assertEquals("", ((Map)m.get("")).get(""));
- t = "(=(=))";
- m = p.parseMap(t, HashMap.class, String.class, HashMap.class);
- assertEquals("", ((Map)m.get("")).get(""));
-
- // Newline character
- // Top level
- t = "(%0A)";
- assertEquals("\n", pe.parse(t, Object.class));
- assertEquals("%0A", p.parse(t, Object.class));
-
- // 2nd level
- t = "$o((%0A)=(%0A))";
- m = (Map)pe.parse(t, Object.class);
- assertEquals("\n", m.get("\n"));
- m = (Map)p.parse(t, Object.class);
- assertEquals("%0A", m.get("%0A"));
-
- // 3rd level
- t = "$o((%0A)=$o((%0A)=(%0A)))";
- m = (Map)pe.parse(t, Object.class);
- assertEquals("\n", ((Map)m.get("\n")).get("\n"));
- }
-
- //====================================================================================================
- // Unicode character test
- //====================================================================================================
- @Test
- public void testUnicodeChars() throws Exception {
- String t;
- Map m;
-
- // 2-byte UTF-8 character
- // Top level
- t = "�";
- assertEquals("�", p.parse(t, Object.class));
- assertEquals("�", p.parse(t, String.class));
- t = "%C2%A2";
- assertEquals("�", pe.parse(t, Object.class));
- assertEquals("�", pe.parse(t, String.class));
-
- // 2nd level
- t = "$o(�=�)";
- m = (Map)p.parse(t, Object.class);
- assertEquals("�", m.get("�"));
- t = "$o(%C2%A2=%C2%A2)";
- m = (Map)pe.parse(t, Object.class);
- assertEquals("�", m.get("�"));
-
- // 3rd level
- t = "$o(�=$o(�=�))";
- m = (Map)p.parse(t, Object.class);
- assertEquals("�", ((Map)m.get("�")).get("�"));
- t = "$o(%C2%A2=$o(%C2%A2=%C2%A2))";
- m = (Map)pe.parse(t, Object.class);
- assertEquals("�", ((Map)m.get("�")).get("�"));
-
- // 3-byte UTF-8 character
- // Top level
- t = "\u20ac";
- assertEquals("\u20ac", p.parse(t, Object.class));
- assertEquals("\u20ac", p.parse(t, String.class));
- t = "%E2%82%AC";
- assertEquals("\u20ac", pe.parse(t, Object.class));
- assertEquals("\u20ac", pe.parse(t, String.class));
-
- // 2nd level
- t = "$o(\u20ac=\u20ac)";
- m = (Map)p.parse(t, Object.class);
- assertEquals("\u20ac", m.get("\u20ac"));
- t = "$o(%E2%82%AC=%E2%82%AC)";
- m = (Map)pe.parse(t, Object.class);
- assertEquals("\u20ac", m.get("\u20ac"));
-
- // 3rd level
- t = "$o(\u20ac=$o(\u20ac=\u20ac))";
- m = (Map)p.parse(t, Object.class);
- assertEquals("\u20ac", ((Map)m.get("\u20ac")).get("\u20ac"));
- t = "$o(%E2%82%AC=$o(%E2%82%AC=%E2%82%AC))";
- m = (Map)pe.parse(t, Object.class);
- assertEquals("\u20ac", ((Map)m.get("\u20ac")).get("\u20ac"));
-
- // 4-byte UTF-8 character
- // Top level
- t = "\U00024b62";
- assertEquals("\U00024b62", p.parse(t, Object.class));
- assertEquals("\U00024b62", p.parse(t, String.class));
- t = "%F0%A4%AD%A2";
- assertEquals("\U00024b62", pe.parse(t, Object.class));
- assertEquals("\U00024b62", pe.parse(t, String.class));
-
- // 2nd level
- t = "$o(\U00024b62=\U00024b62)";
- m = (Map)p.parse(t, Object.class);
- assertEquals("\U00024b62", m.get("\U00024b62"));
- t = "$o(%F0%A4%AD%A2=%F0%A4%AD%A2)";
- m = (Map)pe.parse(t, Object.class);
- assertEquals("\U00024b62", m.get("\U00024b62"));
-
- // 3rd level
- t = "$o(\U00024b62=$o(\U00024b62=\U00024b62))";
- m = (Map)p.parse(t, Object.class);
- assertEquals("\U00024b62", ((Map)m.get("\U00024b62")).get("\U00024b62"));
- t = "$o(%F0%A4%AD%A2=$o(%F0%A4%AD%A2=%F0%A4%AD%A2))";
- m = (Map)pe.parse(t, Object.class);
- assertEquals("\U00024b62", ((Map)m.get("\U00024b62")).get("\U00024b62"));
- }
-
- //====================================================================================================
- // Test simple bean
- //====================================================================================================
- @Test
- public void testSimpleBean() throws Exception {
- UonParser p = UonParser.DEFAULT;
- A t;
-
- String s = "(f1=foo,f2=123)";
- t = p.parse(s, A.class);
- assertEquals("foo", t.f1);
- assertEquals(123, t.f2);
- }
-
- public static class A {
- public String f1;
- public int f2;
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/urlencoding/CT_UonParserReader.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/urlencoding/CT_UonParserReader.java b/org.apache.juneau/src/test/java/org/apache/juneau/urlencoding/CT_UonParserReader.java
deleted file mode 100755
index 8ae5cc7..0000000
--- a/org.apache.juneau/src/test/java/org/apache/juneau/urlencoding/CT_UonParserReader.java
+++ /dev/null
@@ -1,217 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.urlencoding;
-
-import static org.junit.Assert.*;
-
-import java.io.*;
-
-import org.apache.juneau.*;
-import org.junit.*;
-
-public class CT_UonParserReader {
-
- //====================================================================================================
- // Basic tests
- //====================================================================================================
- @Test
- public void testBasic() throws Exception {
-
- UonReader r;
- String s, in;
- r = r("f", true);
- assertEquals('f', r.read());
- assertEquals(-1, r.read());
-
- r = r("%66", true);
- assertEquals('f', r.read());
- assertEquals(-1, r.read());
-
- r = r("%7D", true);
- assertEquals('}', r.read());
- assertEquals(-1, r.read());
-
- r = r("%7D%7D", true);
- assertEquals('}', r.read());
- assertEquals('}', r.read());
- assertEquals(-1, r.read());
-
- r = r("%00%00", true);
- r.mark();
- assertEquals(0, r.read());
- assertEquals(0, r.read());
- assertEquals("\u0000\u0000", r.getMarked());
- assertEquals(-1, r.read());
-
- in = escape("\u0080");
- r = r(in, true);
- assertEquals('\u0080', r.read());
- assertEquals(-1, r.read());
-
- in = escape("\u0800");
- r = r(in, true);
- assertEquals('\u0800', r.read());
- assertEquals(-1, r.read());
-
- in = escape("\uffff");
- r = r(in, true);
- assertEquals('\uffff', r.read());
- assertEquals(-1, r.read());
-
- // 2-byte codepoint
- s = "�";
- r = r(escape(s), true);
- assertEquals(s.codePointAt(0), r.read());
- assertEquals(-1, r.read());
-
- // 3-byte codepoint
- s = "\u20ac";
- r = r(escape(s), true);
- assertEquals(s.codePointAt(0), r.readCodePoint());
- assertEquals(-1, r.read());
-
- // 4-byte codepoint
- s = "\U00024b62";
- r = r(escape(s), true);
- assertEquals(s.codePointAt(0), r.readCodePoint());
- assertEquals(-1, r.read());
-
- s = "\U00024b62\U00024b62";
- r = r(escape(s), true);
- assertEquals(s.codePointAt(0), r.readCodePoint());
- assertEquals(s.codePointAt(2), r.readCodePoint());
- assertEquals(-1, r.read());
-
- // Multiple codepoints
- s = "�\u20ac\U00024b62�\u20ac\U00024b62";
- in = escape(s);
- r = r(in, true);
- assertEquals(s.codePointAt(0), r.readCodePoint());
- assertEquals(s.codePointAt(1), r.readCodePoint());
- assertEquals(s.codePointAt(2), r.readCodePoint());
- assertEquals(s.codePointAt(4), r.readCodePoint());
- assertEquals(s.codePointAt(5), r.readCodePoint());
- assertEquals(s.codePointAt(6), r.readCodePoint());
- assertEquals(-1, r.read());
-
- // Multiple codepoints read in small chunks.
- s = "�\u20ac\U00024b62�\u20ac\U00024b62";
- String s2;
- int i;
- in = escape(s);
- r = r(in, true);
- char[] buff = new char[2];
- i = r.read(buff, 0, buff.length);
- s2 = new String(buff, 0, i);
- assertEquals("�", s2);
- i = r.read(buff, 0, buff.length);
- s2 = new String(buff, 0, i);
- assertEquals("\u20ac", s2);
- i = r.read(buff, 0, buff.length);
- s2 = new String(buff, 0, i);
- assertEquals("\U00024b62", s2);
- i = r.read(buff, 0, buff.length);
- s2 = new String(buff, 0, i);
- assertEquals("�", s2);
- i = r.read(buff, 0, buff.length);
- s2 = new String(buff, 0, i);
- assertEquals("\u20ac", s2);
- i = r.read(buff, 0, buff.length);
- s2 = new String(buff, 0, i);
- assertEquals("\U00024b62", s2);
- i = r.read(buff, 0, buff.length);
- assertEquals(-1, i);
-
- // Multiple codepoints read in slightly larger chunks.
- s = "�\u20ac\U00024b62�\u20ac\U00024b62";
- in = escape(s);
- r = r(in, true);
- buff = new char[3];
- i = r.read(buff, 0, buff.length);
- s2 = new String(buff, 0, i);
- assertEquals("�\u20ac", s2);
- i = r.read(buff, 0, buff.length);
- s2 = new String(buff, 0, i);
- assertEquals("\U00024b62", s2);
- i = r.read(buff, 0, buff.length);
- s2 = new String(buff, 0, i);
- assertEquals("�\u20ac", s2);
- i = r.read(buff, 0, buff.length);
- s2 = new String(buff, 0, i);
- assertEquals("\U00024b62", s2);
- i = r.read(buff, 0, buff.length);
- assertEquals(-1, i);
-
- s = "�\u20ac\U00024b62�\u20ac\U00024b62";
- in = escape(s);
- r = r(in, true);
- buff = new char[4];
- i = r.read(buff, 0, buff.length);
- s2 = new String(buff, 0, i);
- assertEquals("�\u20ac\U00024b62", s2);
- i = r.read(buff, 0, buff.length);
- s2 = new String(buff, 0, i);
- assertEquals("�\u20ac\U00024b62", s2);
- i = r.read(buff, 0, buff.length);
- assertEquals(-1, i);
-
- // Reader that only returns 1 character at a time;
- s = "x�\u20ac\U00024b62x�\u20ac\U00024b62";
- in = "x" + escape("�\u20ac\U00024b62") + "x" + escape("�\u20ac\U00024b62");
- r = new UonReader(new SlowStringReader(in), true);
- assertEquals(s.codePointAt(0), r.readCodePoint());
- assertEquals(s.codePointAt(1), r.readCodePoint());
- assertEquals(s.codePointAt(2), r.readCodePoint());
- assertEquals(s.codePointAt(3), r.readCodePoint());
- assertEquals(s.codePointAt(5), r.readCodePoint());
- assertEquals(s.codePointAt(6), r.readCodePoint());
- assertEquals(s.codePointAt(7), r.readCodePoint());
- assertEquals(s.codePointAt(8), r.readCodePoint());
- assertEquals(-1, r.readCodePoint());
- }
-
- private String escape(String s) throws UnsupportedEncodingException {
- StringBuilder sb = new StringBuilder();
- byte[] b = s.getBytes("UTF-8");
- for (int i = 0; i < b.length; i++)
- sb.append('%').append(TestUtils.toHex(b[i]));
- return sb.toString();
- }
-
- private UonReader r(String in, boolean decodeChars) {
- return new UonReader(in, decodeChars);
- }
-
- private static class SlowStringReader extends Reader {
-
- String s;
- int i = 0;
-
- SlowStringReader(String s) {
- this.s = s;
- }
-
- @Override /* Reader */
- public int read(char[] cbuf, int off, int len) throws IOException {
- if (i >= s.length())
- return -1;
- cbuf[off] = s.charAt(i++);
- return 1;
- }
-
- @Override /* Reader */
- public void close() throws IOException {
- }
-
- }
-}
\ No newline at end of file
[06/44] incubator-juneau git commit: Rename CT_* testcases.
Posted by ja...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/utils/CT_PojoRest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/utils/CT_PojoRest.java b/org.apache.juneau/src/test/java/org/apache/juneau/utils/CT_PojoRest.java
deleted file mode 100755
index ad5e7e6..0000000
--- a/org.apache.juneau/src/test/java/org/apache/juneau/utils/CT_PojoRest.java
+++ /dev/null
@@ -1,852 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.utils;
-
-import static org.apache.juneau.serializer.SerializerContext.*;
-import static org.junit.Assert.*;
-
-import java.util.*;
-
-import org.apache.juneau.*;
-import org.apache.juneau.json.*;
-import org.apache.juneau.parser.*;
-import org.junit.*;
-
-@SuppressWarnings({"unchecked","rawtypes","serial"})
-public class CT_PojoRest {
-
- //====================================================================================================
- // testBasic
- //====================================================================================================
- @Test
- public void testBasic() {
-
- // TODO: Need to write some exhaustive tests here. Will open work item
- // to do that later.
- PojoRest model = new PojoRest(new ObjectMap()); // An empty model.
-
- // Do a PUT
- model.put("A", new ObjectMap());
- model.put("A/B", new ObjectMap());
- model.put("A/B/C", "A new string");
- assertEquals("{A:{B:{C:'A new string'}}}", model.toString());
-
- // Do a POST to a list.
- model.put("A/B/C", new LinkedList());
- model.post("A/B/C", "String #1");
- model.post("A/B/C", "String #2");
- assertEquals("{A:{B:{C:['String #1\','String #2']}}}", model.toString());
-
- // Do some GETs
- String s = (String) model.get("A/B/C/0");
- assertEquals("String #1", s);
-
- Map m = (Map) model.get("A/B");
- assertEquals("{C:['String #1','String #2']}", m.toString());
- }
-
- //====================================================================================================
- // testBeans
- //====================================================================================================
- @Test
- public void testBeans() throws Exception {
- PojoRest model;
-
- // Java beans.
- model = new PojoRest(new ObjectMap());
- Person p = new Person("some name", 123,
- new Address("street A", "city A", "state A", 12345, true),
- new Address("street B", "city B", "state B", 12345, false)
- );
- model.put("/person1", p);
-
- // Make sure it got stored correctly.
- JsonSerializer serializer = JsonSerializer.DEFAULT_LAX;
- assertEquals("{person1:{name:'some name',age:123,addresses:[{street:'street A',city:'city A',state:'state A',zip:12345,isCurrent:true},{street:'street B',city:'city B',state:'state B',zip:12345,isCurrent:false}]}}", serializer.serialize(model.getRootObject()));
-
- // Get the original Person object back.
- p = (Person)model.get("/person1");
- assertEquals("city B", p.addresses[1].city);
-
- // Look for deep information inside beans.
- Address a3 = (Address)model.get("/person1/addresses/1");
- assertEquals("city B", a3.city);
-
- serializer = new JsonSerializer.Simple().setProperty(SERIALIZER_addClassAttrs, true);
- p = new Person("some name", 123,
- new Address("street A", "city A", "state A", 12345, true),
- new Address("street B", "city B", "state B", 12345, false)
- );
-
- // Serialize it to JSON.
- String s = serializer.serialize(p);
- String expectedValue = "{_class:'org.apache.juneau.utils.CT_PojoRest$Person',name:'some name',age:123,addresses:[{street:'street A',city:'city A',state:'state A',zip:12345,isCurrent:true},{street:'street B',city:'city B',state:'state B',zip:12345,isCurrent:false}]}";
- assertEquals(expectedValue, s);
-
- // Parse it back to Java objects.
- p = (Person)JsonParser.DEFAULT.clone().setClassLoader(getClass().getClassLoader()).parse(s, Object.class);
- expectedValue = "city B";
- s = p.addresses[1].city;
- assertEquals(expectedValue, s);
-
- // Parse it back into JSON again.
- s = serializer.serialize(p);
- expectedValue = "{_class:'org.apache.juneau.utils.CT_PojoRest$Person',name:'some name',age:123,addresses:[{street:'street A',city:'city A',state:'state A',zip:12345,isCurrent:true},{street:'street B',city:'city B',state:'state B',zip:12345,isCurrent:false}]}";
- assertEquals(expectedValue, s);
-
- // Try adding an address
- model = new PojoRest(p);
- model.post("addresses", new Address("street C", "city C", "state C", 12345, true));
- s = ((Address)model.get("addresses/2")).toString();
- expectedValue = "Address(street=street C,city=city C,state=state C,zip=12345,isCurrent=true)";
- assertEquals(expectedValue, s);
-
- // Try replacing addresses
- model.put("addresses/0", new Address("street D", "city D", "state D", 12345, false));
- model.put("addresses/1", new Address("street E", "city E", "state E", 12345, false));
- model.put("addresses/2", new Address("street F", "city F", "state F", 12345, false));
- serializer = JsonSerializer.DEFAULT_LAX;
- s = serializer.serialize(p);
- expectedValue = "{name:'some name',age:123,addresses:[{street:'street D',city:'city D',state:'state D',zip:12345,isCurrent:false},{street:'street E',city:'city E',state:'state E',zip:12345,isCurrent:false},{street:'street F',city:'city F',state:'state F',zip:12345,isCurrent:false}]}";
- assertEquals(expectedValue, s);
-
- // Try removing an address
- model.delete("addresses/1");
- s = serializer.serialize(p);
- expectedValue = "{name:'some name',age:123,addresses:[{street:'street D',city:'city D',state:'state D',zip:12345,isCurrent:false},{street:'street F',city:'city F',state:'state F',zip:12345,isCurrent:false}]}";
- assertEquals(expectedValue, s);
-
- model.delete("addresses/0");
- model.delete("addresses/0");
- s = serializer.serialize(p);
- expectedValue = "{name:'some name',age:123,addresses:[]}";
- assertEquals(expectedValue, s);
-
- // Try adding an out-of-bounds address (should pad it with nulls)
- model.put("addresses/2", new Address("street A", "city A", "state A", 12345, true));
- s = serializer.serialize(p);
- expectedValue = "{name:'some name',age:123,addresses:[null,null,{street:'street A',city:'city A',state:'state A',zip:12345,isCurrent:true}]}";
- assertEquals(expectedValue, s);
-
- // Try adding an address as a map (should be automatically converted to an Address)
- Map m = new HashMap();
- m.put("street","street D");
- m.put("city","city D");
- m.put("state","state D");
- m.put("zip",new Integer(12345));
-
- // Try the same for an address in an array.
- model.put("addresses/1", m);
- s = ((Address)model.get("addresses/1")).toString();
- expectedValue = "Address(street=street D,city=city D,state=state D,zip=12345,isCurrent=false)";
- assertEquals(expectedValue, s);
-
- // Try setting some fields.
- model.put("addresses/1/zip", new Integer(99999));
- s = model.get("addresses/1/zip").toString();
- expectedValue = "99999";
- assertEquals(expectedValue, s);
-
- // Make sure we can get non-existent branches without throwing any exceptions.
- // get() method should just return null.
- model = new PojoRest(new ObjectMap());
- Object o = model.get("xxx");
- assertEquals("null", (""+o));
-
- // Make sure blanks and "/" returns the root object.
- s = model.get("").toString();
- assertEquals("{}", s);
- s = model.get("/").toString();
- assertEquals("{}", s);
-
- // Make sure doing a PUT against "" or "/" replaces the root object.
- ObjectMap m2 = new ObjectMap("{x:1}");
- model.put("", m2);
- s = model.get("").toString();
- assertEquals("{x:1}", s);
- m2 = new ObjectMap("{x:2}");
- model.put("/", m2);
- s = model.get("").toString();
- assertEquals("{x:2}", s);
-
- // Make sure doing a POST against "" or "/" adds to the root object.
- model = new PojoRest(new ObjectList());
- model.post("", new Integer(1));
- model.post("/", new Integer(2));
- s = model.get("").toString();
- assertEquals("[1,2]", s);
- }
-
- //====================================================================================================
- // testAddressBook
- //====================================================================================================
- @Test
- public void testAddressBook() {
- PojoRest model;
-
- model = new PojoRest(new AddressBook());
-
- // Try adding a person to the address book.
- Person billClinton = new Person("Bill Clinton", 65,
- new Address("55W. 125th Street", "New York", "NY", 10027, true)
- );
-
- model.post("/", billClinton);
-
- // Make sure we get the original person back.
- billClinton = (Person)model.get("/0");
- }
-
-
- public static class AddressBook extends LinkedList<Person> {
-
- public AddressBook init() {
- add(
- new Person("Bill Clinton", 65,
- new Address("55W. 125th Street", "New York", "NY", 10027, true)
- )
- );
- return this;
- }
- }
-
- public static class Address {
- public String street;
- public String city;
- public String state;
- public int zip;
- public boolean isCurrent;
-
- public Address() {}
-
- public Address(String street, String city, String state, int zip, boolean isCurrent) {
- this.street = street;
- this.city = city;
- this.state = state;
- this.zip = zip;
- this.isCurrent = isCurrent;
- }
- @Override /* Object */
- public String toString() {
- return "Address(street="+street+",city="+city+",state="+state+",zip="+zip+",isCurrent="+isCurrent+")";
- }
- }
-
- public static class Person {
- public String name;
- public int age;
- public Address[] addresses;
-
- public Person() {}
-
- public Person(String name, int age, Address...addresses) {
- this.name = name;
- this.age = age;
- this.addresses = addresses;
- }
-
- @Override /* Object */
- public String toString() {
- return "Person(name="+name+",age="+age+")";
- }
- }
-
- //====================================================================================================
- // PojoRest(Object,ReaderParser)
- //====================================================================================================
- @Test
- public void testConstructors() throws Exception {
- PojoRest model = new PojoRest(new AddressBook(), JsonParser.DEFAULT);
-
- // Try adding a person to the address book.
- Person billClinton = new Person("Bill Clinton", 65,
- new Address("55W. 125th Street", "New York", "NY", 10027, true)
- );
-
- model.post("/", billClinton);
-
- // Make sure we get the original person back.
- billClinton = (Person)model.get("/0");
- }
-
- //====================================================================================================
- // setRootLocked()
- //====================================================================================================
- @Test
- public void testRootLocked() throws Exception {
- PojoRest model = new PojoRest(new AddressBook()).setRootLocked();
- try {
- model.put("", new AddressBook());
- fail();
- } catch (PojoRestException e) {
- assertEquals("Cannot overwrite root object", e.getLocalizedMessage());
- }
- try {
- model.put(null, new AddressBook());
- fail();
- } catch (PojoRestException e) {
- assertEquals("Cannot overwrite root object", e.getLocalizedMessage());
- }
- try {
- model.put("/", new AddressBook());
- fail();
- } catch (PojoRestException e) {
- assertEquals("Cannot overwrite root object", e.getLocalizedMessage());
- }
- }
-
- //====================================================================================================
- // getRootObject()
- //====================================================================================================
- @Test
- public void testGetRootObject() throws Exception {
- PojoRest model = new PojoRest(new AddressBook());
- assertTrue(model.getRootObject() instanceof AddressBook);
- model.put("", "foobar");
- assertTrue(model.getRootObject() instanceof String);
- model.put("", null);
- assertNull(model.getRootObject());
- }
-
- //====================================================================================================
- // get(Class<T> type, String url)
- // get(Class<T> type, String url, T def)
- // getString(String url)
- // getString(String url, String defVal)
- // getInt(String url)
- // getInt(String url, Integer defVal)
- // getLong(String url)
- // getLong(String url, Long defVal)
- // getBoolean(String url)
- // getBoolean(String url, Boolean defVal)
- // getMap(String url)
- // getMap(String url, Map<?,?> defVal)
- // getList(String url)
- // getList(String url, List<?> defVal)
- // getObjectMap(String url)
- // getObjectMap(String url, ObjectMap defVal)
- // getObjectList(String url)
- // getObjectList(String url, ObjectList defVal)
- //====================================================================================================
- @Test
- public void testGetMethods() throws Exception {
- PojoRest model = new PojoRest(new A());
- ObjectList l = new ObjectList("[{a:'b'}]");
- ObjectMap m = new ObjectMap("{a:'b'}");
-
- assertNull(model.get("f1"));
- assertEquals(0, model.get("f2"));
- assertEquals(0l, model.get("f3"));
- assertFalse((Boolean)model.get("f4"));
- assertNull(model.get("f2a"));
- assertNull(model.get("f3a"));
- assertNull(model.get("f4a"));
- assertNull(model.get("f5"));
- assertNull(model.get("f6"));
- assertNull(model.get("f7"));
- assertNull(model.get("f8"));
-
- assertEquals("foo", model.get("f1", "foo"));
- assertEquals(0, model.get("f2", "foo"));
- assertEquals(0l, model.get("f3", "foo"));
- assertEquals(false, model.get("f4", "foo"));
- assertEquals("foo", model.get("f2a", "foo"));
- assertEquals("foo", model.get("f3a", "foo"));
- assertEquals("foo", model.get("f4a", "foo"));
- assertEquals("foo", model.get("f5", "foo"));
- assertEquals("foo", model.get("f6", "foo"));
- assertEquals("foo", model.get("f7", "foo"));
- assertEquals("foo", model.get("f8", "foo"));
-
- assertNull(model.getString("f1"));
- assertEquals("0", model.getString("f2"));
- assertEquals("0", model.getString("f3"));
- assertEquals("false", model.getString("f4"));
- assertNull(model.getString("f2a"));
- assertNull(model.getString("f3a"));
- assertNull(model.getString("f4a"));
- assertNull(model.getString("f5"));
- assertNull(model.getString("f6"));
- assertNull(model.getString("f7"));
- assertNull(model.getString("f8"));
-
- assertEquals("foo", model.getString("f1", "foo"));
- assertEquals("0", model.getString("f2", "foo"));
- assertEquals("0", model.getString("f3", "foo"));
- assertEquals("false", model.getString("f4", "foo"));
- assertEquals("foo", model.getString("f2a", "foo"));
- assertEquals("foo", model.getString("f3a", "foo"));
- assertEquals("foo", model.getString("f4a", "foo"));
- assertEquals("foo", model.getString("f5", "foo"));
- assertEquals("foo", model.getString("f6", "foo"));
- assertEquals("foo", model.getString("f7", "foo"));
- assertEquals("foo", model.getString("f8", "foo"));
-
- assertNull(model.getInt("f1"));
- assertEquals(0, (int)model.getInt("f2"));
- assertEquals(0, (int)model.getInt("f3"));
- assertEquals(0, (int)model.getInt("f4"));
- assertNull(model.getInt("f2a"));
- assertNull(model.getInt("f3a"));
- assertNull(model.getInt("f4a"));
- assertNull(model.getInt("f5"));
- assertNull(model.getInt("f6"));
- assertNull(model.getInt("f7"));
- assertNull(model.getInt("f8"));
-
- assertEquals(1, (int)model.getInt("f1", 1));
- assertEquals(0, (int)model.getInt("f2", 1));
- assertEquals(0, (int)model.getInt("f3", 1));
- assertEquals(0, (int)model.getInt("f4", 1));
- assertEquals(1, (int)model.getInt("f2a", 1));
- assertEquals(1, (int)model.getInt("f3a", 1));
- assertEquals(1, (int)model.getInt("f4a", 1));
- assertEquals(1, (int)model.getInt("f5", 1));
- assertEquals(1, (int)model.getInt("f6", 1));
- assertEquals(1, (int)model.getInt("f7", 1));
- assertEquals(1, (int)model.getInt("f8", 1));
-
- assertNull(model.getLong("f1"));
- assertEquals(0, (long)model.getLong("f2"));
- assertEquals(0, (long)model.getLong("f3"));
- assertEquals(0, (long)model.getLong("f4"));
- assertNull(model.getLong("f2a"));
- assertNull(model.getLong("f3a"));
- assertNull(model.getLong("f4a"));
- assertNull(model.getLong("f5"));
- assertNull(model.getLong("f6"));
- assertNull(model.getLong("f7"));
- assertNull(model.getLong("f8"));
-
- assertEquals(1, (long)model.getLong("f1", 1l));
- assertEquals(0, (long)model.getLong("f2", 1l));
- assertEquals(0, (long)model.getLong("f3", 1l));
- assertEquals(0, (long)model.getLong("f4", 1l));
- assertEquals(1, (long)model.getLong("f2a", 1l));
- assertEquals(1, (long)model.getLong("f3a", 1l));
- assertEquals(1, (long)model.getLong("f4a", 1l));
- assertEquals(1, (long)model.getLong("f5", 1l));
- assertEquals(1, (long)model.getLong("f6", 1l));
- assertEquals(1, (long)model.getLong("f7", 1l));
- assertEquals(1, (long)model.getLong("f8", 1l));
-
- assertNull(model.getBoolean("f1"));
- assertEquals(false, model.getBoolean("f2"));
- assertEquals(false, model.getBoolean("f3"));
- assertEquals(false, model.getBoolean("f4"));
- assertNull(model.getBoolean("f2a"));
- assertNull(model.getBoolean("f3a"));
- assertNull(model.getBoolean("f4a"));
- assertNull(model.getBoolean("f5"));
- assertNull(model.getBoolean("f6"));
- assertNull(model.getBoolean("f7"));
- assertNull(model.getBoolean("f8"));
-
- assertEquals(true, model.getBoolean("f1", true));
- assertEquals(false, model.getBoolean("f2", true));
- assertEquals(false, model.getBoolean("f3", true));
- assertEquals(false, model.getBoolean("f4", true));
- assertEquals(true, model.getBoolean("f2a", true));
- assertEquals(true, model.getBoolean("f3a", true));
- assertEquals(true, model.getBoolean("f4a", true));
- assertEquals(true, model.getBoolean("f5", true));
- assertEquals(true, model.getBoolean("f6", true));
- assertEquals(true, model.getBoolean("f7", true));
- assertEquals(true, model.getBoolean("f8", true));
-
- assertNull(model.getMap("f1"));
- try { model.getMap("f2"); fail(); } catch (InvalidDataConversionException e) {}
- try { model.getMap("f3"); fail(); } catch (InvalidDataConversionException e) {}
- try { model.getMap("f4"); fail(); } catch (InvalidDataConversionException e) {}
- assertNull(model.getMap("f2a"));
- assertNull(model.getMap("f3a"));
- assertNull(model.getMap("f4a"));
- assertNull(model.getMap("f5"));
- assertNull(model.getMap("f6"));
- assertNull(model.getMap("f7"));
- assertNull(model.getMap("f8"));
-
- assertEquals("{a:'b'}", model.getMap("f1", m).toString());
- try { model.getMap("f2", m); fail(); } catch (InvalidDataConversionException e) {}
- try { model.getMap("f3", m); fail(); } catch (InvalidDataConversionException e) {}
- try { model.getMap("f4", m); fail(); } catch (InvalidDataConversionException e) {}
- assertEquals("{a:'b'}", model.getMap("f2a", m).toString());
- assertEquals("{a:'b'}", model.getMap("f3a", m).toString());
- assertEquals("{a:'b'}", model.getMap("f4a", m).toString());
- assertEquals("{a:'b'}", model.getMap("f5", m).toString());
- assertEquals("{a:'b'}", model.getMap("f6", m).toString());
- assertEquals("{a:'b'}", model.getMap("f7", m).toString());
- assertEquals("{a:'b'}", model.getMap("f8", m).toString());
-
- assertNull(model.getMap("f1"));
- try { model.getObjectMap("f2"); fail(); } catch (InvalidDataConversionException e) {}
- try { model.getObjectMap("f3"); fail(); } catch (InvalidDataConversionException e) {}
- try { model.getObjectMap("f4"); fail(); } catch (InvalidDataConversionException e) {}
- assertNull(model.getObjectMap("f2a"));
- assertNull(model.getObjectMap("f3a"));
- assertNull(model.getObjectMap("f4a"));
- assertNull(model.getObjectMap("f5"));
- assertNull(model.getObjectMap("f6"));
- assertNull(model.getObjectMap("f7"));
- assertNull(model.getObjectMap("f8"));
-
- assertEquals("{a:'b'}", model.getObjectMap("f1", m).toString());
- try { model.getObjectMap("f2", m); fail(); } catch (InvalidDataConversionException e) {}
- try { model.getObjectMap("f3", m); fail(); } catch (InvalidDataConversionException e) {}
- try { model.getObjectMap("f4", m); fail(); } catch (InvalidDataConversionException e) {}
- assertEquals("{a:'b'}", model.getObjectMap("f2a", m).toString());
- assertEquals("{a:'b'}", model.getObjectMap("f3a", m).toString());
- assertEquals("{a:'b'}", model.getObjectMap("f4a", m).toString());
- assertEquals("{a:'b'}", model.getObjectMap("f5", m).toString());
- assertEquals("{a:'b'}", model.getObjectMap("f6", m).toString());
- assertEquals("{a:'b'}", model.getObjectMap("f7", m).toString());
- assertEquals("{a:'b'}", model.getObjectMap("f8", m).toString());
-
- assertNull(model.getList("f1"));
- try { model.getList("f2"); fail(); } catch (InvalidDataConversionException e) {}
- try { model.getList("f3"); fail(); } catch (InvalidDataConversionException e) {}
- try { model.getList("f4"); fail(); } catch (InvalidDataConversionException e) {}
- assertNull(model.getList("f2a"));
- assertNull(model.getList("f3a"));
- assertNull(model.getList("f4a"));
- assertNull(model.getList("f5"));
- assertNull(model.getList("f6"));
- assertNull(model.getList("f7"));
- assertNull(model.getList("f8"));
-
- assertEquals("[{a:'b'}]", model.getList("f1", l).toString());
- try { model.getList("f2", l); fail(); } catch (InvalidDataConversionException e) {}
- try { model.getList("f3", l); fail(); } catch (InvalidDataConversionException e) {}
- try { model.getList("f4", l); fail(); } catch (InvalidDataConversionException e) {}
- assertEquals("[{a:'b'}]", model.getList("f2a", l).toString());
- assertEquals("[{a:'b'}]", model.getList("f3a", l).toString());
- assertEquals("[{a:'b'}]", model.getList("f4a", l).toString());
- assertEquals("[{a:'b'}]", model.getList("f5", l).toString());
- assertEquals("[{a:'b'}]", model.getList("f6", l).toString());
- assertEquals("[{a:'b'}]", model.getList("f7", l).toString());
- assertEquals("[{a:'b'}]", model.getList("f8", l).toString());
-
- assertNull(model.getObjectList("f1"));
- try { model.getObjectList("f2"); fail(); } catch (InvalidDataConversionException e) {}
- try { model.getObjectList("f3"); fail(); } catch (InvalidDataConversionException e) {}
- try { model.getObjectList("f4"); fail(); } catch (InvalidDataConversionException e) {}
- assertNull(model.getObjectList("f2a"));
- assertNull(model.getObjectList("f3a"));
- assertNull(model.getObjectList("f4a"));
- assertNull(model.getObjectList("f5"));
- assertNull(model.getObjectList("f6"));
- assertNull(model.getObjectList("f7"));
- assertNull(model.getObjectList("f8"));
-
- assertEquals("[{a:'b'}]", model.getObjectList("f1", l).toString());
- try { model.getObjectList("f2", l); fail(); } catch (InvalidDataConversionException e) {}
- try { model.getObjectList("f3", l); fail(); } catch (InvalidDataConversionException e) {}
- try { model.getObjectList("f4", l); fail(); } catch (InvalidDataConversionException e) {}
- assertEquals("[{a:'b'}]", model.getObjectList("f2a", l).toString());
- assertEquals("[{a:'b'}]", model.getObjectList("f3a", l).toString());
- assertEquals("[{a:'b'}]", model.getObjectList("f4a", l).toString());
- assertEquals("[{a:'b'}]", model.getObjectList("f5", l).toString());
- assertEquals("[{a:'b'}]", model.getObjectList("f6", l).toString());
- assertEquals("[{a:'b'}]", model.getObjectList("f7", l).toString());
- assertEquals("[{a:'b'}]", model.getObjectList("f8", l).toString());
-
- ((A)model.getRootObject()).init();
-
- assertEquals("1", model.get("f1"));
- assertEquals("2", model.get("f2").toString());
- assertEquals("3", model.get("f3").toString());
- assertEquals("true", model.get("f4").toString());
- assertEquals("2", model.get("f2a").toString());
- assertEquals("3", model.get("f3a").toString());
- assertEquals("true", model.get("f4a").toString());
- assertEquals("{f5a:'a'}", model.get("f5").toString());
- assertEquals("[{f6a:'a'}]", model.get("f6").toString());
- assertEquals("{f5a:'a'}", model.get("f7").toString());
- assertEquals("[{f6a:'a'}]", model.get("f8").toString());
-
- assertEquals("1", model.get("f1", "foo"));
- assertEquals("2", model.get("f2", "foo").toString());
- assertEquals("3", model.get("f3", "foo").toString());
- assertEquals("true", model.get("f4", "foo").toString());
- assertEquals("2", model.get("f2a", "foo").toString());
- assertEquals("3", model.get("f3a", "foo").toString());
- assertEquals("true", model.get("f4a", "foo").toString());
- assertEquals("{f5a:'a'}", model.get("f5", "foo").toString());
- assertEquals("[{f6a:'a'}]", model.get("f6", "foo").toString());
- assertEquals("{f5a:'a'}", model.get("f7", "foo").toString());
- assertEquals("[{f6a:'a'}]", model.get("f8", "foo").toString());
-
- assertEquals("1", model.getString("f1"));
- assertEquals("2", model.getString("f2"));
- assertEquals("3", model.getString("f3"));
- assertEquals("true", model.getString("f4"));
- assertEquals("2", model.getString("f2a"));
- assertEquals("3", model.getString("f3a"));
- assertEquals("true", model.getString("f4a"));
- assertEquals("{f5a:'a'}", model.getString("f5"));
- assertEquals("[{f6a:'a'}]", model.getString("f6"));
- assertEquals("{f5a:'a'}", model.getString("f7"));
- assertEquals("[{f6a:'a'}]", model.getString("f8"));
-
- assertEquals("1", model.getString("f1", "foo"));
- assertEquals("2", model.getString("f2", "foo"));
- assertEquals("3", model.getString("f3", "foo"));
- assertEquals("true", model.getString("f4", "foo"));
- assertEquals("2", model.getString("f2a", "foo"));
- assertEquals("3", model.getString("f3a", "foo"));
- assertEquals("true", model.getString("f4a", "foo"));
- assertEquals("{f5a:'a'}", model.getString("f5", "foo"));
- assertEquals("[{f6a:'a'}]", model.getString("f6", "foo"));
- assertEquals("{f5a:'a'}", model.getString("f7", "foo"));
- assertEquals("[{f6a:'a'}]", model.getString("f8", "foo"));
-
- assertEquals(1, (int)model.getInt("f1"));
- assertEquals(2, (int)model.getInt("f2"));
- assertEquals(3, (int)model.getInt("f3"));
- assertEquals(1, (int)model.getInt("f4"));
- assertEquals(2, (int)model.getInt("f2a"));
- assertEquals(3, (int)model.getInt("f3a"));
- assertEquals(1, (int)model.getInt("f4a"));
- try { model.getInt("f5"); fail(); } catch (InvalidDataConversionException e) {}
- try { model.getInt("f6"); fail(); } catch (InvalidDataConversionException e) {}
- try { model.getInt("f7"); fail(); } catch (InvalidDataConversionException e) {}
- try { model.getInt("f8"); fail(); } catch (InvalidDataConversionException e) {}
-
- assertEquals(1, (int)model.getInt("f1", 9));
- assertEquals(2, (int)model.getInt("f2", 9));
- assertEquals(3, (int)model.getInt("f3", 9));
- assertEquals(1, (int)model.getInt("f4", 9));
- assertEquals(2, (int)model.getInt("f2a", 9));
- assertEquals(3, (int)model.getInt("f3a", 9));
- assertEquals(1, (int)model.getInt("f4a", 9));
- try { model.getInt("f5", 9); fail(); } catch (InvalidDataConversionException e) {}
- try { model.getInt("f6", 9); fail(); } catch (InvalidDataConversionException e) {}
- try { model.getInt("f7", 9); fail(); } catch (InvalidDataConversionException e) {}
- try { model.getInt("f8", 9); fail(); } catch (InvalidDataConversionException e) {}
-
- assertEquals(1, (long)model.getLong("f1"));
- assertEquals(2, (long)model.getLong("f2"));
- assertEquals(3, (long)model.getLong("f3"));
- assertEquals(1, (long)model.getLong("f4"));
- assertEquals(2, (long)model.getLong("f2a"));
- assertEquals(3, (long)model.getLong("f3a"));
- assertEquals(1, (long)model.getLong("f4a"));
- try { model.getLong("f5"); fail(); } catch (InvalidDataConversionException e) {}
- try { model.getLong("f6"); fail(); } catch (InvalidDataConversionException e) {}
- try { model.getLong("f7"); fail(); } catch (InvalidDataConversionException e) {}
- try { model.getInt("f8"); fail(); } catch (InvalidDataConversionException e) {}
-
- assertEquals(1, (long)model.getLong("f1", 9l));
- assertEquals(2, (long)model.getLong("f2", 9l));
- assertEquals(3, (long)model.getLong("f3", 9l));
- assertEquals(1, (long)model.getLong("f4", 9l));
- assertEquals(2, (long)model.getLong("f2a", 9l));
- assertEquals(3, (long)model.getLong("f3a", 9l));
- assertEquals(1, (long)model.getLong("f4a", 9l));
- try { model.getLong("f5", 9l); fail(); } catch (InvalidDataConversionException e) {}
- try { model.getLong("f6", 9l); fail(); } catch (InvalidDataConversionException e) {}
- try { model.getLong("f7", 9l); fail(); } catch (InvalidDataConversionException e) {}
- try { model.getLong("f8", 9l); fail(); } catch (InvalidDataConversionException e) {}
-
- assertEquals(false, model.getBoolean("f1")); // String "1" equates to false.
- assertEquals(true, model.getBoolean("f2"));
- assertEquals(true, model.getBoolean("f3"));
- assertEquals(true, model.getBoolean("f4"));
- assertEquals(true, model.getBoolean("f2a"));
- assertEquals(true, model.getBoolean("f3a"));
- assertEquals(true, model.getBoolean("f4a"));
- assertEquals(false, model.getBoolean("f5")); // "{a:'b'}" equates to false.
- assertEquals(false, model.getBoolean("f6"));
- assertEquals(false, model.getBoolean("f7"));
- assertEquals(false, model.getBoolean("f8"));
-
- assertEquals(false, model.getBoolean("f1", true)); // String "1" equates to false.
- assertEquals(true, model.getBoolean("f2", true));
- assertEquals(true, model.getBoolean("f3", true));
- assertEquals(true, model.getBoolean("f4", true));
- assertEquals(true, model.getBoolean("f2a", true));
- assertEquals(true, model.getBoolean("f3a", true));
- assertEquals(true, model.getBoolean("f4a", true));
- assertEquals(false, model.getBoolean("f5", true)); // "{a:'b'}" equates to false.
- assertEquals(false, model.getBoolean("f6", true));
- assertEquals(false, model.getBoolean("f7", true));
- assertEquals(false, model.getBoolean("f8", true));
-
- try { model.getMap("f1"); fail(); } catch (InvalidDataConversionException e) {}
- try { model.getMap("f2"); fail(); } catch (InvalidDataConversionException e) {}
- try { model.getMap("f3"); fail(); } catch (InvalidDataConversionException e) {}
- try { model.getMap("f4"); fail(); } catch (InvalidDataConversionException e) {}
- try { model.getMap("f2a"); fail(); } catch (InvalidDataConversionException e) {}
- try { model.getMap("f3a"); fail(); } catch (InvalidDataConversionException e) {}
- try { model.getMap("f4a"); fail(); } catch (InvalidDataConversionException e) {}
- assertEquals("{f5a:'a'}", model.getMap("f5").toString());
- try { model.getMap("f6"); fail(); } catch (InvalidDataConversionException e) {}
- assertEquals("{f5a:'a'}", model.getMap("f7").toString());
- try { model.getMap("f8"); fail(); } catch (InvalidDataConversionException e) {}
-
- try { model.getMap("f1", m); fail(); } catch (InvalidDataConversionException e) {}
- try { model.getMap("f2", m); fail(); } catch (InvalidDataConversionException e) {}
- try { model.getMap("f3", m); fail(); } catch (InvalidDataConversionException e) {}
- try { model.getMap("f4", m); fail(); } catch (InvalidDataConversionException e) {}
- try { model.getMap("f2a", m); fail(); } catch (InvalidDataConversionException e) {}
- try { model.getMap("f3a", m); fail(); } catch (InvalidDataConversionException e) {}
- try { model.getMap("f4a", m); fail(); } catch (InvalidDataConversionException e) {}
- assertEquals("{f5a:'a'}", model.getMap("f5", m).toString());
- try { model.getMap("f6", m); fail(); } catch (InvalidDataConversionException e) {}
- assertEquals("{f5a:'a'}", model.getMap("f7", m).toString());
- try { model.getMap("f8", m); fail(); } catch (InvalidDataConversionException e) {}
-
- try { model.getObjectMap("f1"); fail(); } catch (InvalidDataConversionException e) {}
- try { model.getObjectMap("f2"); fail(); } catch (InvalidDataConversionException e) {}
- try { model.getObjectMap("f3"); fail(); } catch (InvalidDataConversionException e) {}
- try { model.getObjectMap("f4"); fail(); } catch (InvalidDataConversionException e) {}
- try { model.getObjectMap("f2a"); fail(); } catch (InvalidDataConversionException e) {}
- try { model.getObjectMap("f3a"); fail(); } catch (InvalidDataConversionException e) {}
- try { model.getObjectMap("f4a"); fail(); } catch (InvalidDataConversionException e) {}
- assertEquals("{f5a:'a'}", model.getObjectMap("f5").toString());
- try { model.getObjectMap("f6"); fail(); } catch (InvalidDataConversionException e) {}
- assertEquals("{f5a:'a'}", model.getObjectMap("f7").toString());
- try { model.getObjectMap("f8"); fail(); } catch (InvalidDataConversionException e) {}
-
- try { model.getObjectMap("f1", m); fail(); } catch (InvalidDataConversionException e) {}
- try { model.getObjectMap("f2", m); fail(); } catch (InvalidDataConversionException e) {}
- try { model.getObjectMap("f3", m); fail(); } catch (InvalidDataConversionException e) {}
- try { model.getObjectMap("f4", m); fail(); } catch (InvalidDataConversionException e) {}
- try { model.getObjectMap("f2a", m); fail(); } catch (InvalidDataConversionException e) {}
- try { model.getObjectMap("f3a", m); fail(); } catch (InvalidDataConversionException e) {}
- try { model.getObjectMap("f4a", m); fail(); } catch (InvalidDataConversionException e) {}
- assertEquals("{f5a:'a'}", model.getObjectMap("f5", m).toString());
- try { model.getObjectMap("f6", m); fail(); } catch (InvalidDataConversionException e) {}
- assertEquals("{f5a:'a'}", model.getObjectMap("f7", m).toString());
- try { model.getObjectMap("f8", m); fail(); } catch (InvalidDataConversionException e) {}
-
- try { model.getList("f1"); fail(); } catch (InvalidDataConversionException e) {}
- try { model.getList("f2"); fail(); } catch (InvalidDataConversionException e) {}
- try { model.getList("f3"); fail(); } catch (InvalidDataConversionException e) {}
- try { model.getList("f4"); fail(); } catch (InvalidDataConversionException e) {}
- try { model.getList("f2a"); fail(); } catch (InvalidDataConversionException e) {}
- try { model.getList("f3a"); fail(); } catch (InvalidDataConversionException e) {}
- try { model.getList("f4a"); fail(); } catch (InvalidDataConversionException e) {}
- assertEquals("[{f5a:'a'}]", model.getList("f5").toString());
- assertEquals("[{f6a:'a'}]", model.getList("f6").toString());
- assertEquals("[{f5a:'a'}]", model.getList("f7").toString());
- assertEquals("[{f6a:'a'}]", model.getList("f8").toString());
-
- try { model.getList("f1", l); fail(); } catch (InvalidDataConversionException e) {}
- try { model.getList("f2", l); fail(); } catch (InvalidDataConversionException e) {}
- try { model.getList("f3", l); fail(); } catch (InvalidDataConversionException e) {}
- try { model.getList("f4", l); fail(); } catch (InvalidDataConversionException e) {}
- try { model.getList("f2a", l); fail(); } catch (InvalidDataConversionException e) {}
- try { model.getList("f3a", l); fail(); } catch (InvalidDataConversionException e) {}
- try { model.getList("f4a", l); fail(); } catch (InvalidDataConversionException e) {}
- assertEquals("[{f5a:'a'}]", model.getList("f5", l).toString());
- assertEquals("[{f6a:'a'}]", model.getList("f6", l).toString());
- assertEquals("[{f5a:'a'}]", model.getList("f7", l).toString());
- assertEquals("[{f6a:'a'}]", model.getList("f8", l).toString());
-
- try { model.getObjectList("f1"); fail(); } catch (InvalidDataConversionException e) {}
- try { model.getObjectList("f2"); fail(); } catch (InvalidDataConversionException e) {}
- try { model.getObjectList("f3"); fail(); } catch (InvalidDataConversionException e) {}
- try { model.getObjectList("f4"); fail(); } catch (InvalidDataConversionException e) {}
- try { model.getObjectList("f2a"); fail(); } catch (InvalidDataConversionException e) {}
- try { model.getObjectList("f3a"); fail(); } catch (InvalidDataConversionException e) {}
- try { model.getObjectList("f4a"); fail(); } catch (InvalidDataConversionException e) {}
- assertEquals("[{f5a:'a'}]", model.getObjectList("f5").toString());
- assertEquals("[{f6a:'a'}]", model.getObjectList("f6").toString());
- assertEquals("[{f5a:'a'}]", model.getObjectList("f7").toString());
- assertEquals("[{f6a:'a'}]", model.getObjectList("f8").toString());
-
- try { model.getObjectList("f1", l); fail(); } catch (InvalidDataConversionException e) {}
- try { model.getObjectList("f2", l); fail(); } catch (InvalidDataConversionException e) {}
- try { model.getObjectList("f3", l); fail(); } catch (InvalidDataConversionException e) {}
- try { model.getObjectList("f4", l); fail(); } catch (InvalidDataConversionException e) {}
- try { model.getObjectList("f2a", l); fail(); } catch (InvalidDataConversionException e) {}
- try { model.getObjectList("f3a", l); fail(); } catch (InvalidDataConversionException e) {}
- try { model.getObjectList("f4a", l); fail(); } catch (InvalidDataConversionException e) {}
- assertEquals("[{f5a:'a'}]", model.getObjectList("f5", l).toString());
- assertEquals("[{f6a:'a'}]", model.getObjectList("f6", l).toString());
- assertEquals("[{f5a:'a'}]", model.getObjectList("f7", l).toString());
- assertEquals("[{f6a:'a'}]", model.getObjectList("f8", l).toString());
- }
-
- public static class A {
- public String f1;
- public int f2;
- public long f3;
- public boolean f4;
- public Integer f2a;
- public Long f3a;
- public Boolean f4a;
- public Map f5;
- public List f6;
- public ObjectMap f7;
- public ObjectList f8;
-
- public A init() {
- f1 = "1";
- f2 = 2;
- f3 = 3l;
- f4 = true;
- f2a = 2;
- f3a = 3l;
- f4a = true;
- try {
- f5 = new ObjectMap("{f5a:'a'}");
- f6 = new ObjectList("[{f6a:'a'}]");
- f7 = new ObjectMap("{f5a:'a'}");
- f8 = new ObjectList("[{f6a:'a'}]");
- } catch (ParseException e) {
- throw new RuntimeException(e);
- }
- return this;
- }
- }
-
- //====================================================================================================
- // invokeMethod(String url, String method, String args)
- //====================================================================================================
- @Test
- public void testInvokeMethod() throws Exception {
-
- PojoRest model = new PojoRest(new AddressBook().init());
- assertEquals("Person(name=Bill Clinton,age=65)", model.invokeMethod("0", "toString", ""));
-
- model = new PojoRest(new AddressBook().init(), JsonParser.DEFAULT);
- assertEquals("Person(name=Bill Clinton,age=65)", model.invokeMethod("0", "toString", ""));
- assertEquals("NY", model.invokeMethod("0/addresses/0/state", "toString", ""));
- assertNull(model.invokeMethod("1", "toString", ""));
- }
-
- //====================================================================================================
- // getPublicMethods(String url)
- //====================================================================================================
- @Test
- public void testGetPublicMethods() throws Exception {
- PojoRest model = new PojoRest(new AddressBook().init());
- assertTrue(JsonSerializer.DEFAULT_LAX.toString(model.getPublicMethods("0")).contains("'toString'"));
- assertTrue(JsonSerializer.DEFAULT_LAX.toString(model.getPublicMethods("0/addresses/0/state")).contains("'toString'"));
- assertNull(model.getPublicMethods("1"));
- }
-
- //====================================================================================================
- // getClassMeta(String url)
- //====================================================================================================
- @Test
- public void testGetClassMeta() throws Exception {
- PojoRest model = new PojoRest(new AddressBook().init());
- assertEquals("Person", model.getClassMeta("0").getInnerClass().getSimpleName());
- assertEquals("String", model.getClassMeta("0/addresses/0/state").getInnerClass().getSimpleName());
- assertNull(model.getClassMeta("1"));
- assertNull(model.getClassMeta("0/addresses/1/state"));
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/utils/CT_SimpleMap.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/utils/CT_SimpleMap.java b/org.apache.juneau/src/test/java/org/apache/juneau/utils/CT_SimpleMap.java
deleted file mode 100755
index 039f03b..0000000
--- a/org.apache.juneau/src/test/java/org/apache/juneau/utils/CT_SimpleMap.java
+++ /dev/null
@@ -1,48 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.utils;
-
-import static org.apache.juneau.TestUtils.*;
-import static org.junit.Assert.*;
-
-import org.apache.juneau.internal.*;
-import org.junit.*;
-
-public class CT_SimpleMap {
-
- @Test
- public void doTest() throws Exception {
- String[] keys = {"a","b"};
- Object[] vals = {"A","B"};
- SimpleMap m = new SimpleMap(keys, vals);
- assertEquals(2, m.size());
- assertEquals("A", m.get("a"));
- assertEquals("B", m.get("b"));
- assertObjectEquals("{a:'A',b:'B'}", m);
- assertObjectEquals("['a','b']", m.keySet());
- m.put("a", "1");
- assertObjectEquals("{a:'1',b:'B'}", m);
- m.entrySet().iterator().next().setValue("2");
- assertObjectEquals("{a:'2',b:'B'}", m);
- try { m.put("c", "1"); fail(); } catch (IllegalArgumentException e) {}
-
- assertNull(m.get("c"));
-
- try { m = new SimpleMap(null, vals); fail(); } catch (IllegalArgumentException e) {}
- try { m = new SimpleMap(keys, null); fail(); } catch (IllegalArgumentException e) {}
- try { m = new SimpleMap(keys, new Object[0]); fail(); } catch (IllegalArgumentException e) {}
-
- keys[0] = null;
- try { m = new SimpleMap(keys, vals); fail(); } catch (IllegalArgumentException e) {}
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/utils/CT_StringBuilderWriter.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/utils/CT_StringBuilderWriter.java b/org.apache.juneau/src/test/java/org/apache/juneau/utils/CT_StringBuilderWriter.java
deleted file mode 100755
index 841b78e..0000000
--- a/org.apache.juneau/src/test/java/org/apache/juneau/utils/CT_StringBuilderWriter.java
+++ /dev/null
@@ -1,59 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.utils;
-
-import static org.junit.Assert.*;
-
-import org.apache.juneau.internal.*;
-import org.junit.*;
-
-public class CT_StringBuilderWriter {
-
- //====================================================================================================
- // Basic tests
- //====================================================================================================
- @Test
- public void test() throws Exception {
- StringBuilderWriter sbw = new StringBuilderWriter();
- sbw.write("abc");
- assertEquals("abc", sbw.toString());
- sbw.append("abc");
- assertEquals("abcabc", sbw.toString());
- sbw.write("abc", 1, 1);
- assertEquals("abcabcb", sbw.toString());
- sbw.append("abc", 1, 2);
- assertEquals("abcabcbb", sbw.toString());
- sbw.write((String)null);
- assertEquals("abcabcbbnull", sbw.toString());
- sbw.append((String)null);
- assertEquals("abcabcbbnullnull", sbw.toString());
- sbw.append((String)null,0,4);
- assertEquals("abcabcbbnullnullnull", sbw.toString());
-
- char[] buff = "abc".toCharArray();
- sbw = new StringBuilderWriter();
- sbw.write(buff, 0, buff.length);
- assertEquals("abc", sbw.toString());
- sbw.write(buff, 0, 0);
- assertEquals("abc", sbw.toString());
-
- try { sbw.write(buff, -1, buff.length); fail(); } catch (IndexOutOfBoundsException e) {}
- try { sbw.write(buff, buff.length+1, 0); fail(); } catch (IndexOutOfBoundsException e) {}
- try { sbw.write(buff, buff.length-1, 2); fail(); } catch (IndexOutOfBoundsException e) {}
- try { sbw.write(buff, 0, buff.length+1); fail(); } catch (IndexOutOfBoundsException e) {}
- try { sbw.write(buff, 0, -1); fail(); } catch (IndexOutOfBoundsException e) {}
-
- sbw.flush();
- sbw.close();
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/utils/CT_StringUtils.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/utils/CT_StringUtils.java b/org.apache.juneau/src/test/java/org/apache/juneau/utils/CT_StringUtils.java
deleted file mode 100755
index ba2c84f..0000000
--- a/org.apache.juneau/src/test/java/org/apache/juneau/utils/CT_StringUtils.java
+++ /dev/null
@@ -1,676 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.utils;
-
-import static org.apache.juneau.TestUtils.*;
-import static org.apache.juneau.internal.StringUtils.*;
-import static org.junit.Assert.*;
-
-import java.io.ObjectInputStream.*;
-import java.math.*;
-import java.util.*;
-import java.util.concurrent.atomic.*;
-
-import org.apache.juneau.*;
-import org.apache.juneau.json.*;
-import org.apache.juneau.parser.*;
-import org.apache.juneau.serializer.*;
-import org.apache.juneau.transforms.*;
-import org.junit.*;
-
-public class CT_StringUtils {
-
- //====================================================================================================
- // isNumeric(String,Class)
- // parseNumber(String,Class)
- //====================================================================================================
- @Test
- public void testParseNumber() throws Exception {
-
- // Integers
- assertTrue(isNumeric("123"));
- assertEquals(123, parseNumber("123", null));
- assertEquals(123, parseNumber("123", Integer.class));
- assertEquals((short)123, parseNumber("123", Short.class));
- assertEquals((long)123, parseNumber("123", Long.class));
-
- assertTrue(isNumeric("0123"));
- assertEquals(0123, parseNumber("0123", null));
-
- assertTrue(isNumeric("-0123"));
- assertEquals(-0123, parseNumber("-0123", null));
-
- // Hexadecimal
- assertTrue(isNumeric("0x123"));
- assertEquals(0x123, parseNumber("0x123", null));
-
- assertTrue(isNumeric("-0x123"));
- assertEquals(-0x123, parseNumber("-0x123", null));
-
- assertTrue(isNumeric("0X123"));
- assertEquals(0X123, parseNumber("0X123", null));
-
- assertTrue(isNumeric("-0X123"));
- assertEquals(-0X123, parseNumber("-0X123", null));
-
- assertTrue(isNumeric("#123"));
- assertEquals(0x123, parseNumber("#123", null));
-
- assertTrue(isNumeric("-#123"));
- assertEquals(-0x123, parseNumber("-#123", null));
-
- assertFalse(isNumeric("x123"));
- assertFalse(isNumeric("0x123x"));
-
- // Decimal
- assertTrue(isNumeric("0.123"));
- assertEquals(0.123f, parseNumber("0.123", null));
-
- assertTrue(isNumeric("-0.123"));
- assertEquals(-0.123f, parseNumber("-0.123", null));
-
- assertTrue(isNumeric(".123"));
- assertEquals(.123f, parseNumber(".123", null));
-
- assertTrue(isNumeric("-.123"));
- assertEquals(-.123f, parseNumber("-.123", null));
-
- assertFalse(isNumeric("0.123.4"));
-
- // Scientific notation
- assertTrue(isNumeric("1e1"));
- assertEquals(1e1f, parseNumber("1e1", null));
-
- assertTrue(isNumeric("1e+1"));
- assertEquals(1e+1f, parseNumber("1e+1", null));
-
- assertTrue(isNumeric("1e-1"));
- assertEquals(1e-1f, parseNumber("1e-1", null));
-
- assertTrue(isNumeric("1.1e1"));
- assertEquals(1.1e1f, parseNumber("1.1e1", null));
-
- assertTrue(isNumeric("1.1e+1"));
- assertEquals(1.1e+1f, parseNumber("1.1e+1", null));
-
- assertTrue(isNumeric("1.1e-1"));
- assertEquals(1.1e-1f, parseNumber("1.1e-1", null));
-
- assertTrue(isNumeric(".1e1"));
- assertEquals(.1e1f, parseNumber(".1e1", null));
-
- assertTrue(isNumeric(".1e+1"));
- assertEquals(.1e+1f, parseNumber(".1e+1", null));
-
- assertTrue(isNumeric(".1e-1"));
- assertEquals(.1e-1f, parseNumber(".1e-1", null));
-
- // Hexadecimal + scientific
- assertTrue(isNumeric("0x123e1"));
- assertEquals(0x123e1, parseNumber("0x123e1", null));
-
- try {
- parseNumber("x", Number.class);
- fail();
- } catch (ParseException e) {
- assertTrue(e.getCause() instanceof NumberFormatException);
- }
-
- try {
- parseNumber("x", null);
- fail();
- } catch (ParseException e) {
- assertTrue(e.getCause() instanceof NumberFormatException);
- }
-
- try {
- parseNumber("x", BadNumber.class);
- fail();
- } catch (ParseException e) {
- assertTrue(e.getLocalizedMessage().startsWith("Unsupported Number type"));
- }
- }
-
- @SuppressWarnings("serial")
- private abstract static class BadNumber extends Number {}
-
- //====================================================================================================
- // parseNumber(ParserReader,Class)
- //====================================================================================================
- @SuppressWarnings({ "rawtypes", "unchecked" })
- @Test
- public void testParseNumberFromReader() throws Exception {
- ParserReader in;
- Number n;
-
- for (Class c : new Class[]{ Integer.class, Double.class, Float.class, Long.class, Short.class, Byte.class, BigInteger.class, BigDecimal.class, Number.class, AtomicInteger.class, AtomicLong.class}) {
- in = new ParserReader("123'");
- n = parseNumber(in, c);
- assertTrue(c.isInstance(n));
- assertEquals(123, n.intValue());
- }
- }
-
- //====================================================================================================
- // test - Basic tests
- //====================================================================================================
- @Test
- public void testNumberRanges() throws Exception {
- String s;
-
- // An integer range is -2,147,483,648 to 2,147,483,647
-
- assertFalse(isNumeric(null));
- assertFalse(isNumeric(""));
- assertFalse(isNumeric("x"));
-
- s = "-2147483648";
- assertTrue(isNumeric(s));
- assertTrue(parseNumber(s, null) instanceof Integer);
- assertEquals(-2147483648, parseNumber(s, null));
-
- s = "2147483647";
- assertTrue(isNumeric(s));
- assertTrue(parseNumber(s, null) instanceof Integer);
- assertEquals(2147483647, parseNumber(s, null));
-
- s = "-2147483649";
- assertTrue(isNumeric(s));
- assertTrue(parseNumber(s, null) instanceof Long);
- assertEquals(-2147483649L, parseNumber(s, null));
-
- s = "2147483648";
- assertTrue(isNumeric(s));
- assertTrue(parseNumber(s, null) instanceof Long);
- assertEquals(2147483648L, parseNumber(s, null));
-
- // An long range is -9,223,372,036,854,775,808 to +9,223,372,036,854,775,807
-
- s = "-9223372036854775808";
- assertTrue(isNumeric(s));
- assertTrue(parseNumber(s, null) instanceof Long);
- assertEquals(-9223372036854775808L, parseNumber(s, null));
-
- s = "9223372036854775807";
- assertTrue(isNumeric(s));
- assertTrue(parseNumber(s, null) instanceof Long);
- assertEquals(9223372036854775807L, parseNumber(s, null));
-
- // Anything that falls outside this range should be a double.
-
- s = "-9223372036854775809";
- assertTrue(isNumeric(s));
- assertTrue(parseNumber(s, null) instanceof Double);
- assertEquals(-9223372036854775808L, parseNumber(s, null).longValue());
- assertEquals(-9.223372036854776E18, parseNumber(s, null));
-
- s = "9223372036854775808";
- assertTrue(isNumeric(s));
- assertTrue(parseNumber(s, null) instanceof Double);
- assertEquals(9223372036854775807L, parseNumber(s, null).longValue());
- assertEquals(9.223372036854776E18, parseNumber(s, null));
-
- // Check case where string is longer than 20 characters since it's a different code path.
-
- s = "-123456789012345678901";
- assertTrue(isNumeric(s));
- assertTrue(parseNumber(s, null) instanceof Double);
- assertEquals(-9223372036854775808L, parseNumber(s, null).longValue());
- assertEquals(-1.2345678901234568E20, parseNumber(s, null));
-
- s = "123456789012345678901";
- assertTrue(isNumeric(s));
- assertTrue(parseNumber(s, null) instanceof Double);
- assertEquals(9223372036854775807L, parseNumber(s, null).longValue());
- assertEquals(1.2345678901234568E20, parseNumber(s, null));
-
- // Autodetected floating point numbers smaller than Float.MAX_VALUE
- s = String.valueOf(Float.MAX_VALUE / 2);
- assertTrue(isNumeric(s));
- assertTrue(parseNumber(s, null) instanceof Float);
- assertEquals(1.7014117E38f, parseNumber(s, null));
-
- s = String.valueOf((-Float.MAX_VALUE) / 2);
- assertTrue(isNumeric(s));
- assertTrue(parseNumber(s, null) instanceof Float);
- assertEquals(-1.7014117E38f, parseNumber(s, null));
-
- // Autodetected floating point numbers larger than Float.MAX_VALUE
- s = String.valueOf((double)Float.MAX_VALUE * 2);
- assertTrue(isNumeric(s));
- assertTrue(parseNumber(s, null) instanceof Double);
- assertEquals("6.805646932770577E38", parseNumber(s, null).toString());
-
- s = String.valueOf((double)Float.MAX_VALUE * -2);
- assertTrue(isNumeric(s));
- assertTrue(parseNumber(s, null) instanceof Double);
- assertEquals("-6.805646932770577E38", parseNumber(s, null).toString());
-
- s = String.valueOf("214748364x");
- assertFalse(isNumeric(s));
- try {
- parseNumber(s, Number.class);
- } catch (ParseException e) {}
-
- s = String.valueOf("2147483640x");
- assertFalse(isNumeric(s));
- try {
- parseNumber(s, Long.class);
- } catch (ParseException e) {}
-
-
- }
-
- //====================================================================================================
- // testReplaceVars
- //====================================================================================================
- @Test
- public void testReplaceVars() throws Exception {
- ObjectMap m = new ObjectMap("{a:'A',b:1,c:true,d:'{e}',e:'E{f}E',f:'F',g:'{a}',h:'a',i:null}");
-
- String s = "xxx";
- assertEquals("xxx", replaceVars(s, m));
-
- s = "{a}";
- assertEquals("A", replaceVars(s, m));
- s = "{a}{a}";
- assertEquals("AA", replaceVars(s, m));
- s = "x{a}x";
- assertEquals("xAx", replaceVars(s, m));
- s = "x{a}x{a}x";
- assertEquals("xAxAx", replaceVars(s, m));
-
- s = "{b}";
- assertEquals("1", replaceVars(s, m));
- s = "{b}{b}";
- assertEquals("11", replaceVars(s, m));
- s = "x{b}x";
- assertEquals("x1x", replaceVars(s, m));
- s = "x{b}x{b}x";
- assertEquals("x1x1x", replaceVars(s, m));
-
- s = "{c}";
- assertEquals("true", replaceVars(s, m));
- s = "{c}{c}";
- assertEquals("truetrue", replaceVars(s, m));
- s = "x{c}x{c}x";
- assertEquals("xtruextruex", replaceVars(s, m));
-
- s = "{d}";
- assertEquals("EFE", replaceVars(s, m));
- s = "{d}{d}";
- assertEquals("EFEEFE", replaceVars(s, m));
- s = "x{d}x";
- assertEquals("xEFEx", replaceVars(s, m));
- s = "x{d}x{d}x";
- assertEquals("xEFExEFEx", replaceVars(s, m));
-
- s = "{g}";
- assertEquals("A", replaceVars(s, m));
- s = "{g}{g}";
- assertEquals("AA", replaceVars(s, m));
- s = "x{g}x";
- assertEquals("xAx", replaceVars(s, m));
- s = "x{g}x{g}x";
- assertEquals("xAxAx", replaceVars(s, m));
-
- s = "{x}";
- assertEquals("{x}", replaceVars(s, m));
- s = "{x}{x}";
- assertEquals("{x}{x}", replaceVars(s, m));
- s = "x{x}x{x}x";
- assertEquals("x{x}x{x}x", replaceVars(s, m));
-
- s = "{{g}}";
- assertEquals("{A}", replaceVars(s, m));
- s = "{{h}}";
- assertEquals("A", replaceVars(s, m));
-
- s = "{{i}}";
- assertEquals("{}", replaceVars(s, m));
- s = "{}";
- assertEquals("{}", replaceVars(s, m));
- }
-
- //====================================================================================================
- // isFloat(String)
- //====================================================================================================
- @Test
- public void testisFloat() throws Exception {
- String[] valid = {
- "+1.0",
- "-1.0",
- ".0",
- "NaN",
- "Infinity",
- "1e1",
- "-1e-1",
- "+1e+1",
- "-1.1e-1",
- "+1.1e+1",
- "1.1f",
- "1.1F",
- "1.1d",
- "1.1D",
- "0x1.fffffffffffffp1023",
- "0x1.FFFFFFFFFFFFFP1023",
- };
- for (String s : valid)
- assertTrue(isFloat(s));
-
- String[] invalid = {
- null,
- "",
- "a",
- "+",
- "-",
- ".",
- "a",
- "+a",
- "11a",
- };
- for (String s : invalid)
- assertFalse(isFloat(s));
- }
-
- //====================================================================================================
- // isDecimal(String)
- //====================================================================================================
- @Test
- public void testisDecimal() throws Exception {
- String[] valid = {
- "+1",
- "-1",
- "0x123",
- "0X123",
- "0xdef",
- "0XDEF",
- "#def",
- "#DEF",
- "0123",
- };
- for (String s : valid)
- assertTrue(isDecimal(s));
-
- String[] invalid = {
- null,
- "",
- "a",
- "+",
- "-",
- ".",
- "0xdeg",
- "0XDEG",
- "#deg",
- "#DEG",
- "0128",
- "012A",
- };
- for (String s : invalid)
- assertFalse(isDecimal(s));
- }
-
- //====================================================================================================
- // join(Object[],String)
- // join(int[],String)
- // join(Collection,String)
- // join(Object[],char)
- // join(int[],char)
- // join(Collection,char)
- //====================================================================================================
- @Test
- public void testJoin() throws Exception {
- assertNull(join((Object[])null, ","));
- assertEquals("1", join(new Object[]{1}, ","));
- assertEquals("1,2", join(new Object[]{1,2}, ","));
-
- assertNull(join((int[])null, ","));
- assertEquals("1", join(new int[]{1}, ","));
- assertEquals("1,2", join(new int[]{1,2}, ","));
-
- assertNull(join((Collection<?>)null, ","));
- assertEquals("1", join(Arrays.asList(new Integer[]{1}), ","));
- assertEquals("1,2", join(Arrays.asList(new Integer[]{1,2}), ","));
-
- assertNull(join((Object[])null, ','));
- assertEquals("1", join(new Object[]{1}, ','));
- assertEquals("1,2", join(new Object[]{1,2}, ','));
-
- assertNull(join((int[])null, ','));
- assertEquals("1", join(new int[]{1}, ','));
- assertEquals("1,2", join(new int[]{1,2}, ','));
-
- assertNull(join((Collection<?>)null, ','));
- assertEquals("1", join(Arrays.asList(new Integer[]{1}), ','));
- assertEquals("1,2", join(Arrays.asList(new Integer[]{1,2}), ','));
- }
-
- //====================================================================================================
- // split(String,char)
- //====================================================================================================
- @Test
- public void testSplit() throws Exception {
- String[] r;
-
- assertNull(split(null, ','));
- assertObjectEquals("[]", split("", ','));
- assertObjectEquals("['1']", split("1", ','));
- assertObjectEquals("['1','2']", split("1,2", ','));
- assertObjectEquals("['1,2']", split("1\\,2", ','));
-
- r = split("1\\\\,2", ',');
- assertEquals("1\\", r[0]);
- assertEquals("2", r[1]);
-
- r = split("1\\\\\\,2", ',');
- assertEquals(1, r.length);
- assertEquals("1\\,2", r[0]);
-
- r = split("1,2\\", ',');
- assertEquals("2\\", r[1]);
-
- r = split("1,2\\\\", ',');
- assertEquals("2\\", r[1]);
-
- r = split("1,2\\,", ',');
- assertEquals("2,", r[1]);
-
- r = split("1,2\\\\,", ',');
- assertEquals("2\\", r[1]);
- assertEquals("", r[2]);
- }
-
- //====================================================================================================
- // nullIfEmpty(String)
- //====================================================================================================
- @Test
- public void testNullIfEmpty() throws Exception {
- assertNull(nullIfEmpty(null));
- assertNull(nullIfEmpty(""));
- assertNotNull(nullIfEmpty("x"));
- }
-
- //====================================================================================================
- // unescapeChars(String,char[],char)
- //====================================================================================================
- @Test
- public void testUnescapeChars() throws Exception {
- char[] toEscape = {'\\',',','|'};
- char escape = '\\';
-
- assertNull(unEscapeChars(null, toEscape, escape));
- assertEquals("xxx", unEscapeChars("xxx", new char[0], escape));
- assertEquals("xxx", unEscapeChars("xxx", null, escape));
- assertEquals("xxx", unEscapeChars("xxx", toEscape, (char)0));
-
- assertEquals("xxx", unEscapeChars("xxx", toEscape, escape));
- assertEquals("x,xx", unEscapeChars("x\\,xx", toEscape, escape));
- assertEquals("x\\xx", unEscapeChars("x\\xx", toEscape, escape));
- assertEquals("x\\,xx", unEscapeChars("x\\\\,xx", toEscape, escape));
- assertEquals("x\\,xx", unEscapeChars("x\\\\\\,xx", toEscape, escape));
- assertEquals("\\", unEscapeChars("\\", toEscape, escape));
- assertEquals(",", unEscapeChars("\\,", toEscape, escape));
- assertEquals("|", unEscapeChars("\\|", toEscape, escape));
-
- toEscape = new char[] {',','|'};
- assertEquals("x\\\\xx", unEscapeChars("x\\\\xx", toEscape, escape));
- }
-
- //====================================================================================================
- // decodeHex(String)
- //====================================================================================================
- @Test
- public void testDecodeHex() throws Exception {
- assertNull(decodeHex(null));
- assertEquals("19azAZ", decodeHex("19azAZ"));
- assertEquals("[0][1][ffff]", decodeHex("\u0000\u0001\uFFFF"));
- }
-
- //====================================================================================================
- // startsWith(String,char)
- //====================================================================================================
- @Test
- public void testStartsWith() throws Exception {
- assertFalse(startsWith(null, 'a'));
- assertFalse(startsWith("", 'a'));
- assertTrue(startsWith("a", 'a'));
- assertTrue(startsWith("ab", 'a'));
- }
-
- //====================================================================================================
- // endsWith(String,char)
- //====================================================================================================
- @Test
- public void testEndsWith() throws Exception {
- assertFalse(endsWith(null, 'a'));
- assertFalse(endsWith("", 'a'));
- assertTrue(endsWith("a", 'a'));
- assertTrue(endsWith("ba", 'a'));
- }
-
- //====================================================================================================
- // base64EncodeToString(String)
- // base64DecodeToString(String)
- //====================================================================================================
- @Test
- public void testBase64EncodeToString() throws Exception {
- String s = null;
-
- assertEquals(s, base64DecodeToString(base64EncodeToString(s)));
- s = "";
- assertEquals(s, base64DecodeToString(base64EncodeToString(s)));
- s = "foobar";
- assertEquals(s, base64DecodeToString(base64EncodeToString(s)));
- s = "\u0000\uffff";
- assertEquals(s, base64DecodeToString(base64EncodeToString(s)));
-
- try {
- base64Decode("a");
- fail();
- } catch (IllegalArgumentException e) {
- assertEquals("Invalid BASE64 string length. Must be multiple of 4.", e.getLocalizedMessage());
- // OK.
- }
- try {
- base64Decode("aaa");
- fail();
- } catch (IllegalArgumentException e) {
- // OK.
- }
- }
-
- //====================================================================================================
- // generateUUID(String)
- //====================================================================================================
- @Test
- public void testGenerateUUID() throws Exception {
- for (int i = 0; i < 10; i++) {
- String s = generateUUID(i);
- assertEquals(i, s.length());
- for (char c : s.toCharArray())
- assertTrue(Character.isLowerCase(c) || Character.isDigit(c));
- }
- }
-
- //====================================================================================================
- // trim(String)
- //====================================================================================================
- @Test
- public void testTrim() throws Exception {
- assertNull(trim(null));
- assertEquals("", trim(""));
- assertEquals("", trim(" "));
- }
-
- //====================================================================================================
- // parseISO8601Date(String)
- //====================================================================================================
- @Test
- public void testParseISO8601Date() throws Exception {
- WriterSerializer s = new JsonSerializer.Simple().addTransforms(DateTransform.ISO8601DTPNZ.class);
-
- assertNull(parseISO8601Date(null));
- assertNull(parseISO8601Date(""));
-
- assertEquals("'2000-01-01T00:00:00.000'", s.serialize(parseISO8601Date("2000")));
- assertEquals("'2000-02-01T00:00:00.000'", s.serialize(parseISO8601Date("2000-02")));
- assertEquals("'2000-02-03T00:00:00.000'", s.serialize(parseISO8601Date("2000-02-03")));
- assertEquals("'2000-02-03T04:00:00.000'", s.serialize(parseISO8601Date("2000-02-03T04")));
- assertEquals("'2000-02-03T04:05:00.000'", s.serialize(parseISO8601Date("2000-02-03T04:05")));
- assertEquals("'2000-02-03T04:05:06.000'", s.serialize(parseISO8601Date("2000-02-03T04:05:06")));
- assertEquals("'2000-02-03T04:00:00.000'", s.serialize(parseISO8601Date("2000-02-03 04")));
- assertEquals("'2000-02-03T04:05:00.000'", s.serialize(parseISO8601Date("2000-02-03 04:05")));
- assertEquals("'2000-02-03T04:05:06.000'", s.serialize(parseISO8601Date("2000-02-03 04:05:06")));
-
- // ISO8601 doesn't support milliseconds, so it gets trimmed.
- assertEquals("'2000-02-03T04:05:06.000'", s.serialize(parseISO8601Date("2000-02-03 04:05:06,789")));
- }
-
- //====================================================================================================
- // pathStartsWith(String, String)
- //====================================================================================================
- @Test
- public void testPathStartsWith() throws Exception {
- assertTrue(pathStartsWith("foo", "foo"));
- assertTrue(pathStartsWith("foo/bar", "foo"));
- assertFalse(pathStartsWith("foo2/bar", "foo"));
- assertFalse(pathStartsWith("foo2", "foo"));
- assertFalse(pathStartsWith("foo2", ""));
- }
-
- //====================================================================================================
- // getField(int, String, char)
- //====================================================================================================
- @Test
- public void testGetField() {
- String in = "0,1,2";
- assertEquals("0", getField(0, in, ','));
- assertEquals("1", getField(1, in, ','));
- assertEquals("2", getField(2, in, ','));
- assertEquals("", getField(3, in, ','));
-
- in = ",1,,3,";
- assertEquals("", getField(0, in, ','));
- assertEquals("1", getField(1, in, ','));
- assertEquals("", getField(2, in, ','));
- assertEquals("3", getField(3, in, ','));
- assertEquals("", getField(4, in, ','));
- assertEquals("", getField(5, in, ','));
-
- in = "";
- assertEquals("", getField(0, in, ','));
-
- in = null;
- assertEquals("", getField(0, in, ','));
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/utils/CT_StringVarResolver.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/utils/CT_StringVarResolver.java b/org.apache.juneau/src/test/java/org/apache/juneau/utils/CT_StringVarResolver.java
deleted file mode 100755
index b005d69..0000000
--- a/org.apache.juneau/src/test/java/org/apache/juneau/utils/CT_StringVarResolver.java
+++ /dev/null
@@ -1,332 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.utils;
-
-import static org.junit.Assert.*;
-
-import org.apache.juneau.internal.*;
-import org.apache.juneau.svl.*;
-import org.junit.*;
-
-public class CT_StringVarResolver {
-
- //====================================================================================================
- // test - Basic tests
- //====================================================================================================
- @Test
- public void test() throws Exception {
- VarResolver vr = new VarResolver().addVars(XVar.class);
- String t;
-
- t = null;
- assertEquals("", vr.resolve(t));
-
- t = "";
- assertEquals("", vr.resolve(t));
-
- t = "foo";
- assertEquals("foo", vr.resolve(t));
-
- t = "$X{y}";
- assertEquals("xyx", vr.resolve(t));
-
- t = "$X{y}x";
- assertEquals("xyxx", vr.resolve(t));
-
- t = "x$X{y}";
- assertEquals("xxyx", vr.resolve(t));
-
- t = "$X{y}$X{y}";
- assertEquals("xyxxyx", vr.resolve(t));
-
- t = "z$X{y}z$X{y}z";
- assertEquals("zxyxzxyxz", vr.resolve(t));
-
- t = "$X{$X{y}}";
- assertEquals("xxyxx", vr.resolve(t));
-
- t = "$X{z$X{y}z}";
- assertEquals("xzxyxzx", vr.resolve(t));
-
- t = "$X.{y}";
- assertEquals("$X.{y}", vr.resolve(t));
-
- t = "z$X.{y}z";
- assertEquals("z$X.{y}z", vr.resolve(t));
-
- t = "z$X.{$X.{z}}z";
- assertEquals("z$X.{$X.{z}}z", vr.resolve(t));
-
- // Non-existent vars
- t = "$Y{y}";
- assertEquals("$Y{y}", vr.resolve(t));
-
- t = "$Y{y}x";
- assertEquals("$Y{y}x", vr.resolve(t));
-
- t = "x$Y{y}";
- assertEquals("x$Y{y}", vr.resolve(t));
-
- // Incomplete vars
- // TODO - fix
-// t = "x$Y{y";
-// assertEquals("x$Y{y", vr.resolve(t));
- }
-
- public static class XVar extends SimpleVar {
- public XVar() {
- super("X");
- }
- @Override
- public String resolve(VarResolverSession session, String arg) {
- return "x" + arg + "x";
- }
- }
-
- //====================================================================================================
- // test - No-name variables
- //====================================================================================================
- @Test
- public void test2() throws Exception {
- VarResolver vr = new VarResolver().addVars(BlankVar.class);
- String t;
-
- t = "${y}";
- assertEquals("xyx", vr.resolve(t));
-
- t = "${${y}}";
- assertEquals("xxyxx", vr.resolve(t));
-
- t = "${${y}${y}}";
- assertEquals("xxyxxyxx", vr.resolve(t));
-
- t = "z${z${y}z}z";
- assertEquals("zxzxyxzxz", vr.resolve(t));
- }
-
- public static class BlankVar extends SimpleVar {
- public BlankVar() {
- super("");
- }
- @Override
- public String resolve(VarResolverSession session, String arg) {
- return "x" + arg + "x";
- }
- }
-
- //====================================================================================================
- // test - No-name variables
- //====================================================================================================
- @Test
- public void testEscaped$() throws Exception {
- VarResolver vr = new VarResolver().addVars(BlankVar.class);
- String t;
-
- t = "${y}";
- assertEquals("xyx", vr.resolve(t));
- t = "\\${y}";
- assertEquals("${y}", vr.resolve(t));
-
- t = "foo\\${y}foo";
- assertEquals("foo${y}foo", vr.resolve(t));
-
- // TODO - This doesn't work.
- //t = "${\\${y}}";
- //assertEquals("x${y}x", vr.resolve(t));
- }
-
- //====================================================================================================
- // test - Escape sequences.
- //====================================================================================================
- @Test
- public void testEscapedSequences() throws Exception {
- VarResolver vr = new VarResolver().addVars(XVar.class);
- String t;
- char b = '\\';
-
- t = "A|A".replace('|',b);
- assertEquals("A|A".replace('|',b), vr.resolve(t));
- t = "A||A".replace('|',b);
- assertEquals("A|A".replace('|',b), vr.resolve(t));
- t = "A|A$X{B}".replace('|',b);
- assertEquals("A|AxBx".replace('|',b), vr.resolve(t));
- t = "A||A$X{B}".replace('|',b);
- assertEquals("A|AxBx".replace('|',b), vr.resolve(t));
- t = "A|$X{B}".replace('|',b);
- assertEquals("A$X{B}".replace('|',b), vr.resolve(t));
- t = "A||$X{B}".replace('|',b);
- assertEquals("A|xBx".replace('|',b), vr.resolve(t));
- t = "A$X|{B}".replace('|',b);
- assertEquals("A$X{B}".replace('|',b), vr.resolve(t));
- t = "A$X{B|}".replace('|',b);
- assertEquals("A$X{B}".replace('|',b), vr.resolve(t));
- t = "A$X{B}|".replace('|',b);
- assertEquals("AxBx|".replace('|',b), vr.resolve(t));
- }
-
- //====================================================================================================
- // Test $E variables
- //====================================================================================================
- @Test
- public void test$E() throws Exception {
- String t;
-
- t = "$E{PATH}";
- assertFalse(StringUtils.isEmpty(VarResolver.DEFAULT.resolve(t)));
- }
-
- //====================================================================================================
- // Test that StringResolver(parent) works as expected.
- //====================================================================================================
- @Test
- public void testParent() throws Exception {
- VarResolver svr = VarResolver.DEFAULT.clone().addVars(XMultipartVar.class);
- String t;
- System.setProperty("a", "a1");
- System.setProperty("b", "b1");
-
- t = "$X{$S{a},$S{b}}";
- assertEquals("a1+b1", svr.resolve(t));
- t = "$X{$S{a}}";
- assertEquals("a1", svr.resolve(t));
- }
-
- public static class XMultipartVar extends MultipartVar {
- public XMultipartVar() {
- super("X");
- }
- @Override /* MultipartVar */
- public String resolve(VarResolverSession session, String[] args) {
- return StringUtils.join(args, '+');
- }
- }
-
- //====================================================================================================
- // Test false triggers.
- //====================================================================================================
- @Test
- public void testFalseTriggers() throws Exception {
- VarResolver svr = VarResolver.DEFAULT.clone();
- String in = null;
-
- // Should reject names with characters outside A-Za-z
- for (Class<?> c : new Class[]{InvalidVar1.class, InvalidVar2.class, InvalidVar3.class, InvalidVar4.class, InvalidVar5.class}) {
- try {
- svr.addVars(c);
- fail();
- } catch (IllegalArgumentException e) {
- assertEquals("Invalid var name. Must consist of only uppercase and lowercase ASCII letters.", e.getLocalizedMessage());
- }
- }
-
- // These should all be unchanged.
- in = "$@{foobar}";
- assertEquals(in, svr.resolve(in));
- in = "$[{foobar}";
- assertEquals(in, svr.resolve(in));
- in = "$`{foobar}";
- assertEquals(in, svr.resolve(in));
- in = "$|{foobar}";
- assertEquals(in, svr.resolve(in));
- in = "${{foobar}";
- assertEquals(in, svr.resolve(in));
- in = "${$foobar}";
- assertEquals(in, svr.resolve(in));
-
- System.setProperty("foobar", "baz");
-
- in = "$";
- assertEquals(in, svr.resolve(in));
-
- in = "$S";
- assertEquals(in, svr.resolve(in));
-
- in = "$S{";
- assertEquals(in, svr.resolve(in));
-
- in = "$S{foobar";
-
- assertEquals(in, svr.resolve(in));
- in = "$S{foobar}$";
- assertEquals("baz$", svr.resolve(in));
-
- in = "$S{foobar}$S";
- assertEquals("baz$S", svr.resolve(in));
-
- in = "$S{foobar}$S{";
- assertEquals("baz$S{", svr.resolve(in));
-
- in = "$S{foobar}$S{foobar";
- assertEquals("baz$S{foobar", svr.resolve(in));
-
- System.clearProperty("foobar");
- in = "$S{foobar}";
-
- // Test nulls returned by StringVar.
- // Should be converted to blanks.
- svr.addVars(AlwaysNullVar.class);
-
- in = "$A{xxx}";
- assertEquals("", svr.resolve(in));
- in = "x$A{xxx}";
- assertEquals("x", svr.resolve(in));
- in = "$A{xxx}x";
- assertEquals("x", svr.resolve(in));
- }
-
- public static class AlwaysNullVar extends SimpleVar {
- public AlwaysNullVar() {
- super("A");
- }
- @Override
- public String resolve(VarResolverSession session, String key) {
- return null;
- }
- }
-
- public static class InvalidVar extends SimpleVar {
- public InvalidVar(String c) {
- super(c);
- }
- @Override
- public String resolve(VarResolverSession session, String key) {
- return null;
- }
- }
-
- public static class InvalidVar1 extends InvalidVar {
- public InvalidVar1() {
- super(null);
- }
- }
- public static class InvalidVar2 extends InvalidVar {
- public InvalidVar2() {
- super("@");
- }
- }
- public static class InvalidVar3 extends InvalidVar {
- public InvalidVar3() {
- super("[");
- }
- }
- public static class InvalidVar4 extends InvalidVar {
- public InvalidVar4() {
- super("`");
- }
- }
- public static class InvalidVar5 extends InvalidVar {
- public InvalidVar5() {
- super("|");
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/utils/CharSetTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/utils/CharSetTest.java b/org.apache.juneau/src/test/java/org/apache/juneau/utils/CharSetTest.java
new file mode 100755
index 0000000..f480e66
--- /dev/null
+++ b/org.apache.juneau/src/test/java/org/apache/juneau/utils/CharSetTest.java
@@ -0,0 +1,34 @@
+/***************************************************************************************************************************
+ * 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.juneau.utils;
+
+import static org.junit.Assert.*;
+
+import org.apache.juneau.internal.*;
+import org.junit.*;
+
+public class CharSetTest {
+
+ //====================================================================================================
+ // test - Basic tests
+ //====================================================================================================
+ @Test
+ public void test() throws Exception {
+ AsciiSet cs = new AsciiSet("abc\u1234");
+ assertTrue(cs.contains('a'));
+ assertFalse(cs.contains('d'));
+ assertFalse(cs.contains('\u1234'));
+ assertFalse(cs.contains((char)-1));
+ assertFalse(cs.contains((char)128));
+ }
+}
[44/44] incubator-juneau git commit: Rename CT_* testcases.
Posted by ja...@apache.org.
Rename CT_* testcases.
Project: http://git-wip-us.apache.org/repos/asf/incubator-juneau/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-juneau/commit/df0f8689
Tree: http://git-wip-us.apache.org/repos/asf/incubator-juneau/tree/df0f8689
Diff: http://git-wip-us.apache.org/repos/asf/incubator-juneau/diff/df0f8689
Branch: refs/heads/master
Commit: df0f8689f2f10449c3025af2d31cd9775dec5c13
Parents: f24316e
Author: James <ja...@salesforce.com>
Authored: Tue Aug 9 13:14:56 2016 -0400
Committer: James <ja...@salesforce.com>
Committed: Tue Aug 9 13:14:56 2016 -0400
----------------------------------------------------------------------
.../server/samples/AddressBookResourceTest.java | 231 ++
.../server/samples/CT_AddressBookResource.java | 231 --
.../juneau/server/samples/CT_RootResources.java | 146 --
.../CT_SampleRemoteableServicesResource.java | 69 -
.../samples/CT_TestMultiPartFormPosts.java | 47 -
.../server/samples/RootResourcesTest.java | 146 ++
.../SampleRemoteableServicesResourceTest.java | 69 +
.../samples/TestMultiPartFormPostsTest.java | 47 +
.../apache/juneau/server/CT_JacocoDummy.java | 37 -
.../org/apache/juneau/server/CT_RestUtils.java | 188 --
.../juneau/server/CT_TestAcceptCharset.java | 123 -
.../server/CT_TestBeanContextProperties.java | 37 -
.../juneau/server/CT_TestCallbackStrings.java | 50 -
.../juneau/server/CT_TestCharsetEncodings.java | 96 -
.../juneau/server/CT_TestClientVersion.java | 90 -
.../org/apache/juneau/server/CT_TestConfig.java | 58 -
.../apache/juneau/server/CT_TestContent.java | 706 ------
.../server/CT_TestDefaultContentTypes.java | 497 ----
.../juneau/server/CT_TestErrorConditions.java | 220 --
.../org/apache/juneau/server/CT_TestGroups.java | 122 -
.../org/apache/juneau/server/CT_TestGzip.java | 344 ---
.../juneau/server/CT_TestInheritance.java | 128 --
.../apache/juneau/server/CT_TestLargePojos.java | 83 -
.../apache/juneau/server/CT_TestMessages.java | 47 -
.../org/apache/juneau/server/CT_TestNls.java | 170 --
.../juneau/server/CT_TestNlsProperty.java | 48 -
.../juneau/server/CT_TestNoParserInput.java | 70 -
.../apache/juneau/server/CT_TestOnPostCall.java | 121 -
.../apache/juneau/server/CT_TestOnPreCall.java | 61 -
.../juneau/server/CT_TestOptionsWithoutNls.java | 51 -
.../server/CT_TestOverlappingMethods.java | 170 --
.../org/apache/juneau/server/CT_TestParams.java | 716 ------
.../apache/juneau/server/CT_TestParsers.java | 162 --
.../org/apache/juneau/server/CT_TestPath.java | 44 -
.../org/apache/juneau/server/CT_TestPaths.java | 1368 -----------
.../apache/juneau/server/CT_TestProperties.java | 48 -
.../apache/juneau/server/CT_TestRestClient.java | 199 --
.../juneau/server/CT_TestSerializers.java | 152 --
.../juneau/server/CT_TestStaticFiles.java | 56 -
.../apache/juneau/server/CT_TestTransforms.java | 68 -
.../org/apache/juneau/server/CT_TestUris.java | 918 --------
.../apache/juneau/server/CT_TestUrlContent.java | 74 -
.../apache/juneau/server/CT_UrlPathPattern.java | 39 -
.../apache/juneau/server/JacocoDummyTest.java | 37 +
.../org/apache/juneau/server/RestUtilsTest.java | 188 ++
.../juneau/server/TestAcceptCharsetTest.java | 123 +
.../server/TestBeanContextPropertiesTest.java | 37 +
.../juneau/server/TestCallbackStringsTest.java | 50 +
.../juneau/server/TestCharsetEncodingsTest.java | 96 +
.../juneau/server/TestClientVersionTest.java | 90 +
.../apache/juneau/server/TestConfigTest.java | 58 +
.../apache/juneau/server/TestContentTest.java | 706 ++++++
.../server/TestDefaultContentTypesTest.java | 497 ++++
.../juneau/server/TestErrorConditionsTest.java | 220 ++
.../apache/juneau/server/TestGroupsTest.java | 122 +
.../org/apache/juneau/server/TestGzipTest.java | 344 +++
.../juneau/server/TestInheritanceTest.java | 128 ++
.../juneau/server/TestLargePojosTest.java | 83 +
.../apache/juneau/server/TestMessagesTest.java | 47 +
.../juneau/server/TestNlsPropertyTest.java | 48 +
.../org/apache/juneau/server/TestNlsTest.java | 170 ++
.../juneau/server/TestNoParserInputTest.java | 70 +
.../juneau/server/TestOnPostCallTest.java | 121 +
.../apache/juneau/server/TestOnPreCallTest.java | 61 +
.../server/TestOptionsWithoutNlsTest.java | 51 +
.../server/TestOverlappingMethodsTest.java | 170 ++
.../apache/juneau/server/TestParamsTest.java | 716 ++++++
.../apache/juneau/server/TestParsersTest.java | 162 ++
.../org/apache/juneau/server/TestPathTest.java | 44 +
.../org/apache/juneau/server/TestPathsTest.java | 1368 +++++++++++
.../juneau/server/TestPropertiesTest.java | 48 +
.../juneau/server/TestRestClientTest.java | 199 ++
.../juneau/server/TestSerializersTest.java | 152 ++
.../juneau/server/TestStaticFilesTest.java | 56 +
.../juneau/server/TestTransformsTest.java | 68 +
.../org/apache/juneau/server/TestUrisTest.java | 918 ++++++++
.../juneau/server/TestUrlContentTest.java | 74 +
.../juneau/server/UrlPathPatternTest.java | 39 +
.../java/org/apache/juneau/AnnotationsTest.java | 82 +
.../java/org/apache/juneau/BeanConfigTest.java | 849 +++++++
.../java/org/apache/juneau/BeanMapTest.java | 1920 ++++++++++++++++
.../org/apache/juneau/BeanTransformTest.java | 144 ++
.../java/org/apache/juneau/CT_Annotations.java | 82 -
.../java/org/apache/juneau/CT_BeanConfig.java | 849 -------
.../test/java/org/apache/juneau/CT_BeanMap.java | 1920 ----------------
.../org/apache/juneau/CT_BeanTransform.java | 144 --
.../java/org/apache/juneau/CT_ClassMeta.java | 281 ---
.../org/apache/juneau/CT_ContextFactory.java | 823 -------
.../apache/juneau/CT_DataConversionTest.java | 145 --
.../org/apache/juneau/CT_IgnoredClasses.java | 72 -
.../java/org/apache/juneau/CT_JacocoDummy.java | 49 -
.../java/org/apache/juneau/CT_ObjectList.java | 98 -
.../java/org/apache/juneau/CT_ObjectMap.java | 313 ---
.../org/apache/juneau/CT_ParserGenerics.java | 71 -
.../java/org/apache/juneau/CT_ParserReader.java | 181 --
.../org/apache/juneau/CT_PojoTransform.java | 56 -
.../apache/juneau/CT_PropertyNamerDashedLC.java | 39 -
.../java/org/apache/juneau/CT_Visibility.java | 169 --
.../java/org/apache/juneau/ClassMetaTest.java | 281 +++
.../org/apache/juneau/ContextFactoryTest.java | 823 +++++++
.../org/apache/juneau/DataConversionTest.java | 145 ++
.../org/apache/juneau/IgnoredClassesTest.java | 72 +
.../java/org/apache/juneau/JacocoDummyTest.java | 49 +
.../java/org/apache/juneau/ObjectListTest.java | 98 +
.../java/org/apache/juneau/ObjectMapTest.java | 313 +++
.../org/apache/juneau/ParserGenericsTest.java | 71 +
.../org/apache/juneau/ParserReaderTest.java | 181 ++
.../org/apache/juneau/PojoTransformTest.java | 56 +
.../juneau/PropertyNamerDashedLcTest.java | 39 +
.../java/org/apache/juneau/VisibilityTest.java | 169 ++
.../a/rttests/CT_RoundTripAddClassAttrs.java | 349 ---
.../a/rttests/CT_RoundTripBeanInheritance.java | 220 --
.../juneau/a/rttests/CT_RoundTripBeanMaps.java | 1012 --------
.../juneau/a/rttests/CT_RoundTripClasses.java | 53 -
.../juneau/a/rttests/CT_RoundTripDTOs.java | 50 -
.../juneau/a/rttests/CT_RoundTripEnum.java | 246 --
.../juneau/a/rttests/CT_RoundTripGenerics.java | 97 -
.../a/rttests/CT_RoundTripLargeObjects.java | 193 --
.../juneau/a/rttests/CT_RoundTripMaps.java | 215 --
.../CT_RoundTripNumericConstructors.java | 54 -
.../a/rttests/CT_RoundTripObjectsAsStrings.java | 272 ---
.../CT_RoundTripObjectsWithSpecialMethods.java | 116 -
.../CT_RoundTripPrimitiveObjectBeans.java | 197 --
.../a/rttests/CT_RoundTripPrimitivesBeans.java | 367 ---
.../a/rttests/CT_RoundTripReadOnlyBeans.java | 100 -
.../a/rttests/CT_RoundTripSimpleObjects.java | 750 ------
.../a/rttests/CT_RoundTripToObjectMaps.java | 78 -
.../a/rttests/CT_RoundTripTransformBeans.java | 382 ----
.../a/rttests/CT_RoundTripTrimStrings.java | 98 -
.../a/rttests/RoundTripAddClassAttrsTest.java | 349 +++
.../a/rttests/RoundTripBeanInheritanceTest.java | 220 ++
.../juneau/a/rttests/RoundTripBeanMapsTest.java | 1012 ++++++++
.../juneau/a/rttests/RoundTripClassesTest.java | 53 +
.../juneau/a/rttests/RoundTripDTOsTest.java | 50 +
.../juneau/a/rttests/RoundTripEnumTest.java | 246 ++
.../juneau/a/rttests/RoundTripGenericsTest.java | 97 +
.../a/rttests/RoundTripLargeObjectsTest.java | 193 ++
.../juneau/a/rttests/RoundTripMapsTest.java | 215 ++
.../RoundTripNumericConstructorsTest.java | 54 +
.../rttests/RoundTripObjectsAsStringsTest.java | 272 +++
.../RoundTripObjectsWithSpecialMethodsTest.java | 116 +
.../RoundTripPrimitiveObjectBeansTest.java | 197 ++
.../a/rttests/RoundTripPrimitivesBeansTest.java | 367 +++
.../a/rttests/RoundTripReadOnlyBeansTest.java | 100 +
.../a/rttests/RoundTripSimpleObjectsTest.java | 750 ++++++
.../a/rttests/RoundTripToObjectMapsTest.java | 78 +
.../a/rttests/RoundTripTransformBeansTest.java | 382 ++++
.../a/rttests/RoundTripTrimStringsTest.java | 98 +
.../test/java/org/apache/juneau/csv/CT_Csv.java | 50 -
.../java/org/apache/juneau/csv/CsvTest.java | 50 +
.../org/apache/juneau/dto/atom/AtomTest.java | 102 +
.../org/apache/juneau/dto/atom/CT_Atom.java | 102 -
.../apache/juneau/dto/cognos/CT_CognosXml.java | 106 -
.../apache/juneau/dto/cognos/CognosXmlTest.java | 106 +
.../juneau/dto/jsonschema/CT_JsonSchema.java | 103 -
.../juneau/dto/jsonschema/JsonSchemaTest.java | 103 +
.../java/org/apache/juneau/html/CT_Common.java | 564 -----
.../org/apache/juneau/html/CT_CommonParser.java | 162 --
.../java/org/apache/juneau/html/CT_Html.java | 389 ----
.../apache/juneau/html/CommonParserTest.java | 162 ++
.../java/org/apache/juneau/html/CommonTest.java | 564 +++++
.../java/org/apache/juneau/html/HtmlTest.java | 389 ++++
.../org/apache/juneau/ini/CT_ConfigFile.java | 2154 ------------------
.../org/apache/juneau/ini/CT_ConfigMgr.java | 204 --
.../org/apache/juneau/ini/ConfigFileTest.java | 2154 ++++++++++++++++++
.../org/apache/juneau/ini/ConfigMgrTest.java | 204 ++
.../apache/juneau/internal/CT_VersionRange.java | 68 -
.../juneau/internal/VersionRangeTest.java | 68 +
.../java/org/apache/juneau/jena/CT_Common.java | 513 -----
.../org/apache/juneau/jena/CT_CommonParser.java | 208 --
.../org/apache/juneau/jena/CT_CommonXml.java | 95 -
.../java/org/apache/juneau/jena/CT_Rdf.java | 597 -----
.../org/apache/juneau/jena/CT_RdfParser.java | 149 --
.../apache/juneau/jena/CommonParserTest.java | 208 ++
.../java/org/apache/juneau/jena/CommonTest.java | 513 +++++
.../org/apache/juneau/jena/CommonXmlTest.java | 95 +
.../org/apache/juneau/jena/RdfParserTest.java | 149 ++
.../java/org/apache/juneau/jena/RdfTest.java | 597 +++++
.../java/org/apache/juneau/json/CT_Common.java | 501 ----
.../org/apache/juneau/json/CT_CommonParser.java | 180 --
.../java/org/apache/juneau/json/CT_Json.java | 308 ---
.../org/apache/juneau/json/CT_JsonParser.java | 331 ---
.../org/apache/juneau/json/CT_JsonSchema.java | 44 -
.../apache/juneau/json/CommonParserTest.java | 180 ++
.../java/org/apache/juneau/json/CommonTest.java | 501 ++++
.../org/apache/juneau/json/JsonParserTest.java | 331 +++
.../org/apache/juneau/json/JsonSchemaTest.java | 44 +
.../java/org/apache/juneau/json/JsonTest.java | 308 +++
.../juneau/msgpack/CT_MsgPackSerialzier.java | 220 --
.../juneau/msgpack/MsgPackSerialzierTest.java | 220 ++
.../apache/juneau/transforms/BeanMapTest.java | 96 +
.../juneau/transforms/BeanTransformTest.java | 204 ++
.../ByteArrayBase64TransformTest.java | 172 ++
.../apache/juneau/transforms/CT_BeanMap.java | 96 -
.../juneau/transforms/CT_BeanTransform.java | 204 --
.../transforms/CT_ByteArrayBase64Transform.java | 172 --
.../juneau/transforms/CT_CalendarTransform.java | 696 ------
.../apache/juneau/transforms/CT_DateFilter.java | 170 --
.../transforms/CT_EnumerationTransform.java | 35 -
.../juneau/transforms/CT_IteratorTransform.java | 37 -
.../juneau/transforms/CT_ReaderFilter.java | 47 -
.../transforms/CalendarTransformTest.java | 696 ++++++
.../juneau/transforms/DateFilterTest.java | 170 ++
.../transforms/EnumerationTransformTest.java | 35 +
.../transforms/IteratorTransformTest.java | 37 +
.../juneau/transforms/ReaderFilterTest.java | 47 +
.../juneau/urlencoding/CT_CommonParser_Uon.java | 168 --
.../CT_CommonParser_UrlEncoding.java | 185 --
.../juneau/urlencoding/CT_Common_Uon.java | 450 ----
.../urlencoding/CT_Common_UrlEncoding.java | 442 ----
.../apache/juneau/urlencoding/CT_UonParser.java | 542 -----
.../juneau/urlencoding/CT_UonParserReader.java | 217 --
.../juneau/urlencoding/CT_UonSerializer.java | 460 ----
.../urlencoding/CT_UrlEncodingParser.java | 1000 --------
.../urlencoding/CT_UrlEncodingSerializer.java | 497 ----
.../urlencoding/CommonParser_UonTest.java | 168 ++
.../CommonParser_UrlEncodingTest.java | 185 ++
.../juneau/urlencoding/Common_UonTest.java | 450 ++++
.../urlencoding/Common_UrlEncodingTest.java | 442 ++++
.../juneau/urlencoding/UonParserReaderTest.java | 217 ++
.../juneau/urlencoding/UonParserTest.java | 542 +++++
.../juneau/urlencoding/UonSerializerTest.java | 460 ++++
.../urlencoding/UrlEncodingParserTest.java | 1000 ++++++++
.../urlencoding/UrlEncodingSerializerTest.java | 497 ++++
.../java/org/apache/juneau/utils/ArgsTest.java | 70 +
.../org/apache/juneau/utils/ArrayUtilsTest.java | 160 ++
.../apache/juneau/utils/ByteArrayCacheTest.java | 60 +
.../juneau/utils/ByteArrayInOutStreamTest.java | 34 +
.../java/org/apache/juneau/utils/CT_Args.java | 70 -
.../org/apache/juneau/utils/CT_ArrayUtils.java | 160 --
.../apache/juneau/utils/CT_ByteArrayCache.java | 60 -
.../juneau/utils/CT_ByteArrayInOutStream.java | 34 -
.../org/apache/juneau/utils/CT_CharSet.java | 34 -
.../org/apache/juneau/utils/CT_ClassUtils.java | 114 -
.../apache/juneau/utils/CT_CollectionUtils.java | 34 -
.../org/apache/juneau/utils/CT_FilteredMap.java | 44 -
.../java/org/apache/juneau/utils/CT_IOPipe.java | 282 ---
.../org/apache/juneau/utils/CT_IOUtils.java | 103 -
.../apache/juneau/utils/CT_IdentityList.java | 38 -
.../apache/juneau/utils/CT_KeywordStore.java | 45 -
.../apache/juneau/utils/CT_MultiIterable.java | 70 -
.../org/apache/juneau/utils/CT_MultiSet.java | 143 --
.../apache/juneau/utils/CT_ParserReader.java | 48 -
.../juneau/utils/CT_PojoIntrospector.java | 53 -
.../org/apache/juneau/utils/CT_PojoQuery.java | 680 ------
.../org/apache/juneau/utils/CT_PojoRest.java | 852 -------
.../org/apache/juneau/utils/CT_SimpleMap.java | 48 -
.../juneau/utils/CT_StringBuilderWriter.java | 59 -
.../org/apache/juneau/utils/CT_StringUtils.java | 676 ------
.../juneau/utils/CT_StringVarResolver.java | 332 ---
.../org/apache/juneau/utils/CharSetTest.java | 34 +
.../org/apache/juneau/utils/ClassUtilsTest.java | 114 +
.../juneau/utils/CollectionUtilsTest.java | 34 +
.../apache/juneau/utils/FilteredMapTest.java | 44 +
.../org/apache/juneau/utils/IOPipeTest.java | 282 +++
.../org/apache/juneau/utils/IOUtilsTest.java | 103 +
.../apache/juneau/utils/IdentityListTest.java | 38 +
.../apache/juneau/utils/KeywordStoreTest.java | 45 +
.../apache/juneau/utils/MultiIterableTest.java | 70 +
.../org/apache/juneau/utils/MultiSetTest.java | 143 ++
.../apache/juneau/utils/ParserReaderTest.java | 48 +
.../juneau/utils/PojoIntrospectorTest.java | 53 +
.../org/apache/juneau/utils/PojoQueryTest.java | 680 ++++++
.../org/apache/juneau/utils/PojoRestTest.java | 852 +++++++
.../org/apache/juneau/utils/SimpleMapTest.java | 48 +
.../juneau/utils/StringBuilderWriterTest.java | 59 +
.../apache/juneau/utils/StringUtilsTest.java | 676 ++++++
.../juneau/utils/StringVarResolverTest.java | 332 +++
.../java/org/apache/juneau/xml/CT_Common.java | 453 ----
.../org/apache/juneau/xml/CT_CommonParser.java | 179 --
.../org/apache/juneau/xml/CT_CommonXml.java | 81 -
.../test/java/org/apache/juneau/xml/CT_Xml.java | 1050 ---------
.../org/apache/juneau/xml/CT_XmlCollapsed.java | 459 ----
.../org/apache/juneau/xml/CT_XmlContent.java | 301 ---
.../org/apache/juneau/xml/CT_XmlParser.java | 95 -
.../org/apache/juneau/xml/CommonParserTest.java | 179 ++
.../java/org/apache/juneau/xml/CommonTest.java | 453 ++++
.../org/apache/juneau/xml/CommonXmlTest.java | 81 +
.../org/apache/juneau/xml/XmlCollapsedTest.java | 459 ++++
.../org/apache/juneau/xml/XmlContentTest.java | 301 +++
.../org/apache/juneau/xml/XmlParserTest.java | 95 +
.../java/org/apache/juneau/xml/XmlTest.java | 1050 +++++++++
282 files changed, 37058 insertions(+), 37058 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau.samples/src/test/java/org/apache/juneau/server/samples/AddressBookResourceTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau.samples/src/test/java/org/apache/juneau/server/samples/AddressBookResourceTest.java b/org.apache.juneau.samples/src/test/java/org/apache/juneau/server/samples/AddressBookResourceTest.java
new file mode 100755
index 0000000..1287b56
--- /dev/null
+++ b/org.apache.juneau.samples/src/test/java/org/apache/juneau/server/samples/AddressBookResourceTest.java
@@ -0,0 +1,231 @@
+/***************************************************************************************************************************
+ * 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.juneau.server.samples;
+
+import static org.apache.juneau.server.samples.TestUtils.*;
+import static org.junit.Assert.*;
+
+import java.util.*;
+
+import org.apache.juneau.*;
+import org.apache.juneau.client.*;
+import org.apache.juneau.html.*;
+import org.apache.juneau.internal.*;
+import org.apache.juneau.json.*;
+import org.apache.juneau.samples.addressbook.*;
+import org.apache.juneau.transforms.*;
+import org.apache.juneau.xml.*;
+import org.junit.*;
+
+@SuppressWarnings({"serial"})
+public class AddressBookResourceTest {
+
+ private static boolean debug = false;
+
+ static RestClient[] clients;
+
+ @BeforeClass
+ public static void beforeClass() throws Exception {
+ clients = new RestClient[] {
+ new SamplesRestClient(JsonSerializer.class, JsonParser.class),
+ new SamplesRestClient(XmlSerializer.class, XmlParser.class),
+ new SamplesRestClient(HtmlSerializer.class, HtmlParser.class).setAccept("text/html+stripped"),
+ new SamplesRestClient(XmlSerializer.class, HtmlParser.class).setAccept("text/html+stripped")
+ };
+ for (RestClient c : clients) {
+ c.getSerializer().addTransforms(CalendarTransform.Medium.class);
+ c.getParser().addTransforms(CalendarTransform.Medium.class);
+ c.getSerializer().setProperty(XmlSerializerContext.XML_autoDetectNamespaces, true);
+ }
+ }
+
+ @AfterClass
+ public static void afterClass() {
+ for (RestClient c : clients) {
+ c.closeQuietly();
+ }
+ }
+
+ //====================================================================================================
+ // Get AddressBookResource as JSON
+ //====================================================================================================
+ @Test
+ public void testBasic() throws Exception {
+ String in = IOUtils.read(getClass().getResourceAsStream("/org/apache/juneau/server/test/AddressBookResource_test0Test.json"));
+ JsonParser p = new JsonParser().addTransforms(CalendarTransform.Medium.class);
+ Person person = p.parse(in, Person.class);
+ if (debug) System.err.println(person);
+ }
+
+ // A list of People objects.
+ public static class PersonList extends LinkedList<Person> {}
+
+ //====================================================================================================
+ // PojoRest tests
+ //====================================================================================================
+ @Test
+ public void testPojoRest() throws Exception {
+ for (RestClient client : clients) {
+ int rc;
+ Person p;
+ List<Person> people;
+
+ // Reinitialize the resource
+ rc = client.doGet("/addressBook?method=init").run();
+ assertEquals(200, rc);
+
+ // Simple GETs
+ people = client.doGet("/addressBook/people").getResponse(PersonList.class);
+ assertEquals("Barack Obama", people.get(0).name);
+ assertEquals(76638, people.get(1).addresses.get(0).zip);
+
+ // PUT a simple String field
+ p = people.get(0);
+ rc = client.doPut(p.uri+"/name", "foo").run();
+ assertEquals(200, rc);
+ String name = client.doGet(p.uri+"/name").getResponse(String.class);
+ assertEquals("foo", name);
+ p = client.doGet(p.uri).getResponse(Person.class);
+ assertEquals("foo", p.name);
+
+ // POST an address as JSON
+ CreateAddress ca = new CreateAddress("a1","b1","c1",1,false);
+ Address a = client.doPost(p.uri + "/addresses", new ObjectMap(BeanContext.DEFAULT.forBean(ca))).getResponse(Address.class);
+ assertEquals("a1", a.street);
+ a = client.doGet(a.uri).getResponse(Address.class);
+ assertEquals("a1", a.street);
+ assertEquals(1, a.zip);
+ assertFalse(a.isCurrent);
+
+ // POST an address as a bean
+ ca = new CreateAddress("a2","b2","c2",2,true);
+ a = client.doPost(p.uri + "/addresses", ca).getResponse(Address.class);
+ assertEquals("a2", a.street);
+ a = client.doGet(a.uri).getResponse(Address.class);
+ assertEquals("a2", a.street);
+ assertEquals(2, a.zip);
+ assertTrue(a.isCurrent);
+
+ // POST a person
+ CreatePerson billClinton = new CreatePerson("Bill Clinton", AddressBook.toCalendar("Aug 19, 1946"),
+ new CreateAddress("a3","b3","c3",3,false)
+ );
+ rc = client.doPost("/addressBook/people", billClinton).run();
+ assertEquals(200, rc);
+ people = client.doGet("/addressBook/people").getResponse(PersonList.class);
+ p = people.get(2);
+ assertEquals(3, people.size());
+ assertEquals("Bill Clinton", p.name);
+
+ // DELETE an address
+ rc = client.doDelete(p.addresses.get(0).uri).run();
+ assertEquals(200, rc);
+ people = client.doGet("/addressBook/people").getResponse(PersonList.class);
+ p = people.get(2);
+ assertEquals(0, p.addresses.size());
+
+ // DELETE a person
+ rc = client.doDelete(p.uri).run();
+ assertEquals(200, rc);
+ people = client.doGet("/addressBook/people").getResponse(PersonList.class);
+ assertEquals(2, people.size());
+
+ // Reinitialize the resource
+ rc = client.doGet("/addressBook?method=init").run();
+ assertEquals(200, rc);
+ }
+ }
+
+ //====================================================================================================
+ // PojoQuery tests
+ //====================================================================================================
+ @Test
+ public void testPojoQuery() throws Exception {
+
+ for (RestClient client : clients) {
+ RestCall r;
+ List<Person> people;
+
+ // Reinitialize the resource
+ int rc = client.doGet("/addressBook?method=init").run();
+ assertEquals(200, rc);
+
+ r = client.doGet("/addressBook/people?q=(name=B*)");
+ people = r.getResponse(PersonList.class);
+ assertEquals(1, people.size());
+ assertEquals("Barack Obama", people.get(0).name);
+
+ r = client.doGet("/addressBook/people?q=(name='Barack+Obama')");
+ people = r.getResponse(PersonList.class);
+ assertEquals(1, people.size());
+ assertEquals("Barack Obama", people.get(0).name);
+
+ r = client.doGet("/addressBook/people?q=(name='Barack%20Obama')");
+ people = r.getResponse(PersonList.class);
+ assertEquals(1, people.size());
+ assertEquals("Barack Obama", people.get(0).name);
+
+ r = client.doGet("/addressBook/people?v=(name,birthDate)");
+ people = r.getResponse(PersonList.class);
+ assertEquals("Barack Obama", people.get(0).name);
+ assertTrue(people.get(0).getAge() > 10);
+ assertEquals(0, people.get(0).addresses.size());
+
+ r = client.doGet("/addressBook/people?v=(addresses,birthDate)");
+ people = r.getResponse(PersonList.class);
+ assertNull(people.get(0).name);
+ assertTrue(people.get(0).getAge() > 10);
+ assertEquals(2, people.get(0).addresses.size());
+
+ r = client.doGet("/addressBook/people?s=($o(age=d))");
+ people = r.getResponse(PersonList.class);
+ assertTrue(people.get(0).getAge() > 10);
+ r = client.doGet("/addressBook/people?s=(age)");
+ people = r.getResponse(PersonList.class);
+ assertTrue(people.get(0).getAge() > 10);
+ r = client.doGet("/addressBook/people?s=($o(age=a))");
+ people = r.getResponse(PersonList.class);
+ assertTrue(people.get(0).getAge() > 10);
+
+ r = client.doGet("/addressBook/people?p=1&l=1");
+ people = r.getResponse(PersonList.class);
+ assertEquals(1, people.size());
+ assertTrue(people.get(0).getAge() > 10);
+ }
+ }
+
+ //====================================================================================================
+ // PojoIntrospector tests
+ //====================================================================================================
+ @Test
+ public void testPojoIntrospector() throws Exception {
+
+ for (RestClient client : clients) {
+
+ List<Person> people;
+
+ // Reinitialize the resource
+ int rc = client.doGet("/addressBook?method=init").run();
+ assertEquals(200, rc);
+
+ // Simple GETs
+ people = client.doGet("/addressBook/people").getResponse(PersonList.class);
+ Person p = people.get(0);
+ int length = client.doGet(p.uri+"/name?invokeMethod=length").getResponse(Integer.class);
+ assertEquals(12, length);
+
+ String[] tokens = client.doGet(p.uri+"/name?invokeMethod=split(java.lang.String,int)&invokeArgs=['a',3]").getResponse(String[].class);
+ assertObjectEquals("['B','r','ck Obama']", tokens);
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau.samples/src/test/java/org/apache/juneau/server/samples/CT_AddressBookResource.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau.samples/src/test/java/org/apache/juneau/server/samples/CT_AddressBookResource.java b/org.apache.juneau.samples/src/test/java/org/apache/juneau/server/samples/CT_AddressBookResource.java
deleted file mode 100755
index 1c086fb..0000000
--- a/org.apache.juneau.samples/src/test/java/org/apache/juneau/server/samples/CT_AddressBookResource.java
+++ /dev/null
@@ -1,231 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.server.samples;
-
-import static org.apache.juneau.server.samples.TestUtils.*;
-import static org.junit.Assert.*;
-
-import java.util.*;
-
-import org.apache.juneau.*;
-import org.apache.juneau.client.*;
-import org.apache.juneau.html.*;
-import org.apache.juneau.internal.*;
-import org.apache.juneau.json.*;
-import org.apache.juneau.samples.addressbook.*;
-import org.apache.juneau.transforms.*;
-import org.apache.juneau.xml.*;
-import org.junit.*;
-
-@SuppressWarnings({"serial"})
-public class CT_AddressBookResource {
-
- private static boolean debug = false;
-
- static RestClient[] clients;
-
- @BeforeClass
- public static void beforeClass() throws Exception {
- clients = new RestClient[] {
- new SamplesRestClient(JsonSerializer.class, JsonParser.class),
- new SamplesRestClient(XmlSerializer.class, XmlParser.class),
- new SamplesRestClient(HtmlSerializer.class, HtmlParser.class).setAccept("text/html+stripped"),
- new SamplesRestClient(XmlSerializer.class, HtmlParser.class).setAccept("text/html+stripped")
- };
- for (RestClient c : clients) {
- c.getSerializer().addTransforms(CalendarTransform.Medium.class);
- c.getParser().addTransforms(CalendarTransform.Medium.class);
- c.getSerializer().setProperty(XmlSerializerContext.XML_autoDetectNamespaces, true);
- }
- }
-
- @AfterClass
- public static void afterClass() {
- for (RestClient c : clients) {
- c.closeQuietly();
- }
- }
-
- //====================================================================================================
- // Get AddressBookResource as JSON
- //====================================================================================================
- @Test
- public void testBasic() throws Exception {
- String in = IOUtils.read(getClass().getResourceAsStream("/org/apache/juneau/server/test/CT_AddressBookResource_test0.json"));
- JsonParser p = new JsonParser().addTransforms(CalendarTransform.Medium.class);
- Person person = p.parse(in, Person.class);
- if (debug) System.err.println(person);
- }
-
- // A list of People objects.
- public static class PersonList extends LinkedList<Person> {}
-
- //====================================================================================================
- // PojoRest tests
- //====================================================================================================
- @Test
- public void testPojoRest() throws Exception {
- for (RestClient client : clients) {
- int rc;
- Person p;
- List<Person> people;
-
- // Reinitialize the resource
- rc = client.doGet("/addressBook?method=init").run();
- assertEquals(200, rc);
-
- // Simple GETs
- people = client.doGet("/addressBook/people").getResponse(PersonList.class);
- assertEquals("Barack Obama", people.get(0).name);
- assertEquals(76638, people.get(1).addresses.get(0).zip);
-
- // PUT a simple String field
- p = people.get(0);
- rc = client.doPut(p.uri+"/name", "foo").run();
- assertEquals(200, rc);
- String name = client.doGet(p.uri+"/name").getResponse(String.class);
- assertEquals("foo", name);
- p = client.doGet(p.uri).getResponse(Person.class);
- assertEquals("foo", p.name);
-
- // POST an address as JSON
- CreateAddress ca = new CreateAddress("a1","b1","c1",1,false);
- Address a = client.doPost(p.uri + "/addresses", new ObjectMap(BeanContext.DEFAULT.forBean(ca))).getResponse(Address.class);
- assertEquals("a1", a.street);
- a = client.doGet(a.uri).getResponse(Address.class);
- assertEquals("a1", a.street);
- assertEquals(1, a.zip);
- assertFalse(a.isCurrent);
-
- // POST an address as a bean
- ca = new CreateAddress("a2","b2","c2",2,true);
- a = client.doPost(p.uri + "/addresses", ca).getResponse(Address.class);
- assertEquals("a2", a.street);
- a = client.doGet(a.uri).getResponse(Address.class);
- assertEquals("a2", a.street);
- assertEquals(2, a.zip);
- assertTrue(a.isCurrent);
-
- // POST a person
- CreatePerson billClinton = new CreatePerson("Bill Clinton", AddressBook.toCalendar("Aug 19, 1946"),
- new CreateAddress("a3","b3","c3",3,false)
- );
- rc = client.doPost("/addressBook/people", billClinton).run();
- assertEquals(200, rc);
- people = client.doGet("/addressBook/people").getResponse(PersonList.class);
- p = people.get(2);
- assertEquals(3, people.size());
- assertEquals("Bill Clinton", p.name);
-
- // DELETE an address
- rc = client.doDelete(p.addresses.get(0).uri).run();
- assertEquals(200, rc);
- people = client.doGet("/addressBook/people").getResponse(PersonList.class);
- p = people.get(2);
- assertEquals(0, p.addresses.size());
-
- // DELETE a person
- rc = client.doDelete(p.uri).run();
- assertEquals(200, rc);
- people = client.doGet("/addressBook/people").getResponse(PersonList.class);
- assertEquals(2, people.size());
-
- // Reinitialize the resource
- rc = client.doGet("/addressBook?method=init").run();
- assertEquals(200, rc);
- }
- }
-
- //====================================================================================================
- // PojoQuery tests
- //====================================================================================================
- @Test
- public void testPojoQuery() throws Exception {
-
- for (RestClient client : clients) {
- RestCall r;
- List<Person> people;
-
- // Reinitialize the resource
- int rc = client.doGet("/addressBook?method=init").run();
- assertEquals(200, rc);
-
- r = client.doGet("/addressBook/people?q=(name=B*)");
- people = r.getResponse(PersonList.class);
- assertEquals(1, people.size());
- assertEquals("Barack Obama", people.get(0).name);
-
- r = client.doGet("/addressBook/people?q=(name='Barack+Obama')");
- people = r.getResponse(PersonList.class);
- assertEquals(1, people.size());
- assertEquals("Barack Obama", people.get(0).name);
-
- r = client.doGet("/addressBook/people?q=(name='Barack%20Obama')");
- people = r.getResponse(PersonList.class);
- assertEquals(1, people.size());
- assertEquals("Barack Obama", people.get(0).name);
-
- r = client.doGet("/addressBook/people?v=(name,birthDate)");
- people = r.getResponse(PersonList.class);
- assertEquals("Barack Obama", people.get(0).name);
- assertTrue(people.get(0).getAge() > 10);
- assertEquals(0, people.get(0).addresses.size());
-
- r = client.doGet("/addressBook/people?v=(addresses,birthDate)");
- people = r.getResponse(PersonList.class);
- assertNull(people.get(0).name);
- assertTrue(people.get(0).getAge() > 10);
- assertEquals(2, people.get(0).addresses.size());
-
- r = client.doGet("/addressBook/people?s=($o(age=d))");
- people = r.getResponse(PersonList.class);
- assertTrue(people.get(0).getAge() > 10);
- r = client.doGet("/addressBook/people?s=(age)");
- people = r.getResponse(PersonList.class);
- assertTrue(people.get(0).getAge() > 10);
- r = client.doGet("/addressBook/people?s=($o(age=a))");
- people = r.getResponse(PersonList.class);
- assertTrue(people.get(0).getAge() > 10);
-
- r = client.doGet("/addressBook/people?p=1&l=1");
- people = r.getResponse(PersonList.class);
- assertEquals(1, people.size());
- assertTrue(people.get(0).getAge() > 10);
- }
- }
-
- //====================================================================================================
- // PojoIntrospector tests
- //====================================================================================================
- @Test
- public void testPojoIntrospector() throws Exception {
-
- for (RestClient client : clients) {
-
- List<Person> people;
-
- // Reinitialize the resource
- int rc = client.doGet("/addressBook?method=init").run();
- assertEquals(200, rc);
-
- // Simple GETs
- people = client.doGet("/addressBook/people").getResponse(PersonList.class);
- Person p = people.get(0);
- int length = client.doGet(p.uri+"/name?invokeMethod=length").getResponse(Integer.class);
- assertEquals(12, length);
-
- String[] tokens = client.doGet(p.uri+"/name?invokeMethod=split(java.lang.String,int)&invokeArgs=['a',3]").getResponse(String[].class);
- assertObjectEquals("['B','r','ck Obama']", tokens);
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau.samples/src/test/java/org/apache/juneau/server/samples/CT_RootResources.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau.samples/src/test/java/org/apache/juneau/server/samples/CT_RootResources.java b/org.apache.juneau.samples/src/test/java/org/apache/juneau/server/samples/CT_RootResources.java
deleted file mode 100755
index a3fbc3e..0000000
--- a/org.apache.juneau.samples/src/test/java/org/apache/juneau/server/samples/CT_RootResources.java
+++ /dev/null
@@ -1,146 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.server.samples;
-
-import static org.junit.Assert.*;
-
-import java.net.*;
-
-import org.apache.juneau.*;
-import org.apache.juneau.client.*;
-import org.apache.juneau.html.*;
-import org.apache.juneau.json.*;
-import org.apache.juneau.server.labels.*;
-import org.apache.juneau.xml.*;
-import org.junit.*;
-
-public class CT_RootResources {
-
- private static String path = URI.create(Constants.getSampleUrl()).getPath(); // /jazz/juneau/sample
- private static boolean debug = false;
-
- private static RestClient jsonClient;
-
- @BeforeClass
- public static void beforeClass() {
- jsonClient = new SamplesRestClient(JsonSerializer.DEFAULT, JsonParser.DEFAULT);
- }
-
- @AfterClass
- public static void afterClass() {
- jsonClient.closeQuietly();
- }
-
- //====================================================================================================
- // text/json
- //====================================================================================================
- @Test
- public void testJson() throws Exception {
- RestClient client = new SamplesRestClient(JsonSerializer.DEFAULT, JsonParser.DEFAULT);
- RestCall r = client.doGet("");
- ResourceDescription[] x = r.getResponse(ResourceDescription[].class);
- assertEquals("helloWorld", x[0].getName().getName());
- assertEquals(path + "/helloWorld", x[0].getName().getHref());
- assertEquals("Hello World sample resource", x[0].getDescription());
-
- r = jsonClient.doOptions("");
- ObjectMap x2 = r.getResponse(ObjectMap.class);
- String s = x2.getString("description");
- if (debug) System.err.println(s);
- assertTrue(s, s.startsWith("This is an example"));
-
- client.closeQuietly();
- }
-
- //====================================================================================================
- // text/xml
- //====================================================================================================
- @Test
- public void testXml() throws Exception {
- RestClient client = new SamplesRestClient().setParser(XmlParser.DEFAULT);
- RestCall r = client.doGet("");
- ResourceDescription[] x = r.getResponse(ResourceDescription[].class);
- assertEquals("helloWorld", x[0].getName().getName());
- assertEquals(path + "/helloWorld", x[0].getName().getHref());
- assertEquals("Hello World sample resource", x[0].getDescription());
-
- r = jsonClient.doOptions("");
- ObjectMap x2 = r.getResponse(ObjectMap.class);
- String s = x2.getString("description");
- if (debug) System.err.println(s);
- assertTrue(s, s.startsWith("This is an example"));
-
- client.closeQuietly();
- }
-
- //====================================================================================================
- // text/html+stripped
- //====================================================================================================
- @Test
- public void testHtmlStripped() throws Exception {
- RestClient client = new SamplesRestClient().setParser(HtmlParser.DEFAULT).setAccept("text/html+stripped");
- RestCall r = client.doGet("");
- ResourceDescription[] x = r.getResponse(ResourceDescription[].class);
- assertEquals("helloWorld", x[0].getName().getName());
- assertTrue(x[0].getName().getHref().endsWith("/helloWorld"));
- assertEquals("Hello World sample resource", x[0].getDescription());
-
- r = jsonClient.doOptions("").setHeader("Accept", "text/json");
- ObjectMap x2 = r.getResponse(ObjectMap.class);
- String s = x2.getString("description");
- if (debug) System.err.println(s);
- assertTrue(s, s.startsWith("This is an example"));
-
- client.closeQuietly();
- }
-
- //====================================================================================================
- // /htdoces/styles.css
- //====================================================================================================
- @Test
- public void testStyleSheet() throws Exception {
- RestClient client = new SamplesRestClient().setAccept("text/css");
- RestCall r = client.doGet("/style.css");
- String css = r.getResponseAsString();
- if (debug) System.err.println(css);
- assertTrue(css, css.indexOf("table {") != -1);
-
- client.closeQuietly();
- }
-
- //====================================================================================================
- // application/json+schema
- //====================================================================================================
- @Test
- public void testJsonSchema() throws Exception {
- RestClient client = new SamplesRestClient().setParser(JsonParser.DEFAULT).setAccept("text/json+schema");
- RestCall r = client.doGet("");
- ObjectMap m = r.getResponse(ObjectMap.class);
- if (debug) System.err.println(m);
- assertEquals("org.apache.juneau.server.labels.ChildResourceDescriptions<org.apache.juneau.server.labels.ResourceDescription>", m.getString("description"));
- assertEquals("org.apache.juneau.server.labels.ResourceDescription", m.getObjectMap("items").getString("description"));
-
- client.closeQuietly();
- }
-
- //====================================================================================================
- // OPTIONS page
- //====================================================================================================
- @Test
- public void testOptionsPage() throws Exception {
- RestCall r = jsonClient.doOptions("");
- ResourceOptions o = r.getResponse(ResourceOptions.class);
- if (debug) System.err.println(o);
- assertEquals("This is an example of a router resource that is used to access other resources.", o.getDescription());
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau.samples/src/test/java/org/apache/juneau/server/samples/CT_SampleRemoteableServicesResource.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau.samples/src/test/java/org/apache/juneau/server/samples/CT_SampleRemoteableServicesResource.java b/org.apache.juneau.samples/src/test/java/org/apache/juneau/server/samples/CT_SampleRemoteableServicesResource.java
deleted file mode 100755
index 561bfe6..0000000
--- a/org.apache.juneau.samples/src/test/java/org/apache/juneau/server/samples/CT_SampleRemoteableServicesResource.java
+++ /dev/null
@@ -1,69 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.server.samples;
-
-import static org.junit.Assert.*;
-
-import org.apache.juneau.client.*;
-import org.apache.juneau.json.*;
-import org.apache.juneau.samples.addressbook.*;
-import org.apache.juneau.transforms.*;
-import org.apache.juneau.urlencoding.*;
-import org.apache.juneau.xml.*;
-import org.junit.*;
-
-public class CT_SampleRemoteableServicesResource {
-
- static RestClient[] clients;
-
- @BeforeClass
- public static void beforeClass() throws Exception {
- clients = new RestClient[] {
- new SamplesRestClient(JsonSerializer.class, JsonParser.class),
- new SamplesRestClient(XmlSerializer.class, XmlParser.class),
-// TODO - broken? new TestRestClient(HtmlSerializer.class, HtmlParser.class).setAccept("text/html+stripped"),
- new SamplesRestClient(UonSerializer.class, UonParser.class),
- };
- for (RestClient c : clients) {
- c.addTransforms(CalendarTransform.Medium.class);
- c.setRemoteableServletUri("/remoteable");
- c.setProperty(XmlSerializerContext.XML_autoDetectNamespaces, true);
- }
- }
-
- @AfterClass
- public static void afterClass() {
- for (RestClient c : clients) {
- c.closeQuietly();
- }
- }
-
- //====================================================================================================
- // Get AddressBookResource as JSON
- //====================================================================================================
- @Test
- public void testBasic() throws Exception {
- for (RestClient client : clients) {
- IAddressBook ab = client.getRemoteableProxy(IAddressBook.class);
- Person p = ab.createPerson(
- new CreatePerson("Test Person",
- AddressBook.toCalendar("Aug 1, 1999"),
- new CreateAddress("Test street", "Test city", "Test state", 12345, true))
- );
- assertEquals(
- "{id:x,name:'Test Person',birthDate:'Aug 1, 1999',addresses:[{id:x,street:'Test street',city:'Test city',state:'Test state',zip:12345,isCurrent:true}],age:x}",
- JsonSerializer.DEFAULT_LAX.toString(p).replaceAll("id:\\d+", "id:x").replaceAll("age:\\d+", "age:x"));
- }
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau.samples/src/test/java/org/apache/juneau/server/samples/CT_TestMultiPartFormPosts.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau.samples/src/test/java/org/apache/juneau/server/samples/CT_TestMultiPartFormPosts.java b/org.apache.juneau.samples/src/test/java/org/apache/juneau/server/samples/CT_TestMultiPartFormPosts.java
deleted file mode 100755
index 168caca..0000000
--- a/org.apache.juneau.samples/src/test/java/org/apache/juneau/server/samples/CT_TestMultiPartFormPosts.java
+++ /dev/null
@@ -1,47 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.server.samples;
-
-import static org.junit.Assert.*;
-
-import java.io.*;
-
-import org.apache.http.*;
-import org.apache.http.entity.mime.*;
-import org.apache.juneau.client.*;
-import org.apache.juneau.internal.*;
-import org.apache.juneau.utils.*;
-import org.junit.*;
-
-public class CT_TestMultiPartFormPosts {
-
- private static String URL = "/tempDir";
- boolean debug = false;
-
- //====================================================================================================
- // Test that RestClient can handle multi-part form posts.
- //====================================================================================================
- @Test
- public void testUpload() throws Exception {
- RestClient client = new SamplesRestClient();
- File f = FileUtils.createTempFile("testMultiPartFormPosts.txt");
- IOPipe.create(new StringReader("test!"), new FileWriter(f)).closeOut().run();
- HttpEntity entity = MultipartEntityBuilder.create().addBinaryBody(f.getName(), f).build();
- client.doPost(URL + "/upload", entity);
-
- String downloaded = client.doGet(URL + '/' + f.getName() + "?method=VIEW").getResponseAsString();
- assertEquals("test!", downloaded);
-
- client.closeQuietly();
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau.samples/src/test/java/org/apache/juneau/server/samples/RootResourcesTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau.samples/src/test/java/org/apache/juneau/server/samples/RootResourcesTest.java b/org.apache.juneau.samples/src/test/java/org/apache/juneau/server/samples/RootResourcesTest.java
new file mode 100755
index 0000000..6fe41cb
--- /dev/null
+++ b/org.apache.juneau.samples/src/test/java/org/apache/juneau/server/samples/RootResourcesTest.java
@@ -0,0 +1,146 @@
+/***************************************************************************************************************************
+ * 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.juneau.server.samples;
+
+import static org.junit.Assert.*;
+
+import java.net.*;
+
+import org.apache.juneau.*;
+import org.apache.juneau.client.*;
+import org.apache.juneau.html.*;
+import org.apache.juneau.json.*;
+import org.apache.juneau.server.labels.*;
+import org.apache.juneau.xml.*;
+import org.junit.*;
+
+public class RootResourcesTest {
+
+ private static String path = URI.create(Constants.getSampleUrl()).getPath(); // /jazz/juneau/sample
+ private static boolean debug = false;
+
+ private static RestClient jsonClient;
+
+ @BeforeClass
+ public static void beforeClass() {
+ jsonClient = new SamplesRestClient(JsonSerializer.DEFAULT, JsonParser.DEFAULT);
+ }
+
+ @AfterClass
+ public static void afterClass() {
+ jsonClient.closeQuietly();
+ }
+
+ //====================================================================================================
+ // text/json
+ //====================================================================================================
+ @Test
+ public void testJson() throws Exception {
+ RestClient client = new SamplesRestClient(JsonSerializer.DEFAULT, JsonParser.DEFAULT);
+ RestCall r = client.doGet("");
+ ResourceDescription[] x = r.getResponse(ResourceDescription[].class);
+ assertEquals("helloWorld", x[0].getName().getName());
+ assertEquals(path + "/helloWorld", x[0].getName().getHref());
+ assertEquals("Hello World sample resource", x[0].getDescription());
+
+ r = jsonClient.doOptions("");
+ ObjectMap x2 = r.getResponse(ObjectMap.class);
+ String s = x2.getString("description");
+ if (debug) System.err.println(s);
+ assertTrue(s, s.startsWith("This is an example"));
+
+ client.closeQuietly();
+ }
+
+ //====================================================================================================
+ // text/xml
+ //====================================================================================================
+ @Test
+ public void testXml() throws Exception {
+ RestClient client = new SamplesRestClient().setParser(XmlParser.DEFAULT);
+ RestCall r = client.doGet("");
+ ResourceDescription[] x = r.getResponse(ResourceDescription[].class);
+ assertEquals("helloWorld", x[0].getName().getName());
+ assertEquals(path + "/helloWorld", x[0].getName().getHref());
+ assertEquals("Hello World sample resource", x[0].getDescription());
+
+ r = jsonClient.doOptions("");
+ ObjectMap x2 = r.getResponse(ObjectMap.class);
+ String s = x2.getString("description");
+ if (debug) System.err.println(s);
+ assertTrue(s, s.startsWith("This is an example"));
+
+ client.closeQuietly();
+ }
+
+ //====================================================================================================
+ // text/html+stripped
+ //====================================================================================================
+ @Test
+ public void testHtmlStripped() throws Exception {
+ RestClient client = new SamplesRestClient().setParser(HtmlParser.DEFAULT).setAccept("text/html+stripped");
+ RestCall r = client.doGet("");
+ ResourceDescription[] x = r.getResponse(ResourceDescription[].class);
+ assertEquals("helloWorld", x[0].getName().getName());
+ assertTrue(x[0].getName().getHref().endsWith("/helloWorld"));
+ assertEquals("Hello World sample resource", x[0].getDescription());
+
+ r = jsonClient.doOptions("").setHeader("Accept", "text/json");
+ ObjectMap x2 = r.getResponse(ObjectMap.class);
+ String s = x2.getString("description");
+ if (debug) System.err.println(s);
+ assertTrue(s, s.startsWith("This is an example"));
+
+ client.closeQuietly();
+ }
+
+ //====================================================================================================
+ // /htdoces/styles.css
+ //====================================================================================================
+ @Test
+ public void testStyleSheet() throws Exception {
+ RestClient client = new SamplesRestClient().setAccept("text/css");
+ RestCall r = client.doGet("/style.css");
+ String css = r.getResponseAsString();
+ if (debug) System.err.println(css);
+ assertTrue(css, css.indexOf("table {") != -1);
+
+ client.closeQuietly();
+ }
+
+ //====================================================================================================
+ // application/json+schema
+ //====================================================================================================
+ @Test
+ public void testJsonSchema() throws Exception {
+ RestClient client = new SamplesRestClient().setParser(JsonParser.DEFAULT).setAccept("text/json+schema");
+ RestCall r = client.doGet("");
+ ObjectMap m = r.getResponse(ObjectMap.class);
+ if (debug) System.err.println(m);
+ assertEquals("org.apache.juneau.server.labels.ChildResourceDescriptions<org.apache.juneau.server.labels.ResourceDescription>", m.getString("description"));
+ assertEquals("org.apache.juneau.server.labels.ResourceDescription", m.getObjectMap("items").getString("description"));
+
+ client.closeQuietly();
+ }
+
+ //====================================================================================================
+ // OPTIONS page
+ //====================================================================================================
+ @Test
+ public void testOptionsPage() throws Exception {
+ RestCall r = jsonClient.doOptions("");
+ ResourceOptions o = r.getResponse(ResourceOptions.class);
+ if (debug) System.err.println(o);
+ assertEquals("This is an example of a router resource that is used to access other resources.", o.getDescription());
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau.samples/src/test/java/org/apache/juneau/server/samples/SampleRemoteableServicesResourceTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau.samples/src/test/java/org/apache/juneau/server/samples/SampleRemoteableServicesResourceTest.java b/org.apache.juneau.samples/src/test/java/org/apache/juneau/server/samples/SampleRemoteableServicesResourceTest.java
new file mode 100755
index 0000000..3884195
--- /dev/null
+++ b/org.apache.juneau.samples/src/test/java/org/apache/juneau/server/samples/SampleRemoteableServicesResourceTest.java
@@ -0,0 +1,69 @@
+/***************************************************************************************************************************
+ * 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.juneau.server.samples;
+
+import static org.junit.Assert.*;
+
+import org.apache.juneau.client.*;
+import org.apache.juneau.json.*;
+import org.apache.juneau.samples.addressbook.*;
+import org.apache.juneau.transforms.*;
+import org.apache.juneau.urlencoding.*;
+import org.apache.juneau.xml.*;
+import org.junit.*;
+
+public class SampleRemoteableServicesResourceTest {
+
+ static RestClient[] clients;
+
+ @BeforeClass
+ public static void beforeClass() throws Exception {
+ clients = new RestClient[] {
+ new SamplesRestClient(JsonSerializer.class, JsonParser.class),
+ new SamplesRestClient(XmlSerializer.class, XmlParser.class),
+// TODO - broken? new TestRestClient(HtmlSerializer.class, HtmlParser.class).setAccept("text/html+stripped"),
+ new SamplesRestClient(UonSerializer.class, UonParser.class),
+ };
+ for (RestClient c : clients) {
+ c.addTransforms(CalendarTransform.Medium.class);
+ c.setRemoteableServletUri("/remoteable");
+ c.setProperty(XmlSerializerContext.XML_autoDetectNamespaces, true);
+ }
+ }
+
+ @AfterClass
+ public static void afterClass() {
+ for (RestClient c : clients) {
+ c.closeQuietly();
+ }
+ }
+
+ //====================================================================================================
+ // Get AddressBookResource as JSON
+ //====================================================================================================
+ @Test
+ public void testBasic() throws Exception {
+ for (RestClient client : clients) {
+ IAddressBook ab = client.getRemoteableProxy(IAddressBook.class);
+ Person p = ab.createPerson(
+ new CreatePerson("Test Person",
+ AddressBook.toCalendar("Aug 1, 1999"),
+ new CreateAddress("Test street", "Test city", "Test state", 12345, true))
+ );
+ assertEquals(
+ "{id:x,name:'Test Person',birthDate:'Aug 1, 1999',addresses:[{id:x,street:'Test street',city:'Test city',state:'Test state',zip:12345,isCurrent:true}],age:x}",
+ JsonSerializer.DEFAULT_LAX.toString(p).replaceAll("id:\\d+", "id:x").replaceAll("age:\\d+", "age:x"));
+ }
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau.samples/src/test/java/org/apache/juneau/server/samples/TestMultiPartFormPostsTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau.samples/src/test/java/org/apache/juneau/server/samples/TestMultiPartFormPostsTest.java b/org.apache.juneau.samples/src/test/java/org/apache/juneau/server/samples/TestMultiPartFormPostsTest.java
new file mode 100755
index 0000000..236e56b
--- /dev/null
+++ b/org.apache.juneau.samples/src/test/java/org/apache/juneau/server/samples/TestMultiPartFormPostsTest.java
@@ -0,0 +1,47 @@
+/***************************************************************************************************************************
+ * 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.juneau.server.samples;
+
+import static org.junit.Assert.*;
+
+import java.io.*;
+
+import org.apache.http.*;
+import org.apache.http.entity.mime.*;
+import org.apache.juneau.client.*;
+import org.apache.juneau.internal.*;
+import org.apache.juneau.utils.*;
+import org.junit.*;
+
+public class TestMultiPartFormPostsTest {
+
+ private static String URL = "/tempDir";
+ boolean debug = false;
+
+ //====================================================================================================
+ // Test that RestClient can handle multi-part form posts.
+ //====================================================================================================
+ @Test
+ public void testUpload() throws Exception {
+ RestClient client = new SamplesRestClient();
+ File f = FileUtils.createTempFile("testMultiPartFormPosts.txt");
+ IOPipe.create(new StringReader("test!"), new FileWriter(f)).closeOut().run();
+ HttpEntity entity = MultipartEntityBuilder.create().addBinaryBody(f.getName(), f).build();
+ client.doPost(URL + "/upload", entity);
+
+ String downloaded = client.doGet(URL + '/' + f.getName() + "?method=VIEW").getResponseAsString();
+ assertEquals("test!", downloaded);
+
+ client.closeQuietly();
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_JacocoDummy.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_JacocoDummy.java b/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_JacocoDummy.java
deleted file mode 100755
index 8c7ebf7..0000000
--- a/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_JacocoDummy.java
+++ /dev/null
@@ -1,37 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.server;
-
-import java.lang.reflect.*;
-
-import org.junit.*;
-
-public class CT_JacocoDummy {
-
- //====================================================================================================
- // Dummy code to add test coverage in Jacoco.
- //====================================================================================================
- @Test
- public void accessPrivateConstructorsOnStaticUtilityClasses() throws Exception {
-
- Class<?>[] classes = new Class[] {
- RestUtils.class
- };
-
- for (Class<?> c : classes) {
- Constructor<?> c1 = c.getDeclaredConstructor();
- c1.setAccessible(true);
- c1.newInstance();
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_RestUtils.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_RestUtils.java b/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_RestUtils.java
deleted file mode 100755
index e97ee08..0000000
--- a/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_RestUtils.java
+++ /dev/null
@@ -1,188 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.server;
-
-import static org.apache.juneau.server.RestUtils.*;
-import static org.junit.Assert.*;
-
-import org.junit.*;
-
-public class CT_RestUtils {
-
- //====================================================================================================
- // decode(String)
- //====================================================================================================
- @Test
- public void testDecode() throws Exception {
- assertNull(decode(null));
- assertEquals("foo/bar baz bing", decode("foo%2Fbar+baz++bing"));
- }
-
- //====================================================================================================
- // encode(String)
- //====================================================================================================
- @Test
- public void testEncode() throws Exception {
- assertNull(encode(null));
- assertEquals("foo%2Fbar+baz++bing", encode("foo/bar baz bing"));
- assertEquals("foobar", encode("foobar"));
- assertEquals("+", encode(" "));
- assertEquals("%2F", encode("/"));
- }
-
- //====================================================================================================
- // trimPathInfo(String,String)
- //====================================================================================================
- @Test
- public void testGetServletURI() throws Exception {
- String e, sp, cp;
-
- e = "http://hostname";
- sp = "";
- cp = "";
-
- for (String s : new String[]{
- "http://hostname",
- "http://hostname/foo",
- "http://hostname?foo",
- "http://hostname/?foo"})
- assertEquals(e, trimPathInfo(new StringBuffer(s), cp, sp).toString());
-
- for (String s : new String[]{
- "http:/hostname?foo"}) {
- try {
- trimPathInfo(new StringBuffer(s), cp, sp);
- fail("Exception expected - " + s);
- } catch (RuntimeException ex) {}
- }
-
-
- e = "http://hostname";
- sp = "/";
- cp = "/";
-
- for (String s : new String[]{
- "http://hostname",
- "http://hostname/foo",
- "http://hostname?foo",
- "http://hostname/?foo"})
- assertEquals(e, trimPathInfo(new StringBuffer(s), cp, sp).toString());
-
- e = "http://hostname/foo";
- sp = "/foo";
- cp = "/";
-
- for (String s : new String[]{
- "http://hostname/foo",
- "http://hostname/foo/bar",
- "http://hostname/foo?bar"})
- assertEquals(e, trimPathInfo(new StringBuffer(s), cp, sp).toString());
-
- for (String s : new String[]{
- "http://hostname/foo2",
- "http://hostname/fo2",
- "http://hostname?foo",
- "http://hostname/fo?bar",
- "http:/hostname/foo"}) {
- try {
- trimPathInfo(new StringBuffer(s), cp, sp);
- fail("Exception expected - " + s);
- } catch (RuntimeException ex) {}
- }
-
- e = "http://hostname/foo/bar";
- sp = "/foo/bar";
- cp = "/";
-
- for (String s : new String[]{
- "http://hostname/foo/bar",
- "http://hostname/foo/bar/baz",
- "http://hostname/foo/bar?baz"})
- assertEquals(e, trimPathInfo(new StringBuffer(s), cp, sp).toString());
-
- for (String s : new String[]{
- "http://hostname/foo2/bar",
- "http://hostname/foo/bar2"
- }) {
- try {
- trimPathInfo(new StringBuffer(s), cp, sp);
- fail("Exception expected - " + s);
- } catch (RuntimeException ex) {}
- }
-
- e = "http://hostname/foo/bar";
- sp = "/bar";
- cp = "/foo";
-
- for (String s : new String[]{
- "http://hostname/foo/bar",
- "http://hostname/foo/bar/baz",
- "http://hostname/foo/bar?baz"})
- assertEquals(e, trimPathInfo(new StringBuffer(s), cp, sp).toString());
-
- for (String s : new String[]{
- "http://hostname/foo2/bar",
- "http://hostname/foo/bar2"
- }) {
- try {
- trimPathInfo(new StringBuffer(s), cp, sp);
- fail("Exception expected - " + s);
- } catch (RuntimeException ex) {}
- }
- }
-
- //====================================================================================================
- // trimSlashes(String)
- //====================================================================================================
- @Test
- public void testTrimSlashes() throws Exception {
- assertNull(trimSlashes(null));
- assertEquals("", trimSlashes(""));
- assertEquals("", trimSlashes("/"));
- assertEquals("", trimSlashes("//"));
- assertEquals("foo/bar", trimSlashes("foo/bar"));
- assertEquals("foo/bar", trimSlashes("foo/bar//"));
- assertEquals("foo/bar", trimSlashes("/foo/bar//"));
- assertEquals("foo/bar", trimSlashes("//foo/bar//"));
- }
-
- //====================================================================================================
- // trimTrailingSlashes(String)
- //====================================================================================================
- @Test
- public void testTrimTrailingSlashes() throws Exception {
- assertNull(trimTrailingSlashes((String)null));
- assertEquals("", trimTrailingSlashes(""));
- assertEquals("", trimTrailingSlashes("/"));
- assertEquals("", trimTrailingSlashes("//"));
- assertEquals("foo/bar", trimTrailingSlashes("foo/bar"));
- assertEquals("foo/bar", trimTrailingSlashes("foo/bar//"));
- assertEquals("/foo/bar", trimTrailingSlashes("/foo/bar//"));
- assertEquals("//foo/bar", trimTrailingSlashes("//foo/bar//"));
- }
-
- //====================================================================================================
- // trimTrailingSlashes(StringBuffer)
- //====================================================================================================
- @Test
- public void testTrimTrailingSlashes2() throws Exception {
- assertNull(trimTrailingSlashes((StringBuffer)null));
- assertEquals("", trimTrailingSlashes(new StringBuffer("")).toString());
- assertEquals("", trimTrailingSlashes(new StringBuffer("/")).toString());
- assertEquals("", trimTrailingSlashes(new StringBuffer("//")).toString());
- assertEquals("foo/bar", trimTrailingSlashes(new StringBuffer("foo/bar")).toString());
- assertEquals("foo/bar", trimTrailingSlashes(new StringBuffer("foo/bar//")).toString());
- assertEquals("/foo/bar", trimTrailingSlashes(new StringBuffer("/foo/bar//")).toString());
- assertEquals("//foo/bar", trimTrailingSlashes(new StringBuffer("//foo/bar//")).toString());
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestAcceptCharset.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestAcceptCharset.java b/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestAcceptCharset.java
deleted file mode 100755
index 9162208..0000000
--- a/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestAcceptCharset.java
+++ /dev/null
@@ -1,123 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.server;
-
-import static javax.servlet.http.HttpServletResponse.*;
-import static org.apache.juneau.server.TestUtils.*;
-import static org.junit.Assert.*;
-
-import java.io.*;
-
-import org.apache.juneau.client.*;
-import org.apache.juneau.internal.*;
-import org.junit.*;
-
-public class CT_TestAcceptCharset {
-
- boolean debug = false;
-
- //====================================================================================================
- // Test that Q-values are being resolved correctly.
- //====================================================================================================
- @Test
- public void testQValues() throws Exception {
- RestClient client = new TestRestClient().setHeader("Accept", "text/plain");
-
- check1(client, "utf-8", "utf-8");
- check1(client, "iso-8859-1", "iso-8859-1");
- check1(client, "bad,utf-8", "utf-8");
- check1(client, "utf-8,bad", "utf-8");
- check1(client, "bad;q=0.9,utf-8;q=0.1", "utf-8");
- check1(client, "bad;q=0.1,utf-8;q=0.9", "utf-8");
- check1(client, "utf-8,iso-8859-1", "utf-8");
- check1(client, "iso-8859-1,utf-8", "utf-8");
- check1(client, "utf-8;q=0.9,iso-8859-1;q=0.1", "utf-8");
- check1(client, "utf-8;q=0.1,iso-8859-1;q=0.9", "iso-8859-1");
- check1(client, "*", "utf-8");
- check1(client, "bad,iso-8859-1;q=0.5,*;q=0.1", "iso-8859-1");
- check1(client, "bad,iso-8859-1;q=0.1,*;q=0.5", "utf-8");
-
- client.closeQuietly();
- }
-
- private void check1(RestClient client, String requestCharset, String responseCharset) throws Exception {
- RestCall r;
- InputStream is;
- String url = "/testAcceptCharset/testQValues";
- r = client.doGet(url).setHeader("Accept-Charset", requestCharset).connect();
- assertTrue(r.getResponse().getFirstHeader("Content-Type").getValue().toLowerCase().contains(responseCharset));
- is = r.getInputStream();
- assertEquals("foo", IOUtils.read(new InputStreamReader(is, responseCharset)));
- }
-
- //====================================================================================================
- // Validate various Accept-Charset variations.
- //====================================================================================================
- @Test
- public void testCharsetOnResponse() throws Exception {
- RestClient client = new TestRestClient().setAccept("text/plain").setContentType("text/plain");
- String url = "/testAcceptCharset/testCharsetOnResponse";
- String r;
-
- r = client.doPut(url, new StringReader("")).getResponseAsString();
- assertEquals("utf-8/utf-8", r.toLowerCase());
-
- r = client.doPut(url, new StringReader("")).setHeader("Accept-Charset", "Shift_JIS").getResponseAsString();
- assertEquals("utf-8/shift_jis", r.toLowerCase());
-
- try {
- r = client.doPut(url+"?noTrace=true", new StringReader("")).setHeader("Accept-Charset", "BAD").getResponseAsString();
- fail("Exception expected");
- } catch (RestCallException e) {
- checkErrorResponse(debug, e, SC_NOT_ACCEPTABLE, "No supported charsets in header 'Accept-Charset': 'BAD'");
- }
-
- r = client.doPut(url, new StringReader("")).setHeader("Accept-Charset", "UTF-8").getResponseAsString();
- assertEquals("utf-8/utf-8", r.toLowerCase());
-
- r = client.doPut(url, new StringReader("")).setHeader("Accept-Charset", "bad,iso-8859-1").getResponseAsString();
- assertEquals("utf-8/iso-8859-1", r.toLowerCase());
-
- r = client.doPut(url, new StringReader("")).setHeader("Accept-Charset", "bad;q=0.9,iso-8859-1;q=0.1").getResponseAsString();
- assertEquals("utf-8/iso-8859-1", r.toLowerCase());
-
- r = client.doPut(url, new StringReader("")).setHeader("Accept-Charset", "bad;q=0.1,iso-8859-1;q=0.9").getResponseAsString();
- assertEquals("utf-8/iso-8859-1", r.toLowerCase());
-
- client.setHeader("Accept-Charset", "utf-8");
-
- r = client.doPut(url, new StringReader("")).setHeader("Content-Type", "text/plain").getResponseAsString();
- assertEquals("utf-8/utf-8", r.toLowerCase());
-
- r = client.doPut(url, new StringReader("")).setHeader("Content-Type", "text/plain;charset=utf-8").getResponseAsString();
- assertEquals("utf-8/utf-8", r.toLowerCase());
-
- r = client.doPut(url, new StringReader("")).setHeader("Content-Type", "text/plain;charset=UTF-8").getResponseAsString();
- assertEquals("utf-8/utf-8", r.toLowerCase());
-
- r = client.doPut(url, new StringReader("")).setHeader("Content-Type", "text/plain;charset=iso-8859-1").getResponseAsString();
- assertEquals("iso-8859-1/utf-8", r.toLowerCase());
-
- r = client.doPut(url, new StringReader("")).setHeader("Content-Type", "text/plain;charset=Shift_JIS").getResponseAsString();
- assertEquals("shift_jis/utf-8", r.toLowerCase());
-
- try {
- r = client.doPut(url + "?noTrace=true&Content-Type=text/plain;charset=BAD", new StringReader("")).getResponseAsString();
- fail("Exception expected");
- } catch (RestCallException e) {
- checkErrorResponse(debug, e, SC_UNSUPPORTED_MEDIA_TYPE, "Unsupported charset in header 'Content-Type': 'text/plain;charset=BAD'");
- }
-
- client.closeQuietly();
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestBeanContextProperties.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestBeanContextProperties.java b/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestBeanContextProperties.java
deleted file mode 100755
index 3358d26..0000000
--- a/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestBeanContextProperties.java
+++ /dev/null
@@ -1,37 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.server;
-
-import static org.junit.Assert.*;
-
-import org.apache.juneau.client.*;
-import org.apache.juneau.json.*;
-import org.junit.*;
-
-public class CT_TestBeanContextProperties {
-
- boolean debug = false;
-
- //====================================================================================================
- // Validate that filters defined on class filter to underlying bean context.
- //====================================================================================================
- @Test
- public void testClassTransforms() throws Exception {
- RestClient client = new TestRestClient(JsonSerializer.class, JsonParser.class);
- String r;
- r = client.doGet("/testBeanContext/testClassTransforms/2001-07-04T15:30:45Z?d2=2001-07-05T15:30:45Z").setHeader("X-D3", "2001-07-06T15:30:45Z").getResponseAsString();
- assertEquals("d1=2001-07-04T15:30:45Z,d2=2001-07-05T15:30:45Z,d3=2001-07-06T15:30:45Z", r);
-
- client.closeQuietly();
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestCallbackStrings.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestCallbackStrings.java b/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestCallbackStrings.java
deleted file mode 100755
index c1891d8..0000000
--- a/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestCallbackStrings.java
+++ /dev/null
@@ -1,50 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.server;
-
-import static org.junit.Assert.*;
-
-import org.apache.juneau.client.*;
-import org.junit.*;
-
-public class CT_TestCallbackStrings {
-
- //====================================================================================================
- // Basic tests using &Content parameter
- //====================================================================================================
- @Test
- public void test() throws Exception {
- RestClient c = new TestRestClient().setAccept("text/json+simple");
- String r;
-
- r = c.doCallback("GET /testCallback").getResponseAsString();
- assertEquals("{method:'GET',headers:{},content:''}", r);
-
- r = c.doCallback("GET /testCallback some sample content").getResponseAsString();
- assertEquals("{method:'GET',headers:{},content:'some sample content'}", r);
-
- r = c.doCallback("GET {Foo-X:123,Foo-Y:'abc'} /testCallback").getResponseAsString();
- assertEquals("{method:'GET',headers:{'Foo-X':'123','Foo-Y':'abc'},content:''}", r);
-
- r = c.doCallback("GET { Foo-X : 123, Foo-Y : 'abc' } /testCallback").getResponseAsString();
- assertEquals("{method:'GET',headers:{'Foo-X':'123','Foo-Y':'abc'},content:''}", r);
-
- r = c.doCallback("GET {Foo-X:123,Foo-Y:'abc'} /testCallback some sample content ").getResponseAsString();
- assertEquals("{method:'GET',headers:{'Foo-X':'123','Foo-Y':'abc'},content:'some sample content'}", r);
-
- r = c.doCallback("PUT {Foo-X:123,Foo-Y:'abc'} /testCallback some sample content ").getResponseAsString();
- assertEquals("{method:'PUT',headers:{'Foo-X':'123','Foo-Y':'abc'},content:'some sample content'}", r);
-
- c.closeQuietly();
- }
-}
[28/44] incubator-juneau git commit: Rename CT_* testcases.
Posted by ja...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/CT_ObjectMap.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/CT_ObjectMap.java b/org.apache.juneau/src/test/java/org/apache/juneau/CT_ObjectMap.java
deleted file mode 100755
index f66d850..0000000
--- a/org.apache.juneau/src/test/java/org/apache/juneau/CT_ObjectMap.java
+++ /dev/null
@@ -1,313 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau;
-
-import static org.apache.juneau.TestUtils.*;
-import static org.junit.Assert.*;
-
-import org.apache.juneau.utils.*;
-import org.junit.*;
-
-public class CT_ObjectMap {
-
- //====================================================================================================
- // testBasic
- //====================================================================================================
- @Test
- public void testBasic() throws Exception {
- String in;
-
- in = "{A:'asdf'}";
- checkStep(1, in, new ObjectMap(in).getString("A"), "asdf");
-
- in = "{A:{B:'asdf'}}";
- checkStep(2, in, getDeepString(new ObjectMap(in), "A/B"), "asdf");
- checkStep(3, in, new ObjectMap(in).getString("A"), "{B:'asdf'}");
-
- in = "{A:{B:'asdf'+\"asdf\"}}";
- checkStep(4, in, getDeepString(new ObjectMap(in), "A/B"), "asdfasdf");
- checkStep(5, in, new ObjectMap(in).getString("A"), "{B:'asdfasdf'}");
-
- in = "{A:{B:'asdf' + \n\t \"asdf\"}}";
- checkStep(6, in, getDeepString(new ObjectMap(in), "A/B"), "asdfasdf");
- checkStep(7, in, new ObjectMap(in).getString("A"), "{B:'asdfasdf'}");
-
- in = "{A:{B:'asdf\"asdf', C:\"asdf'asdf\", D : \"asdf\\\"asdf\", E: 'asdf\\\'asdf', F:\"asdf\\\'asdf\", G:'asdf\\\"asdf'}}";
- checkStep(8, in, getDeepString(new ObjectMap(in), "A/B"), "asdf\"asdf");
- checkStep(9, in, getDeepString(new ObjectMap(in), "A/C"), "asdf'asdf");
- checkStep(10, in, getDeepString(new ObjectMap(in), "A/D"), "asdf\"asdf");
- checkStep(11, in, getDeepString(new ObjectMap(in), "A/E"), "asdf'asdf");
- checkStep(12, in, getDeepString(new ObjectMap(in), "A/F"), "asdf'asdf");
- checkStep(13, in, getDeepString(new ObjectMap(in), "A/G"), "asdf\"asdf");
-
- in = "{A:123, B: 123}";
- checkStep(16, in, new Integer(new ObjectMap(in).getInt("A")).toString(), "123");
- checkStep(17, in, new Integer(new ObjectMap(in).getInt("B")).toString(), "123");
-
- in = "{A:true, B: true, C:false, D: false}";
- checkStep(18, in, new Boolean(new ObjectMap(in).getBoolean("A")).toString(), "true");
- checkStep(19, in, new Boolean(new ObjectMap(in).getBoolean("B")).toString(), "true");
- checkStep(20, in, new Boolean(new ObjectMap(in).getBoolean("C")).toString(), "false");
- checkStep(21, in, new Boolean(new ObjectMap(in).getBoolean("D")).toString(), "false");
-
- in = "{'AAA':{\"BBB\":\"CCC\",'DDD':false}}";
- checkStep(31, in, getDeepString(new ObjectMap(in), "AAA/BBB"), "CCC");
- checkStep(32, in, getDeepBoolean(new ObjectMap(in), "AAA/DDD").toString(), "false");
-
- in = " \n\n\t { 'AAA' : { \"BBB\" : \"CCC\" , 'DDD' : false } } \n\t";
- checkStep(33, in, getDeepString(new ObjectMap(in), "AAA/BBB"), "CCC");
- checkStep(34, in, getDeepBoolean(new ObjectMap(in), "AAA/DDD").toString(), "false");
-
- in = "/*x*/{A:'B','C':1,\"E\":[1,2,3],G:['g1','g2','g3']}";
- checkStep(100, in, new ObjectMap(in).getString("A"), "B");
- in = "{/*x*/A:'B','C':1,\"E\":[1,2,3],G:['g1','g2','g3']}";
- checkStep(101, in, new ObjectMap(in).getString("A"), "B");
- in = "{A/*x*/:'B','C':1,\"E\":[1,2,3],G:['g1','g2','g3']}";
- checkStep(102, in, new ObjectMap(in).getString("A"), "B");
- in = "{A:/*x*/'B','C':1,\"E\":[1,2,3],G:['g1','g2','g3']}";
- checkStep(103, in, new ObjectMap(in).getString("A"), "B");
- in = "{A:'/*x*/B','C':1,\"E\":[1,2,3],G:['g1','g2','g3']}";
- checkStep(104, in, new ObjectMap(in).getString("A"), "/*x*/B");
- in = "{A:'B/*x*/','C':1,\"E\":[1,2,3],G:['g1','g2','g3']}";
- checkStep(105, in, new ObjectMap(in).getString("A"), "B/*x*/");
- in = "{A:'B'/*x*/,'C':1,\"E\":[1,2,3],G:['g1','g2','g3']}";
- checkStep(106, in, new ObjectMap(in).getString("A"), "B");
- in = "{A:'B',/*x*/'C':1,\"E\":[1,2,3],G:['g1','g2','g3']}";
- checkStep(107, in, new ObjectMap(in).getString("C"), "1");
- in = "{A:'B','C':/*x*/1,\"E\":[1,2,3],G:['g1','g2','g3']}";
- checkStep(108, in, new ObjectMap(in).getString("C"), "1");
- in = "{A:'B','C':1/*x*/,\"E\":[1,2,3],G:['g1','g2','g3']}";
- checkStep(109, in, new ObjectMap(in).getString("C"), "1");
- in = "{A:'B','C':1,/*x*/\"E\":[1,2,3],G:['g1','g2','g3']}";
- checkStep(110, in, new ObjectMap(in).getObjectList("E").getString(0), "1");
- in = "{A:'B','C':1,\"/*x*/E\":[1,2,3],G:['g1','g2','g3']}";
- checkStep(111, in, new ObjectMap(in).getObjectList("/*x*/E").getString(0), "1");
- in = "{A:'B','C':1,\"E/*x*/\":[1,2,3],G:['g1','g2','g3']}";
- checkStep(112, in, new ObjectMap(in).getObjectList("E/*x*/").getString(0), "1");
- in = "{A:'B','C':1,\"E\"/*x*/:[1,2,3],G:['g1','g2','g3']}";
- checkStep(113, in, new ObjectMap(in).getObjectList("E").getString(0), "1");
- in = "{A:'B','C':1,\"E\":/*x*/[1,2,3],G:['g1','g2','g3']}";
- checkStep(114, in, new ObjectMap(in).getObjectList("E").getString(0), "1");
- in = "{A:'B','C':1,\"E\":[/*x*/1,2,3],G:['g1','g2','g3']}";
- checkStep(115, in, new ObjectMap(in).getObjectList("E").getString(0), "1");
- in = "{A:'B','C':1,\"E\":[1/*x*/,2,3],G:['g1','g2','g3']}";
- checkStep(116, in, new ObjectMap(in).getObjectList("E").getString(0), "1");
- in = "{A:'B','C':1,\"E\":[1,/*x*/2,3],G:['g1','g2','g3']}";
- checkStep(117, in, new ObjectMap(in).getObjectList("E").getString(1), "2");
- in = "{A:'B','C':1,\"E\":[1,2/*x*/,3],G:['g1','g2','g3']}";
- checkStep(118, in, new ObjectMap(in).getObjectList("E").getString(1), "2");
- in = "{A:'B','C':1,\"E\":[1,2,/*x*/3],G:['g1','g2','g3']}";
- checkStep(119, in, new ObjectMap(in).getObjectList("E").getString(2), "3");
- in = "{A:'B','C':1,\"E\":[1,2,3]/*x*/,G:['g1','g2','g3']}";
- checkStep(120, in, new ObjectMap(in).getObjectList("E").getString(2), "3");
- in = "{A:'B','C':1,\"E\":[1,2,3],/*x*/G:['g1','g2','g3']}";
- checkStep(121, in, new ObjectMap(in).getObjectList("G").getString(0), "g1");
- in = "{A:'B','C':1,\"E\":[1,2,3],G:[/*x*/'g1','g2','g3']}";
- checkStep(122, in, new ObjectMap(in).getObjectList("G").getString(0), "g1");
- in = "{A:'B','C':1,\"E\":[1,2,3],G:['/*x*/g1','g2','g3']}";
- checkStep(123, in, new ObjectMap(in).getObjectList("G").getString(0), "/*x*/g1");
- in = "{A:'B','C':1,\"E\":[1,2,3],G:['g1'/*x*/,'g2','g3']}";
- checkStep(124, in, new ObjectMap(in).getObjectList("G").getString(0), "g1");
- in = "{A:'B','C':1,\"E\":[1,2,3],G:['g1',/*x*/'g2','g3']}";
- checkStep(125, in, new ObjectMap(in).getObjectList("G").getString(1), "g2");
- in = "{A:'B','C':1,\"E\":[1,2,3],G:['g1','g2'/*x*/,'g3']}";
- checkStep(126, in, new ObjectMap(in).getObjectList("G").getString(1), "g2");
- in = "{A:'B','C':1,\"E\":[1,2,3],G:['g1','g2',/*x*/'g3']}";
- checkStep(127, in, new ObjectMap(in).getObjectList("G").getString(2), "g3");
- in = "{A:'B','C':1,\"E\":[1,2,3],G:['g1','g2','g3'/*x*/]}";
- checkStep(128, in, new ObjectMap(in).getObjectList("G").getString(2), "g3");
- in = "{A:'B','C':1,\"E\":[1,2,3],G:['g1','g2','g3']/*x*/}";
- checkStep(129, in, new ObjectMap(in).getObjectList("G").getString(2), "g3");
- in = "{A:'B','C':1,\"E\":[1,2,3],G:['g1','g2','g3']}/*x*/";
- checkStep(130, in, new ObjectMap(in).getObjectList("G").getString(2), "g3");
-
- in = "/*\tx\t*///\tx\t\n\t/*\tx\t*/{A:'B','C':1,\"E\":[1,2,3],G:['g1','g2','g3']}";
- checkStep(201, in, new ObjectMap(in).getString("A"), "B");
- in = "{/*\tx\t*///\tx\t\n\t/*\tx\t*/A:'B','C':1,\"E\":[1,2,3],G:['g1','g2','g3']}";
- checkStep(202, in, new ObjectMap(in).getString("A"), "B");
- in = "{A/*\tx\t*///\tx\t\n\t/*\tx\t*/:'B','C':1,\"E\":[1,2,3],G:['g1','g2','g3']}";
- checkStep(203, in, new ObjectMap(in).getString("A"), "B");
- in = "{A:/*\tx\t*///\tx\t\n\t/*\tx\t*/'B','C':1,\"E\":[1,2,3],G:['g1','g2','g3']}";
- checkStep(204, in, new ObjectMap(in).getString("A"), "B");
- in = "{A:'/*\tx\t*///\tx\t\n\t/*\tx\t*/B','C':1,\"E\":[1,2,3],G:['g1','g2','g3']}";
- checkStep(205, in, new ObjectMap(in).getString("A"), "/*\tx\t*///\tx\t\n\t/*\tx\t*/B");
- in = "{A:'B/*\tx\t*///\tx\t\n\t/*\tx\t*/','C':1,\"E\":[1,2,3],G:['g1','g2','g3']}";
- checkStep(206, in, new ObjectMap(in).getString("A"), "B/*\tx\t*///\tx\t\n\t/*\tx\t*/");
- in = "{A:'B'/*\tx\t*///\tx\t\n\t/*\tx\t*/,'C':1,\"E\":[1,2,3],G:['g1','g2','g3']}";
- checkStep(207, in, new ObjectMap(in).getString("A"), "B");
- in = "{A:'B',/*\tx\t*///\tx\t\n\t/*\tx\t*/'C':1,\"E\":[1,2,3],G:['g1','g2','g3']}";
- checkStep(208, in, new ObjectMap(in).getString("C"), "1");
- in = "{A:'B','C':/*\tx\t*///\tx\t\n\t/*\tx\t*/1,\"E\":[1,2,3],G:['g1','g2','g3']}";
- checkStep(209, in, new ObjectMap(in).getString("C"), "1");
- in = "{A:'B','C':1/*\tx\t*///\tx\t\n\t/*\tx\t*/,\"E\":[1,2,3],G:['g1','g2','g3']}";
- checkStep(210, in, new ObjectMap(in).getString("C"), "1");
- in = "{A:'B','C':1,/*\tx\t*///\tx\t\n\t/*\tx\t*/\"E\":[1,2,3],G:['g1','g2','g3']}";
- checkStep(211, in, new ObjectMap(in).getObjectList("E").getString(0), "1");
- in = "{A:'B','C':1,\"/*\tx\t*///\tx\t\n\t/*\tx\t*/E\":[1,2,3],G:['g1','g2','g3']}";
- checkStep(212, in, new ObjectMap(in).getObjectList("/*\tx\t*///\tx\t\n\t/*\tx\t*/E").getString(0), "1");
- in = "{A:'B','C':1,\"E/*\tx\t*///\tx\t\n\t/*\tx\t*/\":[1,2,3],G:['g1','g2','g3']}";
- checkStep(213, in, new ObjectMap(in).getObjectList("E/*\tx\t*///\tx\t\n\t/*\tx\t*/").getString(0), "1");
- in = "{A:'B','C':1,\"E\"/*\tx\t*///\tx\t\n\t/*\tx\t*/:[1,2,3],G:['g1','g2','g3']}";
- checkStep(214, in, new ObjectMap(in).getObjectList("E").getString(0), "1");
- in = "{A:'B','C':1,\"E\":/*\tx\t*///\tx\t\n\t/*\tx\t*/[1,2,3],G:['g1','g2','g3']}";
- checkStep(215, in, new ObjectMap(in).getObjectList("E").getString(0), "1");
- in = "{A:'B','C':1,\"E\":[/*\tx\t*///\tx\t\n\t/*\tx\t*/1,2,3],G:['g1','g2','g3']}";
- checkStep(216, in, new ObjectMap(in).getObjectList("E").getString(0), "1");
- in = "{A:'B','C':1,\"E\":[1/*\tx\t*///\tx\t\n\t/*\tx\t*/,2,3],G:['g1','g2','g3']}";
- checkStep(217, in, new ObjectMap(in).getObjectList("E").getString(0), "1");
- in = "{A:'B','C':1,\"E\":[1,/*\tx\t*///\tx\t\n\t/*\tx\t*/2,3],G:['g1','g2','g3']}";
- checkStep(218, in, new ObjectMap(in).getObjectList("E").getString(1), "2");
- in = "{A:'B','C':1,\"E\":[1,2/*\tx\t*///\tx\t\n\t/*\tx\t*/,3],G:['g1','g2','g3']}";
- checkStep(219, in, new ObjectMap(in).getObjectList("E").getString(1), "2");
- in = "{A:'B','C':1,\"E\":[1,2,/*\tx\t*///\tx\t\n\t/*\tx\t*/3],G:['g1','g2','g3']}";
- checkStep(220, in, new ObjectMap(in).getObjectList("E").getString(2), "3");
- in = "{A:'B','C':1,\"E\":[1,2,3]/*\tx\t*///\tx\t\n\t/*\tx\t*/,G:['g1','g2','g3']}";
- checkStep(221, in, new ObjectMap(in).getObjectList("E").getString(2), "3");
- in = "{A:'B','C':1,\"E\":[1,2,3],/*\tx\t*///\tx\t\n\t/*\tx\t*/G:['g1','g2','g3']}";
- checkStep(222, in, new ObjectMap(in).getObjectList("G").getString(0), "g1");
- in = "{A:'B','C':1,\"E\":[1,2,3],G:[/*\tx\t*///\tx\t\n\t/*\tx\t*/'g1','g2','g3']}";
- checkStep(223, in, new ObjectMap(in).getObjectList("G").getString(0), "g1");
- in = "{A:'B','C':1,\"E\":[1,2,3],G:['/*\tx\t*///\tx\t\n\t/*\tx\t*/g1','g2','g3']}";
- checkStep(224, in, new ObjectMap(in).getObjectList("G").getString(0), "/*\tx\t*///\tx\t\n\t/*\tx\t*/g1");
- in = "{A:'B','C':1,\"E\":[1,2,3],G:['g1'/*\tx\t*///\tx\t\n\t/*\tx\t*/,'g2','g3']}";
- checkStep(225, in, new ObjectMap(in).getObjectList("G").getString(0), "g1");
- in = "{A:'B','C':1,\"E\":[1,2,3],G:['g1',/*\tx\t*///\tx\t\n\t/*\tx\t*/'g2','g3']}";
- checkStep(226, in, new ObjectMap(in).getObjectList("G").getString(1), "g2");
- in = "{A:'B','C':1,\"E\":[1,2,3],G:['g1','g2'/*\tx\t*///\tx\t\n\t/*\tx\t*/,'g3']}";
- checkStep(227, in, new ObjectMap(in).getObjectList("G").getString(1), "g2");
- in = "{A:'B','C':1,\"E\":[1,2,3],G:['g1','g2',/*\tx\t*///\tx\t\n\t/*\tx\t*/'g3']}";
- checkStep(228, in, new ObjectMap(in).getObjectList("G").getString(2), "g3");
- in = "{A:'B','C':1,\"E\":[1,2,3],G:['g1','g2','g3'/*\tx\t*///\tx\t\n\t/*\tx\t*/]}";
- checkStep(229, in, new ObjectMap(in).getObjectList("G").getString(2), "g3");
- in = "{A:'B','C':1,\"E\":[1,2,3],G:['g1','g2','g3']/*\tx\t*///\tx\t\n\t/*\tx\t*/}";
- checkStep(230, in, new ObjectMap(in).getObjectList("G").getString(2), "g3");
- in = "{A:'B','C':1,\"E\":[1,2,3],G:['g1','g2','g3']}/*\tx\t*///\tx\t\n\t/*\tx\t*/";
- checkStep(231, in, new ObjectMap(in).getObjectList("G").getString(2), "g3");
-
- in = "{ /* x */ // x \n /* x */ A:'B','C':1,\"E\":[1,2,3],G:['g1','g2','g3']}";
- checkStep(240, in, new ObjectMap(in).getString("A"), "B");
-
- in = "{A:'B','C':1,\"E\":[1,2,3],G:['g1','g2','g3']}";
- checkStep(301, in, new ObjectMap(in).getString("A", "default"), "B");
- in = "{/*A:'B',*/'C':1,\"E\":[1,2,3],G:['g1','g2','g3']}";
- checkStep(302, in, new ObjectMap(in).getString("A", "default"), "default");
- in = "{A:'B',/*'C':1,*/\"E\":[1,2,3],G:['g1','g2','g3']}";
- checkStep(303, in, new ObjectMap(in).getString("C", "default"), "default");
- in = "{A:'B','C':1,/*\"E\":[1,2,3],*/G:['g1','g2','g3']}";
- checkStep(304, in, new ObjectMap(in).getString("E", "default"), "default");
- in = "{A:'B','C':1,\"E\":[/*1,*/2,3],G:['g1','g2','g3']}";
- checkStep(305, in, new ObjectMap(in).getObjectList("E").getString(0), "2");
- in = "{A:'B','C':1,\"E\":[1,/*2,*/3],G:['g1','g2','g3']}";
- checkStep(306, in, new ObjectMap(in).getObjectList("E").getString(1), "3");
- in = "{A:'B','C':1,\"E\":[1,2/*,3*/],G:['g1','g2','g3']}";
- checkStep(307, in, new ObjectMap(in).getObjectList("E").getString(1), "2");
- in = "{A:'B','C':1,\"E\":[1,2,3],G:[/*'g1',*/'g2','g3']}";
- checkStep(308, in, new ObjectMap(in).getObjectList("G").getString(0), "g2");
- in = "{A:'B','C':1,\"E\":[1,2,3],G:['g1'/*,'g2'*/,'g3']}";
- checkStep(309, in, new ObjectMap(in).getObjectList("G").getString(1), "g3");
- in = "{A:'B','C':1,\"E\":[1,2,3],G:['g1','g2'/*,'g3'*/]}";
- checkStep(310, in, new ObjectMap(in).getObjectList("G").getString(1), "g2");
- in = "{A:'B','C':1,\"E\":[1,2,3],G:['g1','g2','g3']}";
- checkStep(310, in, new ObjectMap(in).getObjectList("G").getString(1), "g2");
-
- // Check keys that contain array indexes
- in = "{A:{B:[{C:'c0'},{C:'c1'},{C:'c2'}]}}";
- checkStep(401, in, getDeepString(new ObjectMap(in), "A/B/0/C"), "c0");
- checkStep(402, in, getDeepString(new ObjectMap(in), "A/B/1/C"), "c1");
- checkStep(403, in, getDeepString(new ObjectMap(in), "A/B/2/C"), "c2");
-
- // Check extended unicode characters.
- in = "{'\U00024b62\U00024b62':'\U00024b62\U00024b62'}";
- checkStep(1, in, new ObjectMap(in).getString("\U00024b62\U00024b62"), "\U00024b62\U00024b62");
- }
-
- private String getDeepString(ObjectMap m, String url) {
- PojoRest r = new PojoRest(m);
- return (String)r.get(url);
- }
-
- private Boolean getDeepBoolean(ObjectMap m, String url) {
- PojoRest r = new PojoRest(m);
- return (Boolean)r.get(url);
- }
-
- private void checkStep(int step, String input, String output, String expectedValue) {
- if (!output.equals(expectedValue)) {
- String msg = "Step #" + step + " failed: [" + input + "]->[" + output + "]...Expected value=[" + expectedValue + "]";
- fail(msg);
- }
- }
-
- //====================================================================================================
- // testComparison
- //====================================================================================================
- @Test
- public void testComparison() throws Exception {
- ObjectMap m1 = new ObjectMap("{ firstName:'John', lastName:'Smith', age:123, isDeceased:false }");
- ObjectMap m2 = new ObjectMap("{ age:123, isDeceased:false, lastName:'Smith', firstName:'John' }");
-
- assertTrue(m1.equals(m2));
- }
-
- //====================================================================================================
- // testParent
- //====================================================================================================
- @Test
- public void testParent() throws Exception {
- ObjectMap m1 = new ObjectMap("{a:1}");
- ObjectMap m2 = new ObjectMap("{b:2}").setInner(m1);
-
- assertEquals(new Integer(1), m2.getInt("a"));
- }
-
- //====================================================================================================
- // testUpdatability
- //====================================================================================================
- @Test
- public void testUpdatability() throws Exception {
- ObjectMap m = new ObjectMap("{a:[{b:'c'}]}");
- ObjectList l = m.getObjectList("a");
- ObjectMap m2 = l.getObjectMap(0);
- m2.put("b", "x");
- assertObjectEquals("{a:[{b:'x'}]}", m);
-
- m = new ObjectMap("{a:[{b:'c'}]}");
- for (ObjectMap m3 : m.getObjectList("a").elements(ObjectMap.class))
- m3.put("b", "y");
-
- assertObjectEquals("{a:[{b:'y'}]}", m);
- }
-
- //====================================================================================================
- // testAtMethods
- //====================================================================================================
- @Test
- public void testAtMethods() throws Exception {
- ObjectMap m = new ObjectMap("{a:[{b:'c'}]}");
- String r;
-
- r = m.getAt(String.class, "a/0/b");
- assertEquals("c", r);
-
- m.putAt("a/0/b", "d");
- r = m.getAt(String.class, "a/0/b");
- assertEquals("d", r);
-
- m.postAt("a", "e");
- r = m.getAt(String.class, "a/1");
- assertEquals("e", r);
-
- m.deleteAt("a/1");
- assertEquals("{a:[{b:'d'}]}", m.toString());
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/CT_ParserGenerics.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/CT_ParserGenerics.java b/org.apache.juneau/src/test/java/org/apache/juneau/CT_ParserGenerics.java
deleted file mode 100755
index 11f23b1..0000000
--- a/org.apache.juneau/src/test/java/org/apache/juneau/CT_ParserGenerics.java
+++ /dev/null
@@ -1,71 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau;
-
-import static org.junit.Assert.*;
-
-import java.util.*;
-
-import org.apache.juneau.json.*;
-import org.apache.juneau.parser.*;
-import org.junit.*;
-
-@SuppressWarnings("serial")
-public class CT_ParserGenerics {
-
- //====================================================================================================
- // Test generic maps
- //====================================================================================================
- @Test
- public void testMap() throws Exception {
- ReaderParser p = JsonParser.DEFAULT;
-
- String t = "{foo:{bar:'baz'}}";
- Map<String,TreeMap<String,String>> r1 = p.parse(t, TestMap1.class);
- assertEquals(TestMap1.class, r1.getClass());
- assertEquals(TreeMap.class, r1.get("foo").getClass());
-
- t = "{foo:[1,2,3]}";
- Map<String,LinkedList<Integer>> r2 = p.parse(t, TestMap2.class);
- assertEquals(TestMap2.class, r2.getClass());
- assertEquals(LinkedList.class, r2.get("foo").getClass());
- assertEquals(Integer.class, r2.get("foo").get(0).getClass());
- }
-
- public static class TestMap1 extends LinkedHashMap<String,TreeMap<String,String>> {}
- public static class TestMap2 extends LinkedHashMap<String,LinkedList<Integer>> {}
-
- //====================================================================================================
- // Test generic maps
- //====================================================================================================
- @Test
- public void testCollection() throws Exception {
- ReaderParser p = JsonParser.DEFAULT;
-
- String t = "[{foo:{bar:'baz'}}]";
- List<TestMap1> r1 = p.parse(t, TestCollection1.class);
- assertEquals(TestCollection1.class, r1.getClass());
- assertEquals(TestMap1.class, r1.get(0).getClass());
- assertEquals(TreeMap.class, r1.get(0).get("foo").getClass());
-
- t = "[{foo:[1,2,3]}]";
- List<TestMap2> r2 = p.parse(t, TestCollection2.class);
- assertEquals(TestCollection2.class, r2.getClass());
- assertEquals(TestMap2.class, r2.get(0).getClass());
- assertEquals(LinkedList.class, r2.get(0).get("foo").getClass());
- assertEquals(Integer.class, r2.get(0).get("foo").get(0).getClass());
- }
-
- public static class TestCollection1 extends LinkedList<TestMap1> {}
- public static class TestCollection2 extends LinkedList<TestMap2> {}
-}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/CT_ParserReader.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/CT_ParserReader.java b/org.apache.juneau/src/test/java/org/apache/juneau/CT_ParserReader.java
deleted file mode 100755
index af23b4a..0000000
--- a/org.apache.juneau/src/test/java/org/apache/juneau/CT_ParserReader.java
+++ /dev/null
@@ -1,181 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau;
-
-import static org.junit.Assert.*;
-
-import java.io.*;
-
-import org.apache.juneau.parser.*;
-import org.junit.*;
-
-public class CT_ParserReader {
-
- //====================================================================================================
- // testBasic
- //====================================================================================================
- @Test
- public void testBasic() throws Exception {
- String t = "01234567890123456789012345678901234567890123456789";
-
- // Min buff size is 20.
- ParserReader pr = new ParserReader(new StringReader(t));
- String r = read(pr);
- assertEquals(t, r);
- pr.close();
-
- pr = new ParserReader(new StringReader(t));
- pr.read();
- pr.unread();
- r = read(pr);
- assertEquals(t, r);
- pr.close();
-
- pr = new ParserReader(new StringReader(t));
- assertEquals('0', (char)pr.peek());
- assertEquals('0', (char)pr.peek());
- r = read(pr);
- assertEquals(t, r);
-
- pr = new ParserReader(new StringReader(t));
- pr.read();
- pr.unread();
- try {
- pr.unread();
- fail("Exception expected");
- } catch (IOException e) {
- // Good
- }
- }
-
- //====================================================================================================
- // testMarking
- //====================================================================================================
- @Test
- public void testMarking() throws Exception {
- String t = "a123456789b123456789c123456789d123456789e123456789f123456789g123456789h123456789i123456789j123456789";
- String r = null;
-
- // Min buff size is 20.
- ParserReader pr = new ParserReader(t);
- read(pr, 5);
- pr.mark();
- read(pr, 10);
- r = pr.getMarked();
- assertEquals("56789b1234", r);
- r = read(pr);
- assertEquals("56789c123456789d123456789e123456789f123456789g123456789h123456789i123456789j123456789", r);
-
- // Force doubling of buffer size
- pr = new ParserReader(t);
- read(pr, 5);
- pr.mark();
- read(pr, 20);
- r = pr.getMarked();
- assertEquals("56789b123456789c1234", r);
- r = read(pr);
- assertEquals("56789d123456789e123456789f123456789g123456789h123456789i123456789j123456789", r);
- }
-
- //====================================================================================================
- // testReadStrings
- //====================================================================================================
- @Test
- public void testReadStrings() throws Exception {
- String t = "a123456789b123456789c123456789d123456789e123456789f123456789g123456789h123456789i123456789j123456789";
-
- // Min buff size is 20.
- ParserReader pr = new ParserReader(t);
- assertEquals("a123456789", pr.read(10));
- pr.mark();
- assertEquals("b123456789c123456789", pr.read(20));
- assertEquals("d123456789e123456789f123456789", pr.read(30));
- assertEquals("123456789c123456789d123456789e123456789f12345678", pr.getMarked(1, -1));
- assertEquals("g123456789h123456789i123456789j123456789", pr.read(100));
- assertEquals("", pr.read(100));
- pr.close();
- }
-
- //====================================================================================================
- // testReplace
- //====================================================================================================
- @Test
- public void testReplace() throws Exception {
- String t = "a123456789b123456789c123456789d123456789e123456789f123456789g123456789h123456789i123456789j123456789";
-
- // Min buff size is 20.
- ParserReader pr = new ParserReader(t);
- assertEquals("a123456789", pr.read(10));
- pr.mark();
- assertEquals("b123456789", pr.read(10));
- pr.replace('x');
- assertEquals("c123456789", pr.read(10));
- assertEquals("b12345678xc123456789", pr.getMarked());
- pr.close();
-
- pr = new ParserReader(t);
- assertEquals("a123456789", pr.read(10));
- pr.mark();
- assertEquals("b123456789", pr.read(10));
- pr.replace('x', 5);
- assertEquals("c123456789", pr.read(10));
- assertEquals("b1234xc123456789", pr.getMarked());
- pr.close();
- }
-
- //====================================================================================================
- // testDelete
- //====================================================================================================
- @Test
- public void testDelete() throws Exception {
- String t = "a123456789b123456789c123456789d123456789e123456789f123456789g123456789h123456789i123456789j123456789";
-
- // Min buff size is 20.
- ParserReader pr = new ParserReader(t);
- assertEquals("a123456789", pr.read(10));
- pr.mark();
- assertEquals("b123456789", pr.read(10));
- pr.delete();
- assertEquals("c123456789", pr.read(10));
- assertEquals("b12345678c123456789", pr.getMarked());
- pr.close();
-
- pr = new ParserReader(t);
- assertEquals("a123456789", pr.read(10));
- pr.mark();
- assertEquals("b123456789", pr.read(10));
- pr.delete(5);
- assertEquals("c123456789", pr.read(10));
- assertEquals("b1234c123456789", pr.getMarked());
- pr.close();
- }
-
- //====================================================================================================
- // Utility methods
- //====================================================================================================
-
- private String read(ParserReader r) throws IOException {
- return read(r, Integer.MAX_VALUE);
- }
-
- private String read(ParserReader r, int length) throws IOException {
- StringBuilder sb = new StringBuilder();
- for (int i = 0; i < length; i++) {
- int c = r.read();
- if (c == -1)
- return sb.toString();
- sb.append((char)c);
- }
- return sb.toString();
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/CT_PojoTransform.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/CT_PojoTransform.java b/org.apache.juneau/src/test/java/org/apache/juneau/CT_PojoTransform.java
deleted file mode 100755
index 3f55c22..0000000
--- a/org.apache.juneau/src/test/java/org/apache/juneau/CT_PojoTransform.java
+++ /dev/null
@@ -1,56 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau;
-
-import static org.junit.Assert.*;
-
-import org.apache.juneau.json.*;
-import org.apache.juneau.parser.*;
-import org.apache.juneau.serializer.*;
-import org.apache.juneau.transform.*;
-import org.junit.*;
-
-public class CT_PojoTransform {
-
- //====================================================================================================
- // Test same type
- // If you define a PojoTransform<String,String> filter, then it should be invoked on all strings.
- //====================================================================================================
- @Test
- public void testSameType() throws Exception {
- JsonSerializer s = JsonSerializer.DEFAULT_LAX.clone().addTransforms(ATransform.class);
- JsonParser p = JsonParser.DEFAULT.clone().addTransforms(ATransform.class);
- String r;
-
- r = s.serialize("foobar");
- assertEquals("'xfoobarx'", r);
- r = p.parse(r, String.class);
- assertEquals("foobar", r);
-
- ObjectMap m = new ObjectMap("{foo:'bar'}");
- r = s.serialize(m);
- assertEquals("{xfoox:'xbarx'}", r);
- }
-
- public static class ATransform extends PojoTransform<String,String> {
- @Override
- public String transform(String o) throws SerializeException {
- return "x" + o + "x";
- }
-
- @Override
- public String normalize(String f, ClassMeta<?> hint) throws ParseException {
- return f.substring(1, f.length()-1);
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/CT_PropertyNamerDashedLC.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/CT_PropertyNamerDashedLC.java b/org.apache.juneau/src/test/java/org/apache/juneau/CT_PropertyNamerDashedLC.java
deleted file mode 100755
index a0720a6..0000000
--- a/org.apache.juneau/src/test/java/org/apache/juneau/CT_PropertyNamerDashedLC.java
+++ /dev/null
@@ -1,39 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau;
-
-import static org.junit.Assert.*;
-
-import org.junit.*;
-
-public class CT_PropertyNamerDashedLC {
-
- //====================================================================================================
- // test
- //====================================================================================================
- @Test
- public void test() throws Exception {
- PropertyNamer n = new PropertyNamerDashedLC();
-
- assertEquals("abc", n.getPropertyName("ABC"));
- assertEquals("abc", n.getPropertyName("abc"));
- assertEquals("foo-bar-baz", n.getPropertyName("FooBarBaz"));
- assertEquals("foo-bar-baz", n.getPropertyName("FooBarBAZ"));
- assertEquals("foo-bar-baz", n.getPropertyName("fooBarBAZ"));
- assertEquals("", n.getPropertyName(""));
- assertNull(n.getPropertyName(null));
- assertEquals("a", n.getPropertyName("A"));
- assertEquals("a", n.getPropertyName("A"));
-
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/CT_Visibility.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/CT_Visibility.java b/org.apache.juneau/src/test/java/org/apache/juneau/CT_Visibility.java
deleted file mode 100755
index d31fc62..0000000
--- a/org.apache.juneau/src/test/java/org/apache/juneau/CT_Visibility.java
+++ /dev/null
@@ -1,169 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau;
-
-import static org.apache.juneau.BeanContext.*;
-import static org.apache.juneau.Visibility.*;
-import static org.junit.Assert.*;
-
-import org.apache.juneau.a.*;
-import org.apache.juneau.json.*;
-import org.junit.*;
-
-public class CT_Visibility {
-
- //====================================================================================================
- // testVisibility
- //====================================================================================================
- @Test
- public void testClassDefault() throws Exception {
- JsonSerializer s1 = JsonSerializer.DEFAULT_LAX.clone().setProperty(BEAN_beansRequireSomeProperties, "false");
- JsonSerializer s2 = JsonSerializer.DEFAULT_LAX.clone().setProperty(BEAN_beansRequireSomeProperties, "false").setProperty(BEAN_beanClassVisibility, PROTECTED);
- JsonSerializer s3 = JsonSerializer.DEFAULT_LAX.clone().setProperty(BEAN_beansRequireSomeProperties, "false").setProperty(BEAN_beanClassVisibility, Visibility.DEFAULT);
- JsonSerializer s4 = JsonSerializer.DEFAULT_LAX.clone().setProperty(BEAN_beansRequireSomeProperties, "false").setProperty(BEAN_beanClassVisibility, PRIVATE);
-
- A1 a1 = A1.create();
- String r;
-
- s1.setProperty(BEAN_beanFieldVisibility, NONE);
- s2.setProperty(BEAN_beanFieldVisibility, NONE);
- s3.setProperty(BEAN_beanFieldVisibility, NONE);
- s4.setProperty(BEAN_beanFieldVisibility, NONE);
-
- r = s1.serialize(a1);
- assertEquals("{f5:5}", r);
-
- r = s2.serialize(a1);
- assertEquals("{f5:5}", r);
-
- r = s3.serialize(a1);
- assertEquals("{f5:5}", r);
-
- r = s4.serialize(a1);
- assertEquals("{f5:5}", r);
-
- s1.setProperty(BEAN_beanFieldVisibility, PUBLIC);
- s2.setProperty(BEAN_beanFieldVisibility, PUBLIC);
- s3.setProperty(BEAN_beanFieldVisibility, PUBLIC);
- s4.setProperty(BEAN_beanFieldVisibility, PUBLIC);
-
- r = s1.serialize(a1);
- assertEquals("{f1:1,f5:5,g2:{f1:1,f5:5},g3:'A3',g4:'A4',g5:'A5'}", r);
-
- r = s2.serialize(a1);
- assertEquals("{f1:1,f5:5,g2:{f1:1,f5:5},g3:{f1:1,f5:5},g4:'A4',g5:'A5'}", r);
-
- r = s3.serialize(a1);
- assertEquals("{f1:1,f5:5,g2:{f1:1,f5:5},g3:{f1:1,f5:5},g4:{f1:1,f5:5},g5:'A5'}", r);
-
- r = s4.serialize(a1);
- assertEquals("{f1:1,f5:5,g2:{f1:1,f5:5},g3:{f1:1,f5:5},g4:{f1:1,f5:5},g5:{f1:1,f5:5}}", r);
-
- s1.setProperty(BEAN_beanFieldVisibility, PROTECTED);
- s2.setProperty(BEAN_beanFieldVisibility, PROTECTED);
- s3.setProperty(BEAN_beanFieldVisibility, PROTECTED);
- s4.setProperty(BEAN_beanFieldVisibility, PROTECTED);
-
- r = s1.serialize(a1);
- assertEquals("{f1:1,f2:2,f5:5,g2:{f1:1,f2:2,f5:5},g3:'A3',g4:'A4',g5:'A5'}", r);
-
- r = s2.serialize(a1);
- assertEquals("{f1:1,f2:2,f5:5,g2:{f1:1,f2:2,f5:5},g3:{f1:1,f2:2,f5:5},g4:'A4',g5:'A5'}", r);
-
- r = s3.serialize(a1);
- assertEquals("{f1:1,f2:2,f5:5,g2:{f1:1,f2:2,f5:5},g3:{f1:1,f2:2,f5:5},g4:{f1:1,f2:2,f5:5},g5:'A5'}", r);
-
- r = s4.serialize(a1);
- assertEquals("{f1:1,f2:2,f5:5,g2:{f1:1,f2:2,f5:5},g3:{f1:1,f2:2,f5:5},g4:{f1:1,f2:2,f5:5},g5:{f1:1,f2:2,f5:5}}", r);
-
- s1.setProperty(BEAN_beanFieldVisibility, Visibility.DEFAULT);
- s2.setProperty(BEAN_beanFieldVisibility, Visibility.DEFAULT);
- s3.setProperty(BEAN_beanFieldVisibility, Visibility.DEFAULT);
- s4.setProperty(BEAN_beanFieldVisibility, Visibility.DEFAULT);
-
- r = s1.serialize(a1);
- assertEquals("{f1:1,f2:2,f3:3,f5:5,g2:{f1:1,f2:2,f3:3,f5:5},g3:'A3',g4:'A4',g5:'A5'}", r);
-
- r = s2.serialize(a1);
- assertEquals("{f1:1,f2:2,f3:3,f5:5,g2:{f1:1,f2:2,f3:3,f5:5},g3:{f1:1,f2:2,f3:3,f5:5},g4:'A4',g5:'A5'}", r);
-
- r = s3.serialize(a1);
- assertEquals("{f1:1,f2:2,f3:3,f5:5,g2:{f1:1,f2:2,f3:3,f5:5},g3:{f1:1,f2:2,f3:3,f5:5},g4:{f1:1,f2:2,f3:3,f5:5},g5:'A5'}", r);
-
- r = s4.serialize(a1);
- assertEquals("{f1:1,f2:2,f3:3,f5:5,g2:{f1:1,f2:2,f3:3,f5:5},g3:{f1:1,f2:2,f3:3,f5:5},g4:{f1:1,f2:2,f3:3,f5:5},g5:{f1:1,f2:2,f3:3,f5:5}}", r);
-
- s1.setProperty(BEAN_beanFieldVisibility, PRIVATE);
- s2.setProperty(BEAN_beanFieldVisibility, PRIVATE);
- s3.setProperty(BEAN_beanFieldVisibility, PRIVATE);
- s4.setProperty(BEAN_beanFieldVisibility, PRIVATE);
-
- r = s1.serialize(a1);
- assertEquals("{f1:1,f2:2,f3:3,f4:4,f5:5,g2:{f1:1,f2:2,f3:3,f4:4,f5:5},g3:'A3',g4:'A4',g5:'A5'}", r);
-
- r = s2.serialize(a1);
- assertEquals("{f1:1,f2:2,f3:3,f4:4,f5:5,g2:{f1:1,f2:2,f3:3,f4:4,f5:5},g3:{f1:1,f2:2,f3:3,f4:4,f5:5},g4:'A4',g5:'A5'}", r);
-
- r = s3.serialize(a1);
- assertEquals("{f1:1,f2:2,f3:3,f4:4,f5:5,g2:{f1:1,f2:2,f3:3,f4:4,f5:5},g3:{f1:1,f2:2,f3:3,f4:4,f5:5},g4:{f1:1,f2:2,f3:3,f4:4,f5:5},g5:'A5'}", r);
-
- r = s4.serialize(a1);
- assertEquals("{f1:1,f2:2,f3:3,f4:4,f5:5,g2:{f1:1,f2:2,f3:3,f4:4,f5:5},g3:{f1:1,f2:2,f3:3,f4:4,f5:5},g4:{f1:1,f2:2,f3:3,f4:4,f5:5},g5:{f1:1,f2:2,f3:3,f4:4,f5:5}}", r);
-
- s1.setProperty(BEAN_methodVisibility, NONE);
- s2.setProperty(BEAN_methodVisibility, NONE);
- s3.setProperty(BEAN_methodVisibility, NONE);
- s4.setProperty(BEAN_methodVisibility, NONE);
-
- r = s1.serialize(a1);
- assertEquals("{f1:1,f2:2,f3:3,f4:4,g2:{f1:1,f2:2,f3:3,f4:4},g3:'A3',g4:'A4',g5:'A5'}", r);
-
- r = s2.serialize(a1);
- assertEquals("{f1:1,f2:2,f3:3,f4:4,g2:{f1:1,f2:2,f3:3,f4:4},g3:{f1:1,f2:2,f3:3,f4:4},g4:'A4',g5:'A5'}", r);
-
- r = s3.serialize(a1);
- assertEquals("{f1:1,f2:2,f3:3,f4:4,g2:{f1:1,f2:2,f3:3,f4:4},g3:{f1:1,f2:2,f3:3,f4:4},g4:{f1:1,f2:2,f3:3,f4:4},g5:'A5'}", r);
-
- r = s4.serialize(a1);
- assertEquals("{f1:1,f2:2,f3:3,f4:4,g2:{f1:1,f2:2,f3:3,f4:4},g3:{f1:1,f2:2,f3:3,f4:4},g4:{f1:1,f2:2,f3:3,f4:4},g5:{f1:1,f2:2,f3:3,f4:4}}", r);
-
- s1.setProperty(BEAN_methodVisibility, PROTECTED);
- s2.setProperty(BEAN_methodVisibility, PROTECTED);
- s3.setProperty(BEAN_methodVisibility, PROTECTED);
- s4.setProperty(BEAN_methodVisibility, PROTECTED);
-
- r = s1.serialize(a1);
- assertEquals("{f1:1,f2:2,f3:3,f4:4,f5:5,f6:6,g2:{f1:1,f2:2,f3:3,f4:4,f5:5,f6:6},g3:'A3',g4:'A4',g5:'A5'}", r);
-
- r = s2.serialize(a1);
- assertEquals("{f1:1,f2:2,f3:3,f4:4,f5:5,f6:6,g2:{f1:1,f2:2,f3:3,f4:4,f5:5,f6:6},g3:{f1:1,f2:2,f3:3,f4:4,f5:5,f6:6},g4:'A4',g5:'A5'}", r);
-
- r = s3.serialize(a1);
- assertEquals("{f1:1,f2:2,f3:3,f4:4,f5:5,f6:6,g2:{f1:1,f2:2,f3:3,f4:4,f5:5,f6:6},g3:{f1:1,f2:2,f3:3,f4:4,f5:5,f6:6},g4:{f1:1,f2:2,f3:3,f4:4,f5:5,f6:6},g5:'A5'}", r);
-
- r = s4.serialize(a1);
- assertEquals("{f1:1,f2:2,f3:3,f4:4,f5:5,f6:6,g2:{f1:1,f2:2,f3:3,f4:4,f5:5,f6:6},g3:{f1:1,f2:2,f3:3,f4:4,f5:5,f6:6},g4:{f1:1,f2:2,f3:3,f4:4,f5:5,f6:6},g5:{f1:1,f2:2,f3:3,f4:4,f5:5,f6:6}}", r);
-
- }
-
- static class A {
- public int f1;
- public A(){}
-
- static A create() {
- A x = new A();
- x.f1 = 1;
- return x;
- }
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/ClassMetaTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/ClassMetaTest.java b/org.apache.juneau/src/test/java/org/apache/juneau/ClassMetaTest.java
new file mode 100755
index 0000000..cbd0eae
--- /dev/null
+++ b/org.apache.juneau/src/test/java/org/apache/juneau/ClassMetaTest.java
@@ -0,0 +1,281 @@
+/***************************************************************************************************************************
+ * 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.juneau;
+
+import static org.junit.Assert.*;
+
+import java.util.*;
+
+import org.apache.juneau.transform.*;
+import org.junit.*;
+
+@SuppressWarnings({"rawtypes","serial","hiding"})
+public class ClassMetaTest {
+
+ BeanContext bc = BeanContext.DEFAULT;
+
+ //====================================================================================================
+ // Map<String,String> field
+ //====================================================================================================
+ public Map<String,String> fa;
+
+ @Test
+ public void testMap() throws Exception {
+ ClassMeta t = bc.getClassMeta(this.getClass().getField("fa").getGenericType());
+ assertEquals("java.util.Map<java.lang.String,java.lang.String>", t.toString());
+ assertTrue(t.isMap());
+ assertFalse(t.isCollection());
+ assertNull(t.newInstance());
+ assertEquals(Map.class, t.getInnerClass());
+ assertEquals(String.class, t.getKeyType().getInnerClass());
+ assertEquals(String.class, t.getValueType().getInnerClass());
+ }
+
+ //====================================================================================================
+ // String field
+ //====================================================================================================
+ public String fb;
+
+ @Test
+ public void testString() throws Exception {
+ ClassMeta t = bc.getClassMeta(this.getClass().getField("fb").getGenericType());
+ assertEquals(String.class, t.getInnerClass());
+ t = bc.getClassMeta(this.getClass().getField("fb").getType());
+ assertEquals(String.class, t.getInnerClass());
+ }
+
+ //====================================================================================================
+ // Map<String,Map<String,Integer>> field
+ //====================================================================================================
+ public Map<String,Map<String,Integer>> fc;
+
+ @Test
+ public void testMapWithMapValues() throws Exception {
+ ClassMeta t = bc.getClassMeta(this.getClass().getField("fc").getGenericType());
+ assertEquals("java.util.Map<java.lang.String,java.util.Map<java.lang.String,java.lang.Integer>>", t.toString());
+ t = bc.getClassMeta(this.getClass().getField("fc").getType());
+ assertEquals("java.util.Map", t.toString());
+ }
+
+ //====================================================================================================
+ // List<Map<String,List>> field
+ //====================================================================================================
+ public List<Map<String,List>> fd;
+
+ @Test
+ public void testListWithMapValues() throws Exception {
+ ClassMeta t = bc.getClassMeta(this.getClass().getField("fd").getGenericType());
+ assertEquals("java.util.List<java.util.Map<java.lang.String,java.util.List>>", t.toString());
+ }
+
+ //====================================================================================================
+ // List<? extends String> field, List<? super String> field
+ //====================================================================================================
+ public List<? extends String> fe1;
+ public List<? super String> fe2;
+
+ @Test
+ public void testListWithUpperBoundGenericEntryTypes() throws Exception {
+ ClassMeta t = bc.getClassMeta(this.getClass().getField("fe1").getGenericType());
+ assertEquals("java.util.List", t.toString());
+ t = bc.getClassMeta(this.getClass().getField("fe2").getGenericType());
+ assertEquals("java.util.List", t.toString());
+ }
+
+ //====================================================================================================
+ // Bean extends HashMap<String,Object> field
+ //====================================================================================================
+ public class G extends HashMap<String,Object> {}
+ public G g;
+
+ @Test
+ public void testBeanExtendsMap() throws Exception {
+ ClassMeta t = bc.getClassMeta(this.getClass().getField("g").getGenericType());
+ assertEquals("org.apache.juneau.ClassMetaTest$G<java.lang.String,java.lang.Object>", t.toString());
+ assertTrue(t.isMap());
+ assertFalse(t.isCollection());
+ }
+
+ //====================================================================================================
+ // testTransforms
+ // Ensure filters on parent and child classes are properly detected.
+ //====================================================================================================
+ @Test
+ public void testTransforms() throws Exception {
+ BeanContext bc;
+ ClassMeta<?> ooo, hi1, hc1, hi2, hc2;
+
+ bc = ContextFactory.create().getBeanContext();
+ ooo = bc.getClassMeta(Object.class);
+ hi1 = bc.getClassMeta(HI1.class);
+ hc1 = bc.getClassMeta(HC1.class);
+ hi2 = bc.getClassMeta(HI2.class);
+ hc2 = bc.getClassMeta(HC2.class);
+ assertFalse(ooo.hasChildPojoTransforms());
+ assertFalse(hi1.hasChildPojoTransforms());
+ assertFalse(hc1.hasChildPojoTransforms());
+ assertFalse(hi2.hasChildPojoTransforms());
+ assertFalse(hc2.hasChildPojoTransforms());
+ assertNull(ooo.getPojoTransform());
+ assertNull(hi1.getPojoTransform());
+ assertNull(hc1.getPojoTransform());
+ assertNull(hi2.getPojoTransform());
+ assertNull(hc2.getPojoTransform());
+ assertEquals(ooo.getTransformedClassMeta().getInnerClass(), Object.class);
+ assertEquals(hi1.getTransformedClassMeta().getInnerClass(), HI1.class);
+ assertEquals(hc1.getTransformedClassMeta().getInnerClass(), HC1.class);
+ assertEquals(hi2.getTransformedClassMeta().getInnerClass(), HI2.class);
+ assertEquals(hc2.getTransformedClassMeta().getInnerClass(), HC2.class);
+
+ bc = ContextFactory.create().addTransforms(HI1Transform.class).getBeanContext();
+ ooo = bc.getClassMeta(Object.class);
+ hi1 = bc.getClassMeta(HI1.class);
+ hc1 = bc.getClassMeta(HC1.class);
+ hi2 = bc.getClassMeta(HI2.class);
+ hc2 = bc.getClassMeta(HC2.class);
+ assertTrue(ooo.hasChildPojoTransforms());
+ assertTrue(hi1.hasChildPojoTransforms());
+ assertFalse(hc1.hasChildPojoTransforms());
+ assertFalse(hi2.hasChildPojoTransforms());
+ assertFalse(hc2.hasChildPojoTransforms());
+ assertNull(ooo.getPojoTransform());
+ assertEquals(hi1.getPojoTransform().getClass(), HI1Transform.class);
+ assertEquals(hc1.getPojoTransform().getClass(), HI1Transform.class);
+ assertEquals(hi2.getPojoTransform().getClass(), HI1Transform.class);
+ assertEquals(hc2.getPojoTransform().getClass(), HI1Transform.class);
+ assertEquals(ooo.getTransformedClassMeta().getInnerClass(), Object.class);
+ assertEquals(hi1.getTransformedClassMeta().getInnerClass(), Map.class);
+ assertEquals(hc1.getTransformedClassMeta().getInnerClass(), Map.class);
+ assertEquals(hi2.getTransformedClassMeta().getInnerClass(), Map.class);
+ assertEquals(hc2.getTransformedClassMeta().getInnerClass(), Map.class);
+
+ bc = ContextFactory.create().addTransforms(HC1Transform.class).getBeanContext();
+ ooo = bc.getClassMeta(Object.class);
+ hi1 = bc.getClassMeta(HI1.class);
+ hc1 = bc.getClassMeta(HC1.class);
+ hi2 = bc.getClassMeta(HI2.class);
+ hc2 = bc.getClassMeta(HC2.class);
+ assertTrue(ooo.hasChildPojoTransforms());
+ assertTrue(hi1.hasChildPojoTransforms());
+ assertTrue(hc1.hasChildPojoTransforms());
+ assertFalse(hi2.hasChildPojoTransforms());
+ assertFalse(hc2.hasChildPojoTransforms());
+ assertNull(ooo.getPojoTransform());
+ assertNull(hi1.getPojoTransform());
+ assertEquals(hc1.getPojoTransform().getClass(), HC1Transform.class);
+ assertNull(hi2.getPojoTransform());
+ assertEquals(hc2.getPojoTransform().getClass(), HC1Transform.class);
+ assertEquals(ooo.getTransformedClassMeta().getInnerClass(), Object.class);
+ assertEquals(hi1.getTransformedClassMeta().getInnerClass(), HI1.class);
+ assertEquals(hc1.getTransformedClassMeta().getInnerClass(), Map.class);
+ assertEquals(hi2.getTransformedClassMeta().getInnerClass(), HI2.class);
+ assertEquals(hc2.getTransformedClassMeta().getInnerClass(), Map.class);
+
+ bc = ContextFactory.create().addTransforms(HI2Transform.class).getBeanContext();
+ ooo = bc.getClassMeta(Object.class);
+ hi1 = bc.getClassMeta(HI1.class);
+ hc1 = bc.getClassMeta(HC1.class);
+ hi2 = bc.getClassMeta(HI2.class);
+ hc2 = bc.getClassMeta(HC2.class);
+ assertTrue(ooo.hasChildPojoTransforms());
+ assertTrue(hi1.hasChildPojoTransforms());
+ assertFalse(hc1.hasChildPojoTransforms());
+ assertTrue(hi2.hasChildPojoTransforms());
+ assertFalse(hc2.hasChildPojoTransforms());
+ assertNull(ooo.getPojoTransform());
+ assertNull(hi1.getPojoTransform());
+ assertNull(hc1.getPojoTransform());
+ assertEquals(hi2.getPojoTransform().getClass(), HI2Transform.class);
+ assertEquals(hc2.getPojoTransform().getClass(), HI2Transform.class);
+ assertEquals(ooo.getTransformedClassMeta().getInnerClass(), Object.class);
+ assertEquals(hi1.getTransformedClassMeta().getInnerClass(), HI1.class);
+ assertEquals(hc1.getTransformedClassMeta().getInnerClass(), HC1.class);
+ assertEquals(hi2.getTransformedClassMeta().getInnerClass(), Map.class);
+ assertEquals(hc2.getTransformedClassMeta().getInnerClass(), Map.class);
+
+ bc = ContextFactory.create().addTransforms(HC2Transform.class).getBeanContext();
+ ooo = bc.getClassMeta(Object.class);
+ hi1 = bc.getClassMeta(HI1.class);
+ hc1 = bc.getClassMeta(HC1.class);
+ hi2 = bc.getClassMeta(HI2.class);
+ hc2 = bc.getClassMeta(HC2.class);
+ assertTrue(ooo.hasChildPojoTransforms());
+ assertTrue(hi1.hasChildPojoTransforms());
+ assertTrue(hc1.hasChildPojoTransforms());
+ assertTrue(hi2.hasChildPojoTransforms());
+ assertTrue(hc2.hasChildPojoTransforms());
+ assertNull(ooo.getPojoTransform());
+ assertNull(hi1.getPojoTransform());
+ assertNull(hc1.getPojoTransform());
+ assertNull(hi2.getPojoTransform());
+ assertEquals(hc2.getPojoTransform().getClass(), HC2Transform.class);
+ assertEquals(ooo.getTransformedClassMeta().getInnerClass(), Object.class);
+ assertEquals(hi1.getTransformedClassMeta().getInnerClass(), HI1.class);
+ assertEquals(hc1.getTransformedClassMeta().getInnerClass(), HC1.class);
+ assertEquals(hi2.getTransformedClassMeta().getInnerClass(), HI2.class);
+ assertEquals(hc2.getTransformedClassMeta().getInnerClass(), Map.class);
+
+ bc = ContextFactory.create().addTransforms(HI1Transform.class,HC1Transform.class,HI2Transform.class,HC2Transform.class).getBeanContext();
+ ooo = bc.getClassMeta(Object.class);
+ hi1 = bc.getClassMeta(HI1.class);
+ hc1 = bc.getClassMeta(HC1.class);
+ hi2 = bc.getClassMeta(HI2.class);
+ hc2 = bc.getClassMeta(HC2.class);
+ assertTrue(ooo.hasChildPojoTransforms());
+ assertTrue(hi1.hasChildPojoTransforms());
+ assertTrue(hc1.hasChildPojoTransforms());
+ assertTrue(hi2.hasChildPojoTransforms());
+ assertTrue(hc2.hasChildPojoTransforms());
+ assertNull(ooo.getPojoTransform());
+ assertEquals(hi1.getPojoTransform().getClass(), HI1Transform.class);
+ assertEquals(hc1.getPojoTransform().getClass(), HI1Transform.class);
+ assertEquals(hi2.getPojoTransform().getClass(), HI1Transform.class);
+ assertEquals(hc2.getPojoTransform().getClass(), HI1Transform.class);
+ assertEquals(ooo.getTransformedClassMeta().getInnerClass(), Object.class);
+ assertEquals(hi1.getTransformedClassMeta().getInnerClass(), Map.class);
+ assertEquals(hc1.getTransformedClassMeta().getInnerClass(), Map.class);
+ assertEquals(hi2.getTransformedClassMeta().getInnerClass(), Map.class);
+ assertEquals(hc2.getTransformedClassMeta().getInnerClass(), Map.class);
+
+ bc = ContextFactory.create().addTransforms(HC2Transform.class,HI2Transform.class,HC1Transform.class,HI1Transform.class).getBeanContext();
+ ooo = bc.getClassMeta(Object.class);
+ hi1 = bc.getClassMeta(HI1.class);
+ hc1 = bc.getClassMeta(HC1.class);
+ hi2 = bc.getClassMeta(HI2.class);
+ hc2 = bc.getClassMeta(HC2.class);
+ assertTrue(ooo.hasChildPojoTransforms());
+ assertTrue(hi1.hasChildPojoTransforms());
+ assertTrue(hc1.hasChildPojoTransforms());
+ assertTrue(hi2.hasChildPojoTransforms());
+ assertTrue(hc2.hasChildPojoTransforms());
+ assertNull(ooo.getPojoTransform());
+ assertEquals(hi1.getPojoTransform().getClass(), HI1Transform.class);
+ assertEquals(hc1.getPojoTransform().getClass(), HC1Transform.class);
+ assertEquals(hi2.getPojoTransform().getClass(), HI2Transform.class);
+ assertEquals(hc2.getPojoTransform().getClass(), HC2Transform.class);
+ assertEquals(ooo.getTransformedClassMeta().getInnerClass(), Object.class);
+ assertEquals(hi1.getTransformedClassMeta().getInnerClass(), Map.class);
+ assertEquals(hc1.getTransformedClassMeta().getInnerClass(), Map.class);
+ assertEquals(hi2.getTransformedClassMeta().getInnerClass(), Map.class);
+ assertEquals(hc2.getTransformedClassMeta().getInnerClass(), Map.class);
+ }
+
+ public interface HI1 {}
+ public class HC1 implements HI1 {}
+ public interface HI2 extends HI1 {}
+ public class HC2 extends HC1 implements HI2 {}
+ public static class HC1Transform extends PojoTransform<HC1,Map> {}
+ public static class HI1Transform extends PojoTransform<HI1,Map> {}
+ public static class HC2Transform extends PojoTransform<HC2,Map> {}
+ public static class HI2Transform extends PojoTransform<HI2,Map> {}
+}
[13/44] incubator-juneau git commit: Rename CT_* testcases.
Posted by ja...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/msgpack/CT_MsgPackSerialzier.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/msgpack/CT_MsgPackSerialzier.java b/org.apache.juneau/src/test/java/org/apache/juneau/msgpack/CT_MsgPackSerialzier.java
deleted file mode 100755
index 0ee57f0..0000000
--- a/org.apache.juneau/src/test/java/org/apache/juneau/msgpack/CT_MsgPackSerialzier.java
+++ /dev/null
@@ -1,220 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.msgpack;
-
-import static org.junit.Assert.*;
-
-import java.io.*;
-
-import org.apache.juneau.*;
-import org.junit.*;
-
-@SuppressWarnings("serial")
-public class CT_MsgPackSerialzier {
-
- //====================================================================================================
- // testBasic
- //====================================================================================================
- @Test
- public void testBasic() throws Exception {
-
- test(null, "C0");
-
- test(false, "C2");
- test(true, "C3");
-
- // positive fixnum stores 7-bit positive integer
- // +--------+
- // |0XXXXXXX|
- // +--------+
- //
- // int 8 stores a 8-bit signed integer
- // +--------+--------+
- // | 0xd0 |ZZZZZZZZ|
- // +--------+--------+
- //
- // int 16 stores a 16-bit big-endian signed integer
- // +--------+--------+--------+
- // | 0xd1 |ZZZZZZZZ|ZZZZZZZZ|
- // +--------+--------+--------+
- //
- // int 32 stores a 32-bit big-endian signed integer
- // +--------+--------+--------+--------+--------+
- // | 0xd2 |ZZZZZZZZ|ZZZZZZZZ|ZZZZZZZZ|ZZZZZZZZ|
- // +--------+--------+--------+--------+--------+
- //
- // int 64 stores a 64-bit big-endian signed integer
- // +--------+--------+--------+--------+--------+--------+--------+--------+--------+
- // | 0xd3 |ZZZZZZZZ|ZZZZZZZZ|ZZZZZZZZ|ZZZZZZZZ|ZZZZZZZZ|ZZZZZZZZ|ZZZZZZZZ|ZZZZZZZZ|
- // +--------+--------+--------+--------+--------+--------+--------+--------+--------+
- //
- // negative fixnum stores 5-bit negative integer
- // +--------+
- // |111YYYYY|
- // +--------+
- //
- // * 0XXXXXXX is 8-bit unsigned integer
- // * 111YYYYY is 8-bit signed integer
- //
-
- test(0, "00");
- test(0x7F, "7F");
-
- test(0x80, "D1 00 80");
- test(0x0100, "D1 01 00");
- test(0x7FFF, "D1 7F FF");
- test(0x8000, "D2 00 00 80 00");
- test(0xFFFF, "D2 00 00 FF FF");
- test(0x00010000, "D2 00 01 00 00");
- test(Long.decode("0x000000007FFFFFFF").longValue(), "D2 7F FF FF FF");
- test(Long.decode("0x0000000080000000").longValue(), "D3 00 00 00 00 80 00 00 00");
- test(Long.decode("0x0000000100000000").longValue(), "D3 00 00 00 01 00 00 00 00");
- test(Long.decode("0x7FFFFFFFFFFFFFFF").longValue(), "D3 7F FF FF FF FF FF FF FF");
- test(-Long.decode("0x7FFFFFFFFFFFFFFF").longValue(), "D3 80 00 00 00 00 00 00 01");
- test(-1, "E1");
- test(-63, "FF");
- test(-64, "D0 C0");
-
- test(-0x7F, "D0 81");
- test(-0x80, "D1 FF 80");
- test(-0x0100, "D1 FF 00");
- test(-0x7FFF, "D1 80 01");
- test(-0x8000, "D2 FF FF 80 00");
- test(-0xFFFF, "D2 FF FF 00 01");
- test(-0x00010000, "D2 FF FF 00 00");
- test(-Long.decode("0x000000007FFFFFFF").longValue(), "D2 80 00 00 01");
- test(-Long.decode("0x0000000080000000").longValue(), "D3 FF FF FF FF 80 00 00 00");
- test(-Long.decode("0x0000000100000000").longValue(), "D3 FF FF FF FF 00 00 00 00");
- test(-Long.decode("0x7FFFFFFFFFFFFFFF").longValue(), "D3 80 00 00 00 00 00 00 01");
-
- // float 32 stores a floating point number in IEEE 754 single precision floating point number format:
- // +--------+--------+--------+--------+--------+
- // | 0xca |XXXXXXXX|XXXXXXXX|XXXXXXXX|XXXXXXXX|
- // +--------+--------+--------+--------+--------+
- //
- // float 64 stores a floating point number in IEEE 754 double precision floating point number format:
- // +--------+--------+--------+--------+--------+--------+--------+--------+--------+
- // | 0xcb |YYYYYYYY|YYYYYYYY|YYYYYYYY|YYYYYYYY|YYYYYYYY|YYYYYYYY|YYYYYYYY|YYYYYYYY|
- // +--------+--------+--------+--------+--------+--------+--------+--------+--------+
- //
- // where
- // * XXXXXXXX_XXXXXXXX_XXXXXXXX_XXXXXXXX is a big-endian IEEE 754 single precision floating point number.
- // Extension of precision from single-precision to double-precision does not lose precision.
- // * YYYYYYYY_YYYYYYYY_YYYYYYYY_YYYYYYYY_YYYYYYYY_YYYYYYYY_YYYYYYYY_YYYYYYYY is a big-endian
- // IEEE 754 double precision floating point number
-
- test(0f, "CA 00 00 00 00");
- test(1f, "CA 3F 80 00 00");
- test(-1f, "CA BF 80 00 00");
- test(1d, "CB 3F F0 00 00 00 00 00 00");
- test(-1d, "CB BF F0 00 00 00 00 00 00");
-
- // fixstr stores a byte array whose length is upto 31 bytes:
- // +--------+========+
- // |101XXXXX| data |
- // +--------+========+
- //
- // str 8 stores a byte array whose length is upto (2^8)-1 bytes:
- // +--------+--------+========+
- // | 0xd9 |YYYYYYYY| data |
- // +--------+--------+========+
- //
- // str 16 stores a byte array whose length is upto (2^16)-1 bytes:
- // +--------+--------+--------+========+
- // | 0xda |ZZZZZZZZ|ZZZZZZZZ| data |
- // +--------+--------+--------+========+
- //
- // str 32 stores a byte array whose length is upto (2^32)-1 bytes:
- // +--------+--------+--------+--------+--------+========+
- // | 0xdb |AAAAAAAA|AAAAAAAA|AAAAAAAA|AAAAAAAA| data |
- // +--------+--------+--------+--------+--------+========+
- //
- // where
- // * XXXXX is a 5-bit unsigned integer which represents N
- // * YYYYYYYY is a 8-bit unsigned integer which represents N
- // * ZZZZZZZZ_ZZZZZZZZ is a 16-bit big-endian unsigned integer which represents N
- // * AAAAAAAA_AAAAAAAA_AAAAAAAA_AAAAAAAA is a 32-bit big-endian unsigned integer which represents N
- // * N is the length of data
-
- test("", "A0");
- test("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "BF 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61");
- test("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "D9 20 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61");
-
- // fixarray stores an array whose length is upto 15 elements:
- // +--------+~~~~~~~~~~~~~~~~~+
- // |1001XXXX| N objects |
- // +--------+~~~~~~~~~~~~~~~~~+
- //
- // array 16 stores an array whose length is upto (2^16)-1 elements:
- // +--------+--------+--------+~~~~~~~~~~~~~~~~~+
- // | 0xdc |YYYYYYYY|YYYYYYYY| N objects |
- // +--------+--------+--------+~~~~~~~~~~~~~~~~~+
- //
- // array 32 stores an array whose length is upto (2^32)-1 elements:
- // +--------+--------+--------+--------+--------+~~~~~~~~~~~~~~~~~+
- // | 0xdd |ZZZZZZZZ|ZZZZZZZZ|ZZZZZZZZ|ZZZZZZZZ| N objects |
- // +--------+--------+--------+--------+--------+~~~~~~~~~~~~~~~~~+
- //
- // where
- // * XXXX is a 4-bit unsigned integer which represents N
- // * YYYYYYYY_YYYYYYYY is a 16-bit big-endian unsigned integer which represents N
- // * ZZZZZZZZ_ZZZZZZZZ_ZZZZZZZZ_ZZZZZZZZ is a 32-bit big-endian unsigned integer which represents N
- // N is the size of a array
-
- test(new int[0], "90");
- test(new int[]{1}, "91 01");
- test(new int[]{1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}, "9F 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01");
- test(new int[]{1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}, "DC 00 10 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01");
-
- // fixmap stores a map whose length is upto 15 elements
- // +--------+~~~~~~~~~~~~~~~~~+
- // |1000XXXX| N*2 objects |
- // +--------+~~~~~~~~~~~~~~~~~+
- //
- // map 16 stores a map whose length is upto (2^16)-1 elements
- // +--------+--------+--------+~~~~~~~~~~~~~~~~~+
- // | 0xde |YYYYYYYY|YYYYYYYY| N*2 objects |
- // +--------+--------+--------+~~~~~~~~~~~~~~~~~+
- //
- // map 32 stores a map whose length is upto (2^32)-1 elements
- // +--------+--------+--------+--------+--------+~~~~~~~~~~~~~~~~~+
- // | 0xdf |ZZZZZZZZ|ZZZZZZZZ|ZZZZZZZZ|ZZZZZZZZ| N*2 objects |
- // +--------+--------+--------+--------+--------+~~~~~~~~~~~~~~~~~+
- //
- // where
- // * XXXX is a 4-bit unsigned integer which represents N
- // * YYYYYYYY_YYYYYYYY is a 16-bit big-endian unsigned integer which represents N
- // * ZZZZZZZZ_ZZZZZZZZ_ZZZZZZZZ_ZZZZZZZZ is a 32-bit big-endian unsigned integer which represents N
- // * N is the size of a map
- // * odd elements in objects are keys of a map
- // * the next element of a key is its associated value
-
- test(new ObjectMap("{}"), "80");
- test(new ObjectMap("{1:1}"), "81 A1 31 01");
- test(new ObjectMap("{1:1,2:1,3:1,4:1,5:1,6:1,7:1,8:1,9:1,a:1,b:1,c:1,d:1,e:1,f:1}"), "8F A1 31 01 A1 32 01 A1 33 01 A1 34 01 A1 35 01 A1 36 01 A1 37 01 A1 38 01 A1 39 01 A1 61 01 A1 62 01 A1 63 01 A1 64 01 A1 65 01 A1 66 01");
- test(new ObjectMap("{1:1,2:1,3:1,4:1,5:1,6:1,7:1,8:1,9:1,a:1,b:1,c:1,d:1,e:1,f:1,g:1}"), "DE 00 10 A1 31 01 A1 32 01 A1 33 01 A1 34 01 A1 35 01 A1 36 01 A1 37 01 A1 38 01 A1 39 01 A1 61 01 A1 62 01 A1 63 01 A1 64 01 A1 65 01 A1 66 01 A1 67 01");
-
- byte[] b = MsgPackSerializer.DEFAULT.serialize(new Person());
- System.err.println(TestUtils.toReadableBytes2(b));
- }
-
- public static class Person {
- public String name = "John Smith";
- public int age = 21;
- }
-
- private void test(Object input, String expected) throws Exception {
- byte[] b = MsgPackSerializer.DEFAULT.serialize(input);
- assertEquals(expected, TestUtils.toReadableBytes2(b));
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/msgpack/MsgPackSerialzierTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/msgpack/MsgPackSerialzierTest.java b/org.apache.juneau/src/test/java/org/apache/juneau/msgpack/MsgPackSerialzierTest.java
new file mode 100755
index 0000000..1e49f63
--- /dev/null
+++ b/org.apache.juneau/src/test/java/org/apache/juneau/msgpack/MsgPackSerialzierTest.java
@@ -0,0 +1,220 @@
+/***************************************************************************************************************************
+ * 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.juneau.msgpack;
+
+import static org.junit.Assert.*;
+
+import java.io.*;
+
+import org.apache.juneau.*;
+import org.junit.*;
+
+@SuppressWarnings("serial")
+public class MsgPackSerialzierTest {
+
+ //====================================================================================================
+ // testBasic
+ //====================================================================================================
+ @Test
+ public void testBasic() throws Exception {
+
+ test(null, "C0");
+
+ test(false, "C2");
+ test(true, "C3");
+
+ // positive fixnum stores 7-bit positive integer
+ // +--------+
+ // |0XXXXXXX|
+ // +--------+
+ //
+ // int 8 stores a 8-bit signed integer
+ // +--------+--------+
+ // | 0xd0 |ZZZZZZZZ|
+ // +--------+--------+
+ //
+ // int 16 stores a 16-bit big-endian signed integer
+ // +--------+--------+--------+
+ // | 0xd1 |ZZZZZZZZ|ZZZZZZZZ|
+ // +--------+--------+--------+
+ //
+ // int 32 stores a 32-bit big-endian signed integer
+ // +--------+--------+--------+--------+--------+
+ // | 0xd2 |ZZZZZZZZ|ZZZZZZZZ|ZZZZZZZZ|ZZZZZZZZ|
+ // +--------+--------+--------+--------+--------+
+ //
+ // int 64 stores a 64-bit big-endian signed integer
+ // +--------+--------+--------+--------+--------+--------+--------+--------+--------+
+ // | 0xd3 |ZZZZZZZZ|ZZZZZZZZ|ZZZZZZZZ|ZZZZZZZZ|ZZZZZZZZ|ZZZZZZZZ|ZZZZZZZZ|ZZZZZZZZ|
+ // +--------+--------+--------+--------+--------+--------+--------+--------+--------+
+ //
+ // negative fixnum stores 5-bit negative integer
+ // +--------+
+ // |111YYYYY|
+ // +--------+
+ //
+ // * 0XXXXXXX is 8-bit unsigned integer
+ // * 111YYYYY is 8-bit signed integer
+ //
+
+ test(0, "00");
+ test(0x7F, "7F");
+
+ test(0x80, "D1 00 80");
+ test(0x0100, "D1 01 00");
+ test(0x7FFF, "D1 7F FF");
+ test(0x8000, "D2 00 00 80 00");
+ test(0xFFFF, "D2 00 00 FF FF");
+ test(0x00010000, "D2 00 01 00 00");
+ test(Long.decode("0x000000007FFFFFFF").longValue(), "D2 7F FF FF FF");
+ test(Long.decode("0x0000000080000000").longValue(), "D3 00 00 00 00 80 00 00 00");
+ test(Long.decode("0x0000000100000000").longValue(), "D3 00 00 00 01 00 00 00 00");
+ test(Long.decode("0x7FFFFFFFFFFFFFFF").longValue(), "D3 7F FF FF FF FF FF FF FF");
+ test(-Long.decode("0x7FFFFFFFFFFFFFFF").longValue(), "D3 80 00 00 00 00 00 00 01");
+ test(-1, "E1");
+ test(-63, "FF");
+ test(-64, "D0 C0");
+
+ test(-0x7F, "D0 81");
+ test(-0x80, "D1 FF 80");
+ test(-0x0100, "D1 FF 00");
+ test(-0x7FFF, "D1 80 01");
+ test(-0x8000, "D2 FF FF 80 00");
+ test(-0xFFFF, "D2 FF FF 00 01");
+ test(-0x00010000, "D2 FF FF 00 00");
+ test(-Long.decode("0x000000007FFFFFFF").longValue(), "D2 80 00 00 01");
+ test(-Long.decode("0x0000000080000000").longValue(), "D3 FF FF FF FF 80 00 00 00");
+ test(-Long.decode("0x0000000100000000").longValue(), "D3 FF FF FF FF 00 00 00 00");
+ test(-Long.decode("0x7FFFFFFFFFFFFFFF").longValue(), "D3 80 00 00 00 00 00 00 01");
+
+ // float 32 stores a floating point number in IEEE 754 single precision floating point number format:
+ // +--------+--------+--------+--------+--------+
+ // | 0xca |XXXXXXXX|XXXXXXXX|XXXXXXXX|XXXXXXXX|
+ // +--------+--------+--------+--------+--------+
+ //
+ // float 64 stores a floating point number in IEEE 754 double precision floating point number format:
+ // +--------+--------+--------+--------+--------+--------+--------+--------+--------+
+ // | 0xcb |YYYYYYYY|YYYYYYYY|YYYYYYYY|YYYYYYYY|YYYYYYYY|YYYYYYYY|YYYYYYYY|YYYYYYYY|
+ // +--------+--------+--------+--------+--------+--------+--------+--------+--------+
+ //
+ // where
+ // * XXXXXXXX_XXXXXXXX_XXXXXXXX_XXXXXXXX is a big-endian IEEE 754 single precision floating point number.
+ // Extension of precision from single-precision to double-precision does not lose precision.
+ // * YYYYYYYY_YYYYYYYY_YYYYYYYY_YYYYYYYY_YYYYYYYY_YYYYYYYY_YYYYYYYY_YYYYYYYY is a big-endian
+ // IEEE 754 double precision floating point number
+
+ test(0f, "CA 00 00 00 00");
+ test(1f, "CA 3F 80 00 00");
+ test(-1f, "CA BF 80 00 00");
+ test(1d, "CB 3F F0 00 00 00 00 00 00");
+ test(-1d, "CB BF F0 00 00 00 00 00 00");
+
+ // fixstr stores a byte array whose length is upto 31 bytes:
+ // +--------+========+
+ // |101XXXXX| data |
+ // +--------+========+
+ //
+ // str 8 stores a byte array whose length is upto (2^8)-1 bytes:
+ // +--------+--------+========+
+ // | 0xd9 |YYYYYYYY| data |
+ // +--------+--------+========+
+ //
+ // str 16 stores a byte array whose length is upto (2^16)-1 bytes:
+ // +--------+--------+--------+========+
+ // | 0xda |ZZZZZZZZ|ZZZZZZZZ| data |
+ // +--------+--------+--------+========+
+ //
+ // str 32 stores a byte array whose length is upto (2^32)-1 bytes:
+ // +--------+--------+--------+--------+--------+========+
+ // | 0xdb |AAAAAAAA|AAAAAAAA|AAAAAAAA|AAAAAAAA| data |
+ // +--------+--------+--------+--------+--------+========+
+ //
+ // where
+ // * XXXXX is a 5-bit unsigned integer which represents N
+ // * YYYYYYYY is a 8-bit unsigned integer which represents N
+ // * ZZZZZZZZ_ZZZZZZZZ is a 16-bit big-endian unsigned integer which represents N
+ // * AAAAAAAA_AAAAAAAA_AAAAAAAA_AAAAAAAA is a 32-bit big-endian unsigned integer which represents N
+ // * N is the length of data
+
+ test("", "A0");
+ test("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "BF 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61");
+ test("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "D9 20 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61");
+
+ // fixarray stores an array whose length is upto 15 elements:
+ // +--------+~~~~~~~~~~~~~~~~~+
+ // |1001XXXX| N objects |
+ // +--------+~~~~~~~~~~~~~~~~~+
+ //
+ // array 16 stores an array whose length is upto (2^16)-1 elements:
+ // +--------+--------+--------+~~~~~~~~~~~~~~~~~+
+ // | 0xdc |YYYYYYYY|YYYYYYYY| N objects |
+ // +--------+--------+--------+~~~~~~~~~~~~~~~~~+
+ //
+ // array 32 stores an array whose length is upto (2^32)-1 elements:
+ // +--------+--------+--------+--------+--------+~~~~~~~~~~~~~~~~~+
+ // | 0xdd |ZZZZZZZZ|ZZZZZZZZ|ZZZZZZZZ|ZZZZZZZZ| N objects |
+ // +--------+--------+--------+--------+--------+~~~~~~~~~~~~~~~~~+
+ //
+ // where
+ // * XXXX is a 4-bit unsigned integer which represents N
+ // * YYYYYYYY_YYYYYYYY is a 16-bit big-endian unsigned integer which represents N
+ // * ZZZZZZZZ_ZZZZZZZZ_ZZZZZZZZ_ZZZZZZZZ is a 32-bit big-endian unsigned integer which represents N
+ // N is the size of a array
+
+ test(new int[0], "90");
+ test(new int[]{1}, "91 01");
+ test(new int[]{1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}, "9F 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01");
+ test(new int[]{1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}, "DC 00 10 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01");
+
+ // fixmap stores a map whose length is upto 15 elements
+ // +--------+~~~~~~~~~~~~~~~~~+
+ // |1000XXXX| N*2 objects |
+ // +--------+~~~~~~~~~~~~~~~~~+
+ //
+ // map 16 stores a map whose length is upto (2^16)-1 elements
+ // +--------+--------+--------+~~~~~~~~~~~~~~~~~+
+ // | 0xde |YYYYYYYY|YYYYYYYY| N*2 objects |
+ // +--------+--------+--------+~~~~~~~~~~~~~~~~~+
+ //
+ // map 32 stores a map whose length is upto (2^32)-1 elements
+ // +--------+--------+--------+--------+--------+~~~~~~~~~~~~~~~~~+
+ // | 0xdf |ZZZZZZZZ|ZZZZZZZZ|ZZZZZZZZ|ZZZZZZZZ| N*2 objects |
+ // +--------+--------+--------+--------+--------+~~~~~~~~~~~~~~~~~+
+ //
+ // where
+ // * XXXX is a 4-bit unsigned integer which represents N
+ // * YYYYYYYY_YYYYYYYY is a 16-bit big-endian unsigned integer which represents N
+ // * ZZZZZZZZ_ZZZZZZZZ_ZZZZZZZZ_ZZZZZZZZ is a 32-bit big-endian unsigned integer which represents N
+ // * N is the size of a map
+ // * odd elements in objects are keys of a map
+ // * the next element of a key is its associated value
+
+ test(new ObjectMap("{}"), "80");
+ test(new ObjectMap("{1:1}"), "81 A1 31 01");
+ test(new ObjectMap("{1:1,2:1,3:1,4:1,5:1,6:1,7:1,8:1,9:1,a:1,b:1,c:1,d:1,e:1,f:1}"), "8F A1 31 01 A1 32 01 A1 33 01 A1 34 01 A1 35 01 A1 36 01 A1 37 01 A1 38 01 A1 39 01 A1 61 01 A1 62 01 A1 63 01 A1 64 01 A1 65 01 A1 66 01");
+ test(new ObjectMap("{1:1,2:1,3:1,4:1,5:1,6:1,7:1,8:1,9:1,a:1,b:1,c:1,d:1,e:1,f:1,g:1}"), "DE 00 10 A1 31 01 A1 32 01 A1 33 01 A1 34 01 A1 35 01 A1 36 01 A1 37 01 A1 38 01 A1 39 01 A1 61 01 A1 62 01 A1 63 01 A1 64 01 A1 65 01 A1 66 01 A1 67 01");
+
+ byte[] b = MsgPackSerializer.DEFAULT.serialize(new Person());
+ System.err.println(TestUtils.toReadableBytes2(b));
+ }
+
+ public static class Person {
+ public String name = "John Smith";
+ public int age = 21;
+ }
+
+ private void test(Object input, String expected) throws Exception {
+ byte[] b = MsgPackSerializer.DEFAULT.serialize(input);
+ assertEquals(expected, TestUtils.toReadableBytes2(b));
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/transforms/BeanMapTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/transforms/BeanMapTest.java b/org.apache.juneau/src/test/java/org/apache/juneau/transforms/BeanMapTest.java
new file mode 100755
index 0000000..7ed0919
--- /dev/null
+++ b/org.apache.juneau/src/test/java/org/apache/juneau/transforms/BeanMapTest.java
@@ -0,0 +1,96 @@
+/***************************************************************************************************************************
+ * 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.juneau.transforms;
+
+import static org.junit.Assert.*;
+
+import org.apache.juneau.*;
+import org.apache.juneau.transform.*;
+import org.junit.*;
+
+public class BeanMapTest {
+
+ //====================================================================================================
+ // testFilteredEntry
+ //====================================================================================================
+ @Test
+ public void testFilteredEntry() throws Exception {
+ BeanContext bc = ContextFactory.create().addTransforms(ByteArrayBase64Transform.class).getBeanContext();
+ BeanMap<A> m = bc.forBean(new A());
+
+ assertEquals("AQID", m.get("f1"));
+ m.put("f1", "BAUG");
+ assertEquals("BAUG", m.get("f1"));
+ assertEquals(4, m.getBean().f1[0]);
+
+ assertNull(m.get("f3"));
+ }
+
+ public static class A {
+ public byte[] f1 = new byte[]{1,2,3};
+ public byte[] f3 = null;
+ }
+
+ //====================================================================================================
+ // testFilteredEntryWithMultipleMatchingFilters
+ // When bean properties can have multiple filters applied to them, pick the first match.
+ //====================================================================================================
+ @Test
+ public void testFilteredEntryWithMultipleMatchingFilters() throws Exception {
+ BeanContext bc = ContextFactory.create().addTransforms(B2Filter.class,B1Filter.class).getBeanContext();
+ BeanMap<B> bm = bc.forBean(B.create());
+ ObjectMap om = (ObjectMap)bm.get("b1");
+ assertEquals("b2", om.getString("type"));
+
+ bc = ContextFactory.create().addTransforms(B1Filter.class,B2Filter.class).getBeanContext();
+ bm = bc.forBean(B.create());
+ om = (ObjectMap)bm.get("b1");
+ assertEquals("b1", om.getString("type"));
+ }
+
+
+ public static class B {
+ public B1 b1;
+
+ static B create() {
+ B b = new B();
+ B2 b2 = new B2();
+ b2.f1 = "f1";
+ b2.f2 = "f2";
+ b.b1 = b2;
+ return b;
+ }
+ }
+
+ public static class B1 {
+ public String f1;
+ }
+
+ public static class B2 extends B1 {
+ public String f2;
+ }
+
+ public static class B1Filter extends PojoTransform<B1,ObjectMap> {
+ @Override /* PojoTransform */
+ public ObjectMap transform(B1 b1) {
+ return new ObjectMap().append("type", "b1").append("f1", b1.f1);
+ }
+ }
+
+ public static class B2Filter extends PojoTransform<B2,ObjectMap> {
+ @Override /* PojoTransform */
+ public ObjectMap transform(B2 b2) {
+ return new ObjectMap().append("type", "b2").append("f1", b2.f1);
+ }
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/transforms/BeanTransformTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/transforms/BeanTransformTest.java b/org.apache.juneau/src/test/java/org/apache/juneau/transforms/BeanTransformTest.java
new file mode 100755
index 0000000..a0b7843
--- /dev/null
+++ b/org.apache.juneau/src/test/java/org/apache/juneau/transforms/BeanTransformTest.java
@@ -0,0 +1,204 @@
+/***************************************************************************************************************************
+ * 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.juneau.transforms;
+
+import static org.apache.juneau.TestUtils.*;
+import static org.junit.Assert.*;
+
+import org.apache.juneau.*;
+import org.apache.juneau.annotation.*;
+import org.junit.*;
+
+public class BeanTransformTest {
+
+ //====================================================================================================
+ // Transformed interfaces
+ //====================================================================================================
+ @Test
+ public void testTransformedInterfaces() throws Exception {
+ BeanContext bc;
+ BeanMap<A3> bm;
+
+ bc = ContextFactory.create().addTransforms(A1.class).getBeanContext();
+ bm = bc.newBeanMap(A3.class);
+ assertEquals("f1", bm.get("f1"));
+ assertNull(bm.get("f2"));
+ assertNull(bm.get("f3"));
+
+ bc = ContextFactory.create().addTransforms(A2.class).getBeanContext();
+ bm = bc.newBeanMap(A3.class);
+ assertEquals("f1", bm.get("f1"));
+ assertEquals("f2", bm.get("f2"));
+ assertNull(bm.get("f3"));
+ }
+
+ public static interface A1 {
+ public String getF1();
+ }
+
+ public static interface A2 extends A1 {
+ public String getF2();
+ }
+
+ public static class A3 implements A2 {
+ @Override /* A1 */
+ public String getF1() {
+ return "f1";
+ }
+ @Override /* A2 */
+ public String getF2() {
+ return "f2";
+ }
+ public String getF3() {
+ return "f3";
+ }
+ }
+
+ //====================================================================================================
+ // Transformed abstract classes
+ //====================================================================================================
+ @Test
+ public void testTransformedAbstractClasses() throws Exception {
+ BeanContext bc;
+ BeanMap<Test2> bm;
+
+ bc = ContextFactory.create().addTransforms(B1.class).getBeanContext();
+ bm = bc.newBeanMap(Test2.class);
+ assertEquals("f1", bm.get("f1"));
+ assertNull(bm.get("f2"));
+ assertNull(bm.get("f3"));
+
+ bc = ContextFactory.create().addTransforms(B2.class).getBeanContext();
+ bm = bc.newBeanMap(Test2.class);
+ assertEquals("f1", bm.get("f1"));
+ assertEquals("f2", bm.get("f2"));
+ assertNull(bm.get("f3"));
+ }
+
+ public abstract static class B1 {
+ public abstract String getF1();
+ }
+
+ public abstract static class B2 extends B1 {
+ @Override /* B1 */
+ public abstract String getF1();
+ public abstract String getF2();
+ }
+
+ public static class Test2 extends B2 {
+ @Override /* B1 */
+ public String getF1() {
+ return "f1";
+ }
+ @Override /* B2 */
+ public String getF2() {
+ return "f2";
+ }
+ public String getF3() {
+ return "f3";
+ }
+ }
+
+ //====================================================================================================
+ // Transformed with stop classes
+ //====================================================================================================
+ @Test
+ public void testTransformedWithStopClass() throws Exception {
+ C3 c3 = new C3();
+ assertObjectEquals("{f3:3,p3:3}", c3);
+ }
+
+ public class C1 {
+ public int f1 = 1;
+ public int getP1() { return 1; }
+ }
+
+ public class C2 extends C1 {
+ public int f2 = 2;
+ public int getP2() { return 2; }
+ }
+
+ @Bean(stopClass=C2.class)
+ public class C3 extends C2 {
+ public int f3 = 3;
+ public int getP3() { return 3; }
+ }
+
+ @Test
+ public void testTransformedWithStopClassOnParentClass() throws Exception {
+ D3 d3 = new D3();
+ assertObjectEquals("{f3:3,p3:3}", d3);
+ }
+
+ public class D1 {
+ public int f1 = 1;
+ public int getP1() { return 1; }
+ }
+
+ @Bean(stopClass=D2.class)
+ public class D2 extends D1 {
+ public int f2 = 2;
+ public int getP2() { return 2; }
+ }
+
+ public class D3 extends D2 {
+ public int f3 = 3;
+ public int getP3() { return 3; }
+ }
+
+ @Test
+ public void testTransformedWithStopClassOnParentClassWithOverriddenAnnotation() throws Exception {
+ E3 e3 = new E3();
+ assertObjectEquals("{f3:3,p3:3}", e3);
+ }
+
+ public class E1 {
+ public int f1 = 1;
+ public int getP1() { return 1; }
+ }
+
+ @Bean(stopClass=E2.class)
+ public class E2 extends E1 {
+ public int f2 = 2;
+ public int getP2() { return 2; }
+ }
+
+ @Bean(excludeProperties={"foo"})
+ public class E3 extends E2 {
+ public int f3 = 3;
+ public int getP3() { return 3; }
+ }
+
+ @Test
+ public void testTransformedWithStopClassesAtMulitpleLevels() throws Exception {
+ F3 e3 = new F3();
+ assertObjectEquals("{f3:3,p3:3}", e3);
+ }
+
+ @Bean(stopClass=F1.class)
+ public class F1 {
+ public int f1 = 1;
+ public int getP1() { return 1; }
+ }
+
+ public class F2 extends F1 {
+ public int f2 = 2;
+ public int getP2() { return 2; }
+ }
+
+ @Bean(stopClass=F2.class)
+ public class F3 extends F2 {
+ public int f3 = 3;
+ public int getP3() { return 3; }
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/transforms/ByteArrayBase64TransformTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/transforms/ByteArrayBase64TransformTest.java b/org.apache.juneau/src/test/java/org/apache/juneau/transforms/ByteArrayBase64TransformTest.java
new file mode 100755
index 0000000..174a98e
--- /dev/null
+++ b/org.apache.juneau/src/test/java/org/apache/juneau/transforms/ByteArrayBase64TransformTest.java
@@ -0,0 +1,172 @@
+/***************************************************************************************************************************
+ * 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.juneau.transforms;
+
+import static org.apache.juneau.serializer.SerializerContext.*;
+import static org.junit.Assert.*;
+
+import java.util.*;
+
+import org.apache.juneau.a.rttests.*;
+import org.apache.juneau.json.*;
+import org.apache.juneau.parser.*;
+import org.apache.juneau.serializer.*;
+import org.junit.*;
+
+@SuppressWarnings({"unchecked","hiding","serial"})
+public class ByteArrayBase64TransformTest extends RoundTripTest {
+
+ public ByteArrayBase64TransformTest(String label, Serializer s, Parser p, int flags) throws Exception {
+ super(label, s, p, flags);
+ }
+
+ @Override /* RoundTripTest */
+ public Class<?>[] getTransforms() {
+ return new Class<?>[] {
+ ByteArrayBase64Transform.class
+ };
+ }
+
+ //====================================================================================================
+ // testPrimitiveArrays
+ //====================================================================================================
+ @Test
+ public void testPrimitiveArrays() throws Exception {
+ WriterSerializer s = new JsonSerializer.Simple().addTransforms(ByteArrayBase64Transform.class).setProperty(SERIALIZER_trimNullProperties, false);
+
+ byte[] a1 = {1,2,3};
+ assertEquals("'AQID'", s.serialize(a1));
+ a1 = roundTrip(a1, byte[].class);
+ assertEquals(1, a1[0]);
+
+ byte[][] a2 = {{1,2,3},{4,5,6},null};
+ assertEquals("['AQID','BAUG',null]", s.serialize(a2));
+ a2 = roundTrip(a2, byte[][].class);
+ assertEquals(1, a2[0][0]);
+ assertNull(a2[2]);
+
+ byte[] a3 = null;
+ assertEquals("null", s.serialize(a3));
+ a3 = roundTrip(a3, byte[].class);
+ assertNull(a3);
+
+ if (p == null)
+ return;
+
+ List<byte[]> fl = new ArrayList<byte[]>() {{
+ add(new byte[]{1,2,3});
+ add(new byte[]{4,5,6});
+ add(null);
+ }};
+ assertEquals("['AQID','BAUG',null]", s.serialize(fl));
+ fl = roundTrip(fl, p.getBeanContext().getCollectionClassMeta(List.class, byte[].class));
+ assertEquals(1, fl.get(0)[0]);
+ assertEquals(5, fl.get(1)[1]);
+ assertNull(fl.get(2));
+
+ Map<String,byte[]> fm = new LinkedHashMap<String,byte[]>() {{
+ put("foo", new byte[]{1,2,3});
+ put("bar", null);
+ put(null, new byte[]{4,5,6});
+ put("null", new byte[]{7,8,9});
+ }};
+ fm = roundTrip(fm, p.getBeanContext().getMapClassMeta(Map.class, String.class, byte[].class));
+ assertEquals(1, fm.get("foo")[0]);
+ assertNull(fm.get(1));
+ assertEquals(5, fm.get(null)[1]);
+ assertEquals(8, fm.get("null")[1]);
+ }
+
+ //====================================================================================================
+ // testBean
+ //====================================================================================================
+ @Test
+ public void testBean() throws Exception {
+ A t = new A().init();
+ t = roundTrip(t, A.class);
+ assertEquals(1, t.f1[0]);
+ assertEquals(4, t.f2[1][0]);
+ assertNull(t.f2[2]);
+ assertNull(t.f3);
+ assertEquals(1, t.fl.get(0)[0]);
+ assertNull(t.fl.get(2));
+ assertEquals(1, t.fm.get("foo")[0]);
+ assertNull(t.fm.get("bar"));
+ assertEquals(4, t.fm.get(null)[0]);
+ assertEquals(1, t.flb.get(0).fl.get(0)[0]);
+ assertNull(t.flb.get(1));
+ assertEquals(1, t.fmb.get("foo").fl.get(0)[0]);
+ assertNull(t.fmb.get("bar"));
+ }
+
+ public static class A {
+ public byte[] f1;
+ public byte[][] f2;
+ public byte[] f3;
+ public List<byte[]> fl;
+ public Map<String,byte[]> fm;
+ public List<B> flb;
+ public Map<String,B> fmb;
+
+ public A init() {
+ f1 = new byte[]{1,2,3};
+ f2 = new byte[][]{{1,2,3},{4,5,6},null};
+ f3 = null;
+ fl = new ArrayList<byte[]>() {{
+ add(new byte[]{1,2,3});
+ add(new byte[]{4,5,6});
+ add(null);
+ }};
+ fm = new LinkedHashMap<String,byte[]>() {{
+ put("foo", new byte[]{1,2,3});
+ put("bar", null);
+ put(null, new byte[]{4,5,6});
+ }};
+ flb = new ArrayList<B>() {{
+ add(new B().init());
+ add(null);
+ }};
+ fmb = new LinkedHashMap<String,B>() {{
+ put("foo", new B().init());
+ put("bar", null);
+ put(null, new B().init());
+ }};
+ return this;
+ }
+ }
+
+ public static class B {
+ public byte[] f1;
+ public byte[][] f2;
+ public byte[] f3;
+ public List<byte[]> fl;
+ public Map<String,byte[]> fm;
+
+ public B init() {
+ f1 = new byte[]{1,2,3};
+ f2 = new byte[][]{{1,2,3},{4,5,6},null};
+ f3 = null;
+ fl = new ArrayList<byte[]>() {{
+ add(new byte[]{1,2,3});
+ add(new byte[]{4,5,6});
+ add(null);
+ }};
+ fm = new LinkedHashMap<String,byte[]>() {{
+ put("foo", new byte[]{1,2,3});
+ put("bar", null);
+ put(null, new byte[]{4,5,6});
+ }};
+ return this;
+ }
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/transforms/CT_BeanMap.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/transforms/CT_BeanMap.java b/org.apache.juneau/src/test/java/org/apache/juneau/transforms/CT_BeanMap.java
deleted file mode 100755
index edb671b..0000000
--- a/org.apache.juneau/src/test/java/org/apache/juneau/transforms/CT_BeanMap.java
+++ /dev/null
@@ -1,96 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.transforms;
-
-import static org.junit.Assert.*;
-
-import org.apache.juneau.*;
-import org.apache.juneau.transform.*;
-import org.junit.*;
-
-public class CT_BeanMap {
-
- //====================================================================================================
- // testFilteredEntry
- //====================================================================================================
- @Test
- public void testFilteredEntry() throws Exception {
- BeanContext bc = ContextFactory.create().addTransforms(ByteArrayBase64Transform.class).getBeanContext();
- BeanMap<A> m = bc.forBean(new A());
-
- assertEquals("AQID", m.get("f1"));
- m.put("f1", "BAUG");
- assertEquals("BAUG", m.get("f1"));
- assertEquals(4, m.getBean().f1[0]);
-
- assertNull(m.get("f3"));
- }
-
- public static class A {
- public byte[] f1 = new byte[]{1,2,3};
- public byte[] f3 = null;
- }
-
- //====================================================================================================
- // testFilteredEntryWithMultipleMatchingFilters
- // When bean properties can have multiple filters applied to them, pick the first match.
- //====================================================================================================
- @Test
- public void testFilteredEntryWithMultipleMatchingFilters() throws Exception {
- BeanContext bc = ContextFactory.create().addTransforms(B2Filter.class,B1Filter.class).getBeanContext();
- BeanMap<B> bm = bc.forBean(B.create());
- ObjectMap om = (ObjectMap)bm.get("b1");
- assertEquals("b2", om.getString("type"));
-
- bc = ContextFactory.create().addTransforms(B1Filter.class,B2Filter.class).getBeanContext();
- bm = bc.forBean(B.create());
- om = (ObjectMap)bm.get("b1");
- assertEquals("b1", om.getString("type"));
- }
-
-
- public static class B {
- public B1 b1;
-
- static B create() {
- B b = new B();
- B2 b2 = new B2();
- b2.f1 = "f1";
- b2.f2 = "f2";
- b.b1 = b2;
- return b;
- }
- }
-
- public static class B1 {
- public String f1;
- }
-
- public static class B2 extends B1 {
- public String f2;
- }
-
- public static class B1Filter extends PojoTransform<B1,ObjectMap> {
- @Override /* PojoTransform */
- public ObjectMap transform(B1 b1) {
- return new ObjectMap().append("type", "b1").append("f1", b1.f1);
- }
- }
-
- public static class B2Filter extends PojoTransform<B2,ObjectMap> {
- @Override /* PojoTransform */
- public ObjectMap transform(B2 b2) {
- return new ObjectMap().append("type", "b2").append("f1", b2.f1);
- }
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/transforms/CT_BeanTransform.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/transforms/CT_BeanTransform.java b/org.apache.juneau/src/test/java/org/apache/juneau/transforms/CT_BeanTransform.java
deleted file mode 100755
index fa1135d..0000000
--- a/org.apache.juneau/src/test/java/org/apache/juneau/transforms/CT_BeanTransform.java
+++ /dev/null
@@ -1,204 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.transforms;
-
-import static org.apache.juneau.TestUtils.*;
-import static org.junit.Assert.*;
-
-import org.apache.juneau.*;
-import org.apache.juneau.annotation.*;
-import org.junit.*;
-
-public class CT_BeanTransform {
-
- //====================================================================================================
- // Transformed interfaces
- //====================================================================================================
- @Test
- public void testTransformedInterfaces() throws Exception {
- BeanContext bc;
- BeanMap<A3> bm;
-
- bc = ContextFactory.create().addTransforms(A1.class).getBeanContext();
- bm = bc.newBeanMap(A3.class);
- assertEquals("f1", bm.get("f1"));
- assertNull(bm.get("f2"));
- assertNull(bm.get("f3"));
-
- bc = ContextFactory.create().addTransforms(A2.class).getBeanContext();
- bm = bc.newBeanMap(A3.class);
- assertEquals("f1", bm.get("f1"));
- assertEquals("f2", bm.get("f2"));
- assertNull(bm.get("f3"));
- }
-
- public static interface A1 {
- public String getF1();
- }
-
- public static interface A2 extends A1 {
- public String getF2();
- }
-
- public static class A3 implements A2 {
- @Override /* A1 */
- public String getF1() {
- return "f1";
- }
- @Override /* A2 */
- public String getF2() {
- return "f2";
- }
- public String getF3() {
- return "f3";
- }
- }
-
- //====================================================================================================
- // Transformed abstract classes
- //====================================================================================================
- @Test
- public void testTransformedAbstractClasses() throws Exception {
- BeanContext bc;
- BeanMap<Test2> bm;
-
- bc = ContextFactory.create().addTransforms(B1.class).getBeanContext();
- bm = bc.newBeanMap(Test2.class);
- assertEquals("f1", bm.get("f1"));
- assertNull(bm.get("f2"));
- assertNull(bm.get("f3"));
-
- bc = ContextFactory.create().addTransforms(B2.class).getBeanContext();
- bm = bc.newBeanMap(Test2.class);
- assertEquals("f1", bm.get("f1"));
- assertEquals("f2", bm.get("f2"));
- assertNull(bm.get("f3"));
- }
-
- public abstract static class B1 {
- public abstract String getF1();
- }
-
- public abstract static class B2 extends B1 {
- @Override /* B1 */
- public abstract String getF1();
- public abstract String getF2();
- }
-
- public static class Test2 extends B2 {
- @Override /* B1 */
- public String getF1() {
- return "f1";
- }
- @Override /* B2 */
- public String getF2() {
- return "f2";
- }
- public String getF3() {
- return "f3";
- }
- }
-
- //====================================================================================================
- // Transformed with stop classes
- //====================================================================================================
- @Test
- public void testTransformedWithStopClass() throws Exception {
- C3 c3 = new C3();
- assertObjectEquals("{f3:3,p3:3}", c3);
- }
-
- public class C1 {
- public int f1 = 1;
- public int getP1() { return 1; }
- }
-
- public class C2 extends C1 {
- public int f2 = 2;
- public int getP2() { return 2; }
- }
-
- @Bean(stopClass=C2.class)
- public class C3 extends C2 {
- public int f3 = 3;
- public int getP3() { return 3; }
- }
-
- @Test
- public void testTransformedWithStopClassOnParentClass() throws Exception {
- D3 d3 = new D3();
- assertObjectEquals("{f3:3,p3:3}", d3);
- }
-
- public class D1 {
- public int f1 = 1;
- public int getP1() { return 1; }
- }
-
- @Bean(stopClass=D2.class)
- public class D2 extends D1 {
- public int f2 = 2;
- public int getP2() { return 2; }
- }
-
- public class D3 extends D2 {
- public int f3 = 3;
- public int getP3() { return 3; }
- }
-
- @Test
- public void testTransformedWithStopClassOnParentClassWithOverriddenAnnotation() throws Exception {
- E3 e3 = new E3();
- assertObjectEquals("{f3:3,p3:3}", e3);
- }
-
- public class E1 {
- public int f1 = 1;
- public int getP1() { return 1; }
- }
-
- @Bean(stopClass=E2.class)
- public class E2 extends E1 {
- public int f2 = 2;
- public int getP2() { return 2; }
- }
-
- @Bean(excludeProperties={"foo"})
- public class E3 extends E2 {
- public int f3 = 3;
- public int getP3() { return 3; }
- }
-
- @Test
- public void testTransformedWithStopClassesAtMulitpleLevels() throws Exception {
- F3 e3 = new F3();
- assertObjectEquals("{f3:3,p3:3}", e3);
- }
-
- @Bean(stopClass=F1.class)
- public class F1 {
- public int f1 = 1;
- public int getP1() { return 1; }
- }
-
- public class F2 extends F1 {
- public int f2 = 2;
- public int getP2() { return 2; }
- }
-
- @Bean(stopClass=F2.class)
- public class F3 extends F2 {
- public int f3 = 3;
- public int getP3() { return 3; }
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/transforms/CT_ByteArrayBase64Transform.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/transforms/CT_ByteArrayBase64Transform.java b/org.apache.juneau/src/test/java/org/apache/juneau/transforms/CT_ByteArrayBase64Transform.java
deleted file mode 100755
index f616902..0000000
--- a/org.apache.juneau/src/test/java/org/apache/juneau/transforms/CT_ByteArrayBase64Transform.java
+++ /dev/null
@@ -1,172 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.transforms;
-
-import static org.apache.juneau.serializer.SerializerContext.*;
-import static org.junit.Assert.*;
-
-import java.util.*;
-
-import org.apache.juneau.a.rttests.*;
-import org.apache.juneau.json.*;
-import org.apache.juneau.parser.*;
-import org.apache.juneau.serializer.*;
-import org.junit.*;
-
-@SuppressWarnings({"unchecked","hiding","serial"})
-public class CT_ByteArrayBase64Transform extends RoundTripTest {
-
- public CT_ByteArrayBase64Transform(String label, Serializer s, Parser p, int flags) throws Exception {
- super(label, s, p, flags);
- }
-
- @Override /* RoundTripTest */
- public Class<?>[] getTransforms() {
- return new Class<?>[] {
- ByteArrayBase64Transform.class
- };
- }
-
- //====================================================================================================
- // testPrimitiveArrays
- //====================================================================================================
- @Test
- public void testPrimitiveArrays() throws Exception {
- WriterSerializer s = new JsonSerializer.Simple().addTransforms(ByteArrayBase64Transform.class).setProperty(SERIALIZER_trimNullProperties, false);
-
- byte[] a1 = {1,2,3};
- assertEquals("'AQID'", s.serialize(a1));
- a1 = roundTrip(a1, byte[].class);
- assertEquals(1, a1[0]);
-
- byte[][] a2 = {{1,2,3},{4,5,6},null};
- assertEquals("['AQID','BAUG',null]", s.serialize(a2));
- a2 = roundTrip(a2, byte[][].class);
- assertEquals(1, a2[0][0]);
- assertNull(a2[2]);
-
- byte[] a3 = null;
- assertEquals("null", s.serialize(a3));
- a3 = roundTrip(a3, byte[].class);
- assertNull(a3);
-
- if (p == null)
- return;
-
- List<byte[]> fl = new ArrayList<byte[]>() {{
- add(new byte[]{1,2,3});
- add(new byte[]{4,5,6});
- add(null);
- }};
- assertEquals("['AQID','BAUG',null]", s.serialize(fl));
- fl = roundTrip(fl, p.getBeanContext().getCollectionClassMeta(List.class, byte[].class));
- assertEquals(1, fl.get(0)[0]);
- assertEquals(5, fl.get(1)[1]);
- assertNull(fl.get(2));
-
- Map<String,byte[]> fm = new LinkedHashMap<String,byte[]>() {{
- put("foo", new byte[]{1,2,3});
- put("bar", null);
- put(null, new byte[]{4,5,6});
- put("null", new byte[]{7,8,9});
- }};
- fm = roundTrip(fm, p.getBeanContext().getMapClassMeta(Map.class, String.class, byte[].class));
- assertEquals(1, fm.get("foo")[0]);
- assertNull(fm.get(1));
- assertEquals(5, fm.get(null)[1]);
- assertEquals(8, fm.get("null")[1]);
- }
-
- //====================================================================================================
- // testBean
- //====================================================================================================
- @Test
- public void testBean() throws Exception {
- A t = new A().init();
- t = roundTrip(t, A.class);
- assertEquals(1, t.f1[0]);
- assertEquals(4, t.f2[1][0]);
- assertNull(t.f2[2]);
- assertNull(t.f3);
- assertEquals(1, t.fl.get(0)[0]);
- assertNull(t.fl.get(2));
- assertEquals(1, t.fm.get("foo")[0]);
- assertNull(t.fm.get("bar"));
- assertEquals(4, t.fm.get(null)[0]);
- assertEquals(1, t.flb.get(0).fl.get(0)[0]);
- assertNull(t.flb.get(1));
- assertEquals(1, t.fmb.get("foo").fl.get(0)[0]);
- assertNull(t.fmb.get("bar"));
- }
-
- public static class A {
- public byte[] f1;
- public byte[][] f2;
- public byte[] f3;
- public List<byte[]> fl;
- public Map<String,byte[]> fm;
- public List<B> flb;
- public Map<String,B> fmb;
-
- public A init() {
- f1 = new byte[]{1,2,3};
- f2 = new byte[][]{{1,2,3},{4,5,6},null};
- f3 = null;
- fl = new ArrayList<byte[]>() {{
- add(new byte[]{1,2,3});
- add(new byte[]{4,5,6});
- add(null);
- }};
- fm = new LinkedHashMap<String,byte[]>() {{
- put("foo", new byte[]{1,2,3});
- put("bar", null);
- put(null, new byte[]{4,5,6});
- }};
- flb = new ArrayList<B>() {{
- add(new B().init());
- add(null);
- }};
- fmb = new LinkedHashMap<String,B>() {{
- put("foo", new B().init());
- put("bar", null);
- put(null, new B().init());
- }};
- return this;
- }
- }
-
- public static class B {
- public byte[] f1;
- public byte[][] f2;
- public byte[] f3;
- public List<byte[]> fl;
- public Map<String,byte[]> fm;
-
- public B init() {
- f1 = new byte[]{1,2,3};
- f2 = new byte[][]{{1,2,3},{4,5,6},null};
- f3 = null;
- fl = new ArrayList<byte[]>() {{
- add(new byte[]{1,2,3});
- add(new byte[]{4,5,6});
- add(null);
- }};
- fm = new LinkedHashMap<String,byte[]>() {{
- put("foo", new byte[]{1,2,3});
- put("bar", null);
- put(null, new byte[]{4,5,6});
- }};
- return this;
- }
- }
-}
\ No newline at end of file
[12/44] incubator-juneau git commit: Rename CT_* testcases.
Posted by ja...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/transforms/CT_CalendarTransform.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/transforms/CT_CalendarTransform.java b/org.apache.juneau/src/test/java/org/apache/juneau/transforms/CT_CalendarTransform.java
deleted file mode 100755
index f3a6180..0000000
--- a/org.apache.juneau/src/test/java/org/apache/juneau/transforms/CT_CalendarTransform.java
+++ /dev/null
@@ -1,696 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.transforms;
-
-import static org.apache.juneau.jena.RdfCommonContext.*;
-import static org.apache.juneau.serializer.SerializerContext.*;
-import static org.junit.Assert.*;
-
-import java.net.*;
-import java.text.*;
-import java.util.*;
-
-import javax.xml.bind.*;
-
-import org.apache.juneau.annotation.*;
-import org.apache.juneau.html.*;
-import org.apache.juneau.jena.*;
-import org.apache.juneau.json.*;
-import org.apache.juneau.parser.*;
-import org.apache.juneau.serializer.*;
-import org.apache.juneau.transform.*;
-import org.apache.juneau.urlencoding.*;
-import org.apache.juneau.xml.*;
-import org.junit.*;
-
-public class CT_CalendarTransform {
-
- private static Calendar testDate = new GregorianCalendar(TimeZone.getTimeZone("PST"));
- static {
- testDate.setTimeInMillis(0);
- testDate.set(1901, 2, 3, 10, 11, 12);
- }
-
- private RdfSerializer getRdfSerializer() {
- return new RdfSerializer()
- .setProperty(SERIALIZER_quoteChar, '\'')
- .setProperty(SERIALIZER_useIndentation, false)
- .setProperty(RDF_rdfxml_allowBadUris, true)
- .setProperty(RDF_rdfxml_showDoctypeDeclaration, false)
- .setProperty(RDF_rdfxml_showXmlDeclaration, false);
- }
-
- private String stripRdf(String s) {
- return s.replaceFirst("<rdf:RDF[^>]+>\\s*", "").replaceAll("</rdf:RDF>$", "").trim().replaceAll("[\\r\\n]", "");
- }
-
- //====================================================================================================
- // testTimezone - Make sure timezone on calendar is preserved.
- //====================================================================================================
- @Test
- public void testTimezone() throws Exception {
- PojoTransform<Calendar,String> f;
- String s;
- Calendar c;
-
- //--------------------
- // ISO8601DT
- //--------------------
- f = new CalendarTransform.ISO8601DT();
-
- s = "2001-01-31T12:34:56Z";
- c = DatatypeConverter.parseDateTime(s);
- assertEquals(s, f.transform(c));
-
- s = "2001-01-31T09:34:56-03:00";
- c = DatatypeConverter.parseDateTime(s);
- assertEquals(s, f.transform(c));
-
- s = "2001-01-31T06:34:56-06:00";
- c = DatatypeConverter.parseDateTime(s);
- assertEquals(s, f.transform(c));
-
-
- //--------------------
- // ISO8601DTZ
- //--------------------
- f = new CalendarTransform.ISO8601DTZ();
-
- s = "2001-01-31T12:34:56Z";
- c = DatatypeConverter.parseDateTime(s);
- assertEquals(s, f.transform(c));
-
- s = "2001-01-31T09:34:56-03:00";
- c = DatatypeConverter.parseDateTime(s);
- assertEquals("2001-01-31T12:34:56Z", f.transform(c));
-
- s = "2001-01-31T06:34:56-06:00";
- c = DatatypeConverter.parseDateTime(s);
- assertEquals("2001-01-31T12:34:56Z", f.transform(c));
-
- //--------------------
- // RFC2822DTZ
- //--------------------
- f = new CalendarTransform.RFC2822DT();
-
- s = "2001-01-31T12:34:56Z";
- c = DatatypeConverter.parseDateTime(s);
- assertEquals("Wed, 31 Jan 2001 12:34:56 +0000", f.transform(c));
-
- s = "2001-01-31T09:34:56-03:00";
- c = DatatypeConverter.parseDateTime(s);
- assertEquals("Wed, 31 Jan 2001 09:34:56 -0300", f.transform(c));
-
- s = "2001-01-31T06:34:56-06:00";
- c = DatatypeConverter.parseDateTime(s);
- assertEquals("Wed, 31 Jan 2001 06:34:56 -0600", f.transform(c));
-
- //--------------------
- // RFC2822DTZ
- //--------------------
- f = new CalendarTransform.RFC2822DTZ();
-
- s = "2001-01-31T12:34:56Z";
- c = DatatypeConverter.parseDateTime(s);
- assertEquals("Wed, 31 Jan 2001 12:34:56 GMT", f.transform(c));
-
- s = "2001-01-31T09:34:56-03:00";
- c = DatatypeConverter.parseDateTime(s);
- assertEquals("Wed, 31 Jan 2001 12:34:56 GMT", f.transform(c));
-
- s = "2001-01-31T06:34:56-06:00";
- c = DatatypeConverter.parseDateTime(s);
- assertEquals("Wed, 31 Jan 2001 12:34:56 GMT", f.transform(c));
- }
-
-
- //====================================================================================================
- // testDefaultStringJson - DEFAULT_STRING, JSON
- //====================================================================================================
- @Test
- public void testDefaultStringJson() throws Exception {
- Class<?> f = CalendarTransform.ToString.class;
- WriterSerializer s = new JsonSerializer.Simple().addTransforms(f);
- ReaderParser p = new JsonParser().addTransforms(f);
- doTest(s, p, true, "'Sun Mar 03 10:11:12 PST 1901'");
- }
-
- //====================================================================================================
- // testDefaultStringXml - DEFAULT_STRING, XML
- //====================================================================================================
- @Test
- public void testDefaultStringXml() throws Exception {
- Class<?> f = CalendarTransform.ToString.class;
- WriterSerializer s = new XmlSerializer.SimpleSq().addTransforms(f);
- ReaderParser p = new XmlParser().addTransforms(f);
- doTest(s, p, true, "<string>Sun Mar 03 10:11:12 PST 1901</string>");
- }
-
- //====================================================================================================
- // testDefaultStringHtml - DEFAULT_STRING, HTML
- //====================================================================================================
- @Test
- public void testDefaultStringHtml() throws Exception {
- Class<?> f = CalendarTransform.ToString.class;
- WriterSerializer s = new HtmlSerializer().addTransforms(f);
- ReaderParser p = new HtmlParser().addTransforms(f);
- doTest(s, p, true, "<string>Sun Mar 03 10:11:12 PST 1901</string>");
- }
-
- //====================================================================================================
- // testDefaultStringUrlParam - DEFAULT_STRING, UON
- //====================================================================================================
- @Test
- public void testDefaultStringUon() throws Exception {
- Class<?> f = CalendarTransform.ToString.class;
- WriterSerializer s = new UonSerializer.Encoding().addTransforms(f);
- ReaderParser p = UonParser.DEFAULT_DECODING.clone().addTransforms(f);
- doTest(s, p, true, "Sun+Mar+03+10:11:12+PST+1901");
- }
-
- //====================================================================================================
- // testDefaultStringUrlParam - DEFAULT_STRING, URL-ENCODING
- //====================================================================================================
- @Test
- public void testDefaultStringUrlEncoding() throws Exception {
- Class<?> f = CalendarTransform.ToString.class;
- WriterSerializer s = new UrlEncodingSerializer().addTransforms(f);
- ReaderParser p = UrlEncodingParser.DEFAULT.clone().addTransforms(f);
- doTest(s, p, true, "_value=Sun+Mar+03+10:11:12+PST+1901");
- }
-
- //====================================================================================================
- // testDefaultStringRdfXml - DEFAULT_STRING, RDF/XML
- //====================================================================================================
- @Test
- public void testDefaultStringRdfXml() throws Exception {
- Class<?> f = CalendarTransform.ToString.class;
- WriterSerializer s = getRdfSerializer().addTransforms(f);
- ReaderParser p = new RdfParser.Xml().addTransforms(f);
- doTest(s, p, true, "<rdf:Description><j:value>Sun Mar 03 10:11:12 PST 1901</j:value></rdf:Description>");
- }
-
- //====================================================================================================
- // testISO8601DTJson - DEFAULT_ISO8601DT, JSON
- //====================================================================================================
- @Test
- public void testISO8601DTJson() throws Exception {
- Class<?> f = CalendarTransform.ISO8601DT.class;
- WriterSerializer s = new JsonSerializer.Simple().addTransforms(f);
- ReaderParser p = new JsonParser().addTransforms(f);
- String x = "'1901-03-03T10:11:12-08:00'";
- doTest(s, p, true, x);
- }
-
- //====================================================================================================
- // testISO8601DTXml - DEFAULT_ISO8601DT, XML
- //====================================================================================================
- @Test
- public void testISO8601DTXml() throws Exception {
- Class<?> f = CalendarTransform.ISO8601DT.class;
- WriterSerializer s = new XmlSerializer.SimpleSq().addTransforms(f);
- ReaderParser p = new XmlParser().addTransforms(f);
- doTest(s, p, true, "<string>1901-03-03T10:11:12-08:00</string>");
- }
-
- //====================================================================================================
- // testISO8601DTHtml - DEFAULT_ISO8601DT, HTML
- //====================================================================================================
- @Test
- public void testISO8601DTHtml() throws Exception {
- Class<?> f = CalendarTransform.ISO8601DT.class;
- WriterSerializer s = new HtmlSerializer().addTransforms(f);
- ReaderParser p = new HtmlParser().addTransforms(f);
- doTest(s, p, true, "<string>1901-03-03T10:11:12-08:00</string>");
- }
-
- //====================================================================================================
- // testISO8601DTUrlParam - DEFAULT_ISO8601DT, UON
- //====================================================================================================
- @Test
- public void testISO8601DTUon() throws Exception {
- Class<?> f = CalendarTransform.ISO8601DT.class;
- WriterSerializer s = new UonSerializer().addTransforms(f);
- ReaderParser p = new UonParser().addTransforms(f);
- doTest(s, p, true, "1901-03-03T10:11:12-08:00");
- }
-
- //====================================================================================================
- // testISO8601DTUrlParam - DEFAULT_ISO8601DT, URL-ENCODING
- //====================================================================================================
- @Test
- public void testISO8601DTUrlEncoding() throws Exception {
- Class<?> f = CalendarTransform.ISO8601DT.class;
- WriterSerializer s = new UrlEncodingSerializer().addTransforms(f);
- ReaderParser p = new UrlEncodingParser().addTransforms(f);
- doTest(s, p, true, "_value=1901-03-03T10:11:12-08:00");
- }
-
- //====================================================================================================
- // testISO8601DTRdfXml - DEFAULT_ISO8601DT, RDF/XML
- //====================================================================================================
- @Test
- public void testISO8601DTRdfXml() throws Exception {
- Class<?> f = CalendarTransform.ISO8601DT.class;
- WriterSerializer s = getRdfSerializer().addTransforms(f);
- ReaderParser p = new RdfParser.Xml().addTransforms(f);
- doTest(s, p, true, "<rdf:Description><j:value>1901-03-03T10:11:12-08:00</j:value></rdf:Description>");
- }
-
- //====================================================================================================
- // testRFC2822DTJson - DEFAULT_RFC2822DT, JSON
- //====================================================================================================
- @Test
- public void testRFC2822DTJson() throws Exception {
- Class<?> f = CalendarTransform.RFC2822DTZ.class;
- WriterSerializer s = new JsonSerializer.Simple().addTransforms(f);
- ReaderParser p = new JsonParser().addTransforms(f);
- doTest(s, p, true, "'Sun, 03 Mar 1901 18:11:12 GMT'");
- }
-
- //====================================================================================================
- // testRFC2822DTXml - DEFAULT_RFC2822DT, XML
- //====================================================================================================
- @Test
- public void testRFC2822DTXml() throws Exception {
- Class<?> f = CalendarTransform.RFC2822DTZ.class;
- WriterSerializer s = new XmlSerializer.SimpleSq().addTransforms(f);
- ReaderParser p = new XmlParser().addTransforms(f);
- doTest(s, p, true, "<string>Sun, 03 Mar 1901 18:11:12 GMT</string>");
- }
-
- //====================================================================================================
- // testRFC2822DTHtml - DEFAULT_RFC2822DT, HTML
- //====================================================================================================
- @Test
- public void testRFC2822DTHtml() throws Exception {
- Class<?> f = CalendarTransform.RFC2822DTZ.class;
- WriterSerializer s = new HtmlSerializer().addTransforms(f);
- ReaderParser p = new HtmlParser().addTransforms(f);
- doTest(s, p, true, "<string>Sun, 03 Mar 1901 18:11:12 GMT</string>");
- }
-
- //====================================================================================================
- // testRFC2822DTUrlParam - DEFAULT_RFC2822DT, UON
- //====================================================================================================
- @Test
- public void testRFC2822DTUon() throws Exception {
- Class<?> f = CalendarTransform.RFC2822DTZ.class;
- WriterSerializer s = new UonSerializer.Encoding().addTransforms(f);
- ReaderParser p = UonParser.DEFAULT_DECODING.clone().addTransforms(f);
- doTest(s, p, true, "Sun,+03+Mar+1901+18:11:12+GMT");
- }
-
- //====================================================================================================
- // testRFC2822DTUrlParam - DEFAULT_RFC2822DT, URL-ENCODING
- //====================================================================================================
- @Test
- public void testRFC2822DTUrlEncoding() throws Exception {
- Class<?> f = CalendarTransform.RFC2822DTZ.class;
- WriterSerializer s = new UrlEncodingSerializer().addTransforms(f);
- ReaderParser p = UrlEncodingParser.DEFAULT.clone().addTransforms(f);
- doTest(s, p, true, "_value=Sun,+03+Mar+1901+18:11:12+GMT");
- }
-
- //====================================================================================================
- // testRFC2822DTRdfXml - DEFAULT_RFC2822DT, RDF/XML
- //====================================================================================================
- @Test
- public void testRFC2822DTRdfXml() throws Exception {
- Class<?> f = CalendarTransform.RFC2822DTZ.class;
- WriterSerializer s = getRdfSerializer().addTransforms(f);
- ReaderParser p = new RdfParser.Xml().addTransforms(f);
- doTest(s, p, true, "<rdf:Description><j:value>Sun, 03 Mar 1901 18:11:12 GMT</j:value></rdf:Description>");
- }
-
- //====================================================================================================
- // testDefaultLongJson - DEFAULT_LONG, JSON
- //====================================================================================================
- @Test
- public void testDefaultLongJson() throws Exception {
- Class<?> f = CalendarLongTransform.class;
- WriterSerializer s = new JsonSerializer.Simple().addTransforms(f);
- ReaderParser p = new JsonParser().addTransforms(f);
- doTest(s, p, true, "-2172116928000");
- }
-
- //====================================================================================================
- // testDefaultLongXml - DEFAULT_LONG, XML
- //====================================================================================================
- @Test
- public void testDefaultLongXml() throws Exception {
- Class<?> f = CalendarLongTransform.class;
- WriterSerializer s = new XmlSerializer.SimpleSq().addTransforms(f);
- ReaderParser p = new XmlParser().addTransforms(f);
- doTest(s, p, true, "<number>-2172116928000</number>");
- }
-
- //====================================================================================================
- // testDefaultLongHtml - DEFAULT_LONG, HTML
- //====================================================================================================
- @Test
- public void testDefaultLongHtml() throws Exception {
- Class<?> f = CalendarLongTransform.class;
- WriterSerializer s = new HtmlSerializer().addTransforms(f);
- ReaderParser p = new HtmlParser().addTransforms(f);
- doTest(s, p, true, "<number>-2172116928000</number>");
- }
-
- //====================================================================================================
- // testDefaultLongUrlParam - DEFAULT_LONG, UON
- //====================================================================================================
- @Test
- public void testDefaultLongUon() throws Exception {
- Class<?> f = CalendarLongTransform.class;
- WriterSerializer s = UonSerializer.DEFAULT_SIMPLE.clone().addTransforms(f);
- ReaderParser p = new UonParser().addTransforms(f);
- doTest(s, p, true, "-2172116928000");
- }
-
- //====================================================================================================
- // testDefaultLongUrlParam - DEFAULT_LONG, URL-ENCODING
- //====================================================================================================
- @Test
- public void testDefaultLongUrlEncoding() throws Exception {
- Class<?> f = CalendarLongTransform.class;
- WriterSerializer s = UrlEncodingSerializer.DEFAULT_SIMPLE.clone().addTransforms(f);
- ReaderParser p = new UrlEncodingParser().addTransforms(f);
- doTest(s, p, true, "_value=-2172116928000");
- }
-
- //====================================================================================================
- // testDefaultLongRdfXml - DEFAULT_LONG, RDF/XML
- //====================================================================================================
- @Test
- public void testDefaultLongRdfXml() throws Exception {
- Class<?> f = CalendarLongTransform.class;
- WriterSerializer s = getRdfSerializer().addTransforms(f);
- ReaderParser p = new RdfParser.Xml().addTransforms(f);
- doTest(s, p, true, "<rdf:Description><j:value>-2172116928000</j:value></rdf:Description>");
- }
-
- //====================================================================================================
- // testDefaultMapJson - DEFAULT_MAP, JSON
- //====================================================================================================
- @Test
- public void testDefaultMapJson() throws Exception {
- Class<?> f = CalendarMapTransform.class;
- WriterSerializer s = new JsonSerializer.Simple().addTransforms(f);
- ReaderParser p = new JsonParser().addTransforms(f);
- doTest(s, p, true, "{time:-2172116928000,timeZone:'PST'}");
- }
-
- //====================================================================================================
- // testDefaultMapXml - DEFAULT_MAP, XML
- //====================================================================================================
- @Test
- public void testDefaultMapXml() throws Exception {
- Class<?> f = CalendarMapTransform.class;
- WriterSerializer s = new XmlSerializer.SimpleXmlJsonSq().addTransforms(f);
- ReaderParser p = new XmlParser().addTransforms(f);
- doTest(s, p, true, "<object><time type='number'>-2172116928000</time><timeZone>PST</timeZone></object>");
- }
-
- //====================================================================================================
- // testDefaultMapHtml - DEFAULT_MAP, HTML
- //====================================================================================================
- @Test
- public void testDefaultMapHtml() throws Exception {
- Class<?> f = CalendarMapTransform.class;
- WriterSerializer s = new HtmlSerializer.Sq().addTransforms(f);
- ReaderParser p = new HtmlParser().addTransforms(f);
- doTest(s, p, true, "<table type='object'><tr><th><string>key</string></th><th><string>value</string></th></tr><tr><td><string>time</string></td><td><number>-2172116928000</number></td></tr><tr><td><string>timeZone</string></td><td><string>PST</string></td></tr></table>");
- }
-
- //====================================================================================================
- // testDefaultMapUrlParam - DEFAULT_MAP, UON
- //====================================================================================================
- @Test
- public void testDefaultMapUon() throws Exception {
- Class<?> f = CalendarMapTransform.class;
- WriterSerializer s = UonSerializer.DEFAULT_SIMPLE.clone().addTransforms(f);
- ReaderParser p = new UonParser().addTransforms(f);
- doTest(s, p, true, "(time=-2172116928000,timeZone=PST)");
- }
-
- //====================================================================================================
- // testDefaultMapUrlParam - DEFAULT_MAP, URL-ENCODING
- //====================================================================================================
- @Test
- public void testDefaultMapUrlEncoding() throws Exception {
- Class<?> f = CalendarMapTransform.class;
- WriterSerializer s = UrlEncodingSerializer.DEFAULT_SIMPLE.clone().addTransforms(f);
- ReaderParser p = new UrlEncodingParser().addTransforms(f);
- doTest(s, p, true, "time=-2172116928000&timeZone=PST");
- }
-
- //====================================================================================================
- // testDefaultMapRdfXml - DEFAULT_MAP, RDF/XML
- //====================================================================================================
- @Test
- public void testDefaultMapRdfXml() throws Exception {
- Class<?> f = CalendarMapTransform.class;
- WriterSerializer s = getRdfSerializer().addTransforms(f);
- ReaderParser p = new RdfParser.Xml().addTransforms(f);
- doTest(s, p, true, "<rdf:Description><jp:time>-2172116928000</jp:time><jp:timeZone>PST</jp:timeZone></rdf:Description>");
- }
-
- //====================================================================================================
- // testDefaultMediumJson - DEFAULT_MEDIUM, JSON
- //====================================================================================================
- @Test
- public void testDefaultMediumJson() throws Exception {
- Class<?> f = CalendarTransform.Medium.class;
- WriterSerializer s = new JsonSerializer.Simple().addTransforms(f);
- ReaderParser p = new JsonParser().addTransforms(f);
- doTest(s, p, false, "'Mar 3, 1901'");
- }
-
- //====================================================================================================
- // testDefaultMediumXml - DEFAULT_MEDIUM, XML
- //====================================================================================================
- @Test
- public void testDefaultMediumXml() throws Exception {
- Class<?> f = CalendarTransform.Medium.class;
- WriterSerializer s = new XmlSerializer.SimpleSq().addTransforms(f);
- ReaderParser p = new XmlParser().addTransforms(f);
- doTest(s, p, false, "<string>Mar 3, 1901</string>");
- }
-
- //====================================================================================================
- // testDefaultMediumHtml - DEFAULT_MEDIUM, HTML
- //====================================================================================================
- @Test
- public void testDefaultMediumHtml() throws Exception {
- Class<?> f = CalendarTransform.Medium.class;
- WriterSerializer s = new HtmlSerializer().addTransforms(f);
- ReaderParser p = new HtmlParser().addTransforms(f);
- doTest(s, p, false, "<string>Mar 3, 1901</string>");
- }
-
- //====================================================================================================
- // testDefaultMediumUrlParam - DEFAULT_MEDIUM, UON
- //====================================================================================================
- @Test
- public void testDefaultMediumUon() throws Exception {
- Class<?> f = CalendarTransform.Medium.class;
- WriterSerializer s = new UonSerializer.Encoding().addTransforms(f);
- ReaderParser p = UonParser.DEFAULT_DECODING.clone().addTransforms(f);
- doTest(s, p, false, "Mar+3,+1901");
- }
-
- //====================================================================================================
- // testDefaultMediumUrlParam - DEFAULT_MEDIUM, URL-ENCODING
- //====================================================================================================
- @Test
- public void testDefaultMediumUrlEncoding() throws Exception {
- Class<?> f = CalendarTransform.Medium.class;
- WriterSerializer s = new UrlEncodingSerializer().addTransforms(f);
- ReaderParser p = UrlEncodingParser.DEFAULT.clone().addTransforms(f);
- doTest(s, p, false, "_value=Mar+3,+1901");
- }
-
- //====================================================================================================
- // testDefaultMediumRdfXml - DEFAULT_MEDIUM, RDF/XML
- //====================================================================================================
- @Test
- public void testDefaultMediumRdfXml() throws Exception {
- Class<?> f = CalendarTransform.Medium.class;
- WriterSerializer s = getRdfSerializer().addTransforms(f);
- ReaderParser p = new RdfParser.Xml().addTransforms(f);
- doTest(s, p, false, "<rdf:Description><j:value>Mar 3, 1901</j:value></rdf:Description>");
- }
-
- //====================================================================================================
- // Test 7a - BeanProperty.filter, JSON
- //====================================================================================================
- @Test
- public void testBeanProperyFilterJson() throws Exception {
- WriterSerializer s = JsonSerializer.DEFAULT_LAX;
- ReaderParser p = JsonParser.DEFAULT;
-
- Calendar c = testDate;
- A t = new A(c);
- String json = s.serialize(t);
- assertEquals("{d1:'1901-03-03T18:11:12Z',d2:'Sun, 03 Mar 1901 18:11:12 GMT',d3:-2172116928000}", json);
- t = p.parse(json, A.class);
- assertEquals(t.d1.getTime().getTime(), c.getTime().getTime());
- assertEquals(t.getD2().getTime().getTime(), c.getTime().getTime());
- assertEquals(t.getD3().getTime().getTime(), c.getTime().getTime());
- }
-
- //====================================================================================================
- // Test 7b - BeanProperty.filter, XML
- //====================================================================================================
- @Test
- public void testBeanProperyFilterXml() throws Exception {
- WriterSerializer s = XmlSerializer.DEFAULT_SIMPLE_SQ;
- ReaderParser p = XmlParser.DEFAULT;
-
- Calendar c = testDate;
- A t = new A(c);
- String xml = s.serialize(t);
- assertEquals("<object><d1>1901-03-03T18:11:12Z</d1><d2>Sun, 03 Mar 1901 18:11:12 GMT</d2><d3>-2172116928000</d3></object>", xml);
- t = p.parse(xml, A.class);
- assertEquals(t.d1.getTime().getTime(), c.getTime().getTime());
- assertEquals(t.getD2().getTime().getTime(), c.getTime().getTime());
- assertEquals(t.getD3().getTime().getTime(), c.getTime().getTime());
- }
-
- //====================================================================================================
- // Test 7c - BeanProperty.filter, HTML
- //====================================================================================================
- @Test
- public void testBeanProperyFilterHtml() throws Exception {
- WriterSerializer s = HtmlSerializer.DEFAULT_SQ;
- ReaderParser p = HtmlParser.DEFAULT;
-
- Calendar c = testDate;
- A t = new A(c);
- String html = s.serialize(t);
- assertEquals("<table type='object'><tr><th><string>key</string></th><th><string>value</string></th></tr><tr><td><string>d1</string></td><td><string>1901-03-03T18:11:12Z</string></td></tr><tr><td><string>d2</string></td><td><string>Sun, 03 Mar 1901 18:11:12 GMT</string></td></tr><tr><td><string>d3</string></td><td><number>-2172116928000</number></td></tr></table>", html);
- t = p.parse(html, A.class);
- assertEquals(t.d1.getTime().getTime(), c.getTime().getTime());
- assertEquals(t.getD2().getTime().getTime(), c.getTime().getTime());
- assertEquals(t.getD3().getTime().getTime(), c.getTime().getTime());
- }
-
- //====================================================================================================
- // Test 7d - BeanProperty.filter, UON
- //====================================================================================================
- @Test
- public void testBeanProperyFilterUon() throws Exception {
- WriterSerializer s = UonSerializer.DEFAULT_SIMPLE_ENCODING;
- ReaderParser p = UonParser.DEFAULT;
- ReaderParser pe = UonParser.DEFAULT_DECODING;
-
- Calendar c = testDate;
- A t = new A(c);
- String url = s.serialize(t);
- assertEquals("(d1=1901-03-03T18:11:12Z,d2=Sun~,+03+Mar+1901+18:11:12+GMT,d3=-2172116928000)", url);
- t = pe.parse(url, A.class);
- assertEquals(t.d1.getTime().getTime(), c.getTime().getTime());
- assertEquals(t.getD2().getTime().getTime(), c.getTime().getTime());
- assertEquals(t.getD3().getTime().getTime(), c.getTime().getTime());
- url = URLDecoder.decode(url, "UTF-8");
- t = p.parse(url, A.class);
- assertEquals(t.d1.getTime().getTime(), c.getTime().getTime());
- assertEquals(t.getD2().getTime().getTime(), c.getTime().getTime());
- assertEquals(t.getD3().getTime().getTime(), c.getTime().getTime());
- }
-
- //====================================================================================================
- // Test 7d - BeanProperty.filter, URL-ENCODING
- //====================================================================================================
- @Test
- public void testBeanProperyFilterUrlEncoding() throws Exception {
- WriterSerializer s = UrlEncodingSerializer.DEFAULT_SIMPLE;
- ReaderParser p = UrlEncodingParser.DEFAULT;
-
- Calendar c = testDate;
- A t = new A(c);
- String url = s.serialize(t);
- assertEquals("d1=1901-03-03T18:11:12Z&d2=Sun,+03+Mar+1901+18:11:12+GMT&d3=-2172116928000", url);
- t = p.parse(url, A.class);
- assertEquals(t.d1.getTime().getTime(), c.getTime().getTime());
- assertEquals(t.getD2().getTime().getTime(), c.getTime().getTime());
- assertEquals(t.getD3().getTime().getTime(), c.getTime().getTime());
- url = URLDecoder.decode(url, "UTF-8");
- t = p.parse(url, A.class);
- assertEquals(t.d1.getTime().getTime(), c.getTime().getTime());
- assertEquals(t.getD2().getTime().getTime(), c.getTime().getTime());
- assertEquals(t.getD3().getTime().getTime(), c.getTime().getTime());
- }
-
- //====================================================================================================
- // Test 7f - BeanProperty.filter, RDF/XML
- //====================================================================================================
- @Test
- public void testBeanProperyFilterRdfXmlWithNs() throws Exception {
- WriterSerializer s = getRdfSerializer();
-
- Calendar c = testDate;
- A t = new A(c);
- String rdf = stripRdf(s.serialize(t));
- assertEquals("<rdf:Description><jp:d1>1901-03-03T18:11:12Z</jp:d1><jp:d2>Sun, 03 Mar 1901 18:11:12 GMT</jp:d2><jp:d3>-2172116928000</jp:d3></rdf:Description>", rdf);
- }
-
- @Bean(sort=true)
- public static class A {
- @BeanProperty(transform=CalendarTransform.ISO8601DTZ.class)
- public Calendar d1;
- private Calendar d2, d3;
- public A(Calendar date) {
- d1 = d2 = d3 = date;
- }
-
- public A() {}
-
- @BeanProperty(transform=CalendarTransform.RFC2822DTZ.class)
- public Calendar getD2() {
- return d2;
- }
- public void setD2(Calendar d2) {
- this.d2 = d2;
- }
-
- public Calendar getD3() {
- return d3;
- }
- @BeanProperty(transform=CalendarLongTransform.class)
- public void setD3(Calendar d3) {
- this.d3 = d3;
- }
- }
-
- private void doTest(WriterSerializer s, ReaderParser p, boolean doTestTimeToo, String expected) throws Exception {
- Calendar d;
- String actual;
-
- SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy");
- sdf.setTimeZone(TimeZone.getTimeZone("PST"));
- actual = s.serialize(testDate);
- String a = (s instanceof RdfSerializer ? stripRdf(actual) : actual);
- assertEquals(expected, a);
- d = p.parse(actual, GregorianCalendar.class);
- d.setTimeZone(TimeZone.getTimeZone("PST"));
- assertEquals(1901, d.get(Calendar.YEAR));
- assertEquals(2, d.get(Calendar.MONTH));
-// assertEquals(3, d.get(Calendar.DATE));
- if (doTestTimeToo) {
- assertEquals(10, d.get(Calendar.HOUR));
- assertEquals(11, d.get(Calendar.MINUTE));
- assertEquals(12, d.get(Calendar.SECOND));
- }
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/transforms/CT_DateFilter.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/transforms/CT_DateFilter.java b/org.apache.juneau/src/test/java/org/apache/juneau/transforms/CT_DateFilter.java
deleted file mode 100755
index e516d7e..0000000
--- a/org.apache.juneau/src/test/java/org/apache/juneau/transforms/CT_DateFilter.java
+++ /dev/null
@@ -1,170 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.transforms;
-
-import static org.junit.Assert.*;
-
-import java.text.*;
-import java.util.*;
-
-import org.apache.juneau.*;
-import org.apache.juneau.json.*;
-import org.apache.juneau.parser.*;
-import org.apache.juneau.serializer.*;
-import org.junit.*;
-
-@SuppressWarnings("deprecation")
-public class CT_DateFilter {
-
- private static TimeZone tz;
-
- @BeforeClass
- public static void beforeClass() {
- tz = TimeZone.getDefault();
- TimeZone.setDefault(TimeZone.getTimeZone("GMT-5"));
- }
-
- @AfterClass
- public static void afterClass() {
- TimeZone.setDefault(tz);
- }
-
- private Date testDate = new Date(1, 2, 3, 4, 5, 6);
- private String tz1 = new SimpleDateFormat("zzz").format(testDate);
-
- //====================================================================================================
- // testString - DEFAULT_STRING
- //====================================================================================================
- @Test
- public void testString() throws Exception {
- Class<?> f = DateTransform.ToString.class;
- WriterSerializer s = new JsonSerializer.Simple().addTransforms(f);
- ReaderParser p = new JsonParser().addTransforms(f);
- doTest(s, p, "'Sun Mar 03 04:05:06 "+tz1+" 1901'");
- }
-
- //====================================================================================================
- // testISO8601DTZ - DEFAULT_ISO8601DTZ
- //====================================================================================================
- @Test
- public void testISO8601DTZ() throws Exception {
- Class<?> f = DateTransform.ISO8601DTZ.class;
- WriterSerializer s = new JsonSerializer.Simple().addTransforms(f);
- ReaderParser p = new JsonParser().addTransforms(f);
- doTest(s, p, "'1901-03-03T09:05:06Z'");
- }
-
- //====================================================================================================
- // testRFC2822DT - DEFAULT_RFC2822DT
- //====================================================================================================
- @Test
- public void testRFC2822DT() throws Exception {
- Class<?> f = DateTransform.RFC2822DT.class;
- WriterSerializer s = new JsonSerializer.Simple().addTransforms(f);
- ReaderParser p = new JsonParser().addTransforms(f);
- doTest(s, p, "'Sun, 03 Mar 1901 04:05:06 "+tz1+"'");
- }
-
- //====================================================================================================
- // testLong - DEFAULT_LONG
- //====================================================================================================
- @Test
- public void testLong() throws Exception {
- Class<?> f = DateLongTransform.class;
- WriterSerializer s = new JsonSerializer.Simple().addTransforms(f);
- ReaderParser p = new JsonParser().addTransforms(f);
- doTest(s, p, "-2172149694000");
- }
-
- //====================================================================================================
- // testMap - DEFAULT_MAP
- //====================================================================================================
- @Test
- public void testMap() throws Exception {
- Class<?> f = DateMapTransform.class;
- WriterSerializer s = new JsonSerializer.Simple().addTransforms(f);
- ReaderParser p = new JsonParser().addTransforms(f);
- doTest(s, p, "{time:-2172149694000}");
- }
-
- public void doTest(WriterSerializer s, ReaderParser p, String expected) throws Exception {
- Date d;
- String actual;
-
- d = testDate;
- actual = s.serialize(d);
- assertEquals(expected, actual);
- d = p.parse(actual, Date.class);
- assertEquals(1, d.getYear());
- assertEquals(2, d.getMonth());
- assertEquals(3, d.getDate());
- assertEquals(4, d.getHours());
- assertEquals(5, d.getMinutes());
- assertEquals(6, d.getSeconds());
-
- d = new java.sql.Date(testDate.getTime());
- actual = s.serialize(d);
- assertEquals(expected, actual);
- d = p.parse(actual, java.sql.Date.class);
- assertEquals(1, d.getYear());
- assertEquals(2, d.getMonth());
- assertEquals(3, d.getDate());
-
- d = new java.sql.Time(testDate.getTime());
- actual = s.serialize(d);
- assertEquals(expected, actual);
- d = p.parse(actual, java.sql.Time.class);
- assertEquals(4, d.getHours());
- assertEquals(5, d.getMinutes());
- assertEquals(6, d.getSeconds());
-
- d = new java.sql.Timestamp(testDate.getTime());
- actual = s.serialize(d);
- assertEquals(expected, actual);
- d = p.parse(actual, java.sql.Timestamp.class);
- assertEquals(1, d.getYear());
- assertEquals(2, d.getMonth());
- assertEquals(3, d.getDate());
- assertEquals(4, d.getHours());
- assertEquals(5, d.getMinutes());
- assertEquals(6, d.getSeconds());
- }
-
- //====================================================================================================
- //====================================================================================================
- @Test
- public void testBeanWithDate() throws Exception {
- A testBeanA = new A().init();
-
- final String jsonData = new JsonSerializer().addTransforms(
- DateTransform.ISO8601DT.class).serialize(testBeanA);
- final ObjectMap data = new JsonParser().addTransforms(
- DateTransform.ISO8601DT.class).parse(jsonData, ObjectMap.class);
-
- final DateTransform.ISO8601DT dateTransform = new DateTransform.ISO8601DT();
- // this works
- final String sValue = data.getString("birthday"); //$NON-NLS-1$
- dateTransform.normalize(sValue, data.getBeanContext().getClassMeta(Date.class));
- // this does not work
- data.get(dateTransform, "birthday"); //$NON-NLS-1$
- }
-
- public static class A {
- public Date birthday;
-
- public A init() {
- birthday = new Date();
- return this;
- }
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/transforms/CT_EnumerationTransform.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/transforms/CT_EnumerationTransform.java b/org.apache.juneau/src/test/java/org/apache/juneau/transforms/CT_EnumerationTransform.java
deleted file mode 100755
index b5845b2..0000000
--- a/org.apache.juneau/src/test/java/org/apache/juneau/transforms/CT_EnumerationTransform.java
+++ /dev/null
@@ -1,35 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.transforms;
-
-import static org.junit.Assert.*;
-
-import java.util.*;
-
-import org.apache.juneau.json.*;
-import org.apache.juneau.serializer.*;
-import org.junit.*;
-
-public class CT_EnumerationTransform {
-
- //====================================================================================================
- // test
- //====================================================================================================
- @Test
- public void test() throws Exception {
- WriterSerializer s = new JsonSerializer.Simple().addTransforms(EnumerationTransform.class);
- Vector<String> v = new Vector<String>(Arrays.asList(new String[]{"foo","bar","baz"}));
- Enumeration<String> e = v.elements();
- assertEquals("['foo','bar','baz']", s.serialize(e));
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/transforms/CT_IteratorTransform.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/transforms/CT_IteratorTransform.java b/org.apache.juneau/src/test/java/org/apache/juneau/transforms/CT_IteratorTransform.java
deleted file mode 100755
index 2ad4ac1..0000000
--- a/org.apache.juneau/src/test/java/org/apache/juneau/transforms/CT_IteratorTransform.java
+++ /dev/null
@@ -1,37 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.transforms;
-
-import static org.junit.Assert.*;
-
-import java.util.*;
-
-import org.apache.juneau.json.*;
-import org.apache.juneau.serializer.*;
-import org.junit.*;
-
-public class CT_IteratorTransform {
-
- //====================================================================================================
- // test
- //====================================================================================================
- @Test
- public void test() throws Exception {
- WriterSerializer s = new JsonSerializer.Simple().addTransforms(IteratorTransform.class);
-
- // Iterators
- List<String> l = new ArrayList<String>(Arrays.asList(new String[]{"foo","bar","baz"}));
- Iterator<String> i = l.iterator();
- assertEquals("['foo','bar','baz']", s.serialize(i));
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/transforms/CT_ReaderFilter.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/transforms/CT_ReaderFilter.java b/org.apache.juneau/src/test/java/org/apache/juneau/transforms/CT_ReaderFilter.java
deleted file mode 100755
index 6c19252..0000000
--- a/org.apache.juneau/src/test/java/org/apache/juneau/transforms/CT_ReaderFilter.java
+++ /dev/null
@@ -1,47 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.transforms;
-
-import static org.junit.Assert.*;
-
-import java.io.*;
-import java.util.*;
-
-import org.apache.juneau.json.*;
-import org.apache.juneau.serializer.*;
-import org.junit.*;
-
-public class CT_ReaderFilter {
-
- //====================================================================================================
- // test
- //====================================================================================================
- @Test
- public void test() throws Exception {
- WriterSerializer s = new JsonSerializer.Simple().addTransforms(ReaderTransform.Json.class);
-
- Reader r;
- Map<String,Object> m;
-
- r = new StringReader("{foo:'bar',baz:'quz'}");
- m = new HashMap<String,Object>();
- m.put("X", r);
- assertEquals("{X:{foo:'bar',baz:'quz'}}", s.serialize(m));
-
- s.addTransforms(ReaderTransform.Xml.class);
- r = new StringReader("<object><foo type='string'>bar</foo><baz type='string'>quz</baz></object>");
- m = new HashMap<String,Object>();
- m.put("X", r);
- assertEquals("{X:{foo:'bar',baz:'quz'}}", s.serialize(m));
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/transforms/CalendarTransformTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/transforms/CalendarTransformTest.java b/org.apache.juneau/src/test/java/org/apache/juneau/transforms/CalendarTransformTest.java
new file mode 100755
index 0000000..8580b9e
--- /dev/null
+++ b/org.apache.juneau/src/test/java/org/apache/juneau/transforms/CalendarTransformTest.java
@@ -0,0 +1,696 @@
+/***************************************************************************************************************************
+ * 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.juneau.transforms;
+
+import static org.apache.juneau.jena.RdfCommonContext.*;
+import static org.apache.juneau.serializer.SerializerContext.*;
+import static org.junit.Assert.*;
+
+import java.net.*;
+import java.text.*;
+import java.util.*;
+
+import javax.xml.bind.*;
+
+import org.apache.juneau.annotation.*;
+import org.apache.juneau.html.*;
+import org.apache.juneau.jena.*;
+import org.apache.juneau.json.*;
+import org.apache.juneau.parser.*;
+import org.apache.juneau.serializer.*;
+import org.apache.juneau.transform.*;
+import org.apache.juneau.urlencoding.*;
+import org.apache.juneau.xml.*;
+import org.junit.*;
+
+public class CalendarTransformTest {
+
+ private static Calendar testDate = new GregorianCalendar(TimeZone.getTimeZone("PST"));
+ static {
+ testDate.setTimeInMillis(0);
+ testDate.set(1901, 2, 3, 10, 11, 12);
+ }
+
+ private RdfSerializer getRdfSerializer() {
+ return new RdfSerializer()
+ .setProperty(SERIALIZER_quoteChar, '\'')
+ .setProperty(SERIALIZER_useIndentation, false)
+ .setProperty(RDF_rdfxml_allowBadUris, true)
+ .setProperty(RDF_rdfxml_showDoctypeDeclaration, false)
+ .setProperty(RDF_rdfxml_showXmlDeclaration, false);
+ }
+
+ private String stripRdf(String s) {
+ return s.replaceFirst("<rdf:RDF[^>]+>\\s*", "").replaceAll("</rdf:RDF>$", "").trim().replaceAll("[\\r\\n]", "");
+ }
+
+ //====================================================================================================
+ // testTimezone - Make sure timezone on calendar is preserved.
+ //====================================================================================================
+ @Test
+ public void testTimezone() throws Exception {
+ PojoTransform<Calendar,String> f;
+ String s;
+ Calendar c;
+
+ //--------------------
+ // ISO8601DT
+ //--------------------
+ f = new CalendarTransform.ISO8601DT();
+
+ s = "2001-01-31T12:34:56Z";
+ c = DatatypeConverter.parseDateTime(s);
+ assertEquals(s, f.transform(c));
+
+ s = "2001-01-31T09:34:56-03:00";
+ c = DatatypeConverter.parseDateTime(s);
+ assertEquals(s, f.transform(c));
+
+ s = "2001-01-31T06:34:56-06:00";
+ c = DatatypeConverter.parseDateTime(s);
+ assertEquals(s, f.transform(c));
+
+
+ //--------------------
+ // ISO8601DTZ
+ //--------------------
+ f = new CalendarTransform.ISO8601DTZ();
+
+ s = "2001-01-31T12:34:56Z";
+ c = DatatypeConverter.parseDateTime(s);
+ assertEquals(s, f.transform(c));
+
+ s = "2001-01-31T09:34:56-03:00";
+ c = DatatypeConverter.parseDateTime(s);
+ assertEquals("2001-01-31T12:34:56Z", f.transform(c));
+
+ s = "2001-01-31T06:34:56-06:00";
+ c = DatatypeConverter.parseDateTime(s);
+ assertEquals("2001-01-31T12:34:56Z", f.transform(c));
+
+ //--------------------
+ // RFC2822DTZ
+ //--------------------
+ f = new CalendarTransform.RFC2822DT();
+
+ s = "2001-01-31T12:34:56Z";
+ c = DatatypeConverter.parseDateTime(s);
+ assertEquals("Wed, 31 Jan 2001 12:34:56 +0000", f.transform(c));
+
+ s = "2001-01-31T09:34:56-03:00";
+ c = DatatypeConverter.parseDateTime(s);
+ assertEquals("Wed, 31 Jan 2001 09:34:56 -0300", f.transform(c));
+
+ s = "2001-01-31T06:34:56-06:00";
+ c = DatatypeConverter.parseDateTime(s);
+ assertEquals("Wed, 31 Jan 2001 06:34:56 -0600", f.transform(c));
+
+ //--------------------
+ // RFC2822DTZ
+ //--------------------
+ f = new CalendarTransform.RFC2822DTZ();
+
+ s = "2001-01-31T12:34:56Z";
+ c = DatatypeConverter.parseDateTime(s);
+ assertEquals("Wed, 31 Jan 2001 12:34:56 GMT", f.transform(c));
+
+ s = "2001-01-31T09:34:56-03:00";
+ c = DatatypeConverter.parseDateTime(s);
+ assertEquals("Wed, 31 Jan 2001 12:34:56 GMT", f.transform(c));
+
+ s = "2001-01-31T06:34:56-06:00";
+ c = DatatypeConverter.parseDateTime(s);
+ assertEquals("Wed, 31 Jan 2001 12:34:56 GMT", f.transform(c));
+ }
+
+
+ //====================================================================================================
+ // testDefaultStringJson - DEFAULT_STRING, JSON
+ //====================================================================================================
+ @Test
+ public void testDefaultStringJson() throws Exception {
+ Class<?> f = CalendarTransform.ToString.class;
+ WriterSerializer s = new JsonSerializer.Simple().addTransforms(f);
+ ReaderParser p = new JsonParser().addTransforms(f);
+ doTest(s, p, true, "'Sun Mar 03 10:11:12 PST 1901'");
+ }
+
+ //====================================================================================================
+ // testDefaultStringXml - DEFAULT_STRING, XML
+ //====================================================================================================
+ @Test
+ public void testDefaultStringXml() throws Exception {
+ Class<?> f = CalendarTransform.ToString.class;
+ WriterSerializer s = new XmlSerializer.SimpleSq().addTransforms(f);
+ ReaderParser p = new XmlParser().addTransforms(f);
+ doTest(s, p, true, "<string>Sun Mar 03 10:11:12 PST 1901</string>");
+ }
+
+ //====================================================================================================
+ // testDefaultStringHtml - DEFAULT_STRING, HTML
+ //====================================================================================================
+ @Test
+ public void testDefaultStringHtml() throws Exception {
+ Class<?> f = CalendarTransform.ToString.class;
+ WriterSerializer s = new HtmlSerializer().addTransforms(f);
+ ReaderParser p = new HtmlParser().addTransforms(f);
+ doTest(s, p, true, "<string>Sun Mar 03 10:11:12 PST 1901</string>");
+ }
+
+ //====================================================================================================
+ // testDefaultStringUrlParam - DEFAULT_STRING, UON
+ //====================================================================================================
+ @Test
+ public void testDefaultStringUon() throws Exception {
+ Class<?> f = CalendarTransform.ToString.class;
+ WriterSerializer s = new UonSerializer.Encoding().addTransforms(f);
+ ReaderParser p = UonParser.DEFAULT_DECODING.clone().addTransforms(f);
+ doTest(s, p, true, "Sun+Mar+03+10:11:12+PST+1901");
+ }
+
+ //====================================================================================================
+ // testDefaultStringUrlParam - DEFAULT_STRING, URL-ENCODING
+ //====================================================================================================
+ @Test
+ public void testDefaultStringUrlEncoding() throws Exception {
+ Class<?> f = CalendarTransform.ToString.class;
+ WriterSerializer s = new UrlEncodingSerializer().addTransforms(f);
+ ReaderParser p = UrlEncodingParser.DEFAULT.clone().addTransforms(f);
+ doTest(s, p, true, "_value=Sun+Mar+03+10:11:12+PST+1901");
+ }
+
+ //====================================================================================================
+ // testDefaultStringRdfXml - DEFAULT_STRING, RDF/XML
+ //====================================================================================================
+ @Test
+ public void testDefaultStringRdfXml() throws Exception {
+ Class<?> f = CalendarTransform.ToString.class;
+ WriterSerializer s = getRdfSerializer().addTransforms(f);
+ ReaderParser p = new RdfParser.Xml().addTransforms(f);
+ doTest(s, p, true, "<rdf:Description><j:value>Sun Mar 03 10:11:12 PST 1901</j:value></rdf:Description>");
+ }
+
+ //====================================================================================================
+ // testISO8601DTJson - DEFAULT_ISO8601DT, JSON
+ //====================================================================================================
+ @Test
+ public void testISO8601DTJson() throws Exception {
+ Class<?> f = CalendarTransform.ISO8601DT.class;
+ WriterSerializer s = new JsonSerializer.Simple().addTransforms(f);
+ ReaderParser p = new JsonParser().addTransforms(f);
+ String x = "'1901-03-03T10:11:12-08:00'";
+ doTest(s, p, true, x);
+ }
+
+ //====================================================================================================
+ // testISO8601DTXml - DEFAULT_ISO8601DT, XML
+ //====================================================================================================
+ @Test
+ public void testISO8601DTXml() throws Exception {
+ Class<?> f = CalendarTransform.ISO8601DT.class;
+ WriterSerializer s = new XmlSerializer.SimpleSq().addTransforms(f);
+ ReaderParser p = new XmlParser().addTransforms(f);
+ doTest(s, p, true, "<string>1901-03-03T10:11:12-08:00</string>");
+ }
+
+ //====================================================================================================
+ // testISO8601DTHtml - DEFAULT_ISO8601DT, HTML
+ //====================================================================================================
+ @Test
+ public void testISO8601DTHtml() throws Exception {
+ Class<?> f = CalendarTransform.ISO8601DT.class;
+ WriterSerializer s = new HtmlSerializer().addTransforms(f);
+ ReaderParser p = new HtmlParser().addTransforms(f);
+ doTest(s, p, true, "<string>1901-03-03T10:11:12-08:00</string>");
+ }
+
+ //====================================================================================================
+ // testISO8601DTUrlParam - DEFAULT_ISO8601DT, UON
+ //====================================================================================================
+ @Test
+ public void testISO8601DTUon() throws Exception {
+ Class<?> f = CalendarTransform.ISO8601DT.class;
+ WriterSerializer s = new UonSerializer().addTransforms(f);
+ ReaderParser p = new UonParser().addTransforms(f);
+ doTest(s, p, true, "1901-03-03T10:11:12-08:00");
+ }
+
+ //====================================================================================================
+ // testISO8601DTUrlParam - DEFAULT_ISO8601DT, URL-ENCODING
+ //====================================================================================================
+ @Test
+ public void testISO8601DTUrlEncoding() throws Exception {
+ Class<?> f = CalendarTransform.ISO8601DT.class;
+ WriterSerializer s = new UrlEncodingSerializer().addTransforms(f);
+ ReaderParser p = new UrlEncodingParser().addTransforms(f);
+ doTest(s, p, true, "_value=1901-03-03T10:11:12-08:00");
+ }
+
+ //====================================================================================================
+ // testISO8601DTRdfXml - DEFAULT_ISO8601DT, RDF/XML
+ //====================================================================================================
+ @Test
+ public void testISO8601DTRdfXml() throws Exception {
+ Class<?> f = CalendarTransform.ISO8601DT.class;
+ WriterSerializer s = getRdfSerializer().addTransforms(f);
+ ReaderParser p = new RdfParser.Xml().addTransforms(f);
+ doTest(s, p, true, "<rdf:Description><j:value>1901-03-03T10:11:12-08:00</j:value></rdf:Description>");
+ }
+
+ //====================================================================================================
+ // testRFC2822DTJson - DEFAULT_RFC2822DT, JSON
+ //====================================================================================================
+ @Test
+ public void testRFC2822DTJson() throws Exception {
+ Class<?> f = CalendarTransform.RFC2822DTZ.class;
+ WriterSerializer s = new JsonSerializer.Simple().addTransforms(f);
+ ReaderParser p = new JsonParser().addTransforms(f);
+ doTest(s, p, true, "'Sun, 03 Mar 1901 18:11:12 GMT'");
+ }
+
+ //====================================================================================================
+ // testRFC2822DTXml - DEFAULT_RFC2822DT, XML
+ //====================================================================================================
+ @Test
+ public void testRFC2822DTXml() throws Exception {
+ Class<?> f = CalendarTransform.RFC2822DTZ.class;
+ WriterSerializer s = new XmlSerializer.SimpleSq().addTransforms(f);
+ ReaderParser p = new XmlParser().addTransforms(f);
+ doTest(s, p, true, "<string>Sun, 03 Mar 1901 18:11:12 GMT</string>");
+ }
+
+ //====================================================================================================
+ // testRFC2822DTHtml - DEFAULT_RFC2822DT, HTML
+ //====================================================================================================
+ @Test
+ public void testRFC2822DTHtml() throws Exception {
+ Class<?> f = CalendarTransform.RFC2822DTZ.class;
+ WriterSerializer s = new HtmlSerializer().addTransforms(f);
+ ReaderParser p = new HtmlParser().addTransforms(f);
+ doTest(s, p, true, "<string>Sun, 03 Mar 1901 18:11:12 GMT</string>");
+ }
+
+ //====================================================================================================
+ // testRFC2822DTUrlParam - DEFAULT_RFC2822DT, UON
+ //====================================================================================================
+ @Test
+ public void testRFC2822DTUon() throws Exception {
+ Class<?> f = CalendarTransform.RFC2822DTZ.class;
+ WriterSerializer s = new UonSerializer.Encoding().addTransforms(f);
+ ReaderParser p = UonParser.DEFAULT_DECODING.clone().addTransforms(f);
+ doTest(s, p, true, "Sun,+03+Mar+1901+18:11:12+GMT");
+ }
+
+ //====================================================================================================
+ // testRFC2822DTUrlParam - DEFAULT_RFC2822DT, URL-ENCODING
+ //====================================================================================================
+ @Test
+ public void testRFC2822DTUrlEncoding() throws Exception {
+ Class<?> f = CalendarTransform.RFC2822DTZ.class;
+ WriterSerializer s = new UrlEncodingSerializer().addTransforms(f);
+ ReaderParser p = UrlEncodingParser.DEFAULT.clone().addTransforms(f);
+ doTest(s, p, true, "_value=Sun,+03+Mar+1901+18:11:12+GMT");
+ }
+
+ //====================================================================================================
+ // testRFC2822DTRdfXml - DEFAULT_RFC2822DT, RDF/XML
+ //====================================================================================================
+ @Test
+ public void testRFC2822DTRdfXml() throws Exception {
+ Class<?> f = CalendarTransform.RFC2822DTZ.class;
+ WriterSerializer s = getRdfSerializer().addTransforms(f);
+ ReaderParser p = new RdfParser.Xml().addTransforms(f);
+ doTest(s, p, true, "<rdf:Description><j:value>Sun, 03 Mar 1901 18:11:12 GMT</j:value></rdf:Description>");
+ }
+
+ //====================================================================================================
+ // testDefaultLongJson - DEFAULT_LONG, JSON
+ //====================================================================================================
+ @Test
+ public void testDefaultLongJson() throws Exception {
+ Class<?> f = CalendarLongTransform.class;
+ WriterSerializer s = new JsonSerializer.Simple().addTransforms(f);
+ ReaderParser p = new JsonParser().addTransforms(f);
+ doTest(s, p, true, "-2172116928000");
+ }
+
+ //====================================================================================================
+ // testDefaultLongXml - DEFAULT_LONG, XML
+ //====================================================================================================
+ @Test
+ public void testDefaultLongXml() throws Exception {
+ Class<?> f = CalendarLongTransform.class;
+ WriterSerializer s = new XmlSerializer.SimpleSq().addTransforms(f);
+ ReaderParser p = new XmlParser().addTransforms(f);
+ doTest(s, p, true, "<number>-2172116928000</number>");
+ }
+
+ //====================================================================================================
+ // testDefaultLongHtml - DEFAULT_LONG, HTML
+ //====================================================================================================
+ @Test
+ public void testDefaultLongHtml() throws Exception {
+ Class<?> f = CalendarLongTransform.class;
+ WriterSerializer s = new HtmlSerializer().addTransforms(f);
+ ReaderParser p = new HtmlParser().addTransforms(f);
+ doTest(s, p, true, "<number>-2172116928000</number>");
+ }
+
+ //====================================================================================================
+ // testDefaultLongUrlParam - DEFAULT_LONG, UON
+ //====================================================================================================
+ @Test
+ public void testDefaultLongUon() throws Exception {
+ Class<?> f = CalendarLongTransform.class;
+ WriterSerializer s = UonSerializer.DEFAULT_SIMPLE.clone().addTransforms(f);
+ ReaderParser p = new UonParser().addTransforms(f);
+ doTest(s, p, true, "-2172116928000");
+ }
+
+ //====================================================================================================
+ // testDefaultLongUrlParam - DEFAULT_LONG, URL-ENCODING
+ //====================================================================================================
+ @Test
+ public void testDefaultLongUrlEncoding() throws Exception {
+ Class<?> f = CalendarLongTransform.class;
+ WriterSerializer s = UrlEncodingSerializer.DEFAULT_SIMPLE.clone().addTransforms(f);
+ ReaderParser p = new UrlEncodingParser().addTransforms(f);
+ doTest(s, p, true, "_value=-2172116928000");
+ }
+
+ //====================================================================================================
+ // testDefaultLongRdfXml - DEFAULT_LONG, RDF/XML
+ //====================================================================================================
+ @Test
+ public void testDefaultLongRdfXml() throws Exception {
+ Class<?> f = CalendarLongTransform.class;
+ WriterSerializer s = getRdfSerializer().addTransforms(f);
+ ReaderParser p = new RdfParser.Xml().addTransforms(f);
+ doTest(s, p, true, "<rdf:Description><j:value>-2172116928000</j:value></rdf:Description>");
+ }
+
+ //====================================================================================================
+ // testDefaultMapJson - DEFAULT_MAP, JSON
+ //====================================================================================================
+ @Test
+ public void testDefaultMapJson() throws Exception {
+ Class<?> f = CalendarMapTransform.class;
+ WriterSerializer s = new JsonSerializer.Simple().addTransforms(f);
+ ReaderParser p = new JsonParser().addTransforms(f);
+ doTest(s, p, true, "{time:-2172116928000,timeZone:'PST'}");
+ }
+
+ //====================================================================================================
+ // testDefaultMapXml - DEFAULT_MAP, XML
+ //====================================================================================================
+ @Test
+ public void testDefaultMapXml() throws Exception {
+ Class<?> f = CalendarMapTransform.class;
+ WriterSerializer s = new XmlSerializer.SimpleXmlJsonSq().addTransforms(f);
+ ReaderParser p = new XmlParser().addTransforms(f);
+ doTest(s, p, true, "<object><time type='number'>-2172116928000</time><timeZone>PST</timeZone></object>");
+ }
+
+ //====================================================================================================
+ // testDefaultMapHtml - DEFAULT_MAP, HTML
+ //====================================================================================================
+ @Test
+ public void testDefaultMapHtml() throws Exception {
+ Class<?> f = CalendarMapTransform.class;
+ WriterSerializer s = new HtmlSerializer.Sq().addTransforms(f);
+ ReaderParser p = new HtmlParser().addTransforms(f);
+ doTest(s, p, true, "<table type='object'><tr><th><string>key</string></th><th><string>value</string></th></tr><tr><td><string>time</string></td><td><number>-2172116928000</number></td></tr><tr><td><string>timeZone</string></td><td><string>PST</string></td></tr></table>");
+ }
+
+ //====================================================================================================
+ // testDefaultMapUrlParam - DEFAULT_MAP, UON
+ //====================================================================================================
+ @Test
+ public void testDefaultMapUon() throws Exception {
+ Class<?> f = CalendarMapTransform.class;
+ WriterSerializer s = UonSerializer.DEFAULT_SIMPLE.clone().addTransforms(f);
+ ReaderParser p = new UonParser().addTransforms(f);
+ doTest(s, p, true, "(time=-2172116928000,timeZone=PST)");
+ }
+
+ //====================================================================================================
+ // testDefaultMapUrlParam - DEFAULT_MAP, URL-ENCODING
+ //====================================================================================================
+ @Test
+ public void testDefaultMapUrlEncoding() throws Exception {
+ Class<?> f = CalendarMapTransform.class;
+ WriterSerializer s = UrlEncodingSerializer.DEFAULT_SIMPLE.clone().addTransforms(f);
+ ReaderParser p = new UrlEncodingParser().addTransforms(f);
+ doTest(s, p, true, "time=-2172116928000&timeZone=PST");
+ }
+
+ //====================================================================================================
+ // testDefaultMapRdfXml - DEFAULT_MAP, RDF/XML
+ //====================================================================================================
+ @Test
+ public void testDefaultMapRdfXml() throws Exception {
+ Class<?> f = CalendarMapTransform.class;
+ WriterSerializer s = getRdfSerializer().addTransforms(f);
+ ReaderParser p = new RdfParser.Xml().addTransforms(f);
+ doTest(s, p, true, "<rdf:Description><jp:time>-2172116928000</jp:time><jp:timeZone>PST</jp:timeZone></rdf:Description>");
+ }
+
+ //====================================================================================================
+ // testDefaultMediumJson - DEFAULT_MEDIUM, JSON
+ //====================================================================================================
+ @Test
+ public void testDefaultMediumJson() throws Exception {
+ Class<?> f = CalendarTransform.Medium.class;
+ WriterSerializer s = new JsonSerializer.Simple().addTransforms(f);
+ ReaderParser p = new JsonParser().addTransforms(f);
+ doTest(s, p, false, "'Mar 3, 1901'");
+ }
+
+ //====================================================================================================
+ // testDefaultMediumXml - DEFAULT_MEDIUM, XML
+ //====================================================================================================
+ @Test
+ public void testDefaultMediumXml() throws Exception {
+ Class<?> f = CalendarTransform.Medium.class;
+ WriterSerializer s = new XmlSerializer.SimpleSq().addTransforms(f);
+ ReaderParser p = new XmlParser().addTransforms(f);
+ doTest(s, p, false, "<string>Mar 3, 1901</string>");
+ }
+
+ //====================================================================================================
+ // testDefaultMediumHtml - DEFAULT_MEDIUM, HTML
+ //====================================================================================================
+ @Test
+ public void testDefaultMediumHtml() throws Exception {
+ Class<?> f = CalendarTransform.Medium.class;
+ WriterSerializer s = new HtmlSerializer().addTransforms(f);
+ ReaderParser p = new HtmlParser().addTransforms(f);
+ doTest(s, p, false, "<string>Mar 3, 1901</string>");
+ }
+
+ //====================================================================================================
+ // testDefaultMediumUrlParam - DEFAULT_MEDIUM, UON
+ //====================================================================================================
+ @Test
+ public void testDefaultMediumUon() throws Exception {
+ Class<?> f = CalendarTransform.Medium.class;
+ WriterSerializer s = new UonSerializer.Encoding().addTransforms(f);
+ ReaderParser p = UonParser.DEFAULT_DECODING.clone().addTransforms(f);
+ doTest(s, p, false, "Mar+3,+1901");
+ }
+
+ //====================================================================================================
+ // testDefaultMediumUrlParam - DEFAULT_MEDIUM, URL-ENCODING
+ //====================================================================================================
+ @Test
+ public void testDefaultMediumUrlEncoding() throws Exception {
+ Class<?> f = CalendarTransform.Medium.class;
+ WriterSerializer s = new UrlEncodingSerializer().addTransforms(f);
+ ReaderParser p = UrlEncodingParser.DEFAULT.clone().addTransforms(f);
+ doTest(s, p, false, "_value=Mar+3,+1901");
+ }
+
+ //====================================================================================================
+ // testDefaultMediumRdfXml - DEFAULT_MEDIUM, RDF/XML
+ //====================================================================================================
+ @Test
+ public void testDefaultMediumRdfXml() throws Exception {
+ Class<?> f = CalendarTransform.Medium.class;
+ WriterSerializer s = getRdfSerializer().addTransforms(f);
+ ReaderParser p = new RdfParser.Xml().addTransforms(f);
+ doTest(s, p, false, "<rdf:Description><j:value>Mar 3, 1901</j:value></rdf:Description>");
+ }
+
+ //====================================================================================================
+ // Test 7a - BeanProperty.filter, JSON
+ //====================================================================================================
+ @Test
+ public void testBeanProperyFilterJson() throws Exception {
+ WriterSerializer s = JsonSerializer.DEFAULT_LAX;
+ ReaderParser p = JsonParser.DEFAULT;
+
+ Calendar c = testDate;
+ A t = new A(c);
+ String json = s.serialize(t);
+ assertEquals("{d1:'1901-03-03T18:11:12Z',d2:'Sun, 03 Mar 1901 18:11:12 GMT',d3:-2172116928000}", json);
+ t = p.parse(json, A.class);
+ assertEquals(t.d1.getTime().getTime(), c.getTime().getTime());
+ assertEquals(t.getD2().getTime().getTime(), c.getTime().getTime());
+ assertEquals(t.getD3().getTime().getTime(), c.getTime().getTime());
+ }
+
+ //====================================================================================================
+ // Test 7b - BeanProperty.filter, XML
+ //====================================================================================================
+ @Test
+ public void testBeanProperyFilterXml() throws Exception {
+ WriterSerializer s = XmlSerializer.DEFAULT_SIMPLE_SQ;
+ ReaderParser p = XmlParser.DEFAULT;
+
+ Calendar c = testDate;
+ A t = new A(c);
+ String xml = s.serialize(t);
+ assertEquals("<object><d1>1901-03-03T18:11:12Z</d1><d2>Sun, 03 Mar 1901 18:11:12 GMT</d2><d3>-2172116928000</d3></object>", xml);
+ t = p.parse(xml, A.class);
+ assertEquals(t.d1.getTime().getTime(), c.getTime().getTime());
+ assertEquals(t.getD2().getTime().getTime(), c.getTime().getTime());
+ assertEquals(t.getD3().getTime().getTime(), c.getTime().getTime());
+ }
+
+ //====================================================================================================
+ // Test 7c - BeanProperty.filter, HTML
+ //====================================================================================================
+ @Test
+ public void testBeanProperyFilterHtml() throws Exception {
+ WriterSerializer s = HtmlSerializer.DEFAULT_SQ;
+ ReaderParser p = HtmlParser.DEFAULT;
+
+ Calendar c = testDate;
+ A t = new A(c);
+ String html = s.serialize(t);
+ assertEquals("<table type='object'><tr><th><string>key</string></th><th><string>value</string></th></tr><tr><td><string>d1</string></td><td><string>1901-03-03T18:11:12Z</string></td></tr><tr><td><string>d2</string></td><td><string>Sun, 03 Mar 1901 18:11:12 GMT</string></td></tr><tr><td><string>d3</string></td><td><number>-2172116928000</number></td></tr></table>", html);
+ t = p.parse(html, A.class);
+ assertEquals(t.d1.getTime().getTime(), c.getTime().getTime());
+ assertEquals(t.getD2().getTime().getTime(), c.getTime().getTime());
+ assertEquals(t.getD3().getTime().getTime(), c.getTime().getTime());
+ }
+
+ //====================================================================================================
+ // Test 7d - BeanProperty.filter, UON
+ //====================================================================================================
+ @Test
+ public void testBeanProperyFilterUon() throws Exception {
+ WriterSerializer s = UonSerializer.DEFAULT_SIMPLE_ENCODING;
+ ReaderParser p = UonParser.DEFAULT;
+ ReaderParser pe = UonParser.DEFAULT_DECODING;
+
+ Calendar c = testDate;
+ A t = new A(c);
+ String url = s.serialize(t);
+ assertEquals("(d1=1901-03-03T18:11:12Z,d2=Sun~,+03+Mar+1901+18:11:12+GMT,d3=-2172116928000)", url);
+ t = pe.parse(url, A.class);
+ assertEquals(t.d1.getTime().getTime(), c.getTime().getTime());
+ assertEquals(t.getD2().getTime().getTime(), c.getTime().getTime());
+ assertEquals(t.getD3().getTime().getTime(), c.getTime().getTime());
+ url = URLDecoder.decode(url, "UTF-8");
+ t = p.parse(url, A.class);
+ assertEquals(t.d1.getTime().getTime(), c.getTime().getTime());
+ assertEquals(t.getD2().getTime().getTime(), c.getTime().getTime());
+ assertEquals(t.getD3().getTime().getTime(), c.getTime().getTime());
+ }
+
+ //====================================================================================================
+ // Test 7d - BeanProperty.filter, URL-ENCODING
+ //====================================================================================================
+ @Test
+ public void testBeanProperyFilterUrlEncoding() throws Exception {
+ WriterSerializer s = UrlEncodingSerializer.DEFAULT_SIMPLE;
+ ReaderParser p = UrlEncodingParser.DEFAULT;
+
+ Calendar c = testDate;
+ A t = new A(c);
+ String url = s.serialize(t);
+ assertEquals("d1=1901-03-03T18:11:12Z&d2=Sun,+03+Mar+1901+18:11:12+GMT&d3=-2172116928000", url);
+ t = p.parse(url, A.class);
+ assertEquals(t.d1.getTime().getTime(), c.getTime().getTime());
+ assertEquals(t.getD2().getTime().getTime(), c.getTime().getTime());
+ assertEquals(t.getD3().getTime().getTime(), c.getTime().getTime());
+ url = URLDecoder.decode(url, "UTF-8");
+ t = p.parse(url, A.class);
+ assertEquals(t.d1.getTime().getTime(), c.getTime().getTime());
+ assertEquals(t.getD2().getTime().getTime(), c.getTime().getTime());
+ assertEquals(t.getD3().getTime().getTime(), c.getTime().getTime());
+ }
+
+ //====================================================================================================
+ // Test 7f - BeanProperty.filter, RDF/XML
+ //====================================================================================================
+ @Test
+ public void testBeanProperyFilterRdfXmlWithNs() throws Exception {
+ WriterSerializer s = getRdfSerializer();
+
+ Calendar c = testDate;
+ A t = new A(c);
+ String rdf = stripRdf(s.serialize(t));
+ assertEquals("<rdf:Description><jp:d1>1901-03-03T18:11:12Z</jp:d1><jp:d2>Sun, 03 Mar 1901 18:11:12 GMT</jp:d2><jp:d3>-2172116928000</jp:d3></rdf:Description>", rdf);
+ }
+
+ @Bean(sort=true)
+ public static class A {
+ @BeanProperty(transform=CalendarTransform.ISO8601DTZ.class)
+ public Calendar d1;
+ private Calendar d2, d3;
+ public A(Calendar date) {
+ d1 = d2 = d3 = date;
+ }
+
+ public A() {}
+
+ @BeanProperty(transform=CalendarTransform.RFC2822DTZ.class)
+ public Calendar getD2() {
+ return d2;
+ }
+ public void setD2(Calendar d2) {
+ this.d2 = d2;
+ }
+
+ public Calendar getD3() {
+ return d3;
+ }
+ @BeanProperty(transform=CalendarLongTransform.class)
+ public void setD3(Calendar d3) {
+ this.d3 = d3;
+ }
+ }
+
+ private void doTest(WriterSerializer s, ReaderParser p, boolean doTestTimeToo, String expected) throws Exception {
+ Calendar d;
+ String actual;
+
+ SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy");
+ sdf.setTimeZone(TimeZone.getTimeZone("PST"));
+ actual = s.serialize(testDate);
+ String a = (s instanceof RdfSerializer ? stripRdf(actual) : actual);
+ assertEquals(expected, a);
+ d = p.parse(actual, GregorianCalendar.class);
+ d.setTimeZone(TimeZone.getTimeZone("PST"));
+ assertEquals(1901, d.get(Calendar.YEAR));
+ assertEquals(2, d.get(Calendar.MONTH));
+// assertEquals(3, d.get(Calendar.DATE));
+ if (doTestTimeToo) {
+ assertEquals(10, d.get(Calendar.HOUR));
+ assertEquals(11, d.get(Calendar.MINUTE));
+ assertEquals(12, d.get(Calendar.SECOND));
+ }
+ }
+}
\ No newline at end of file
[07/44] incubator-juneau git commit: Rename CT_* testcases.
Posted by ja...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/utils/CT_ClassUtils.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/utils/CT_ClassUtils.java b/org.apache.juneau/src/test/java/org/apache/juneau/utils/CT_ClassUtils.java
deleted file mode 100755
index e946033..0000000
--- a/org.apache.juneau/src/test/java/org/apache/juneau/utils/CT_ClassUtils.java
+++ /dev/null
@@ -1,114 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.utils;
-
-import static org.apache.juneau.internal.ClassUtils.*;
-import static org.junit.Assert.*;
-
-import org.junit.*;
-
-public class CT_ClassUtils {
-
- //====================================================================================================
- // getReadableClassName(Class)
- // getReadableClassName(String)
- //====================================================================================================
- @Test
- public void testGetReadableClassName() throws Exception {
- assertEquals("java.lang.Object", getReadableClassName(Object.class));
- assertEquals("java.lang.Object[]", getReadableClassName(Object[].class));
- assertEquals("java.lang.Object[][]", getReadableClassName(Object[][].class));
-
- assertEquals("boolean", getReadableClassName(boolean.class));
- assertEquals("boolean[]", getReadableClassName(boolean[].class));
- assertEquals("boolean[][]", getReadableClassName(boolean[][].class));
-
- assertEquals("byte", getReadableClassName(byte.class));
- assertEquals("byte[]", getReadableClassName(byte[].class));
- assertEquals("byte[][]", getReadableClassName(byte[][].class));
-
- assertEquals("char", getReadableClassName(char.class));
- assertEquals("char[]", getReadableClassName(char[].class));
- assertEquals("char[][]", getReadableClassName(char[][].class));
-
- assertEquals("double", getReadableClassName(double.class));
- assertEquals("double[]", getReadableClassName(double[].class));
- assertEquals("double[][]", getReadableClassName(double[][].class));
-
- assertEquals("float", getReadableClassName(float.class));
- assertEquals("float[]", getReadableClassName(float[].class));
- assertEquals("float[][]", getReadableClassName(float[][].class));
-
- assertEquals("int", getReadableClassName(int.class));
- assertEquals("int[]", getReadableClassName(int[].class));
- assertEquals("int[][]", getReadableClassName(int[][].class));
-
- assertEquals("long", getReadableClassName(long.class));
- assertEquals("long[]", getReadableClassName(long[].class));
- assertEquals("long[][]", getReadableClassName(long[][].class));
-
- assertEquals("short", getReadableClassName(short.class));
- assertEquals("short[]", getReadableClassName(short[].class));
- assertEquals("short[][]", getReadableClassName(short[][].class));
-
- assertNull(getReadableClassName((Class<?>)null));
- assertNull(getReadableClassName((String)null));
- }
-
- //====================================================================================================
- // isParentClass(Class, Class)
- //====================================================================================================
- @Test
- public void testIsParentClass() throws Exception {
-
- // Strict
- assertTrue(isParentClass(A.class, A1.class, true));
- assertTrue(isParentClass(A1.class, A2.class, true));
- assertTrue(isParentClass(Object.class, A2.class, true));
- assertFalse(isParentClass(A.class, A.class, true));
- assertFalse(isParentClass(A1.class, A1.class, true));
- assertFalse(isParentClass(A2.class, A2.class, true));
- assertFalse(isParentClass(A2.class, A1.class, true));
- assertFalse(isParentClass(A1.class, A.class, true));
- assertFalse(isParentClass(A2.class, Object.class, true));
-
- // Not strict
- assertTrue(isParentClass(A.class, A1.class, false));
- assertTrue(isParentClass(A1.class, A2.class, false));
- assertTrue(isParentClass(Object.class, A2.class, false));
- assertTrue(isParentClass(A.class, A.class, false));
- assertTrue(isParentClass(A1.class, A1.class, false));
- assertTrue(isParentClass(A2.class, A2.class, false));
- assertFalse(isParentClass(A2.class, A1.class, false));
- assertFalse(isParentClass(A1.class, A.class, false));
- assertFalse(isParentClass(A2.class, Object.class, false));
- }
-
- public interface A {}
-
- public static class A1 implements A {}
-
- public static class A2 extends A1 {}
-
- //====================================================================================================
- // getReadableClassNames(Object[])
- //====================================================================================================
- @Test
- public void testGetReadableClassNames() throws Exception {
- assertEquals("['java.lang.String','java.lang.Integer','java.lang.Boolean','null']", getReadableClassNames(new Object[]{"a",1,true,null}).toString());
- }
-
- public void getClassFromReadableName() throws Exception {
- fail("Not implemented");
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/utils/CT_CollectionUtils.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/utils/CT_CollectionUtils.java b/org.apache.juneau/src/test/java/org/apache/juneau/utils/CT_CollectionUtils.java
deleted file mode 100755
index f671781..0000000
--- a/org.apache.juneau/src/test/java/org/apache/juneau/utils/CT_CollectionUtils.java
+++ /dev/null
@@ -1,34 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.utils;
-
-import static org.apache.juneau.TestUtils.*;
-import static org.apache.juneau.internal.CollectionUtils.*;
-import static org.junit.Assert.*;
-
-import org.apache.juneau.*;
-import org.junit.*;
-
-public class CT_CollectionUtils {
-
- //====================================================================================================
- // reverse(LinkedHashMap)
- //====================================================================================================
- @Test
- public void testReverse() throws Exception {
- assertNull(reverse(null));
-
- assertObjectEquals("{b:2,a:1}", reverse(new ObjectMap("{a:1,b:2}")));
- assertObjectEquals("{}", reverse(new ObjectMap("{}")));
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/utils/CT_FilteredMap.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/utils/CT_FilteredMap.java b/org.apache.juneau/src/test/java/org/apache/juneau/utils/CT_FilteredMap.java
deleted file mode 100755
index 54bddd0..0000000
--- a/org.apache.juneau/src/test/java/org/apache/juneau/utils/CT_FilteredMap.java
+++ /dev/null
@@ -1,44 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.utils;
-
-import static org.apache.juneau.TestUtils.*;
-import static org.junit.Assert.*;
-
-import java.util.*;
-
-import org.apache.juneau.*;
-import org.apache.juneau.internal.*;
-import org.junit.*;
-
-public class CT_FilteredMap {
-
- Map<?,?> m3;
-
- //====================================================================================================
- // testBasic
- //====================================================================================================
- @Test
- public void testBasic() throws Exception {
- ObjectMap m = new ObjectMap("{a:'1',b:'2'}");
- FilteredMap<String,Object> m2 = new FilteredMap<String,Object>(m, new String[]{"a"});
-
- assertObjectEquals("{a:'1'}", m2);
-
- m2.entrySet().iterator().next().setValue("3");
- assertObjectEquals("{a:'3'}", m2);
-
- try { m3 = new FilteredMap<String,String>(null, new String[0]); fail(); } catch (IllegalArgumentException e) {}
- try { m3 = new FilteredMap<String,Object>(m, null); fail(); } catch (IllegalArgumentException e) {}
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/utils/CT_IOPipe.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/utils/CT_IOPipe.java b/org.apache.juneau/src/test/java/org/apache/juneau/utils/CT_IOPipe.java
deleted file mode 100755
index 03559ef..0000000
--- a/org.apache.juneau/src/test/java/org/apache/juneau/utils/CT_IOPipe.java
+++ /dev/null
@@ -1,282 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.utils;
-
-import static org.junit.Assert.*;
-
-import java.io.*;
-
-import org.apache.juneau.internal.*;
-import org.apache.juneau.utils.IOPipe.*;
-import org.junit.*;
-
-public class CT_IOPipe {
-
- //====================================================================================================
- // IOPipe(Object input, Object output)
- //====================================================================================================
- @Test
- public void testConstructor() throws Exception {
- try { IOPipe.create(null, new StringWriter()); fail(); } catch (IllegalArgumentException e) {}
- try { IOPipe.create(new StringReader(""), null); fail(); } catch (IllegalArgumentException e) {}
- try { IOPipe.create(new Integer(1), new StringWriter()); fail(); } catch (IllegalArgumentException e) {}
- try { IOPipe.create("", new Integer(1)); fail(); } catch (IllegalArgumentException e) {}
- }
-
- //====================================================================================================
- // closeOut()
- // close(boolean in, boolean out)
- //====================================================================================================
- @Test
- public void testClose() throws Exception {
- TestReader in;
- TestWriter out;
- TestInputStream in2;
- TestOutputStream out2;
-
- in = new TestReader("foobar");
- out = new TestWriter();
- IOPipe.create(in, out).run();
- assertTrue(in.closed);
- assertFalse(out.closed);
- assertEquals("foobar", out.toString());
-
- in = new TestReader("foobar");
- out = new TestWriter();
- IOPipe.create(in, out).closeOut().run();
- assertTrue(in.closed);
- assertTrue(out.closed);
- assertEquals("foobar", out.toString());
-
- in = new TestReader("foobar");
- out = new TestWriter();
- IOPipe.create(in, out).close(false, true).run();
- assertFalse(in.closed);
- assertTrue(out.closed);
- assertEquals("foobar", out.toString());
-
- in2 = new TestInputStream("foobar");
- out2 = new TestOutputStream();
- IOPipe.create(in2, out2).run();
- assertTrue(in2.closed);
- assertFalse(out2.closed);
- assertEquals("foobar", out2.toString());
-
- in2 = new TestInputStream("foobar");
- out2 = new TestOutputStream();
- IOPipe.create(in2, out2).closeOut().run();
- assertTrue(in2.closed);
- assertTrue(out2.closed);
- assertEquals("foobar", out2.toString());
-
- in2 = new TestInputStream("foobar");
- out2 = new TestOutputStream();
- IOPipe.create(in2, out2).close(false, true).run();
- assertFalse(in2.closed);
- assertTrue(out2.closed);
- assertEquals("foobar", out2.toString());
-
- in = new TestReader("foobar");
- out2 = new TestOutputStream();
- IOPipe.create(in, out2).run();
- assertTrue(in.closed);
- assertFalse(out2.closed);
- assertEquals("foobar", out.toString());
-
- in = new TestReader("foobar");
- out2 = new TestOutputStream();
- IOPipe.create(in, out2).closeOut().run();
- assertTrue(in.closed);
- assertTrue(out2.closed);
- assertEquals("foobar", out.toString());
-
- in = new TestReader("foobar");
- out2 = new TestOutputStream();
- IOPipe.create(in, out2).close(false, true).run();
- assertFalse(in.closed);
- assertTrue(out2.closed);
- assertEquals("foobar", out.toString());
-
- in2 = new TestInputStream("foobar");
- out = new TestWriter();
- IOPipe.create(in2, out).run();
- assertTrue(in2.closed);
- assertFalse(out.closed);
- assertEquals("foobar", out2.toString());
-
- in2 = new TestInputStream("foobar");
- out = new TestWriter();
- IOPipe.create(in2, out).closeOut().run();
- assertTrue(in2.closed);
- assertTrue(out.closed);
- assertEquals("foobar", out2.toString());
-
- in2 = new TestInputStream("foobar");
- out = new TestWriter();
- IOPipe.create(in2, out).close(false, true).run();
- assertFalse(in2.closed);
- assertTrue(out.closed);
- assertEquals("foobar", out2.toString());
- }
-
-
- public static class TestReader extends StringReader {
- boolean closed;
-
- public TestReader(String s) {
- super(s);
- }
-
- @Override /* Reader */
- public void close() {
- closed = true;
- }
- }
-
- public static class TestWriter extends StringWriter {
- boolean closed;
-
- public TestWriter() {
- super();
- }
-
- @Override /* Writer */
- public void close() {
- closed = true;
- }
- }
-
- public static class TestInputStream extends ByteArrayInputStream {
- boolean closed;
-
- public TestInputStream(String s) {
- super(s.getBytes());
- }
-
- @Override /* InputStream */
- public void close() throws IOException {
- super.close();
- closed = true;
- }
- }
-
- public static class TestOutputStream extends ByteArrayOutputStream {
- boolean closed;
-
- public TestOutputStream() {
- super();
- }
-
- @Override /* OutputStream */
- public void close() throws IOException {
- super.close();
- closed = true;
- }
-
- @Override /* Object */
- public String toString() {
- return new String(this.toByteArray(), IOUtils.UTF8);
- }
- }
-
- //====================================================================================================
- // byLines()
- // byLines(boolean)
- //====================================================================================================
- @Test
- public void testByLines() throws Exception {
- TestReader in;
- TestWriter out;
-
- in = new TestReader("foo\nbar");
- out = new TestWriter() {
- @Override public void write(String s) {
- super.write("["+s+"]");
- }
- };
- IOPipe.create(in, out).byLines().run();
- assertEquals("[foo][][bar][]", out.toString().replaceAll("[\\r\\n]", ""));
-
- in = new TestReader("foo\nbar");
- out = new TestWriter() {
- @Override public void write(String s) {
- super.write("["+s+"]");
- }
- };
- IOPipe.create(in, out).byLines(true).run();
- assertEquals("[foo][][bar][]", out.toString().replaceAll("[\\r\\n]", ""));
-
- in = new TestReader("foo\nbar");
- out = new TestWriter() {
- @Override public void write(String s) {
- super.write("["+s+"]");
- }
- };
- IOPipe.create(in, out).byLines(false).run();
- assertEquals("foo\nbar", out.toString());
- }
-
- //====================================================================================================
- // lineProcessor()
- //====================================================================================================
- @Test
- public void testLineProcessor() throws Exception {
- TestReader in;
- TestWriter out;
- LineProcessor lp = new LineProcessor() {
- @Override /* LineProcessor */
- public String process(String line) {
- return "[" + line + "]";
- }
- };
-
- in = new TestReader("foo\nbar");
- out = new TestWriter();
- IOPipe.create(in, out).lineProcessor(lp).run();
- assertEquals("[foo][bar]", out.toString().replaceAll("[\\r\\n]", ""));
-
- LineProcessor lp2 = new LineProcessor() {
- @Override /* LineProcessor */
- public String process(String line) {
- return line.equals("foo") ? null : line;
- }
- };
- in = new TestReader("foo\nbar");
- out = new TestWriter();
- IOPipe.create(in, out).lineProcessor(lp2).run();
- assertEquals("bar", out.toString().replaceAll("[\\r\\n]", ""));
-
- TestInputStream in2;
- TestOutputStream out2;
- in2 = new TestInputStream("foo\nbar");
- out2 = new TestOutputStream();
- IOPipe.create(in2, out2).lineProcessor(lp).run();
- assertEquals("[foo][bar]", out2.toString().replaceAll("[\\r\\n]", ""));
- }
-
- //====================================================================================================
- // buffSize()
- //====================================================================================================
- @Test
- public void testBuffSize() throws Exception {
- TestReader in;
- TestWriter out;
-
- in = new TestReader("foobar");
- out = new TestWriter();
- IOPipe.create(in, out).buffSize(1).run();
- assertEquals("foobar", out.toString().replaceAll("[\\r\\n]", ""));
-
- try { IOPipe.create(in, out).buffSize(0); fail(); } catch (IllegalArgumentException e) {}
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/utils/CT_IOUtils.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/utils/CT_IOUtils.java b/org.apache.juneau/src/test/java/org/apache/juneau/utils/CT_IOUtils.java
deleted file mode 100755
index c39411a..0000000
--- a/org.apache.juneau/src/test/java/org/apache/juneau/utils/CT_IOUtils.java
+++ /dev/null
@@ -1,103 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.utils;
-
-import static org.junit.Assert.*;
-
-import java.io.*;
-
-import org.apache.juneau.internal.*;
-import org.junit.*;
-
-public class CT_IOUtils {
-
- //====================================================================================================
- // read(File)
- // read(InputStream, Charset)
- // read(InputStream)
- // read(Reader, int, int)
- //====================================================================================================
- @Test
- public void testRead() throws Exception {
-
- TestReader in;
- TestWriter out;
-
- in = new TestReader("foobar");
- out = new TestWriter();
- IOPipe.create(in, out).run();
- assertTrue(in.closed);
- assertFalse(out.closed);
- assertEquals("foobar", out.toString());
- }
-
-
- public static class TestReader extends StringReader {
- boolean closed;
-
- public TestReader(String s) {
- super(s);
- }
-
- @Override /* Reader */
- public void close() {
- closed = true;
- }
- }
-
- public static class TestWriter extends StringWriter {
- boolean closed;
-
- public TestWriter() {
- super();
- }
-
- @Override /* Writer */
- public void close() {
- closed = true;
- }
- }
-
- public static class TestInputStream extends ByteArrayInputStream {
- boolean closed;
-
- public TestInputStream(String s) {
- super(s.getBytes());
- }
-
- @Override /* InputStream */
- public void close() throws IOException {
- super.close();
- closed = true;
- }
- }
-
- public static class TestOutputStream extends ByteArrayOutputStream {
- boolean closed;
-
- public TestOutputStream() {
- super();
- }
-
- @Override /* OutputStream */
- public void close() throws IOException {
- super.close();
- closed = true;
- }
-
- @Override /* Object */
- public String toString() {
- return new String(this.toByteArray(), IOUtils.UTF8);
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/utils/CT_IdentityList.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/utils/CT_IdentityList.java b/org.apache.juneau/src/test/java/org/apache/juneau/utils/CT_IdentityList.java
deleted file mode 100755
index ae84167..0000000
--- a/org.apache.juneau/src/test/java/org/apache/juneau/utils/CT_IdentityList.java
+++ /dev/null
@@ -1,38 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.utils;
-
-import static org.junit.Assert.*;
-
-import java.util.*;
-
-import org.apache.juneau.internal.*;
-import org.junit.*;
-
-public class CT_IdentityList {
-
- //====================================================================================================
- // test - Basic tests
- //====================================================================================================
- @Test
- public void test() throws Exception {
- List<String> l = new IdentityList<String>();
- String a = "a";
- l.add(a);
- l.add(a);
- l.add("b");
- assertEquals(2, l.size());
- assertTrue(l.contains("a"));
- assertFalse(l.contains("c"));
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/utils/CT_KeywordStore.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/utils/CT_KeywordStore.java b/org.apache.juneau/src/test/java/org/apache/juneau/utils/CT_KeywordStore.java
deleted file mode 100755
index 4cce133..0000000
--- a/org.apache.juneau/src/test/java/org/apache/juneau/utils/CT_KeywordStore.java
+++ /dev/null
@@ -1,45 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.utils;
-
-import static org.junit.Assert.*;
-
-import org.apache.juneau.internal.*;
-import org.junit.*;
-
-public class CT_KeywordStore {
-
- //====================================================================================================
- // test - Basic tests
- //====================================================================================================
- @Test
- public void test() throws Exception {
- KeywordSet ks = new KeywordSet("aaa", "zzz");
- assertTrue(ks.contains("aaa"));
- assertTrue(ks.contains("zzz"));
- assertFalse(ks.contains("xxx"));
- assertFalse(ks.contains("aaaa"));
- assertFalse(ks.contains("zzzz"));
- assertFalse(ks.contains("\u0000\u1000"));
- assertFalse(ks.contains("z"));
- assertFalse(ks.contains(null));
- assertFalse(ks.contains("a|"));
- assertFalse(ks.contains("|a"));
- assertFalse(ks.contains("Aa"));
- assertFalse(ks.contains("aA"));
-
- for (String s : new String[]{"a","aA","Aa","a|","|a"}) {
- try { ks = new KeywordSet(s); fail(); } catch (IllegalArgumentException e) {}
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/utils/CT_MultiIterable.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/utils/CT_MultiIterable.java b/org.apache.juneau/src/test/java/org/apache/juneau/utils/CT_MultiIterable.java
deleted file mode 100755
index 16c17a0..0000000
--- a/org.apache.juneau/src/test/java/org/apache/juneau/utils/CT_MultiIterable.java
+++ /dev/null
@@ -1,70 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.utils;
-
-import static org.apache.juneau.TestUtils.*;
-import static org.junit.Assert.*;
-
-import java.util.*;
-
-import org.apache.juneau.*;
-import org.apache.juneau.internal.*;
-import org.junit.*;
-
-public class CT_MultiIterable {
-
- //====================================================================================================
- // Basic tests
- //====================================================================================================
- @SuppressWarnings({ "unchecked", "rawtypes" })
- @Test
- public void test() throws Exception {
- List
- l1 = new ObjectList(),
- l2 = new ObjectList("['a','b']"),
- l3 = new ObjectList("['c']");
-
- MultiIterable mi = new MultiIterable(l1.iterator(),l2.iterator());
- mi.append(l3.iterator());
-
- assertObjectEquals("['a','b','c']", mi.iterator());
-
- mi = new MultiIterable(l1.iterator());
- assertObjectEquals("[]", mi.iterator());
-
- mi = new MultiIterable(l2.iterator(), l1.iterator());
- assertObjectEquals("['a','b']", mi.iterator());
-
- mi = new MultiIterable(l2.iterator(), l1.iterator(), l3.iterator());
- assertObjectEquals("['a','b','c']", mi.iterator());
-
- mi = new MultiIterable();
- assertObjectEquals("[]", mi.iterator());
-
- try { mi.append(null); fail(); } catch (IllegalArgumentException e) {}
-
- mi = new MultiIterable(l1.iterator());
- try { mi.iterator().next(); fail(); } catch (NoSuchElementException e) {}
-
- mi = new MultiIterable(l1.iterator());
- Iterator i = mi.iterator();
- assertFalse(i.hasNext());
- try { i.remove(); fail(); } catch (NoSuchElementException e) {}
-
- mi = new MultiIterable(l2.iterator());
- i = mi.iterator();
- assertTrue(i.hasNext());
- assertEquals("a", i.next());
- i.remove();
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/utils/CT_MultiSet.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/utils/CT_MultiSet.java b/org.apache.juneau/src/test/java/org/apache/juneau/utils/CT_MultiSet.java
deleted file mode 100755
index 809e028..0000000
--- a/org.apache.juneau/src/test/java/org/apache/juneau/utils/CT_MultiSet.java
+++ /dev/null
@@ -1,143 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.utils;
-
-import static org.apache.juneau.TestUtils.*;
-import static org.junit.Assert.*;
-
-import java.util.*;
-
-import org.apache.juneau.internal.*;
-import org.junit.*;
-
-public class CT_MultiSet {
-
- @Test
- @SuppressWarnings({ "unchecked" })
- public void doTest() throws Exception {
- List<String> l1, l2;
- MultiSet<String> ms;
- Iterator<String> i;
-
- l1 = Arrays.asList(new String[]{"1","2"});
- l2 = Arrays.asList(new String[]{"3","4"});
- ms = new MultiSet<String>(l1, l2);
- i = ms.iterator();
- assertTrue(i.hasNext());
- assertEquals("1", i.next());
- assertTrue(i.hasNext());
- assertEquals("2", i.next());
- assertTrue(i.hasNext());
- assertEquals("3", i.next());
- assertTrue(i.hasNext());
- assertEquals("4", i.next());
- assertFalse(i.hasNext());
- try {
- i.next();
- fail("Exception expected");
- } catch (NoSuchElementException e) {
- }
-
- l1 = Arrays.asList(new String[]{"1","2"});
- l2 = Arrays.asList(new String[]{});
- ms = new MultiSet<String>(l1, l2);
- i = ms.iterator();
- assertTrue(i.hasNext());
- assertEquals("1", i.next());
- assertTrue(i.hasNext());
- assertEquals("2", i.next());
- assertFalse(i.hasNext());
- try {
- i.next();
- fail("Exception expected");
- } catch (NoSuchElementException e) {
- }
-
- l1 = Arrays.asList(new String[]{});
- l2 = Arrays.asList(new String[]{"3","4"});
- ms = new MultiSet<String>(l1, l2);
- i = ms.iterator();
- assertTrue(i.hasNext());
- assertEquals("3", i.next());
- assertTrue(i.hasNext());
- assertEquals("4", i.next());
- assertFalse(i.hasNext());
- try {
- i.next();
- fail("Exception expected");
- } catch (NoSuchElementException e) {
- }
-
- l1 = Arrays.asList(new String[]{});
- l2 = Arrays.asList(new String[]{});
- ms = new MultiSet<String>(l1, l2);
- i = ms.iterator();
- assertFalse(i.hasNext());
- try {
- i.next();
- fail("Exception expected");
- } catch (NoSuchElementException e) {
- }
-
- l1 = Arrays.asList(new String[]{"1","2"});
- ms = new MultiSet<String>(l1);
- i = ms.iterator();
- assertTrue(i.hasNext());
- assertEquals("1", i.next());
- assertTrue(i.hasNext());
- assertEquals("2", i.next());
- assertFalse(i.hasNext());
- try {
- i.next();
- fail("Exception expected");
- } catch (NoSuchElementException e) {
- }
-
- l1 = new LinkedList<String>(Arrays.asList(new String[]{"1","2"}));
- l2 = new LinkedList<String>(Arrays.asList(new String[]{"3","4"}));
- ms = new MultiSet<String>(l1).append(l2);
- assertObjectEquals("['1','2','3','4']", ms);
- assertObjectEquals("['1','2','3','4']", ms.enumerator());
- assertEquals(4, ms.size());
-
- Iterator<String> t = ms.iterator();
- t.next();
- t.remove();
- assertObjectEquals("['2','3','4']", ms.enumerator());
-
- t = ms.iterator();
- t.next();
- t.remove();
- assertObjectEquals("['3','4']", ms.enumerator());
-
- t = ms.iterator();
- t.next();
- t.remove();
- assertObjectEquals("['4']", ms.enumerator());
-
- t = ms.iterator();
- t.next();
- t.remove();
- assertObjectEquals("[]", ms.enumerator());
- assertEquals(0, ms.size());
-
- ms = new MultiSet<String>();
- assertObjectEquals("[]", ms);
- assertEquals(0, ms.size());
-
- try { ms = new MultiSet<String>((Collection<String>)null); fail(); } catch (IllegalArgumentException e) {}
- try { new MultiSet<String>().iterator().next(); fail(); } catch (NoSuchElementException e) {}
- try { new MultiSet<String>().iterator().remove(); fail(); } catch (NoSuchElementException e) {}
-
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/utils/CT_ParserReader.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/utils/CT_ParserReader.java b/org.apache.juneau/src/test/java/org/apache/juneau/utils/CT_ParserReader.java
deleted file mode 100755
index 4da114e..0000000
--- a/org.apache.juneau/src/test/java/org/apache/juneau/utils/CT_ParserReader.java
+++ /dev/null
@@ -1,48 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.utils;
-
-import static org.junit.Assert.*;
-
-import org.apache.juneau.parser.*;
-import org.junit.*;
-
-public class CT_ParserReader {
-
- //====================================================================================================
- // test
- //====================================================================================================
- @Test
- public void test() throws Exception {
- ParserReader r = new ParserReader("abc123");
- try {
- assertEquals('a', r.read());
- r.unread();
- assertEquals('a', r.read());
- assertEquals('b', r.read());
- r.unread();
- assertEquals("bc", r.read(2));
- assertEquals('1', r.read());
- r.unread();
- r.read();
- assertEquals('2', r.peek());
- assertEquals('2', r.peek());
- assertEquals('2', r.read());
- assertEquals('3', r.read());
- assertEquals(-1, r.read());
- assertEquals(-1, r.read());
- } finally {
- r.close();
- }
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/utils/CT_PojoIntrospector.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/utils/CT_PojoIntrospector.java b/org.apache.juneau/src/test/java/org/apache/juneau/utils/CT_PojoIntrospector.java
deleted file mode 100755
index 6f44853..0000000
--- a/org.apache.juneau/src/test/java/org/apache/juneau/utils/CT_PojoIntrospector.java
+++ /dev/null
@@ -1,53 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.utils;
-
-import static org.junit.Assert.*;
-
-import org.junit.*;
-
-public class CT_PojoIntrospector {
-
- //====================================================================================================
- // testBasic
- //====================================================================================================
- @Test
- public void testBasic() throws Exception {
- String in = null;
- Object r;
-
- r = new PojoIntrospector(in, null).invokeMethod("substring(int,int)", "[3,6]");
- assertNull(r);
-
- in = "foobar";
- r = new PojoIntrospector(in).invokeMethod("substring(int,int)", "[3,6]");
- assertEquals("bar", r);
-
- r = new PojoIntrospector(in).invokeMethod("toString", null);
- assertEquals("foobar", r);
-
- r = new PojoIntrospector(in).invokeMethod("toString", "");
- assertEquals("foobar", r);
-
- r = new PojoIntrospector(in).invokeMethod("toString", "[]");
- assertEquals("foobar", r);
-
- try { new PojoIntrospector(in).invokeMethod("noSuchMethod", "[3,6]"); fail(); } catch (NoSuchMethodException e) {}
-
- r = new PojoIntrospector(null).invokeMethod(String.class.getMethod("toString"), null);
- assertNull(r);
-
- r = new PojoIntrospector("foobar").invokeMethod(String.class.getMethod("toString"), null);
- assertEquals("foobar", r);
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/utils/CT_PojoQuery.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/utils/CT_PojoQuery.java b/org.apache.juneau/src/test/java/org/apache/juneau/utils/CT_PojoQuery.java
deleted file mode 100755
index bfb98af..0000000
--- a/org.apache.juneau/src/test/java/org/apache/juneau/utils/CT_PojoQuery.java
+++ /dev/null
@@ -1,680 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.utils;
-
-import static org.apache.juneau.TestUtils.*;
-import static org.junit.Assert.*;
-
-import java.util.*;
-
-import org.apache.juneau.*;
-import org.apache.juneau.json.*;
-import org.apache.juneau.serializer.*;
-import org.apache.juneau.transforms.*;
-import org.junit.*;
-
-@SuppressWarnings({"serial","rawtypes"})
-public class CT_PojoQuery {
-
- //====================================================================================================
- // filterCollection, string search, 1 level
- //====================================================================================================
- @Test
- public void testFilterCollectionStringSearchOneLevel() throws Exception {
- ObjectMap query = null;
- List view = null;
- List sort = null;
- int pos = 0;
- int limit = 0;
- boolean ignoreCase = false;
- BeanContext bc = BeanContext.DEFAULT;
- List results;
-
- List<A> in = new LinkedList<A>() {{
- add(new A("foo"));
- add(new A("bar"));
- add(new A("baz"));
- }};
-
- PojoQuery filter = new PojoQuery(in, bc);
-
- query = new ObjectMap("{f:'foo'}");
- results = filter.filterCollection(query, view, sort, pos, limit, ignoreCase);
- assertObjectEquals("[{f:'foo'}]", results);
-
- query = new ObjectMap("{f:'fo*'}");
- results = filter.filterCollection(query, view, sort, pos, limit, ignoreCase);
- assertObjectEquals("[{f:'foo'}]", results);
-
- query = new ObjectMap("{f:'*ar'}");
- results = filter.filterCollection(query, view, sort, pos, limit, ignoreCase);
- assertObjectEquals("[{f:'bar'}]", results);
-
- query = new ObjectMap("{f:'foo bar'}");
- results = filter.filterCollection(query, view, sort, pos, limit, ignoreCase);
- assertObjectEquals("[{f:'foo'},{f:'bar'}]", results);
- }
-
- public class A {
- public String f;
-
- A() {}
-
- A(String f) {
- this.f = f;
- }
- }
-
- //====================================================================================================
- // filterCollection, date search, 1 level
- //====================================================================================================
- @Test
- public void testFilterCollectionDateSearchOneLevel() throws Exception {
- ObjectMap query = null;
- List view = null;
- List sort = null;
- int pos = 0;
- int limit = 0;
- boolean ignoreCase = false;
- BeanContext bc = BeanContext.DEFAULT;
- WriterSerializer s = new JsonSerializer.Simple().addTransforms(CalendarTransform.Simple.class);
- B[] in;
- PojoQuery filter;
-
- List results;
-
- in = new B[] {
- new B(2010, 0, 1),
- new B(2011, 0, 1),
- new B(2011, 0, 31),
- new B(2012, 0, 1)
- };
- filter = new PojoQuery(in, bc);
-
- query = new ObjectMap("{f:'2011'}");
- results = filter.filterCollection(query, view, sort, pos, limit, ignoreCase);
- assertEquals("[{f:'2011/01/01 00:00:00'},{f:'2011/01/31 00:00:00'}]", s.serialize(results));
-
- query = new ObjectMap("{f:'2011.01'}");
- results = filter.filterCollection(query, view, sort, pos, limit, ignoreCase);
- assertEquals("[{f:'2011/01/01 00:00:00'},{f:'2011/01/31 00:00:00'}]", s.serialize(results));
-
- query = new ObjectMap("{f:'2011.01.01'}");
- results = filter.filterCollection(query, view, sort, pos, limit, ignoreCase);
- assertEquals("[{f:'2011/01/01 00:00:00'}]", s.serialize(results));
-
- in = new B[] {
- new B(2011, 00, 01, 11, 59, 59),
- new B(2011, 00, 01, 12, 00, 00),
- new B(2011, 00, 01, 12, 59, 59),
- new B(2011, 00, 01, 13, 00, 00)
- };
- filter = new PojoQuery(in, bc);
-
- query = new ObjectMap("{f:'2011.01.01.12'}");
- results = filter.filterCollection(query, view, sort, pos, limit, ignoreCase);
- assertEquals("[{f:'2011/01/01 12:00:00'},{f:'2011/01/01 12:59:59'}]", s.serialize(results));
-
- in = new B[] {
- new B(2011, 00, 01, 12, 29, 59),
- new B(2011, 00, 01, 12, 30, 00),
- new B(2011, 00, 01, 12, 30, 59),
- new B(2011, 00, 01, 12, 31, 00)
- };
- filter = new PojoQuery(in, bc);
- query = new ObjectMap("{f:'2011.01.01.12.30'}");
- results = filter.filterCollection(query, view, sort, pos, limit, ignoreCase);
- assertEquals("[{f:'2011/01/01 12:30:00'},{f:'2011/01/01 12:30:59'}]", s.serialize(results));
-
- in = new B[] {
- new B(2011, 00, 01, 12, 30, 29),
- new B(2011, 00, 01, 12, 30, 30),
- new B(2011, 00, 01, 12, 30, 31)
- };
- filter = new PojoQuery(in, bc);
- query = new ObjectMap("{f:'2011.01.01.12.30.30'}");
- results = filter.filterCollection(query, view, sort, pos, limit, ignoreCase);
- assertEquals("[{f:'2011/01/01 12:30:30'}]", s.serialize(results));
-
- // Open-ended ranges
-
- in = new B[] {
- new B(2000, 11, 31),
- new B(2001, 00, 01)
- };
- filter = new PojoQuery(in, bc);
-
- query = new ObjectMap("{f:'>2000'}");
- results = filter.filterCollection(query, view, sort, pos, limit, ignoreCase);
- assertEquals("[{f:'2001/01/01 00:00:00'}]", s.serialize(results));
-
- query = new ObjectMap("{f:'>=2001'}");
- results = filter.filterCollection(query, view, sort, pos, limit, ignoreCase);
- assertEquals("[{f:'2001/01/01 00:00:00'}]", s.serialize(results));
-
- query = new ObjectMap("{f:'<2001'}");
- results = filter.filterCollection(query, view, sort, pos, limit, ignoreCase);
- assertEquals("[{f:'2000/12/31 00:00:00'}]", s.serialize(results));
-
- query = new ObjectMap("{f:'<=2000'}");
- results = filter.filterCollection(query, view, sort, pos, limit, ignoreCase);
- assertEquals("[{f:'2000/12/31 00:00:00'}]", s.serialize(results));
-
- in = new B[] {
- new B(2011, 00, 01, 12, 29, 59),
- new B(2011, 00, 01, 12, 30, 00)
- };
- filter = new PojoQuery(in, bc);
-
- query = new ObjectMap("{f:'>=2011.01.01.12.30'}");
- results = filter.filterCollection(query, view, sort, pos, limit, ignoreCase);
- assertEquals("[{f:'2011/01/01 12:30:00'}]", s.serialize(results));
-
- query = new ObjectMap("{f:'<2011.01.01.12.30'}");
- results = filter.filterCollection(query, view, sort, pos, limit, ignoreCase);
- assertEquals("[{f:'2011/01/01 12:29:59'}]", s.serialize(results));
-
- in = new B[] {
- new B(2011, 00, 01, 12, 30, 59),
- new B(2011, 00, 01, 12, 31, 00)
- };
- filter = new PojoQuery(in, bc);
-
- query = new ObjectMap("{f:'>2011.01.01.12.30'}");
- results = filter.filterCollection(query, view, sort, pos, limit, ignoreCase);
- assertEquals("[{f:'2011/01/01 12:31:00'}]", s.serialize(results));
-
- query = new ObjectMap("{f:'<=2011.01.01.12.30'}");
- results = filter.filterCollection(query, view, sort, pos, limit, ignoreCase);
- assertEquals("[{f:'2011/01/01 12:30:59'}]", s.serialize(results));
-
- // Closed range
-
- in = new B[] {
- new B(2000, 11, 31, 23, 59, 59),
- new B(2001, 00, 01, 00, 00, 00),
- new B(2003, 05, 30, 23, 59, 59),
- new B(2003, 06, 01, 00, 00, 00)
- };
- filter = new PojoQuery(in, bc);
-
- query = new ObjectMap("{f:'2001 - 2003.06.30'}");
- results = filter.filterCollection(query, view, sort, pos, limit, ignoreCase);
- assertEquals("[{f:'2001/01/01 00:00:00'},{f:'2003/06/30 23:59:59'}]", s.serialize(results));
-
- // ORed timestamps
-
- in = new B[] {
- new B(2000, 11, 31),
- new B(2001, 00, 01),
- new B(2001, 11, 31),
- new B(2002, 00, 01)
- };
- filter = new PojoQuery(in, bc);
-
- query = new ObjectMap("{f:'2001 2003 2005'}");
- results = filter.filterCollection(query, view, sort, pos, limit, ignoreCase);
- assertEquals("[{f:'2001/01/01 00:00:00'},{f:'2001/12/31 00:00:00'}]", s.serialize(results));
-
- in = new B[] {
- new B(2002, 11, 31),
- new B(2003, 00, 01),
- new B(2003, 11, 31),
- new B(2004, 00, 01)
- };
- filter = new PojoQuery(in, bc);
-
- query = new ObjectMap("{f:'2001 2003 2005'}");
- results = filter.filterCollection(query, view, sort, pos, limit, ignoreCase);
- assertEquals("[{f:'2003/01/01 00:00:00'},{f:'2003/12/31 00:00:00'}]", s.serialize(results));
-
- in = new B[] {
- new B(2004, 11, 31),
- new B(2005, 00, 01),
- new B(2005, 11, 31),
- new B(2006, 00, 01)
- };
- filter = new PojoQuery(in, bc);
-
- query = new ObjectMap("{f:'2001 2003 2005'}");
- results = filter.filterCollection(query, view, sort, pos, limit, ignoreCase);
- assertEquals("[{f:'2005/01/01 00:00:00'},{f:'2005/12/31 00:00:00'}]", s.serialize(results));
- }
-
- public class B {
- public Calendar f;
-
- B() {}
-
- B(int year, int month, int day) {
- this.f = new GregorianCalendar(year, month, day);
- }
-
- B(int year, int month, int day, int hour, int minute, int second) {
- this.f = new GregorianCalendar(year, month, day, hour, minute, second);
- }
- }
-
- //====================================================================================================
- // filterCollection, int search, 1 level
- //====================================================================================================
- @Test
- public void testFilterCollectionIntSearchOneLevel() throws Exception {
- ObjectMap query = null;
- List view = null;
- List sort = null;
- int pos = 0;
- int limit = 0;
- boolean ignoreCase = false;
- BeanContext bc = BeanContext.DEFAULT;
- List results;
-
- List<C> in = new LinkedList<C>() {{
- add(new C(1));
- add(new C(2));
- add(new C(3));
- }};
-
- PojoQuery filter = new PojoQuery(in, bc);
-
- query = new ObjectMap("{f:'1'}");
- results = filter.filterCollection(query, view, sort, pos, limit, ignoreCase);
- assertObjectEquals("[{f:1}]", results);
-
- query = new ObjectMap("{f:'>1'}");
- results = filter.filterCollection(query, view, sort, pos, limit, ignoreCase);
- assertObjectEquals("[{f:2},{f:3}]", results);
-
- query = new ObjectMap("{f:'>=2'}");
- results = filter.filterCollection(query, view, sort, pos, limit, ignoreCase);
- assertObjectEquals("[{f:2},{f:3}]", results);
-
- query = new ObjectMap("{f:'<=2'}");
- results = filter.filterCollection(query, view, sort, pos, limit, ignoreCase);
- assertObjectEquals("[{f:1},{f:2}]", results);
-
- query = new ObjectMap("{f:'<2'}");
- results = filter.filterCollection(query, view, sort, pos, limit, ignoreCase);
- assertObjectEquals("[{f:1}]", results);
-
- query = new ObjectMap("{f:'1 3'}");
- results = filter.filterCollection(query, view, sort, pos, limit, ignoreCase);
- assertObjectEquals("[{f:1},{f:3}]", results);
- }
-
- public class C {
- public int f;
-
- C() {}
-
- C(int f) {
- this.f = f;
- }
- }
-
- //====================================================================================================
- // filterCollection, string search, 2 level
- //====================================================================================================
- @Test
- public void testFilterCollectionStringSearchTwoLevel() throws Exception {
- ObjectMap query = null;
- List view = null;
- List sort = null;
- int pos = 0;
- int limit = 0;
- boolean ignoreCase = false;
- BeanContext bc = BeanContext.DEFAULT;
- List results;
-
- List<D1> in = new LinkedList<D1>() {{
- add(new D1("foo"));
- add(new D1("bar"));
- add(new D1("baz"));
- }};
-
- PojoQuery filter = new PojoQuery(in, bc);
-
- query = new ObjectMap("{f:{f:'foo'}}");
- results = filter.filterCollection(query, view, sort, pos, limit, ignoreCase);
- assertObjectEquals("[{f:{f:'foo'}}]", results);
-
- query = new ObjectMap("{f:{f:'fo*'}}");
- results = filter.filterCollection(query, view, sort, pos, limit, ignoreCase);
- assertObjectEquals("[{f:{f:'foo'}}]", results);
-
- query = new ObjectMap("{f:{f:'*ar'}}");
- results = filter.filterCollection(query, view, sort, pos, limit, ignoreCase);
- assertObjectEquals("[{f:{f:'bar'}}]", results);
-
- query = new ObjectMap("{f:{f:'foo bar'}}");
- results = filter.filterCollection(query, view, sort, pos, limit, ignoreCase);
- assertObjectEquals("[{f:{f:'foo'}},{f:{f:'bar'}}]", results);
- }
-
- public class D1 {
- public D2 f;
-
- D1() {}
-
- D1(String f) {
- this.f = new D2(f);
- }
- }
- public class D2 {
- public String f;
-
- D2() {}
-
- D2(String f) {
- this.f = f;
- }
- }
-
- //====================================================================================================
- // filterCollection, view, 1 level
- //====================================================================================================
- @Test
- public void testFilterCollectionViewOneLevel() throws Exception {
- ObjectMap query = null;
- List view = null;
- List sort = null;
- int pos = 0;
- int limit = 0;
- boolean ignoreCase = false;
- BeanContext bc = BeanContext.DEFAULT;
- List results;
-
- List<E> in = new LinkedList<E>() {{
- add(new E("foo", 1, true));
- add(new E("bar", 2, false));
- add(new E("baz", 3, true));
- }};
-
- PojoQuery filter = new PojoQuery(in, bc);
-
- view = new ObjectList("['f1']");
- results = filter.filterCollection(query, view, sort, pos, limit, ignoreCase);
- assertObjectEquals("[{f1:'foo'},{f1:'bar'},{f1:'baz'}]", results);
-
- view = new ObjectList("['f2']");
- results = filter.filterCollection(query, view, sort, pos, limit, ignoreCase);
- assertObjectEquals("[{f2:1},{f2:2},{f2:3}]", results);
-
- view = new ObjectList("['f3']");
- results = filter.filterCollection(query, view, sort, pos, limit, ignoreCase);
- assertObjectEquals("[{f3:true},{f3:false},{f3:true}]", results);
-
- view = new ObjectList("['f3','f2','f1']");
- results = filter.filterCollection(query, view, sort, pos, limit, ignoreCase);
- assertObjectEquals("[{f3:true,f2:1,f1:'foo'},{f3:false,f2:2,f1:'bar'},{f3:true,f2:3,f1:'baz'}]", results);
- }
-
- public class E {
- public String f1;
- public int f2;
- public boolean f3;
-
- E() {}
-
- E(String f1, int f2, boolean f3) {
- this.f1 = f1;
- this.f2 = f2;
- this.f3 = f3;
- }
- }
-
- //====================================================================================================
- // filterCollection, view, 2 level
- //====================================================================================================
- @Test
- public void testFilterCollectionViewTwoLevel() throws Exception {
- ObjectMap query = null;
- List view = null;
- List sort = null;
- int pos = 0;
- int limit = 0;
- boolean ignoreCase = false;
- BeanContext bc = BeanContext.DEFAULT;
- List results;
-
- List<F1> in = new LinkedList<F1>() {{
- add(new F1("foo"));
- add(new F1("bar"));
- add(new F1("baz"));
- }};
-
- PojoQuery filter = new PojoQuery(in, bc);
-
- view = new ObjectList("['f1']");
- results = filter.filterCollection(query, view, sort, pos, limit, ignoreCase);
- assertObjectEquals("[{f1:'foo'},{f1:'bar'},{f1:'baz'}]", results);
-
- view = new ObjectList("[{f2:['f1']}]");
- results = filter.filterCollection(query, view, sort, pos, limit, ignoreCase);
- assertObjectEquals("[{f2:{f1:'f2_foo'}},{f2:{f1:'f2_bar'}},{f2:{f1:'f2_baz'}}]", results);
-
- view = new ObjectList("['f1',{f3:['f1']}]");
- results = filter.filterCollection(query, view, sort, pos, limit, ignoreCase);
- assertObjectEquals("[{f1:'foo',f3:[{f1:'f31_foo'},{f1:'f32_foo'}]},{f1:'bar',f3:[{f1:'f31_bar'},{f1:'f32_bar'}]},{f1:'baz',f3:[{f1:'f31_baz'},{f1:'f32_baz'}]}]", results);
- }
-
- public class F1 {
- public String f1;
- public F2 f2;
- public List<F2> f3;
-
- F1() {}
-
- F1(final String f1) {
- this.f1 = f1;
- this.f2 = new F2("f2_"+f1);
- this.f3 = new LinkedList<F2>() {{
- add(new F2("f31_"+f1));
- add(new F2("f32_"+f1));
- }};
- }
- }
-
- public class F2 {
- public String f1;
- public String f2;
-
- F2() {}
-
- F2(String f1) {
- this.f1 = f1;
- this.f2 = f1;
- }
- }
-
- //====================================================================================================
- // filterMap, 1 level
- //===================================================================================================
- @Test
- public void testFilterMapOneLevel() throws Exception {
- ObjectList view = null;
- BeanContext bc = BeanContext.DEFAULT;
- Map results;
-
- G in = new G("foo", 1, true);
- PojoQuery filter = new PojoQuery(in, bc);
-
- view = new ObjectList("['f1']");
- results = filter.filterMap(view);
- assertObjectEquals("{f1:'foo'}", results);
-
- view = new ObjectList("['f2']");
- results = filter.filterMap(view);
- assertObjectEquals("{f2:1}", results);
-
- view = new ObjectList("['f3','f1']");
- results = filter.filterMap(view);
- assertObjectEquals("{f3:true,f1:'foo'}", results);
- }
-
- public class G {
- public String f1;
- public int f2;
- public boolean f3;
-
- G() {}
-
- G(String f1, int f2, boolean f3) {
- this.f1 = f1;
- this.f2 = f2;
- this.f3 = f3;
- }
- }
-
- //====================================================================================================
- // filterMap, 2 level
- //====================================================================================================
- @Test
- public void testFilterMapTwoLevel() throws Exception {
- ObjectList view = null;
- BeanContext bc = BeanContext.DEFAULT;
- Map results;
-
- H1 in = new H1("foo");
-
- PojoQuery filter = new PojoQuery(in, bc);
-
- view = new ObjectList("['f1']");
- results = filter.filterMap(view);
- assertObjectEquals("{f1:'foo'}", results);
-
- view = new ObjectList("[{f2:['f1']}]");
- results = filter.filterMap(view);
- assertObjectEquals("{f2:{f1:'f2_foo'}}", results);
-
- view = new ObjectList("['f1',{f3:['f1']}]");
- results = filter.filterMap(view);
- assertObjectEquals("{f1:'foo',f3:[{f1:'f31_foo'},{f1:'f32_foo'}]}", results);
- }
-
- public class H1 {
- public String f1;
- public H2 f2;
- public List<H2> f3;
-
- H1() {}
-
- H1(final String f1) {
- this.f1 = f1;
- this.f2 = new H2("f2_"+f1);
- this.f3 = new LinkedList<H2>() {{
- add(new H2("f31_"+f1));
- add(new H2("f32_"+f1));
- }};
- }
- }
-
- public class H2 {
- public String f1;
- public String f2;
-
- H2() {}
-
- H2(String f1) {
- this.f1 = f1;
- this.f2 = f1;
- }
- }
-
- //====================================================================================================
- // testSorting
- //====================================================================================================
- @Test
- public void testSorting() throws Exception {
- ObjectMap query = null;
- List view = null;
- List sort = null;
- int pos = 0;
- int limit = 0;
- boolean ignoreCase = false;
- BeanContext bc = BeanContext.DEFAULT;
- WriterSerializer s = new JsonSerializer.Simple().addTransforms(CalendarTransform.Simple.class);
- List results;
-
- I[] in = new I[] {
- new I(1, "foo", true, 2010, 1, 1),
- new I(2, "bar", false, 2011, 1, 1),
- new I(3, "baz", true, 2012, 1, 1),
- };
-
- PojoQuery filter = new PojoQuery(in, bc);
-
- sort = new ObjectList("['f2']");
- view = new ObjectList("['f1','f2']");
- results = filter.filterCollection(query, view, sort, pos, limit, ignoreCase);
- assertEquals("[{f1:2,f2:'bar'},{f1:3,f2:'baz'},{f1:1,f2:'foo'}]", s.serialize(results));
-
- sort = new ObjectList("[{f2:'d'}]");
- view = new ObjectList("['f1','f2']");
- results = filter.filterCollection(query, view, sort, pos, limit, ignoreCase);
- assertEquals("[{f1:1,f2:'foo'},{f1:3,f2:'baz'},{f1:2,f2:'bar'}]", s.serialize(results));
-
- sort = new ObjectList("['f3']");
- view = new ObjectList("['f1','f3']");
- results = filter.filterCollection(query, view, sort, pos, limit, ignoreCase);
- assertEquals("[{f1:2,f3:false},{f1:1,f3:true},{f1:3,f3:true}]", s.serialize(results));
-
- sort = new ObjectList("['f3',{f1:'a'}]");
- view = new ObjectList("['f1','f3']");
- results = filter.filterCollection(query, view, sort, pos, limit, ignoreCase);
- assertEquals("[{f1:2,f3:false},{f1:1,f3:true},{f1:3,f3:true}]", s.serialize(results));
-
- sort = new ObjectList("['f3',{f1:'d'}]");
- view = new ObjectList("['f1','f3']");
- results = filter.filterCollection(query, view, sort, pos, limit, ignoreCase);
- assertEquals("[{f1:2,f3:false},{f1:3,f3:true},{f1:1,f3:true}]", s.serialize(results));
-
- sort = new ObjectList("['f1']");
- view = new ObjectList("['f1']");
- limit = 1;
- pos = 0;
- results = filter.filterCollection(query, view, sort, pos, limit, ignoreCase);
- assertEquals("[{f1:1}]", s.serialize(results));
-
- limit = 3;
- pos = 0;
- results = filter.filterCollection(query, view, sort, pos, limit, ignoreCase);
- assertEquals("[{f1:1},{f1:2},{f1:3}]", s.serialize(results));
-
- limit = 1;
- pos = 2;
- results = filter.filterCollection(query, view, sort, pos, limit, ignoreCase);
- assertEquals("[{f1:3}]", s.serialize(results));
-
- limit = 100;
- pos = 2;
- results = filter.filterCollection(query, view, sort, pos, limit, ignoreCase);
- assertEquals("[{f1:3}]", s.serialize(results));
- }
-
- public class I {
- public int f1;
- public String f2;
- public boolean f3;
- public Calendar f4;
-
- I() {}
-
- I(int f1, String f2, boolean f3, int year, int month, int day) {
- this.f1 = f1;
- this.f2 = f2;
- this.f3 = f3;
- this.f4 = new GregorianCalendar(year, month, day);
- }
- }
-}
\ No newline at end of file
[05/44] incubator-juneau git commit: Rename CT_* testcases.
Posted by ja...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/utils/ClassUtilsTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/utils/ClassUtilsTest.java b/org.apache.juneau/src/test/java/org/apache/juneau/utils/ClassUtilsTest.java
new file mode 100755
index 0000000..2b76236
--- /dev/null
+++ b/org.apache.juneau/src/test/java/org/apache/juneau/utils/ClassUtilsTest.java
@@ -0,0 +1,114 @@
+/***************************************************************************************************************************
+ * 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.juneau.utils;
+
+import static org.apache.juneau.internal.ClassUtils.*;
+import static org.junit.Assert.*;
+
+import org.junit.*;
+
+public class ClassUtilsTest {
+
+ //====================================================================================================
+ // getReadableClassName(Class)
+ // getReadableClassName(String)
+ //====================================================================================================
+ @Test
+ public void testGetReadableClassName() throws Exception {
+ assertEquals("java.lang.Object", getReadableClassName(Object.class));
+ assertEquals("java.lang.Object[]", getReadableClassName(Object[].class));
+ assertEquals("java.lang.Object[][]", getReadableClassName(Object[][].class));
+
+ assertEquals("boolean", getReadableClassName(boolean.class));
+ assertEquals("boolean[]", getReadableClassName(boolean[].class));
+ assertEquals("boolean[][]", getReadableClassName(boolean[][].class));
+
+ assertEquals("byte", getReadableClassName(byte.class));
+ assertEquals("byte[]", getReadableClassName(byte[].class));
+ assertEquals("byte[][]", getReadableClassName(byte[][].class));
+
+ assertEquals("char", getReadableClassName(char.class));
+ assertEquals("char[]", getReadableClassName(char[].class));
+ assertEquals("char[][]", getReadableClassName(char[][].class));
+
+ assertEquals("double", getReadableClassName(double.class));
+ assertEquals("double[]", getReadableClassName(double[].class));
+ assertEquals("double[][]", getReadableClassName(double[][].class));
+
+ assertEquals("float", getReadableClassName(float.class));
+ assertEquals("float[]", getReadableClassName(float[].class));
+ assertEquals("float[][]", getReadableClassName(float[][].class));
+
+ assertEquals("int", getReadableClassName(int.class));
+ assertEquals("int[]", getReadableClassName(int[].class));
+ assertEquals("int[][]", getReadableClassName(int[][].class));
+
+ assertEquals("long", getReadableClassName(long.class));
+ assertEquals("long[]", getReadableClassName(long[].class));
+ assertEquals("long[][]", getReadableClassName(long[][].class));
+
+ assertEquals("short", getReadableClassName(short.class));
+ assertEquals("short[]", getReadableClassName(short[].class));
+ assertEquals("short[][]", getReadableClassName(short[][].class));
+
+ assertNull(getReadableClassName((Class<?>)null));
+ assertNull(getReadableClassName((String)null));
+ }
+
+ //====================================================================================================
+ // isParentClass(Class, Class)
+ //====================================================================================================
+ @Test
+ public void testIsParentClass() throws Exception {
+
+ // Strict
+ assertTrue(isParentClass(A.class, A1.class, true));
+ assertTrue(isParentClass(A1.class, A2.class, true));
+ assertTrue(isParentClass(Object.class, A2.class, true));
+ assertFalse(isParentClass(A.class, A.class, true));
+ assertFalse(isParentClass(A1.class, A1.class, true));
+ assertFalse(isParentClass(A2.class, A2.class, true));
+ assertFalse(isParentClass(A2.class, A1.class, true));
+ assertFalse(isParentClass(A1.class, A.class, true));
+ assertFalse(isParentClass(A2.class, Object.class, true));
+
+ // Not strict
+ assertTrue(isParentClass(A.class, A1.class, false));
+ assertTrue(isParentClass(A1.class, A2.class, false));
+ assertTrue(isParentClass(Object.class, A2.class, false));
+ assertTrue(isParentClass(A.class, A.class, false));
+ assertTrue(isParentClass(A1.class, A1.class, false));
+ assertTrue(isParentClass(A2.class, A2.class, false));
+ assertFalse(isParentClass(A2.class, A1.class, false));
+ assertFalse(isParentClass(A1.class, A.class, false));
+ assertFalse(isParentClass(A2.class, Object.class, false));
+ }
+
+ public interface A {}
+
+ public static class A1 implements A {}
+
+ public static class A2 extends A1 {}
+
+ //====================================================================================================
+ // getReadableClassNames(Object[])
+ //====================================================================================================
+ @Test
+ public void testGetReadableClassNames() throws Exception {
+ assertEquals("['java.lang.String','java.lang.Integer','java.lang.Boolean','null']", getReadableClassNames(new Object[]{"a",1,true,null}).toString());
+ }
+
+ public void getClassFromReadableName() throws Exception {
+ fail("Not implemented");
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/utils/CollectionUtilsTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/utils/CollectionUtilsTest.java b/org.apache.juneau/src/test/java/org/apache/juneau/utils/CollectionUtilsTest.java
new file mode 100755
index 0000000..b0446d7
--- /dev/null
+++ b/org.apache.juneau/src/test/java/org/apache/juneau/utils/CollectionUtilsTest.java
@@ -0,0 +1,34 @@
+/***************************************************************************************************************************
+ * 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.juneau.utils;
+
+import static org.apache.juneau.TestUtils.*;
+import static org.apache.juneau.internal.CollectionUtils.*;
+import static org.junit.Assert.*;
+
+import org.apache.juneau.*;
+import org.junit.*;
+
+public class CollectionUtilsTest {
+
+ //====================================================================================================
+ // reverse(LinkedHashMap)
+ //====================================================================================================
+ @Test
+ public void testReverse() throws Exception {
+ assertNull(reverse(null));
+
+ assertObjectEquals("{b:2,a:1}", reverse(new ObjectMap("{a:1,b:2}")));
+ assertObjectEquals("{}", reverse(new ObjectMap("{}")));
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/utils/FilteredMapTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/utils/FilteredMapTest.java b/org.apache.juneau/src/test/java/org/apache/juneau/utils/FilteredMapTest.java
new file mode 100755
index 0000000..b09ac9d
--- /dev/null
+++ b/org.apache.juneau/src/test/java/org/apache/juneau/utils/FilteredMapTest.java
@@ -0,0 +1,44 @@
+/***************************************************************************************************************************
+ * 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.juneau.utils;
+
+import static org.apache.juneau.TestUtils.*;
+import static org.junit.Assert.*;
+
+import java.util.*;
+
+import org.apache.juneau.*;
+import org.apache.juneau.internal.*;
+import org.junit.*;
+
+public class FilteredMapTest {
+
+ Map<?,?> m3;
+
+ //====================================================================================================
+ // testBasic
+ //====================================================================================================
+ @Test
+ public void testBasic() throws Exception {
+ ObjectMap m = new ObjectMap("{a:'1',b:'2'}");
+ FilteredMap<String,Object> m2 = new FilteredMap<String,Object>(m, new String[]{"a"});
+
+ assertObjectEquals("{a:'1'}", m2);
+
+ m2.entrySet().iterator().next().setValue("3");
+ assertObjectEquals("{a:'3'}", m2);
+
+ try { m3 = new FilteredMap<String,String>(null, new String[0]); fail(); } catch (IllegalArgumentException e) {}
+ try { m3 = new FilteredMap<String,Object>(m, null); fail(); } catch (IllegalArgumentException e) {}
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/utils/IOPipeTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/utils/IOPipeTest.java b/org.apache.juneau/src/test/java/org/apache/juneau/utils/IOPipeTest.java
new file mode 100755
index 0000000..6d9a1be
--- /dev/null
+++ b/org.apache.juneau/src/test/java/org/apache/juneau/utils/IOPipeTest.java
@@ -0,0 +1,282 @@
+/***************************************************************************************************************************
+ * 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.juneau.utils;
+
+import static org.junit.Assert.*;
+
+import java.io.*;
+
+import org.apache.juneau.internal.*;
+import org.apache.juneau.utils.IOPipe.*;
+import org.junit.*;
+
+public class IOPipeTest {
+
+ //====================================================================================================
+ // IOPipe(Object input, Object output)
+ //====================================================================================================
+ @Test
+ public void testConstructor() throws Exception {
+ try { IOPipe.create(null, new StringWriter()); fail(); } catch (IllegalArgumentException e) {}
+ try { IOPipe.create(new StringReader(""), null); fail(); } catch (IllegalArgumentException e) {}
+ try { IOPipe.create(new Integer(1), new StringWriter()); fail(); } catch (IllegalArgumentException e) {}
+ try { IOPipe.create("", new Integer(1)); fail(); } catch (IllegalArgumentException e) {}
+ }
+
+ //====================================================================================================
+ // closeOut()
+ // close(boolean in, boolean out)
+ //====================================================================================================
+ @Test
+ public void testClose() throws Exception {
+ TestReader in;
+ TestWriter out;
+ TestInputStream in2;
+ TestOutputStream out2;
+
+ in = new TestReader("foobar");
+ out = new TestWriter();
+ IOPipe.create(in, out).run();
+ assertTrue(in.closed);
+ assertFalse(out.closed);
+ assertEquals("foobar", out.toString());
+
+ in = new TestReader("foobar");
+ out = new TestWriter();
+ IOPipe.create(in, out).closeOut().run();
+ assertTrue(in.closed);
+ assertTrue(out.closed);
+ assertEquals("foobar", out.toString());
+
+ in = new TestReader("foobar");
+ out = new TestWriter();
+ IOPipe.create(in, out).close(false, true).run();
+ assertFalse(in.closed);
+ assertTrue(out.closed);
+ assertEquals("foobar", out.toString());
+
+ in2 = new TestInputStream("foobar");
+ out2 = new TestOutputStream();
+ IOPipe.create(in2, out2).run();
+ assertTrue(in2.closed);
+ assertFalse(out2.closed);
+ assertEquals("foobar", out2.toString());
+
+ in2 = new TestInputStream("foobar");
+ out2 = new TestOutputStream();
+ IOPipe.create(in2, out2).closeOut().run();
+ assertTrue(in2.closed);
+ assertTrue(out2.closed);
+ assertEquals("foobar", out2.toString());
+
+ in2 = new TestInputStream("foobar");
+ out2 = new TestOutputStream();
+ IOPipe.create(in2, out2).close(false, true).run();
+ assertFalse(in2.closed);
+ assertTrue(out2.closed);
+ assertEquals("foobar", out2.toString());
+
+ in = new TestReader("foobar");
+ out2 = new TestOutputStream();
+ IOPipe.create(in, out2).run();
+ assertTrue(in.closed);
+ assertFalse(out2.closed);
+ assertEquals("foobar", out.toString());
+
+ in = new TestReader("foobar");
+ out2 = new TestOutputStream();
+ IOPipe.create(in, out2).closeOut().run();
+ assertTrue(in.closed);
+ assertTrue(out2.closed);
+ assertEquals("foobar", out.toString());
+
+ in = new TestReader("foobar");
+ out2 = new TestOutputStream();
+ IOPipe.create(in, out2).close(false, true).run();
+ assertFalse(in.closed);
+ assertTrue(out2.closed);
+ assertEquals("foobar", out.toString());
+
+ in2 = new TestInputStream("foobar");
+ out = new TestWriter();
+ IOPipe.create(in2, out).run();
+ assertTrue(in2.closed);
+ assertFalse(out.closed);
+ assertEquals("foobar", out2.toString());
+
+ in2 = new TestInputStream("foobar");
+ out = new TestWriter();
+ IOPipe.create(in2, out).closeOut().run();
+ assertTrue(in2.closed);
+ assertTrue(out.closed);
+ assertEquals("foobar", out2.toString());
+
+ in2 = new TestInputStream("foobar");
+ out = new TestWriter();
+ IOPipe.create(in2, out).close(false, true).run();
+ assertFalse(in2.closed);
+ assertTrue(out.closed);
+ assertEquals("foobar", out2.toString());
+ }
+
+
+ public static class TestReader extends StringReader {
+ boolean closed;
+
+ public TestReader(String s) {
+ super(s);
+ }
+
+ @Override /* Reader */
+ public void close() {
+ closed = true;
+ }
+ }
+
+ public static class TestWriter extends StringWriter {
+ boolean closed;
+
+ public TestWriter() {
+ super();
+ }
+
+ @Override /* Writer */
+ public void close() {
+ closed = true;
+ }
+ }
+
+ public static class TestInputStream extends ByteArrayInputStream {
+ boolean closed;
+
+ public TestInputStream(String s) {
+ super(s.getBytes());
+ }
+
+ @Override /* InputStream */
+ public void close() throws IOException {
+ super.close();
+ closed = true;
+ }
+ }
+
+ public static class TestOutputStream extends ByteArrayOutputStream {
+ boolean closed;
+
+ public TestOutputStream() {
+ super();
+ }
+
+ @Override /* OutputStream */
+ public void close() throws IOException {
+ super.close();
+ closed = true;
+ }
+
+ @Override /* Object */
+ public String toString() {
+ return new String(this.toByteArray(), IOUtils.UTF8);
+ }
+ }
+
+ //====================================================================================================
+ // byLines()
+ // byLines(boolean)
+ //====================================================================================================
+ @Test
+ public void testByLines() throws Exception {
+ TestReader in;
+ TestWriter out;
+
+ in = new TestReader("foo\nbar");
+ out = new TestWriter() {
+ @Override public void write(String s) {
+ super.write("["+s+"]");
+ }
+ };
+ IOPipe.create(in, out).byLines().run();
+ assertEquals("[foo][][bar][]", out.toString().replaceAll("[\\r\\n]", ""));
+
+ in = new TestReader("foo\nbar");
+ out = new TestWriter() {
+ @Override public void write(String s) {
+ super.write("["+s+"]");
+ }
+ };
+ IOPipe.create(in, out).byLines(true).run();
+ assertEquals("[foo][][bar][]", out.toString().replaceAll("[\\r\\n]", ""));
+
+ in = new TestReader("foo\nbar");
+ out = new TestWriter() {
+ @Override public void write(String s) {
+ super.write("["+s+"]");
+ }
+ };
+ IOPipe.create(in, out).byLines(false).run();
+ assertEquals("foo\nbar", out.toString());
+ }
+
+ //====================================================================================================
+ // lineProcessor()
+ //====================================================================================================
+ @Test
+ public void testLineProcessor() throws Exception {
+ TestReader in;
+ TestWriter out;
+ LineProcessor lp = new LineProcessor() {
+ @Override /* LineProcessor */
+ public String process(String line) {
+ return "[" + line + "]";
+ }
+ };
+
+ in = new TestReader("foo\nbar");
+ out = new TestWriter();
+ IOPipe.create(in, out).lineProcessor(lp).run();
+ assertEquals("[foo][bar]", out.toString().replaceAll("[\\r\\n]", ""));
+
+ LineProcessor lp2 = new LineProcessor() {
+ @Override /* LineProcessor */
+ public String process(String line) {
+ return line.equals("foo") ? null : line;
+ }
+ };
+ in = new TestReader("foo\nbar");
+ out = new TestWriter();
+ IOPipe.create(in, out).lineProcessor(lp2).run();
+ assertEquals("bar", out.toString().replaceAll("[\\r\\n]", ""));
+
+ TestInputStream in2;
+ TestOutputStream out2;
+ in2 = new TestInputStream("foo\nbar");
+ out2 = new TestOutputStream();
+ IOPipe.create(in2, out2).lineProcessor(lp).run();
+ assertEquals("[foo][bar]", out2.toString().replaceAll("[\\r\\n]", ""));
+ }
+
+ //====================================================================================================
+ // buffSize()
+ //====================================================================================================
+ @Test
+ public void testBuffSize() throws Exception {
+ TestReader in;
+ TestWriter out;
+
+ in = new TestReader("foobar");
+ out = new TestWriter();
+ IOPipe.create(in, out).buffSize(1).run();
+ assertEquals("foobar", out.toString().replaceAll("[\\r\\n]", ""));
+
+ try { IOPipe.create(in, out).buffSize(0); fail(); } catch (IllegalArgumentException e) {}
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/utils/IOUtilsTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/utils/IOUtilsTest.java b/org.apache.juneau/src/test/java/org/apache/juneau/utils/IOUtilsTest.java
new file mode 100755
index 0000000..596d5bb
--- /dev/null
+++ b/org.apache.juneau/src/test/java/org/apache/juneau/utils/IOUtilsTest.java
@@ -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.juneau.utils;
+
+import static org.junit.Assert.*;
+
+import java.io.*;
+
+import org.apache.juneau.internal.*;
+import org.junit.*;
+
+public class IOUtilsTest {
+
+ //====================================================================================================
+ // read(File)
+ // read(InputStream, Charset)
+ // read(InputStream)
+ // read(Reader, int, int)
+ //====================================================================================================
+ @Test
+ public void testRead() throws Exception {
+
+ TestReader in;
+ TestWriter out;
+
+ in = new TestReader("foobar");
+ out = new TestWriter();
+ IOPipe.create(in, out).run();
+ assertTrue(in.closed);
+ assertFalse(out.closed);
+ assertEquals("foobar", out.toString());
+ }
+
+
+ public static class TestReader extends StringReader {
+ boolean closed;
+
+ public TestReader(String s) {
+ super(s);
+ }
+
+ @Override /* Reader */
+ public void close() {
+ closed = true;
+ }
+ }
+
+ public static class TestWriter extends StringWriter {
+ boolean closed;
+
+ public TestWriter() {
+ super();
+ }
+
+ @Override /* Writer */
+ public void close() {
+ closed = true;
+ }
+ }
+
+ public static class TestInputStream extends ByteArrayInputStream {
+ boolean closed;
+
+ public TestInputStream(String s) {
+ super(s.getBytes());
+ }
+
+ @Override /* InputStream */
+ public void close() throws IOException {
+ super.close();
+ closed = true;
+ }
+ }
+
+ public static class TestOutputStream extends ByteArrayOutputStream {
+ boolean closed;
+
+ public TestOutputStream() {
+ super();
+ }
+
+ @Override /* OutputStream */
+ public void close() throws IOException {
+ super.close();
+ closed = true;
+ }
+
+ @Override /* Object */
+ public String toString() {
+ return new String(this.toByteArray(), IOUtils.UTF8);
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/utils/IdentityListTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/utils/IdentityListTest.java b/org.apache.juneau/src/test/java/org/apache/juneau/utils/IdentityListTest.java
new file mode 100755
index 0000000..e554e49
--- /dev/null
+++ b/org.apache.juneau/src/test/java/org/apache/juneau/utils/IdentityListTest.java
@@ -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.juneau.utils;
+
+import static org.junit.Assert.*;
+
+import java.util.*;
+
+import org.apache.juneau.internal.*;
+import org.junit.*;
+
+public class IdentityListTest {
+
+ //====================================================================================================
+ // test - Basic tests
+ //====================================================================================================
+ @Test
+ public void test() throws Exception {
+ List<String> l = new IdentityList<String>();
+ String a = "a";
+ l.add(a);
+ l.add(a);
+ l.add("b");
+ assertEquals(2, l.size());
+ assertTrue(l.contains("a"));
+ assertFalse(l.contains("c"));
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/utils/KeywordStoreTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/utils/KeywordStoreTest.java b/org.apache.juneau/src/test/java/org/apache/juneau/utils/KeywordStoreTest.java
new file mode 100755
index 0000000..b267b06
--- /dev/null
+++ b/org.apache.juneau/src/test/java/org/apache/juneau/utils/KeywordStoreTest.java
@@ -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.juneau.utils;
+
+import static org.junit.Assert.*;
+
+import org.apache.juneau.internal.*;
+import org.junit.*;
+
+public class KeywordStoreTest {
+
+ //====================================================================================================
+ // test - Basic tests
+ //====================================================================================================
+ @Test
+ public void test() throws Exception {
+ KeywordSet ks = new KeywordSet("aaa", "zzz");
+ assertTrue(ks.contains("aaa"));
+ assertTrue(ks.contains("zzz"));
+ assertFalse(ks.contains("xxx"));
+ assertFalse(ks.contains("aaaa"));
+ assertFalse(ks.contains("zzzz"));
+ assertFalse(ks.contains("\u0000\u1000"));
+ assertFalse(ks.contains("z"));
+ assertFalse(ks.contains(null));
+ assertFalse(ks.contains("a|"));
+ assertFalse(ks.contains("|a"));
+ assertFalse(ks.contains("Aa"));
+ assertFalse(ks.contains("aA"));
+
+ for (String s : new String[]{"a","aA","Aa","a|","|a"}) {
+ try { ks = new KeywordSet(s); fail(); } catch (IllegalArgumentException e) {}
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/utils/MultiIterableTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/utils/MultiIterableTest.java b/org.apache.juneau/src/test/java/org/apache/juneau/utils/MultiIterableTest.java
new file mode 100755
index 0000000..2418b44
--- /dev/null
+++ b/org.apache.juneau/src/test/java/org/apache/juneau/utils/MultiIterableTest.java
@@ -0,0 +1,70 @@
+/***************************************************************************************************************************
+ * 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.juneau.utils;
+
+import static org.apache.juneau.TestUtils.*;
+import static org.junit.Assert.*;
+
+import java.util.*;
+
+import org.apache.juneau.*;
+import org.apache.juneau.internal.*;
+import org.junit.*;
+
+public class MultiIterableTest {
+
+ //====================================================================================================
+ // Basic tests
+ //====================================================================================================
+ @SuppressWarnings({ "unchecked", "rawtypes" })
+ @Test
+ public void test() throws Exception {
+ List
+ l1 = new ObjectList(),
+ l2 = new ObjectList("['a','b']"),
+ l3 = new ObjectList("['c']");
+
+ MultiIterable mi = new MultiIterable(l1.iterator(),l2.iterator());
+ mi.append(l3.iterator());
+
+ assertObjectEquals("['a','b','c']", mi.iterator());
+
+ mi = new MultiIterable(l1.iterator());
+ assertObjectEquals("[]", mi.iterator());
+
+ mi = new MultiIterable(l2.iterator(), l1.iterator());
+ assertObjectEquals("['a','b']", mi.iterator());
+
+ mi = new MultiIterable(l2.iterator(), l1.iterator(), l3.iterator());
+ assertObjectEquals("['a','b','c']", mi.iterator());
+
+ mi = new MultiIterable();
+ assertObjectEquals("[]", mi.iterator());
+
+ try { mi.append(null); fail(); } catch (IllegalArgumentException e) {}
+
+ mi = new MultiIterable(l1.iterator());
+ try { mi.iterator().next(); fail(); } catch (NoSuchElementException e) {}
+
+ mi = new MultiIterable(l1.iterator());
+ Iterator i = mi.iterator();
+ assertFalse(i.hasNext());
+ try { i.remove(); fail(); } catch (NoSuchElementException e) {}
+
+ mi = new MultiIterable(l2.iterator());
+ i = mi.iterator();
+ assertTrue(i.hasNext());
+ assertEquals("a", i.next());
+ i.remove();
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/utils/MultiSetTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/utils/MultiSetTest.java b/org.apache.juneau/src/test/java/org/apache/juneau/utils/MultiSetTest.java
new file mode 100755
index 0000000..4d6d927
--- /dev/null
+++ b/org.apache.juneau/src/test/java/org/apache/juneau/utils/MultiSetTest.java
@@ -0,0 +1,143 @@
+/***************************************************************************************************************************
+ * 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.juneau.utils;
+
+import static org.apache.juneau.TestUtils.*;
+import static org.junit.Assert.*;
+
+import java.util.*;
+
+import org.apache.juneau.internal.*;
+import org.junit.*;
+
+public class MultiSetTest {
+
+ @Test
+ @SuppressWarnings({ "unchecked" })
+ public void doTest() throws Exception {
+ List<String> l1, l2;
+ MultiSet<String> ms;
+ Iterator<String> i;
+
+ l1 = Arrays.asList(new String[]{"1","2"});
+ l2 = Arrays.asList(new String[]{"3","4"});
+ ms = new MultiSet<String>(l1, l2);
+ i = ms.iterator();
+ assertTrue(i.hasNext());
+ assertEquals("1", i.next());
+ assertTrue(i.hasNext());
+ assertEquals("2", i.next());
+ assertTrue(i.hasNext());
+ assertEquals("3", i.next());
+ assertTrue(i.hasNext());
+ assertEquals("4", i.next());
+ assertFalse(i.hasNext());
+ try {
+ i.next();
+ fail("Exception expected");
+ } catch (NoSuchElementException e) {
+ }
+
+ l1 = Arrays.asList(new String[]{"1","2"});
+ l2 = Arrays.asList(new String[]{});
+ ms = new MultiSet<String>(l1, l2);
+ i = ms.iterator();
+ assertTrue(i.hasNext());
+ assertEquals("1", i.next());
+ assertTrue(i.hasNext());
+ assertEquals("2", i.next());
+ assertFalse(i.hasNext());
+ try {
+ i.next();
+ fail("Exception expected");
+ } catch (NoSuchElementException e) {
+ }
+
+ l1 = Arrays.asList(new String[]{});
+ l2 = Arrays.asList(new String[]{"3","4"});
+ ms = new MultiSet<String>(l1, l2);
+ i = ms.iterator();
+ assertTrue(i.hasNext());
+ assertEquals("3", i.next());
+ assertTrue(i.hasNext());
+ assertEquals("4", i.next());
+ assertFalse(i.hasNext());
+ try {
+ i.next();
+ fail("Exception expected");
+ } catch (NoSuchElementException e) {
+ }
+
+ l1 = Arrays.asList(new String[]{});
+ l2 = Arrays.asList(new String[]{});
+ ms = new MultiSet<String>(l1, l2);
+ i = ms.iterator();
+ assertFalse(i.hasNext());
+ try {
+ i.next();
+ fail("Exception expected");
+ } catch (NoSuchElementException e) {
+ }
+
+ l1 = Arrays.asList(new String[]{"1","2"});
+ ms = new MultiSet<String>(l1);
+ i = ms.iterator();
+ assertTrue(i.hasNext());
+ assertEquals("1", i.next());
+ assertTrue(i.hasNext());
+ assertEquals("2", i.next());
+ assertFalse(i.hasNext());
+ try {
+ i.next();
+ fail("Exception expected");
+ } catch (NoSuchElementException e) {
+ }
+
+ l1 = new LinkedList<String>(Arrays.asList(new String[]{"1","2"}));
+ l2 = new LinkedList<String>(Arrays.asList(new String[]{"3","4"}));
+ ms = new MultiSet<String>(l1).append(l2);
+ assertObjectEquals("['1','2','3','4']", ms);
+ assertObjectEquals("['1','2','3','4']", ms.enumerator());
+ assertEquals(4, ms.size());
+
+ Iterator<String> t = ms.iterator();
+ t.next();
+ t.remove();
+ assertObjectEquals("['2','3','4']", ms.enumerator());
+
+ t = ms.iterator();
+ t.next();
+ t.remove();
+ assertObjectEquals("['3','4']", ms.enumerator());
+
+ t = ms.iterator();
+ t.next();
+ t.remove();
+ assertObjectEquals("['4']", ms.enumerator());
+
+ t = ms.iterator();
+ t.next();
+ t.remove();
+ assertObjectEquals("[]", ms.enumerator());
+ assertEquals(0, ms.size());
+
+ ms = new MultiSet<String>();
+ assertObjectEquals("[]", ms);
+ assertEquals(0, ms.size());
+
+ try { ms = new MultiSet<String>((Collection<String>)null); fail(); } catch (IllegalArgumentException e) {}
+ try { new MultiSet<String>().iterator().next(); fail(); } catch (NoSuchElementException e) {}
+ try { new MultiSet<String>().iterator().remove(); fail(); } catch (NoSuchElementException e) {}
+
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/utils/ParserReaderTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/utils/ParserReaderTest.java b/org.apache.juneau/src/test/java/org/apache/juneau/utils/ParserReaderTest.java
new file mode 100755
index 0000000..c4b7e01
--- /dev/null
+++ b/org.apache.juneau/src/test/java/org/apache/juneau/utils/ParserReaderTest.java
@@ -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.juneau.utils;
+
+import static org.junit.Assert.*;
+
+import org.apache.juneau.parser.*;
+import org.junit.*;
+
+public class ParserReaderTest {
+
+ //====================================================================================================
+ // test
+ //====================================================================================================
+ @Test
+ public void test() throws Exception {
+ ParserReader r = new ParserReader("abc123");
+ try {
+ assertEquals('a', r.read());
+ r.unread();
+ assertEquals('a', r.read());
+ assertEquals('b', r.read());
+ r.unread();
+ assertEquals("bc", r.read(2));
+ assertEquals('1', r.read());
+ r.unread();
+ r.read();
+ assertEquals('2', r.peek());
+ assertEquals('2', r.peek());
+ assertEquals('2', r.read());
+ assertEquals('3', r.read());
+ assertEquals(-1, r.read());
+ assertEquals(-1, r.read());
+ } finally {
+ r.close();
+ }
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/utils/PojoIntrospectorTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/utils/PojoIntrospectorTest.java b/org.apache.juneau/src/test/java/org/apache/juneau/utils/PojoIntrospectorTest.java
new file mode 100755
index 0000000..e6f3868
--- /dev/null
+++ b/org.apache.juneau/src/test/java/org/apache/juneau/utils/PojoIntrospectorTest.java
@@ -0,0 +1,53 @@
+/***************************************************************************************************************************
+ * 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.juneau.utils;
+
+import static org.junit.Assert.*;
+
+import org.junit.*;
+
+public class PojoIntrospectorTest {
+
+ //====================================================================================================
+ // testBasic
+ //====================================================================================================
+ @Test
+ public void testBasic() throws Exception {
+ String in = null;
+ Object r;
+
+ r = new PojoIntrospector(in, null).invokeMethod("substring(int,int)", "[3,6]");
+ assertNull(r);
+
+ in = "foobar";
+ r = new PojoIntrospector(in).invokeMethod("substring(int,int)", "[3,6]");
+ assertEquals("bar", r);
+
+ r = new PojoIntrospector(in).invokeMethod("toString", null);
+ assertEquals("foobar", r);
+
+ r = new PojoIntrospector(in).invokeMethod("toString", "");
+ assertEquals("foobar", r);
+
+ r = new PojoIntrospector(in).invokeMethod("toString", "[]");
+ assertEquals("foobar", r);
+
+ try { new PojoIntrospector(in).invokeMethod("noSuchMethod", "[3,6]"); fail(); } catch (NoSuchMethodException e) {}
+
+ r = new PojoIntrospector(null).invokeMethod(String.class.getMethod("toString"), null);
+ assertNull(r);
+
+ r = new PojoIntrospector("foobar").invokeMethod(String.class.getMethod("toString"), null);
+ assertEquals("foobar", r);
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/utils/PojoQueryTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/utils/PojoQueryTest.java b/org.apache.juneau/src/test/java/org/apache/juneau/utils/PojoQueryTest.java
new file mode 100755
index 0000000..3c405a3
--- /dev/null
+++ b/org.apache.juneau/src/test/java/org/apache/juneau/utils/PojoQueryTest.java
@@ -0,0 +1,680 @@
+/***************************************************************************************************************************
+ * 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.juneau.utils;
+
+import static org.apache.juneau.TestUtils.*;
+import static org.junit.Assert.*;
+
+import java.util.*;
+
+import org.apache.juneau.*;
+import org.apache.juneau.json.*;
+import org.apache.juneau.serializer.*;
+import org.apache.juneau.transforms.*;
+import org.junit.*;
+
+@SuppressWarnings({"serial","rawtypes"})
+public class PojoQueryTest {
+
+ //====================================================================================================
+ // filterCollection, string search, 1 level
+ //====================================================================================================
+ @Test
+ public void testFilterCollectionStringSearchOneLevel() throws Exception {
+ ObjectMap query = null;
+ List view = null;
+ List sort = null;
+ int pos = 0;
+ int limit = 0;
+ boolean ignoreCase = false;
+ BeanContext bc = BeanContext.DEFAULT;
+ List results;
+
+ List<A> in = new LinkedList<A>() {{
+ add(new A("foo"));
+ add(new A("bar"));
+ add(new A("baz"));
+ }};
+
+ PojoQuery filter = new PojoQuery(in, bc);
+
+ query = new ObjectMap("{f:'foo'}");
+ results = filter.filterCollection(query, view, sort, pos, limit, ignoreCase);
+ assertObjectEquals("[{f:'foo'}]", results);
+
+ query = new ObjectMap("{f:'fo*'}");
+ results = filter.filterCollection(query, view, sort, pos, limit, ignoreCase);
+ assertObjectEquals("[{f:'foo'}]", results);
+
+ query = new ObjectMap("{f:'*ar'}");
+ results = filter.filterCollection(query, view, sort, pos, limit, ignoreCase);
+ assertObjectEquals("[{f:'bar'}]", results);
+
+ query = new ObjectMap("{f:'foo bar'}");
+ results = filter.filterCollection(query, view, sort, pos, limit, ignoreCase);
+ assertObjectEquals("[{f:'foo'},{f:'bar'}]", results);
+ }
+
+ public class A {
+ public String f;
+
+ A() {}
+
+ A(String f) {
+ this.f = f;
+ }
+ }
+
+ //====================================================================================================
+ // filterCollection, date search, 1 level
+ //====================================================================================================
+ @Test
+ public void testFilterCollectionDateSearchOneLevel() throws Exception {
+ ObjectMap query = null;
+ List view = null;
+ List sort = null;
+ int pos = 0;
+ int limit = 0;
+ boolean ignoreCase = false;
+ BeanContext bc = BeanContext.DEFAULT;
+ WriterSerializer s = new JsonSerializer.Simple().addTransforms(CalendarTransform.Simple.class);
+ B[] in;
+ PojoQuery filter;
+
+ List results;
+
+ in = new B[] {
+ new B(2010, 0, 1),
+ new B(2011, 0, 1),
+ new B(2011, 0, 31),
+ new B(2012, 0, 1)
+ };
+ filter = new PojoQuery(in, bc);
+
+ query = new ObjectMap("{f:'2011'}");
+ results = filter.filterCollection(query, view, sort, pos, limit, ignoreCase);
+ assertEquals("[{f:'2011/01/01 00:00:00'},{f:'2011/01/31 00:00:00'}]", s.serialize(results));
+
+ query = new ObjectMap("{f:'2011.01'}");
+ results = filter.filterCollection(query, view, sort, pos, limit, ignoreCase);
+ assertEquals("[{f:'2011/01/01 00:00:00'},{f:'2011/01/31 00:00:00'}]", s.serialize(results));
+
+ query = new ObjectMap("{f:'2011.01.01'}");
+ results = filter.filterCollection(query, view, sort, pos, limit, ignoreCase);
+ assertEquals("[{f:'2011/01/01 00:00:00'}]", s.serialize(results));
+
+ in = new B[] {
+ new B(2011, 00, 01, 11, 59, 59),
+ new B(2011, 00, 01, 12, 00, 00),
+ new B(2011, 00, 01, 12, 59, 59),
+ new B(2011, 00, 01, 13, 00, 00)
+ };
+ filter = new PojoQuery(in, bc);
+
+ query = new ObjectMap("{f:'2011.01.01.12'}");
+ results = filter.filterCollection(query, view, sort, pos, limit, ignoreCase);
+ assertEquals("[{f:'2011/01/01 12:00:00'},{f:'2011/01/01 12:59:59'}]", s.serialize(results));
+
+ in = new B[] {
+ new B(2011, 00, 01, 12, 29, 59),
+ new B(2011, 00, 01, 12, 30, 00),
+ new B(2011, 00, 01, 12, 30, 59),
+ new B(2011, 00, 01, 12, 31, 00)
+ };
+ filter = new PojoQuery(in, bc);
+ query = new ObjectMap("{f:'2011.01.01.12.30'}");
+ results = filter.filterCollection(query, view, sort, pos, limit, ignoreCase);
+ assertEquals("[{f:'2011/01/01 12:30:00'},{f:'2011/01/01 12:30:59'}]", s.serialize(results));
+
+ in = new B[] {
+ new B(2011, 00, 01, 12, 30, 29),
+ new B(2011, 00, 01, 12, 30, 30),
+ new B(2011, 00, 01, 12, 30, 31)
+ };
+ filter = new PojoQuery(in, bc);
+ query = new ObjectMap("{f:'2011.01.01.12.30.30'}");
+ results = filter.filterCollection(query, view, sort, pos, limit, ignoreCase);
+ assertEquals("[{f:'2011/01/01 12:30:30'}]", s.serialize(results));
+
+ // Open-ended ranges
+
+ in = new B[] {
+ new B(2000, 11, 31),
+ new B(2001, 00, 01)
+ };
+ filter = new PojoQuery(in, bc);
+
+ query = new ObjectMap("{f:'>2000'}");
+ results = filter.filterCollection(query, view, sort, pos, limit, ignoreCase);
+ assertEquals("[{f:'2001/01/01 00:00:00'}]", s.serialize(results));
+
+ query = new ObjectMap("{f:'>=2001'}");
+ results = filter.filterCollection(query, view, sort, pos, limit, ignoreCase);
+ assertEquals("[{f:'2001/01/01 00:00:00'}]", s.serialize(results));
+
+ query = new ObjectMap("{f:'<2001'}");
+ results = filter.filterCollection(query, view, sort, pos, limit, ignoreCase);
+ assertEquals("[{f:'2000/12/31 00:00:00'}]", s.serialize(results));
+
+ query = new ObjectMap("{f:'<=2000'}");
+ results = filter.filterCollection(query, view, sort, pos, limit, ignoreCase);
+ assertEquals("[{f:'2000/12/31 00:00:00'}]", s.serialize(results));
+
+ in = new B[] {
+ new B(2011, 00, 01, 12, 29, 59),
+ new B(2011, 00, 01, 12, 30, 00)
+ };
+ filter = new PojoQuery(in, bc);
+
+ query = new ObjectMap("{f:'>=2011.01.01.12.30'}");
+ results = filter.filterCollection(query, view, sort, pos, limit, ignoreCase);
+ assertEquals("[{f:'2011/01/01 12:30:00'}]", s.serialize(results));
+
+ query = new ObjectMap("{f:'<2011.01.01.12.30'}");
+ results = filter.filterCollection(query, view, sort, pos, limit, ignoreCase);
+ assertEquals("[{f:'2011/01/01 12:29:59'}]", s.serialize(results));
+
+ in = new B[] {
+ new B(2011, 00, 01, 12, 30, 59),
+ new B(2011, 00, 01, 12, 31, 00)
+ };
+ filter = new PojoQuery(in, bc);
+
+ query = new ObjectMap("{f:'>2011.01.01.12.30'}");
+ results = filter.filterCollection(query, view, sort, pos, limit, ignoreCase);
+ assertEquals("[{f:'2011/01/01 12:31:00'}]", s.serialize(results));
+
+ query = new ObjectMap("{f:'<=2011.01.01.12.30'}");
+ results = filter.filterCollection(query, view, sort, pos, limit, ignoreCase);
+ assertEquals("[{f:'2011/01/01 12:30:59'}]", s.serialize(results));
+
+ // Closed range
+
+ in = new B[] {
+ new B(2000, 11, 31, 23, 59, 59),
+ new B(2001, 00, 01, 00, 00, 00),
+ new B(2003, 05, 30, 23, 59, 59),
+ new B(2003, 06, 01, 00, 00, 00)
+ };
+ filter = new PojoQuery(in, bc);
+
+ query = new ObjectMap("{f:'2001 - 2003.06.30'}");
+ results = filter.filterCollection(query, view, sort, pos, limit, ignoreCase);
+ assertEquals("[{f:'2001/01/01 00:00:00'},{f:'2003/06/30 23:59:59'}]", s.serialize(results));
+
+ // ORed timestamps
+
+ in = new B[] {
+ new B(2000, 11, 31),
+ new B(2001, 00, 01),
+ new B(2001, 11, 31),
+ new B(2002, 00, 01)
+ };
+ filter = new PojoQuery(in, bc);
+
+ query = new ObjectMap("{f:'2001 2003 2005'}");
+ results = filter.filterCollection(query, view, sort, pos, limit, ignoreCase);
+ assertEquals("[{f:'2001/01/01 00:00:00'},{f:'2001/12/31 00:00:00'}]", s.serialize(results));
+
+ in = new B[] {
+ new B(2002, 11, 31),
+ new B(2003, 00, 01),
+ new B(2003, 11, 31),
+ new B(2004, 00, 01)
+ };
+ filter = new PojoQuery(in, bc);
+
+ query = new ObjectMap("{f:'2001 2003 2005'}");
+ results = filter.filterCollection(query, view, sort, pos, limit, ignoreCase);
+ assertEquals("[{f:'2003/01/01 00:00:00'},{f:'2003/12/31 00:00:00'}]", s.serialize(results));
+
+ in = new B[] {
+ new B(2004, 11, 31),
+ new B(2005, 00, 01),
+ new B(2005, 11, 31),
+ new B(2006, 00, 01)
+ };
+ filter = new PojoQuery(in, bc);
+
+ query = new ObjectMap("{f:'2001 2003 2005'}");
+ results = filter.filterCollection(query, view, sort, pos, limit, ignoreCase);
+ assertEquals("[{f:'2005/01/01 00:00:00'},{f:'2005/12/31 00:00:00'}]", s.serialize(results));
+ }
+
+ public class B {
+ public Calendar f;
+
+ B() {}
+
+ B(int year, int month, int day) {
+ this.f = new GregorianCalendar(year, month, day);
+ }
+
+ B(int year, int month, int day, int hour, int minute, int second) {
+ this.f = new GregorianCalendar(year, month, day, hour, minute, second);
+ }
+ }
+
+ //====================================================================================================
+ // filterCollection, int search, 1 level
+ //====================================================================================================
+ @Test
+ public void testFilterCollectionIntSearchOneLevel() throws Exception {
+ ObjectMap query = null;
+ List view = null;
+ List sort = null;
+ int pos = 0;
+ int limit = 0;
+ boolean ignoreCase = false;
+ BeanContext bc = BeanContext.DEFAULT;
+ List results;
+
+ List<C> in = new LinkedList<C>() {{
+ add(new C(1));
+ add(new C(2));
+ add(new C(3));
+ }};
+
+ PojoQuery filter = new PojoQuery(in, bc);
+
+ query = new ObjectMap("{f:'1'}");
+ results = filter.filterCollection(query, view, sort, pos, limit, ignoreCase);
+ assertObjectEquals("[{f:1}]", results);
+
+ query = new ObjectMap("{f:'>1'}");
+ results = filter.filterCollection(query, view, sort, pos, limit, ignoreCase);
+ assertObjectEquals("[{f:2},{f:3}]", results);
+
+ query = new ObjectMap("{f:'>=2'}");
+ results = filter.filterCollection(query, view, sort, pos, limit, ignoreCase);
+ assertObjectEquals("[{f:2},{f:3}]", results);
+
+ query = new ObjectMap("{f:'<=2'}");
+ results = filter.filterCollection(query, view, sort, pos, limit, ignoreCase);
+ assertObjectEquals("[{f:1},{f:2}]", results);
+
+ query = new ObjectMap("{f:'<2'}");
+ results = filter.filterCollection(query, view, sort, pos, limit, ignoreCase);
+ assertObjectEquals("[{f:1}]", results);
+
+ query = new ObjectMap("{f:'1 3'}");
+ results = filter.filterCollection(query, view, sort, pos, limit, ignoreCase);
+ assertObjectEquals("[{f:1},{f:3}]", results);
+ }
+
+ public class C {
+ public int f;
+
+ C() {}
+
+ C(int f) {
+ this.f = f;
+ }
+ }
+
+ //====================================================================================================
+ // filterCollection, string search, 2 level
+ //====================================================================================================
+ @Test
+ public void testFilterCollectionStringSearchTwoLevel() throws Exception {
+ ObjectMap query = null;
+ List view = null;
+ List sort = null;
+ int pos = 0;
+ int limit = 0;
+ boolean ignoreCase = false;
+ BeanContext bc = BeanContext.DEFAULT;
+ List results;
+
+ List<D1> in = new LinkedList<D1>() {{
+ add(new D1("foo"));
+ add(new D1("bar"));
+ add(new D1("baz"));
+ }};
+
+ PojoQuery filter = new PojoQuery(in, bc);
+
+ query = new ObjectMap("{f:{f:'foo'}}");
+ results = filter.filterCollection(query, view, sort, pos, limit, ignoreCase);
+ assertObjectEquals("[{f:{f:'foo'}}]", results);
+
+ query = new ObjectMap("{f:{f:'fo*'}}");
+ results = filter.filterCollection(query, view, sort, pos, limit, ignoreCase);
+ assertObjectEquals("[{f:{f:'foo'}}]", results);
+
+ query = new ObjectMap("{f:{f:'*ar'}}");
+ results = filter.filterCollection(query, view, sort, pos, limit, ignoreCase);
+ assertObjectEquals("[{f:{f:'bar'}}]", results);
+
+ query = new ObjectMap("{f:{f:'foo bar'}}");
+ results = filter.filterCollection(query, view, sort, pos, limit, ignoreCase);
+ assertObjectEquals("[{f:{f:'foo'}},{f:{f:'bar'}}]", results);
+ }
+
+ public class D1 {
+ public D2 f;
+
+ D1() {}
+
+ D1(String f) {
+ this.f = new D2(f);
+ }
+ }
+ public class D2 {
+ public String f;
+
+ D2() {}
+
+ D2(String f) {
+ this.f = f;
+ }
+ }
+
+ //====================================================================================================
+ // filterCollection, view, 1 level
+ //====================================================================================================
+ @Test
+ public void testFilterCollectionViewOneLevel() throws Exception {
+ ObjectMap query = null;
+ List view = null;
+ List sort = null;
+ int pos = 0;
+ int limit = 0;
+ boolean ignoreCase = false;
+ BeanContext bc = BeanContext.DEFAULT;
+ List results;
+
+ List<E> in = new LinkedList<E>() {{
+ add(new E("foo", 1, true));
+ add(new E("bar", 2, false));
+ add(new E("baz", 3, true));
+ }};
+
+ PojoQuery filter = new PojoQuery(in, bc);
+
+ view = new ObjectList("['f1']");
+ results = filter.filterCollection(query, view, sort, pos, limit, ignoreCase);
+ assertObjectEquals("[{f1:'foo'},{f1:'bar'},{f1:'baz'}]", results);
+
+ view = new ObjectList("['f2']");
+ results = filter.filterCollection(query, view, sort, pos, limit, ignoreCase);
+ assertObjectEquals("[{f2:1},{f2:2},{f2:3}]", results);
+
+ view = new ObjectList("['f3']");
+ results = filter.filterCollection(query, view, sort, pos, limit, ignoreCase);
+ assertObjectEquals("[{f3:true},{f3:false},{f3:true}]", results);
+
+ view = new ObjectList("['f3','f2','f1']");
+ results = filter.filterCollection(query, view, sort, pos, limit, ignoreCase);
+ assertObjectEquals("[{f3:true,f2:1,f1:'foo'},{f3:false,f2:2,f1:'bar'},{f3:true,f2:3,f1:'baz'}]", results);
+ }
+
+ public class E {
+ public String f1;
+ public int f2;
+ public boolean f3;
+
+ E() {}
+
+ E(String f1, int f2, boolean f3) {
+ this.f1 = f1;
+ this.f2 = f2;
+ this.f3 = f3;
+ }
+ }
+
+ //====================================================================================================
+ // filterCollection, view, 2 level
+ //====================================================================================================
+ @Test
+ public void testFilterCollectionViewTwoLevel() throws Exception {
+ ObjectMap query = null;
+ List view = null;
+ List sort = null;
+ int pos = 0;
+ int limit = 0;
+ boolean ignoreCase = false;
+ BeanContext bc = BeanContext.DEFAULT;
+ List results;
+
+ List<F1> in = new LinkedList<F1>() {{
+ add(new F1("foo"));
+ add(new F1("bar"));
+ add(new F1("baz"));
+ }};
+
+ PojoQuery filter = new PojoQuery(in, bc);
+
+ view = new ObjectList("['f1']");
+ results = filter.filterCollection(query, view, sort, pos, limit, ignoreCase);
+ assertObjectEquals("[{f1:'foo'},{f1:'bar'},{f1:'baz'}]", results);
+
+ view = new ObjectList("[{f2:['f1']}]");
+ results = filter.filterCollection(query, view, sort, pos, limit, ignoreCase);
+ assertObjectEquals("[{f2:{f1:'f2_foo'}},{f2:{f1:'f2_bar'}},{f2:{f1:'f2_baz'}}]", results);
+
+ view = new ObjectList("['f1',{f3:['f1']}]");
+ results = filter.filterCollection(query, view, sort, pos, limit, ignoreCase);
+ assertObjectEquals("[{f1:'foo',f3:[{f1:'f31_foo'},{f1:'f32_foo'}]},{f1:'bar',f3:[{f1:'f31_bar'},{f1:'f32_bar'}]},{f1:'baz',f3:[{f1:'f31_baz'},{f1:'f32_baz'}]}]", results);
+ }
+
+ public class F1 {
+ public String f1;
+ public F2 f2;
+ public List<F2> f3;
+
+ F1() {}
+
+ F1(final String f1) {
+ this.f1 = f1;
+ this.f2 = new F2("f2_"+f1);
+ this.f3 = new LinkedList<F2>() {{
+ add(new F2("f31_"+f1));
+ add(new F2("f32_"+f1));
+ }};
+ }
+ }
+
+ public class F2 {
+ public String f1;
+ public String f2;
+
+ F2() {}
+
+ F2(String f1) {
+ this.f1 = f1;
+ this.f2 = f1;
+ }
+ }
+
+ //====================================================================================================
+ // filterMap, 1 level
+ //===================================================================================================
+ @Test
+ public void testFilterMapOneLevel() throws Exception {
+ ObjectList view = null;
+ BeanContext bc = BeanContext.DEFAULT;
+ Map results;
+
+ G in = new G("foo", 1, true);
+ PojoQuery filter = new PojoQuery(in, bc);
+
+ view = new ObjectList("['f1']");
+ results = filter.filterMap(view);
+ assertObjectEquals("{f1:'foo'}", results);
+
+ view = new ObjectList("['f2']");
+ results = filter.filterMap(view);
+ assertObjectEquals("{f2:1}", results);
+
+ view = new ObjectList("['f3','f1']");
+ results = filter.filterMap(view);
+ assertObjectEquals("{f3:true,f1:'foo'}", results);
+ }
+
+ public class G {
+ public String f1;
+ public int f2;
+ public boolean f3;
+
+ G() {}
+
+ G(String f1, int f2, boolean f3) {
+ this.f1 = f1;
+ this.f2 = f2;
+ this.f3 = f3;
+ }
+ }
+
+ //====================================================================================================
+ // filterMap, 2 level
+ //====================================================================================================
+ @Test
+ public void testFilterMapTwoLevel() throws Exception {
+ ObjectList view = null;
+ BeanContext bc = BeanContext.DEFAULT;
+ Map results;
+
+ H1 in = new H1("foo");
+
+ PojoQuery filter = new PojoQuery(in, bc);
+
+ view = new ObjectList("['f1']");
+ results = filter.filterMap(view);
+ assertObjectEquals("{f1:'foo'}", results);
+
+ view = new ObjectList("[{f2:['f1']}]");
+ results = filter.filterMap(view);
+ assertObjectEquals("{f2:{f1:'f2_foo'}}", results);
+
+ view = new ObjectList("['f1',{f3:['f1']}]");
+ results = filter.filterMap(view);
+ assertObjectEquals("{f1:'foo',f3:[{f1:'f31_foo'},{f1:'f32_foo'}]}", results);
+ }
+
+ public class H1 {
+ public String f1;
+ public H2 f2;
+ public List<H2> f3;
+
+ H1() {}
+
+ H1(final String f1) {
+ this.f1 = f1;
+ this.f2 = new H2("f2_"+f1);
+ this.f3 = new LinkedList<H2>() {{
+ add(new H2("f31_"+f1));
+ add(new H2("f32_"+f1));
+ }};
+ }
+ }
+
+ public class H2 {
+ public String f1;
+ public String f2;
+
+ H2() {}
+
+ H2(String f1) {
+ this.f1 = f1;
+ this.f2 = f1;
+ }
+ }
+
+ //====================================================================================================
+ // testSorting
+ //====================================================================================================
+ @Test
+ public void testSorting() throws Exception {
+ ObjectMap query = null;
+ List view = null;
+ List sort = null;
+ int pos = 0;
+ int limit = 0;
+ boolean ignoreCase = false;
+ BeanContext bc = BeanContext.DEFAULT;
+ WriterSerializer s = new JsonSerializer.Simple().addTransforms(CalendarTransform.Simple.class);
+ List results;
+
+ I[] in = new I[] {
+ new I(1, "foo", true, 2010, 1, 1),
+ new I(2, "bar", false, 2011, 1, 1),
+ new I(3, "baz", true, 2012, 1, 1),
+ };
+
+ PojoQuery filter = new PojoQuery(in, bc);
+
+ sort = new ObjectList("['f2']");
+ view = new ObjectList("['f1','f2']");
+ results = filter.filterCollection(query, view, sort, pos, limit, ignoreCase);
+ assertEquals("[{f1:2,f2:'bar'},{f1:3,f2:'baz'},{f1:1,f2:'foo'}]", s.serialize(results));
+
+ sort = new ObjectList("[{f2:'d'}]");
+ view = new ObjectList("['f1','f2']");
+ results = filter.filterCollection(query, view, sort, pos, limit, ignoreCase);
+ assertEquals("[{f1:1,f2:'foo'},{f1:3,f2:'baz'},{f1:2,f2:'bar'}]", s.serialize(results));
+
+ sort = new ObjectList("['f3']");
+ view = new ObjectList("['f1','f3']");
+ results = filter.filterCollection(query, view, sort, pos, limit, ignoreCase);
+ assertEquals("[{f1:2,f3:false},{f1:1,f3:true},{f1:3,f3:true}]", s.serialize(results));
+
+ sort = new ObjectList("['f3',{f1:'a'}]");
+ view = new ObjectList("['f1','f3']");
+ results = filter.filterCollection(query, view, sort, pos, limit, ignoreCase);
+ assertEquals("[{f1:2,f3:false},{f1:1,f3:true},{f1:3,f3:true}]", s.serialize(results));
+
+ sort = new ObjectList("['f3',{f1:'d'}]");
+ view = new ObjectList("['f1','f3']");
+ results = filter.filterCollection(query, view, sort, pos, limit, ignoreCase);
+ assertEquals("[{f1:2,f3:false},{f1:3,f3:true},{f1:1,f3:true}]", s.serialize(results));
+
+ sort = new ObjectList("['f1']");
+ view = new ObjectList("['f1']");
+ limit = 1;
+ pos = 0;
+ results = filter.filterCollection(query, view, sort, pos, limit, ignoreCase);
+ assertEquals("[{f1:1}]", s.serialize(results));
+
+ limit = 3;
+ pos = 0;
+ results = filter.filterCollection(query, view, sort, pos, limit, ignoreCase);
+ assertEquals("[{f1:1},{f1:2},{f1:3}]", s.serialize(results));
+
+ limit = 1;
+ pos = 2;
+ results = filter.filterCollection(query, view, sort, pos, limit, ignoreCase);
+ assertEquals("[{f1:3}]", s.serialize(results));
+
+ limit = 100;
+ pos = 2;
+ results = filter.filterCollection(query, view, sort, pos, limit, ignoreCase);
+ assertEquals("[{f1:3}]", s.serialize(results));
+ }
+
+ public class I {
+ public int f1;
+ public String f2;
+ public boolean f3;
+ public Calendar f4;
+
+ I() {}
+
+ I(int f1, String f2, boolean f3, int year, int month, int day) {
+ this.f1 = f1;
+ this.f2 = f2;
+ this.f3 = f3;
+ this.f4 = new GregorianCalendar(year, month, day);
+ }
+ }
+}
\ No newline at end of file
[43/44] incubator-juneau git commit: Rename CT_* testcases.
Posted by ja...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestCharsetEncodings.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestCharsetEncodings.java b/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestCharsetEncodings.java
deleted file mode 100755
index 3b34af6..0000000
--- a/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestCharsetEncodings.java
+++ /dev/null
@@ -1,96 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.server;
-
-import static javax.servlet.http.HttpServletResponse.*;
-import static org.apache.juneau.server.TestUtils.*;
-import static org.junit.Assert.*;
-
-import java.io.*;
-
-import org.apache.juneau.client.*;
-import org.apache.juneau.internal.*;
-import org.junit.*;
-
-
-public class CT_TestCharsetEncodings {
-
- private static boolean debug = false;
-
- /**
- * Basic tests to ensure that the correct charsets are found and used
- * under a variety of scenarios.
- */
- @Test
- public void test() throws Exception {
- String url = "/testCharsetEncodings";
- RestClient client = new TestRestClient().setAccept("text/s").setContentType("text/p");
- InputStream is;
- String r;
-
- r = client.doPut(url, new StringReader("foo")).getResponseAsString();
- if (debug) System.err.println(r);
- assertEquals("utf-8/foo/utf-8", r);
-
- is = client.doPut(url, new StringReader("foo")).getInputStream();
- r = IOUtils.read(new InputStreamReader(is, "utf-8"));
- if (debug) System.err.println(r);
- assertEquals("utf-8/foo/utf-8", r);
-
- client.setHeader("Accept-Charset", "utf-8").setContentType("text/p;charset=utf-8");
- is = client.doPut(url, new StringReader("foo")).getInputStream();
- r = IOUtils.read(new InputStreamReader(is, "utf-8"));
- if (debug) System.err.println(r);
- assertEquals("utf-8/foo/utf-8", r);
-
- client.setHeader("Accept-Charset", "Shift_JIS").setContentType("text/p;charset=shift_jis");
- is = client.doPut(url, new StringReader("foo")).getInputStream();
- r = IOUtils.read(new InputStreamReader(is, "Shift_JIS"));
- if (debug) System.err.println(r);
- assertEquals("shift_jis/foo/shift_jis", r);
-
- try {
- client.setHeader("Accept-Charset", "BAD").setContentType("text/p;charset=sjis");
- is = client.doPut(url + "?noTrace=true", new StringReader("foo")).getInputStream();
- r = IOUtils.read(new InputStreamReader(is, "sjis"));
- if (debug) System.err.println(r);
- fail("Exception expected");
- } catch (RestCallException e) {
- checkErrorResponse(debug, e, SC_NOT_ACCEPTABLE, "No supported charsets in header 'Accept-Charset': 'BAD'");
- }
-
- client.setAccept("text/s").setHeader("Accept-Charset", "utf-8").setContentType("text/p");
- is = client.doPut(url+"?Content-Type=text/p", new StringReader("foo")).getInputStream();
- r = IOUtils.read(new InputStreamReader(is, "utf-8"));
- if (debug) System.err.println(r);
- assertEquals("utf-8/foo/utf-8", r);
-
- client.setAccept("text/s").setContentType("text/bad").setHeader("Accept-Charset", "utf-8");
- is = client.doPut(url+"?Content-Type=text/p;charset=utf-8", new StringReader("foo")).getInputStream();
- r = IOUtils.read(new InputStreamReader(is, "utf-8"));
- if (debug) System.err.println(r);
- assertEquals("utf-8/foo/utf-8", r);
-
- try {
- client.setAccept("text/s").setContentType("text/p").setHeader("Accept-Charset", "utf-8");
- is = client.doPut(url+"?Content-Type=text/p;charset=BAD&noTrace=true", new StringReader("foo")).getInputStream();
- r = IOUtils.read(new InputStreamReader(is, "utf-8"));
- if (debug) System.err.println(r);
- assertEquals("utf-8/foo/utf-8", r);
- fail("Exception expected");
- } catch (RestCallException e) {
- checkErrorResponse(debug, e, SC_UNSUPPORTED_MEDIA_TYPE, "Unsupported charset in header 'Content-Type': 'text/p;charset=BAD'");
- }
- client.closeQuietly();
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestClientVersion.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestClientVersion.java b/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestClientVersion.java
deleted file mode 100644
index 253bcae..0000000
--- a/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestClientVersion.java
+++ /dev/null
@@ -1,90 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.server;
-
-import static org.junit.Assert.*;
-
-import org.apache.juneau.client.*;
-import org.apache.juneau.plaintext.*;
-import org.junit.*;
-
-public class CT_TestClientVersion {
-
- private static String URL = "/testClientVersion";
-
- //====================================================================================================
- // Basic tests - default X-Client-Version header.
- //====================================================================================================
- @Test
- public void testDefaultHeader() throws Exception {
- RestClient c = new TestRestClient(PlainTextSerializer.class, PlainTextParser.class);
- String url = URL + "/defaultHeader";
-
- assertEquals("no-version", c.doGet(url).getResponseAsString());
-
- for (String s : "0, 0.0, 0.1, .1, .9, .99".split("\\s*,\\s*")) {
- c.setClientVersion(s);
- assertEquals("[0.0,1.0)", c.doGet(url).getResponseAsString());
- }
-
- for (String s : "1, 1.0, 1.0.0, 1.0.1".split("\\s*,\\s*")) {
- c.setClientVersion(s);
- assertEquals("[1.0,1.0]", c.doGet(url).getResponseAsString());
- }
-
- for (String s : "1.1, 1.1.1, 1.2, 1.9.9".split("\\s*,\\s*")) {
- c.setClientVersion(s);
- assertEquals("[1.1,2)", c.doGet(url).getResponseAsString());
- }
-
- for (String s : "2, 2.0, 2.1, 9, 9.9".split("\\s*,\\s*")) {
- c.setClientVersion(s);
- assertEquals("2", c.doGet(url).getResponseAsString());
- }
-
- c.closeQuietly();
- }
-
- //====================================================================================================
- // Basic tests - Custom-Client-Version header.
- //====================================================================================================
- @Test
- public void testCustomHeader() throws Exception {
- RestClient c = new TestRestClient(PlainTextSerializer.class, PlainTextParser.class);
- String url = URL + "/customHeader";
-
- assertEquals("no-version", c.doGet(url).getResponseAsString());
-
- for (String s : "0, 0.0, 0.1, .1, .9, .99".split("\\s*,\\s*")) {
- c.setHeader("Custom-Client-Version", s);
- assertEquals("[0.0,1.0)", c.doGet(url).getResponseAsString());
- }
-
- for (String s : "1, 1.0, 1.0.0, 1.0.1".split("\\s*,\\s*")) {
- c.setHeader("Custom-Client-Version", s);
- assertEquals("[1.0,1.0]", c.doGet(url).getResponseAsString());
- }
-
- for (String s : "1.1, 1.1.1, 1.2, 1.9.9".split("\\s*,\\s*")) {
- c.setHeader("Custom-Client-Version", s);
- assertEquals("[1.1,2)", c.doGet(url).getResponseAsString());
- }
-
- for (String s : "2, 2.0, 2.1, 9, 9.9".split("\\s*,\\s*")) {
- c.setHeader("Custom-Client-Version", s);
- assertEquals("2", c.doGet(url).getResponseAsString());
- }
-
- c.closeQuietly();
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestConfig.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestConfig.java b/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestConfig.java
deleted file mode 100755
index d2e4844..0000000
--- a/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestConfig.java
+++ /dev/null
@@ -1,58 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.server;
-
-import static org.apache.juneau.server.TestUtils.*;
-import static org.junit.Assert.*;
-
-import org.apache.juneau.client.*;
-import org.apache.juneau.ini.*;
-import org.apache.juneau.json.*;
-import org.junit.*;
-
-public class CT_TestConfig {
-
- private static String URL = "/testConfig";
-
- //====================================================================================================
- // Basic tests
- //====================================================================================================
- @Test
- public void test() throws Exception {
- RestClient c = new TestRestClient(JsonSerializer.class, JsonParser.class).setAccept("text/json+simple");
-
- ConfigFile cf = c.doGet(URL).getResponse(ConfigFileImpl.class);
-
- assertObjectEquals("{int1:'1',int2:'1,2,3',int3:'$C{Test/int1, -1}',int4:'$C{Test/int3, -1}',int5:'$C{XXX, -1}',boolean1:'true',boolean2:'true,true',path:'$E{PATH}',mainClass:'$MF{Main-Class}',importPackage:'$MF{Import-Package}'}", cf.get("Test"));
-
- assertEquals("'1'", c.doGet(URL + "/Test%2Fint1/" + getName(String.class)).getResponseAsString());
- assertEquals("['1']", c.doGet(URL + "/Test%2Fint1/" + getName(String[].class)).getResponseAsString());
- assertEquals("'1,2,3'", c.doGet(URL + "/Test%2Fint2/" + getName(String.class)).getResponseAsString());
- assertEquals("['1','2','3']", c.doGet(URL + "/Test%2Fint2/" + getName(String[].class)).getResponseAsString());
- assertEquals("[1,2,3]", c.doGet(URL + "/Test%2Fint2/" + getName(int[].class)).getResponseAsString());
- assertEquals("[1,2,3]", c.doGet(URL + "/Test%2Fint2/" + getName(Integer[].class)).getResponseAsString());
- assertEquals("[1]", c.doGet(URL + "/Test%2Fint3/" + getName(int[].class)).getResponseAsString());
- assertEquals("[1]", c.doGet(URL + "/Test%2Fint4/" + getName(int[].class)).getResponseAsString());
- assertEquals("[-1]", c.doGet(URL + "/Test%2Fint5/" + getName(int[].class)).getResponseAsString());
- assertEquals("true", c.doGet(URL + "/Test%2Fboolean1/" + getName(Boolean.class)).getResponseAsString());
- assertEquals("[true,true]", c.doGet(URL + "/Test%2Fboolean2/" + getName(Boolean[].class)).getResponseAsString());
- assertTrue(c.doGet(URL + "/Test%2Fpath/" + getName(String.class)).getResponseAsString().length() > 10);
- assertEquals("'org.apache.juneau.microservice.RestMicroservice'", c.doGet(URL + "/Test%2FmainClass/" + getName(String.class)).getResponseAsString());
-
- c.closeQuietly();
- }
-
- private String getName(Class<?> c) {
- return RestUtils.encode(c.getName());
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestContent.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestContent.java b/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestContent.java
deleted file mode 100755
index 5e3546a..0000000
--- a/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestContent.java
+++ /dev/null
@@ -1,706 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.server;
-
-import static org.junit.Assert.*;
-
-import java.io.*;
-import java.net.*;
-
-import org.apache.juneau.client.*;
-import org.apache.juneau.json.*;
-import org.apache.juneau.plaintext.*;
-import org.apache.juneau.urlencoding.*;
-import org.junit.*;
-
-public class CT_TestContent {
-
- private static String URL = "/testContent";
-
- //====================================================================================================
- // Basic tests using &Content parameter
- //====================================================================================================
- @Test
- public void testUsingContentParam() throws Exception {
- RestClient c = new TestRestClient().setAccept("text/json+simple");
- String r;
-
- // @RestMethod(name="POST", path="/boolean")
- // public boolean testBool(@Content boolean b) {
- // return b;
- // }
- r = c.doPost(URL + "/boolean?content=true", null).getResponseAsString();
- assertEquals("true", r);
- r = c.doPost(URL + "/boolean?content=(true)", null).getResponseAsString();
- assertEquals("true", r);
- r = c.doPost(URL + "/boolean?content=$b(true)", null).getResponseAsString();
- assertEquals("true", r);
- r = c.doPost(URL + "/boolean?content=false", null).getResponseAsString();
- assertEquals("false", r);
- r = c.doPost(URL + "/boolean?content=(false)", null).getResponseAsString();
- assertEquals("false", r);
- r = c.doPost(URL + "/boolean?content=$b(false)", null).getResponseAsString();
- assertEquals("false", r);
- try {
- r = c.doPost(URL + "/boolean?content=%00&noTrace=true", null).getResponseAsString();
- fail("Exception expected!");
- } catch (RestCallException e) {
- assertEquals(400, e.getResponseCode());
- }
- try {
- r = c.doPost(URL + "/boolean?content=bad&noTrace=true", null).getResponseAsString();
- fail("Exception expected!");
- } catch (RestCallException e) {
- assertEquals(400, e.getResponseCode());
- }
-
-
- // @RestMethod(name="POST", path="/Boolean")
- // public Boolean testBoolean(@Content Boolean b) {
- // return b;
- // }
- r = c.doPost(URL + "/Boolean?content=true", null).getResponseAsString();
- assertEquals("true", r);
- r = c.doPost(URL + "/Boolean?content=(true)", null).getResponseAsString();
- assertEquals("true", r);
- r = c.doPost(URL + "/Boolean?content=$b(true)", null).getResponseAsString();
- assertEquals("true", r);
- r = c.doPost(URL + "/Boolean?content=false", null).getResponseAsString();
- assertEquals("false", r);
- r = c.doPost(URL + "/Boolean?content=(false)", null).getResponseAsString();
- assertEquals("false", r);
- r = c.doPost(URL + "/Boolean?content=$b(false)", null).getResponseAsString();
- assertEquals("false", r);
- r = c.doPost(URL + "/Boolean?content=%00", null).getResponseAsString();
- assertEquals("null", r);
- try {
- r = c.doPost(URL + "/Boolean?content=bad&noTrace=true", null).getResponseAsString();
- fail("Exception expected!");
- } catch (RestCallException e) {
- assertEquals(400, e.getResponseCode());
- }
-
- // @RestMethod(name="POST", path="/int")
- // public int testInt(@Content int i) {
- // return i;
- // }
- r = c.doPost(URL + "/int?content=-123", null).getResponseAsString();
- assertEquals("-123", r);
- r = c.doPost(URL + "/int?content=(-123)", null).getResponseAsString();
- assertEquals("-123", r);
- r = c.doPost(URL + "/int?content=$n(-123)", null).getResponseAsString();
- assertEquals("-123", r);
- try {
- r = c.doPost(URL + "/int?content=%00&noTrace=true", null).getResponseAsString();
- fail("Exception expected!");
- } catch (RestCallException e) {
- assertEquals(400, e.getResponseCode());
- }
- try {
- r = c.doPost(URL + "/int?content=bad&noTrace=true", null).getResponseAsString();
- fail("Exception expected!");
- } catch (RestCallException e) {
- assertEquals(400, e.getResponseCode());
- }
-
- // @RestMethod(name="POST", path="/Integer")
- // public Integer testInteger(@Content Integer i) {
- // return i;
- // }
- r = c.doPost(URL + "/Integer?content=-123", null).getResponseAsString();
- assertEquals("-123", r);
- r = c.doPost(URL + "/Integer?content=(-123)", null).getResponseAsString();
- assertEquals("-123", r);
- r = c.doPost(URL + "/Integer?content=$n(-123)", null).getResponseAsString();
- assertEquals("-123", r);
- r = c.doPost(URL + "/Integer?content=%00", null).getResponseAsString();
- assertEquals("null", r);
- try {
- r = c.doPost(URL + "/Integer?content=bad&noTrace=true", null).getResponseAsString();
- fail("Exception expected!");
- } catch (RestCallException e) {
- assertEquals(400, e.getResponseCode());
- }
-
- // @RestMethod(name="POST", path="/float")
- // public float testFloat(@Content float f) {
- // return f;
- // }
- r = c.doPost(URL + "/float?content=-1.23", null).getResponseAsString();
- assertEquals("-1.23", r);
- r = c.doPost(URL + "/float?content=(-1.23)", null).getResponseAsString();
- assertEquals("-1.23", r);
- r = c.doPost(URL + "/float?content=$n(-1.23)", null).getResponseAsString();
- assertEquals("-1.23", r);
- try {
- r = c.doPost(URL + "/float?content=%00&noTrace=true", null).getResponseAsString();
- fail("Exception expected!");
- } catch (RestCallException e) {
- assertEquals(400, e.getResponseCode());
- }
- try {
- r = c.doPost(URL + "/float?content=bad&noTrace=true", null).getResponseAsString();
- fail("Exception expected!");
- } catch (RestCallException e) {
- assertEquals(400, e.getResponseCode());
- }
-
- // @RestMethod(name="POST", path="/Float")
- // public Float testFloat2(@Content Float f) {
- // return f;
- // }
- r = c.doPost(URL + "/Float?content=-1.23", null).getResponseAsString();
- assertEquals("-1.23", r);
- r = c.doPost(URL + "/Float?content=(-1.23)", null).getResponseAsString();
- assertEquals("-1.23", r);
- r = c.doPost(URL + "/Float?content=$n(-1.23)", null).getResponseAsString();
- assertEquals("-1.23", r);
- r = c.doPost(URL + "/Float?content=%00", null).getResponseAsString();
- assertEquals("null", r);
- try {
- r = c.doPost(URL + "/Float?content=bad&noTrace=true", null).getResponseAsString();
- fail("Exception expected!");
- } catch (RestCallException e) {
- assertEquals(400, e.getResponseCode());
- }
-
- // @RestMethod(name="POST", path="/Map")
- // public TreeMap<String,String> testMap(@Content TreeMap<String,String> m) {
- // return m;
- // }
- r = c.doPost(URL + "/Map?content=(a=b,c=d)", null).getResponseAsString();
- assertEquals("{a:'b',c:'d'}", r);
- r = c.doPost(URL + "/Map?content=%00", null).getResponseAsString();
- assertEquals("null", r);
- try {
- r = c.doPost(URL + "/Map?content=bad&noTrace=true", null).getResponseAsString();
- fail("Exception expected!");
- } catch (RestCallException e) {
- assertEquals(400, e.getResponseCode());
- }
-
- // @RestMethod(name="POST", path="/B")
- // public DTO2s.B testPojo1(@Content DTO2s.B b) {
- // return b;
- // }
- DTOs.B b = DTOs.B.create();
- r = c.doPost(URL + "/B?content=" + UonSerializer.DEFAULT.serialize(b), null).getResponseAsString();
- assertEquals("{f1:['a','b'],f2:['c','d'],f3:[1,2],f4:[3,4],f5:[['e','f'],['g','h']],f6:[['i','j'],['k','l']],f7:[{a:'a',b:1,c:true},{a:'a',b:1,c:true}],f8:[{a:'a',b:1,c:true},{a:'a',b:1,c:true}],f9:[[{a:'a',b:1,c:true}],[{a:'a',b:1,c:true}]],f10:[[{a:'a',b:1,c:true}],[{a:'a',b:1,c:true}]],f11:['a','b'],f12:['c','d'],f13:[1,2],f14:[3,4],f15:[['e','f'],['g','h']],f16:[['i','j'],['k','l']],f17:[{a:'a',b:1,c:true},{a:'a',b:1,c:true}],f18:[{a:'a',b:1,c:true},{a:'a',b:1,c:true}],f19:[[{a:'a',b:1,c:true}],[{a:'a',b:1,c:true}]],f20:[[{a:'a',b:1,c:true}],[{a:'a',b:1,c:true}]]}", r);
- r = c.doPost(URL + "/B?content=" + UonSerializer.DEFAULT_SIMPLE.serialize(b), null).getResponseAsString();
- assertEquals("{f1:['a','b'],f2:['c','d'],f3:[1,2],f4:[3,4],f5:[['e','f'],['g','h']],f6:[['i','j'],['k','l']],f7:[{a:'a',b:1,c:true},{a:'a',b:1,c:true}],f8:[{a:'a',b:1,c:true},{a:'a',b:1,c:true}],f9:[[{a:'a',b:1,c:true}],[{a:'a',b:1,c:true}]],f10:[[{a:'a',b:1,c:true}],[{a:'a',b:1,c:true}]],f11:['a','b'],f12:['c','d'],f13:[1,2],f14:[3,4],f15:[['e','f'],['g','h']],f16:[['i','j'],['k','l']],f17:[{a:'a',b:1,c:true},{a:'a',b:1,c:true}],f18:[{a:'a',b:1,c:true},{a:'a',b:1,c:true}],f19:[[{a:'a',b:1,c:true}],[{a:'a',b:1,c:true}]],f20:[[{a:'a',b:1,c:true}],[{a:'a',b:1,c:true}]]}", r);
-
- // @RestMethod(name="POST", path="/C")
- // public DTO2s.C testPojo2(@Content DTO2s.C c) {
- // return c;
- // }
- DTOs.C x = DTOs.C.create();
- r = c.doPost(URL + "/C?content=" + UonSerializer.DEFAULT.serialize(x), null).getResponseAsString();
- assertEquals("{f1:['a','b'],f2:['c','d'],f3:[1,2],f4:[3,4],f5:[['e','f'],['g','h']],f6:[['i','j'],['k','l']],f7:[{a:'a',b:1,c:true},{a:'a',b:1,c:true}],f8:[{a:'a',b:1,c:true},{a:'a',b:1,c:true}],f9:[[{a:'a',b:1,c:true}],[{a:'a',b:1,c:true}]],f10:[[{a:'a',b:1,c:true}],[{a:'a',b:1,c:true}]],f11:['a','b'],f12:['c','d'],f13:[1,2],f14:[3,4],f15:[['e','f'],['g','h']],f16:[['i','j'],['k','l']],f17:[{a:'a',b:1,c:true},{a:'a',b:1,c:true}],f18:[{a:'a',b:1,c:true},{a:'a',b:1,c:true}],f19:[[{a:'a',b:1,c:true}],[{a:'a',b:1,c:true}]],f20:[[{a:'a',b:1,c:true}],[{a:'a',b:1,c:true}]]}", r);
- r = c.doPost(URL + "/C?content=" + UonSerializer.DEFAULT_SIMPLE.serialize(x), null).getResponseAsString();
- assertEquals("{f1:['a','b'],f2:['c','d'],f3:[1,2],f4:[3,4],f5:[['e','f'],['g','h']],f6:[['i','j'],['k','l']],f7:[{a:'a',b:1,c:true},{a:'a',b:1,c:true}],f8:[{a:'a',b:1,c:true},{a:'a',b:1,c:true}],f9:[[{a:'a',b:1,c:true}],[{a:'a',b:1,c:true}]],f10:[[{a:'a',b:1,c:true}],[{a:'a',b:1,c:true}]],f11:['a','b'],f12:['c','d'],f13:[1,2],f14:[3,4],f15:[['e','f'],['g','h']],f16:[['i','j'],['k','l']],f17:[{a:'a',b:1,c:true},{a:'a',b:1,c:true}],f18:[{a:'a',b:1,c:true},{a:'a',b:1,c:true}],f19:[[{a:'a',b:1,c:true}],[{a:'a',b:1,c:true}]],f20:[[{a:'a',b:1,c:true}],[{a:'a',b:1,c:true}]]}", r);
-
- c.closeQuietly();
- }
-
- //====================================================================================================
- // Basic tests using &Content parameter with &Accept=text/json
- //====================================================================================================
- @Test
- public void testUsingContentParamJsonHeader() throws Exception {
- RestClient c = new TestRestClient().setAccept("text/json+simple").setHeader("Content-Type", "text/json");
- String r;
-
- // @RestMethod(name="POST", path="/boolean")
- // public boolean testBool(@Content boolean b) {
- // return b;
- // }
- r = c.doPost(URL + "/boolean?content=true", null).getResponseAsString();
- assertEquals("true", r);
- r = c.doPost(URL + "/boolean?content=false", null).getResponseAsString();
- assertEquals("false", r);
- try {
- r = c.doPost(URL + "/boolean?content=null&noTrace=true", null).getResponseAsString();
- fail("Exception expected!");
- } catch (RestCallException e) {
- assertEquals(400, e.getResponseCode());
- }
- try {
- r = c.doPost(URL + "/boolean?content=bad&noTrace=true", null).getResponseAsString();
- fail("Exception expected!");
- } catch (RestCallException e) {
- assertEquals(400, e.getResponseCode());
- }
-
-
- // @RestMethod(name="POST", path="/Boolean")
- // public Boolean testBoolean(@Content Boolean b) {
- // return b;
- // }
- r = c.doPost(URL + "/Boolean?content=true", null).getResponseAsString();
- assertEquals("true", r);
- r = c.doPost(URL + "/Boolean?content=false", null).getResponseAsString();
- assertEquals("false", r);
- r = c.doPost(URL + "/Boolean?content=null", null).getResponseAsString();
- assertEquals("null", r);
- try {
- r = c.doPost(URL + "/Boolean?content=bad&noTrace=true", null).getResponseAsString();
- fail("Exception expected!");
- } catch (RestCallException e) {
- assertEquals(400, e.getResponseCode());
- }
-
- // @RestMethod(name="POST", path="/int")
- // public int testInt(@Content int i) {
- // return i;
- // }
- r = c.doPost(URL + "/int?content=-123", null).getResponseAsString();
- assertEquals("-123", r);
- try {
- r = c.doPost(URL + "/int?content=null&noTrace=true", null).getResponseAsString();
- fail("Exception expected!");
- } catch (RestCallException e) {
- assertEquals(400, e.getResponseCode());
- }
- try {
- r = c.doPost(URL + "/int?content=bad&noTrace=true", null).getResponseAsString();
- fail("Exception expected!");
- } catch (RestCallException e) {
- assertEquals(400, e.getResponseCode());
- }
-
- // @RestMethod(name="POST", path="/Integer")
- // public Integer testInteger(@Content Integer i) {
- // return i;
- // }
- r = c.doPost(URL + "/Integer?content=-123", null).getResponseAsString();
- assertEquals("-123", r);
- r = c.doPost(URL + "/Integer?content=null", null).getResponseAsString();
- assertEquals("null", r);
- try {
- r = c.doPost(URL + "/Integer?content=bad&noTrace=true", null).getResponseAsString();
- fail("Exception expected!");
- } catch (RestCallException e) {
- assertEquals(400, e.getResponseCode());
- }
-
- // @RestMethod(name="POST", path="/float")
- // public float testFloat(@Content float f) {
- // return f;
- // }
- r = c.doPost(URL + "/float?content=-1.23", null).getResponseAsString();
- assertEquals("-1.23", r);
- try {
- r = c.doPost(URL + "/float?content=null&noTrace=true", null).getResponseAsString();
- fail("Exception expected!");
- } catch (RestCallException e) {
- assertEquals(400, e.getResponseCode());
- }
- try {
- r = c.doPost(URL + "/float?content=bad&noTrace=true", null).getResponseAsString();
- fail("Exception expected!");
- } catch (RestCallException e) {
- assertEquals(400, e.getResponseCode());
- }
-
- // @RestMethod(name="POST", path="/Float")
- // public Float testFloat2(@Content Float f) {
- // return f;
- // }
- r = c.doPost(URL + "/Float?content=-1.23", null).getResponseAsString();
- assertEquals("-1.23", r);
- r = c.doPost(URL + "/Float?content=null", null).getResponseAsString();
- assertEquals("null", r);
- try {
- r = c.doPost(URL + "/Float?content=bad&noTrace=true", null).getResponseAsString();
- fail("Exception expected!");
- } catch (RestCallException e) {
- assertEquals(400, e.getResponseCode());
- }
-
- // @RestMethod(name="POST", path="/Map")
- // public TreeMap<String,String> testMap(@Content TreeMap<String,String> m) {
- // return m;
- // }
- r = c.doPost(URL + "/Map?content=" + encode("{a:'b',c:'d'}"), null).getResponseAsString();
- assertEquals("{a:'b',c:'d'}", r);
- r = c.doPost(URL + "/Map?content=null", null).getResponseAsString();
- assertEquals("null", r);
- try {
- r = c.doPost(URL + "/Map?content=bad&noTrace=true", null).getResponseAsString();
- fail("Exception expected!");
- } catch (RestCallException e) {
- assertEquals(400, e.getResponseCode());
- }
-
- // @RestMethod(name="POST", path="/B")
- // public DTO2s.B testPojo1(@Content DTO2s.B b) {
- // return b;
- // }
- DTOs.B b = DTOs.B.create();
- r = c.doPost(URL + "/B?content=" + encode(JsonSerializer.DEFAULT_LAX.serialize(b)), null).getResponseAsString();
- assertEquals("{f1:['a','b'],f2:['c','d'],f3:[1,2],f4:[3,4],f5:[['e','f'],['g','h']],f6:[['i','j'],['k','l']],f7:[{a:'a',b:1,c:true},{a:'a',b:1,c:true}],f8:[{a:'a',b:1,c:true},{a:'a',b:1,c:true}],f9:[[{a:'a',b:1,c:true}],[{a:'a',b:1,c:true}]],f10:[[{a:'a',b:1,c:true}],[{a:'a',b:1,c:true}]],f11:['a','b'],f12:['c','d'],f13:[1,2],f14:[3,4],f15:[['e','f'],['g','h']],f16:[['i','j'],['k','l']],f17:[{a:'a',b:1,c:true},{a:'a',b:1,c:true}],f18:[{a:'a',b:1,c:true},{a:'a',b:1,c:true}],f19:[[{a:'a',b:1,c:true}],[{a:'a',b:1,c:true}]],f20:[[{a:'a',b:1,c:true}],[{a:'a',b:1,c:true}]]}", r);
-
- // @RestMethod(name="POST", path="/C")
- // public DTO2s.C testPojo2(@Content DTO2s.C c) {
- // return c;
- // }
- DTOs.C x = DTOs.C.create();
- r = c.doPost(URL + "/C?content=" + encode(JsonSerializer.DEFAULT_LAX.serialize(x)), null).getResponseAsString();
- assertEquals("{f1:['a','b'],f2:['c','d'],f3:[1,2],f4:[3,4],f5:[['e','f'],['g','h']],f6:[['i','j'],['k','l']],f7:[{a:'a',b:1,c:true},{a:'a',b:1,c:true}],f8:[{a:'a',b:1,c:true},{a:'a',b:1,c:true}],f9:[[{a:'a',b:1,c:true}],[{a:'a',b:1,c:true}]],f10:[[{a:'a',b:1,c:true}],[{a:'a',b:1,c:true}]],f11:['a','b'],f12:['c','d'],f13:[1,2],f14:[3,4],f15:[['e','f'],['g','h']],f16:[['i','j'],['k','l']],f17:[{a:'a',b:1,c:true},{a:'a',b:1,c:true}],f18:[{a:'a',b:1,c:true},{a:'a',b:1,c:true}],f19:[[{a:'a',b:1,c:true}],[{a:'a',b:1,c:true}]],f20:[[{a:'a',b:1,c:true}],[{a:'a',b:1,c:true}]]}", r);
-
- c.closeQuietly();
- }
-
- //====================================================================================================
- // Basic tests using &Content parameter with &Accept=text/json
- //====================================================================================================
- @Test
- public void testUsingContentParamJsonParam() throws Exception {
- RestClient c = new TestRestClient().setAccept("text/json+simple");
- String r;
-
- // @RestMethod(name="POST", path="/boolean")
- // public boolean testBool(@Content boolean b) {
- // return b;
- // }
- r = c.doPost(URL + "/boolean?content=true&Content-Type=text/json", null).getResponseAsString();
- assertEquals("true", r);
- r = c.doPost(URL + "/boolean?content=false&Content-Type=text/json", null).getResponseAsString();
- assertEquals("false", r);
- try {
- r = c.doPost(URL + "/boolean?content=null&Content-Type=text/json&noTrace=true", null).getResponseAsString();
- fail("Exception expected!");
- } catch (RestCallException e) {
- assertEquals(400, e.getResponseCode());
- }
- try {
- r = c.doPost(URL + "/boolean?content=bad&Content-Type=text/json&noTrace=true", null).getResponseAsString();
- fail("Exception expected!");
- } catch (RestCallException e) {
- assertEquals(400, e.getResponseCode());
- }
-
-
- // @RestMethod(name="POST", path="/Boolean")
- // public Boolean testBoolean(@Content Boolean b) {
- // return b;
- // }
- r = c.doPost(URL + "/Boolean?content=true&Content-Type=text/json", null).getResponseAsString();
- assertEquals("true", r);
- r = c.doPost(URL + "/Boolean?content=false&Content-Type=text/json", null).getResponseAsString();
- assertEquals("false", r);
- r = c.doPost(URL + "/Boolean?content=null&Content-Type=text/json", null).getResponseAsString();
- assertEquals("null", r);
- try {
- r = c.doPost(URL + "/Boolean?content=bad&Content-Type=text/json&noTrace=true", null).getResponseAsString();
- fail("Exception expected!");
- } catch (RestCallException e) {
- assertEquals(400, e.getResponseCode());
- }
-
- // @RestMethod(name="POST", path="/int")
- // public int testInt(@Content int i) {
- // return i;
- // }
- r = c.doPost(URL + "/int?content=-123&Content-Type=text/json", null).getResponseAsString();
- assertEquals("-123", r);
- try {
- r = c.doPost(URL + "/int?content=null&Content-Type=text/json&noTrace=true", null).getResponseAsString();
- fail("Exception expected!");
- } catch (RestCallException e) {
- assertEquals(400, e.getResponseCode());
- }
- try {
- r = c.doPost(URL + "/int?content=bad&Content-Type=text/json&noTrace=true", null).getResponseAsString();
- fail("Exception expected!");
- } catch (RestCallException e) {
- assertEquals(400, e.getResponseCode());
- }
-
- // @RestMethod(name="POST", path="/Integer")
- // public Integer testInteger(@Content Integer i) {
- // return i;
- // }
- r = c.doPost(URL + "/Integer?content=-123&Content-Type=text/json", null).getResponseAsString();
- assertEquals("-123", r);
- r = c.doPost(URL + "/Integer?content=null&Content-Type=text/json", null).getResponseAsString();
- assertEquals("null", r);
- try {
- r = c.doPost(URL + "/Integer?content=bad&Content-Type=text/json&noTrace=true", null).getResponseAsString();
- fail("Exception expected!");
- } catch (RestCallException e) {
- assertEquals(400, e.getResponseCode());
- }
-
- // @RestMethod(name="POST", path="/float")
- // public float testFloat(@Content float f) {
- // return f;
- // }
- r = c.doPost(URL + "/float?content=-1.23&Content-Type=text/json", null).getResponseAsString();
- assertEquals("-1.23", r);
- try {
- r = c.doPost(URL + "/float?content=null&Content-Type=text/json&noTrace=true", null).getResponseAsString();
- fail("Exception expected!");
- } catch (RestCallException e) {
- assertEquals(400, e.getResponseCode());
- }
- try {
- r = c.doPost(URL + "/float?content=bad&Content-Type=text/json&noTrace=true", null).getResponseAsString();
- fail("Exception expected!");
- } catch (RestCallException e) {
- assertEquals(400, e.getResponseCode());
- }
-
- // @RestMethod(name="POST", path="/Float")
- // public Float testFloat2(@Content Float f) {
- // return f;
- // }
- r = c.doPost(URL + "/Float?content=-1.23&Content-Type=text/json", null).getResponseAsString();
- assertEquals("-1.23", r);
- r = c.doPost(URL + "/Float?content=null&Content-Type=text/json", null).getResponseAsString();
- assertEquals("null", r);
- try {
- r = c.doPost(URL + "/Float?content=bad&Content-Type=text/json&noTrace=true", null).getResponseAsString();
- fail("Exception expected!");
- } catch (RestCallException e) {
- assertEquals(400, e.getResponseCode());
- }
-
- // @RestMethod(name="POST", path="/Map")
- // public TreeMap<String,String> testMap(@Content TreeMap<String,String> m) {
- // return m;
- // }
- r = c.doPost(URL + "/Map?content=" + encode("{a:'b',c:'d'}") + "&Content-Type=text/json", null).getResponseAsString();
- assertEquals("{a:'b',c:'d'}", r);
- r = c.doPost(URL + "/Map?content=null&Content-Type=text/json", null).getResponseAsString();
- assertEquals("null", r);
- try {
- r = c.doPost(URL + "/Map?content=bad&Content-Type=text/json&noTrace=true", null).getResponseAsString();
- fail("Exception expected!");
- } catch (RestCallException e) {
- assertEquals(400, e.getResponseCode());
- }
-
- // @RestMethod(name="POST", path="/B")
- // public DTO2s.B testPojo1(@Content DTO2s.B b) {
- // return b;
- // }
- DTOs.B b = DTOs.B.create();
- r = c.doPost(URL + "/B?content=" + encode(JsonSerializer.DEFAULT_LAX.serialize(b)) + "&Content-Type=text/json", null).getResponseAsString();
- assertEquals("{f1:['a','b'],f2:['c','d'],f3:[1,2],f4:[3,4],f5:[['e','f'],['g','h']],f6:[['i','j'],['k','l']],f7:[{a:'a',b:1,c:true},{a:'a',b:1,c:true}],f8:[{a:'a',b:1,c:true},{a:'a',b:1,c:true}],f9:[[{a:'a',b:1,c:true}],[{a:'a',b:1,c:true}]],f10:[[{a:'a',b:1,c:true}],[{a:'a',b:1,c:true}]],f11:['a','b'],f12:['c','d'],f13:[1,2],f14:[3,4],f15:[['e','f'],['g','h']],f16:[['i','j'],['k','l']],f17:[{a:'a',b:1,c:true},{a:'a',b:1,c:true}],f18:[{a:'a',b:1,c:true},{a:'a',b:1,c:true}],f19:[[{a:'a',b:1,c:true}],[{a:'a',b:1,c:true}]],f20:[[{a:'a',b:1,c:true}],[{a:'a',b:1,c:true}]]}", r);
-
- // @RestMethod(name="POST", path="/C")
- // public DTO2s.C testPojo2(@Content DTO2s.C c) {
- // return c;
- // }
- DTOs.C x = DTOs.C.create();
- r = c.doPost(URL + "/C?content=" + encode(JsonSerializer.DEFAULT_LAX.serialize(x)) + "&Content-Type=text/json", null).getResponseAsString();
- assertEquals("{f1:['a','b'],f2:['c','d'],f3:[1,2],f4:[3,4],f5:[['e','f'],['g','h']],f6:[['i','j'],['k','l']],f7:[{a:'a',b:1,c:true},{a:'a',b:1,c:true}],f8:[{a:'a',b:1,c:true},{a:'a',b:1,c:true}],f9:[[{a:'a',b:1,c:true}],[{a:'a',b:1,c:true}]],f10:[[{a:'a',b:1,c:true}],[{a:'a',b:1,c:true}]],f11:['a','b'],f12:['c','d'],f13:[1,2],f14:[3,4],f15:[['e','f'],['g','h']],f16:[['i','j'],['k','l']],f17:[{a:'a',b:1,c:true},{a:'a',b:1,c:true}],f18:[{a:'a',b:1,c:true},{a:'a',b:1,c:true}],f19:[[{a:'a',b:1,c:true}],[{a:'a',b:1,c:true}]],f20:[[{a:'a',b:1,c:true}],[{a:'a',b:1,c:true}]]}", r);
-
- c.closeQuietly();
- }
-
- //====================================================================================================
- // Basic tests using HTTP body content
- //====================================================================================================
- @Test
- public void testUsingContent() throws Exception {
- RestClient c = new TestRestClient().setAccept("text/json+simple").setHeader("Content-Type", "text/uon").setSerializer(PlainTextSerializer.class);
- String r;
-
- // @RestMethod(name="POST", path="/boolean")
- // public boolean testBool(@Content boolean b) {
- // return b;
- // }
- r = c.doPost(URL + "/boolean", "true").getResponseAsString();
- assertEquals("true", r);
- r = c.doPost(URL + "/boolean", "(true)").getResponseAsString();
- assertEquals("true", r);
- r = c.doPost(URL + "/boolean", "$b(true)").getResponseAsString();
- assertEquals("true", r);
- r = c.doPost(URL + "/boolean", "false").getResponseAsString();
- assertEquals("false", r);
- r = c.doPost(URL + "/boolean", "(false)").getResponseAsString();
- assertEquals("false", r);
- r = c.doPost(URL + "/boolean", "$b(false)").getResponseAsString();
- assertEquals("false", r);
- try {
- r = c.doPost(URL + "/boolean?noTrace=true", "%00").getResponseAsString();
- fail("Exception expected!");
- } catch (RestCallException e) {
- assertEquals(400, e.getResponseCode());
- }
- try {
- r = c.doPost(URL + "/boolean?noTrace=true", "bad").getResponseAsString();
- fail("Exception expected!");
- } catch (RestCallException e) {
- assertEquals(400, e.getResponseCode());
- }
-
-
- // @RestMethod(name="POST", path="/Boolean")
- // public Boolean testBoolean(@Content Boolean b) {
- // return b;
- // }
- r = c.doPost(URL + "/Boolean", "true").getResponseAsString();
- assertEquals("true", r);
- r = c.doPost(URL + "/Boolean", "(true)").getResponseAsString();
- assertEquals("true", r);
- r = c.doPost(URL + "/Boolean", "$b(true)").getResponseAsString();
- assertEquals("true", r);
- r = c.doPost(URL + "/Boolean", "false").getResponseAsString();
- assertEquals("false", r);
- r = c.doPost(URL + "/Boolean", "(false)").getResponseAsString();
- assertEquals("false", r);
- r = c.doPost(URL + "/Boolean", "$b(false)").getResponseAsString();
- assertEquals("false", r);
- r = c.doPost(URL + "/Boolean", "\u0000").getResponseAsString();
- assertEquals("null", r);
- try {
- r = c.doPost(URL + "/Boolean?noTrace=true", "bad").getResponseAsString();
- fail("Exception expected!");
- } catch (RestCallException e) {
- assertEquals(400, e.getResponseCode());
- }
-
- // @RestMethod(name="POST", path="/int")
- // public int testInt(@Content int i) {
- // return i;
- // }
- r = c.doPost(URL + "/int", "-123").getResponseAsString();
- assertEquals("-123", r);
- r = c.doPost(URL + "/int", "(-123)").getResponseAsString();
- assertEquals("-123", r);
- r = c.doPost(URL + "/int", "$n(-123)").getResponseAsString();
- assertEquals("-123", r);
- try {
- r = c.doPost(URL + "/int?noTrace=true", "%00").getResponseAsString();
- fail("Exception expected!");
- } catch (RestCallException e) {
- assertEquals(400, e.getResponseCode());
- }
- try {
- r = c.doPost(URL + "/int?noTrace=true", "bad").getResponseAsString();
- fail("Exception expected!");
- } catch (RestCallException e) {
- assertEquals(400, e.getResponseCode());
- }
-
- // @RestMethod(name="POST", path="/Integer")
- // public Integer testInteger(@Content Integer i) {
- // return i;
- // }
- r = c.doPost(URL + "/Integer", "-123").getResponseAsString();
- assertEquals("-123", r);
- r = c.doPost(URL + "/Integer", "(-123)").getResponseAsString();
- assertEquals("-123", r);
- r = c.doPost(URL + "/Integer", "$n(-123)").getResponseAsString();
- assertEquals("-123", r);
- r = c.doPost(URL + "/Integer", "\u0000").getResponseAsString();
- assertEquals("null", r);
- try {
- r = c.doPost(URL + "/Integer?noTrace=true", "bad").getResponseAsString();
- fail("Exception expected!");
- } catch (RestCallException e) {
- assertEquals(400, e.getResponseCode());
- }
-
- // @RestMethod(name="POST", path="/float")
- // public float testFloat(@Content float f) {
- // return f;
- // }
- r = c.doPost(URL + "/float", "-1.23").getResponseAsString();
- assertEquals("-1.23", r);
- r = c.doPost(URL + "/float", "(-1.23)").getResponseAsString();
- assertEquals("-1.23", r);
- r = c.doPost(URL + "/float", "$n(-1.23)").getResponseAsString();
- assertEquals("-1.23", r);
- try {
- r = c.doPost(URL + "/float?noTrace=true", "\u0000").getResponseAsString();
- fail("Exception expected!");
- } catch (RestCallException e) {
- assertEquals(400, e.getResponseCode());
- }
- try {
- r = c.doPost(URL + "/float?noTrace=true", "bad").getResponseAsString();
- fail("Exception expected!");
- } catch (RestCallException e) {
- assertEquals(400, e.getResponseCode());
- }
-
- // @RestMethod(name="POST", path="/Float")
- // public Float testFloat2(@Content Float f) {
- // return f;
- // }
- r = c.doPost(URL + "/Float", "-1.23").getResponseAsString();
- assertEquals("-1.23", r);
- r = c.doPost(URL + "/Float", "(-1.23)").getResponseAsString();
- assertEquals("-1.23", r);
- r = c.doPost(URL + "/Float", "$n(-1.23)").getResponseAsString();
- assertEquals("-1.23", r);
- r = c.doPost(URL + "/Float", "\u0000").getResponseAsString();
- assertEquals("null", r);
- try {
- r = c.doPost(URL + "/Float?noTrace=true", "bad").getResponseAsString();
- fail("Exception expected!");
- } catch (RestCallException e) {
- assertEquals(400, e.getResponseCode());
- }
-
- // @RestMethod(name="POST", path="/Map")
- // public TreeMap<String,String> testMap(@Content TreeMap<String,String> m) {
- // return m;
- // }
- r = c.doPost(URL + "/Map", "(a=b,c=d)").getResponseAsString();
- assertEquals("{a:'b',c:'d'}", r);
- r = c.doPost(URL + "/Map", "\u0000").getResponseAsString();
- assertEquals("null", r);
- try {
- r = c.doPost(URL + "/Map?noTrace=true", "bad").getResponseAsString();
- fail("Exception expected!");
- } catch (RestCallException e) {
- assertEquals(400, e.getResponseCode());
- }
-
- // @RestMethod(name="POST", path="/B")
- // public DTO2s.B testPojo1(@Content DTO2s.B b) {
- // return b;
- // }
- DTOs.B b = DTOs.B.create();
- r = c.doPost(URL + "/B", "" + UonSerializer.DEFAULT.serialize(b)).getResponseAsString();
- assertEquals("{f1:['a','b'],f2:['c','d'],f3:[1,2],f4:[3,4],f5:[['e','f'],['g','h']],f6:[['i','j'],['k','l']],f7:[{a:'a',b:1,c:true},{a:'a',b:1,c:true}],f8:[{a:'a',b:1,c:true},{a:'a',b:1,c:true}],f9:[[{a:'a',b:1,c:true}],[{a:'a',b:1,c:true}]],f10:[[{a:'a',b:1,c:true}],[{a:'a',b:1,c:true}]],f11:['a','b'],f12:['c','d'],f13:[1,2],f14:[3,4],f15:[['e','f'],['g','h']],f16:[['i','j'],['k','l']],f17:[{a:'a',b:1,c:true},{a:'a',b:1,c:true}],f18:[{a:'a',b:1,c:true},{a:'a',b:1,c:true}],f19:[[{a:'a',b:1,c:true}],[{a:'a',b:1,c:true}]],f20:[[{a:'a',b:1,c:true}],[{a:'a',b:1,c:true}]]}", r);
- r = c.doPost(URL + "/B", "" + UonSerializer.DEFAULT_SIMPLE.serialize(b)).getResponseAsString();
- assertEquals("{f1:['a','b'],f2:['c','d'],f3:[1,2],f4:[3,4],f5:[['e','f'],['g','h']],f6:[['i','j'],['k','l']],f7:[{a:'a',b:1,c:true},{a:'a',b:1,c:true}],f8:[{a:'a',b:1,c:true},{a:'a',b:1,c:true}],f9:[[{a:'a',b:1,c:true}],[{a:'a',b:1,c:true}]],f10:[[{a:'a',b:1,c:true}],[{a:'a',b:1,c:true}]],f11:['a','b'],f12:['c','d'],f13:[1,2],f14:[3,4],f15:[['e','f'],['g','h']],f16:[['i','j'],['k','l']],f17:[{a:'a',b:1,c:true},{a:'a',b:1,c:true}],f18:[{a:'a',b:1,c:true},{a:'a',b:1,c:true}],f19:[[{a:'a',b:1,c:true}],[{a:'a',b:1,c:true}]],f20:[[{a:'a',b:1,c:true}],[{a:'a',b:1,c:true}]]}", r);
-
- // @RestMethod(name="POST", path="/C")
- // public DTO2s.C testPojo2(@Content DTO2s.C c) {
- // return c;
- // }
- DTOs.C x = DTOs.C.create();
- r = c.doPost(URL + "/C", "" + UonSerializer.DEFAULT.serialize(x)).getResponseAsString();
- assertEquals("{f1:['a','b'],f2:['c','d'],f3:[1,2],f4:[3,4],f5:[['e','f'],['g','h']],f6:[['i','j'],['k','l']],f7:[{a:'a',b:1,c:true},{a:'a',b:1,c:true}],f8:[{a:'a',b:1,c:true},{a:'a',b:1,c:true}],f9:[[{a:'a',b:1,c:true}],[{a:'a',b:1,c:true}]],f10:[[{a:'a',b:1,c:true}],[{a:'a',b:1,c:true}]],f11:['a','b'],f12:['c','d'],f13:[1,2],f14:[3,4],f15:[['e','f'],['g','h']],f16:[['i','j'],['k','l']],f17:[{a:'a',b:1,c:true},{a:'a',b:1,c:true}],f18:[{a:'a',b:1,c:true},{a:'a',b:1,c:true}],f19:[[{a:'a',b:1,c:true}],[{a:'a',b:1,c:true}]],f20:[[{a:'a',b:1,c:true}],[{a:'a',b:1,c:true}]]}", r);
- r = c.doPost(URL + "/C", "" + UonSerializer.DEFAULT_SIMPLE.serialize(x)).getResponseAsString();
- assertEquals("{f1:['a','b'],f2:['c','d'],f3:[1,2],f4:[3,4],f5:[['e','f'],['g','h']],f6:[['i','j'],['k','l']],f7:[{a:'a',b:1,c:true},{a:'a',b:1,c:true}],f8:[{a:'a',b:1,c:true},{a:'a',b:1,c:true}],f9:[[{a:'a',b:1,c:true}],[{a:'a',b:1,c:true}]],f10:[[{a:'a',b:1,c:true}],[{a:'a',b:1,c:true}]],f11:['a','b'],f12:['c','d'],f13:[1,2],f14:[3,4],f15:[['e','f'],['g','h']],f16:[['i','j'],['k','l']],f17:[{a:'a',b:1,c:true},{a:'a',b:1,c:true}],f18:[{a:'a',b:1,c:true},{a:'a',b:1,c:true}],f19:[[{a:'a',b:1,c:true}],[{a:'a',b:1,c:true}]],f20:[[{a:'a',b:1,c:true}],[{a:'a',b:1,c:true}]]}", r);
-
- c.closeQuietly();
- }
-
-
- private String encode(String s) {
- try {
- return URLEncoder.encode(s, "UTF-8");
- } catch (UnsupportedEncodingException e) {
- throw new RuntimeException(e);
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestDefaultContentTypes.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestDefaultContentTypes.java b/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestDefaultContentTypes.java
deleted file mode 100755
index 089c0fb..0000000
--- a/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestDefaultContentTypes.java
+++ /dev/null
@@ -1,497 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.server;
-
-import static javax.servlet.http.HttpServletResponse.*;
-import static org.apache.juneau.server.TestUtils.*;
-import static org.junit.Assert.*;
-
-import org.apache.juneau.client.*;
-import org.apache.juneau.json.*;
-import org.junit.*;
-
-
-public class CT_TestDefaultContentTypes {
-
- private static String URL = "/testDefaultContentTypes";
- private static boolean debug = false;
-
- //====================================================================================================
- // Test that default Accept and Content-Type headers on servlet annotation are picked up.
- //====================================================================================================
- @Test
- public void testDefaultHeadersOnServletAnnotation() throws Exception {
- RestClient client = new TestRestClient(JsonSerializer.DEFAULT, JsonParser.DEFAULT);
- String r;
-
- String url = URL + "/testDefaultHeadersOnServletAnnotation";
-
- client.setAccept("").setContentType("");
- r = client.doPut(url, "").getResponseAsString();
- assertEquals("s2/p2", r);
-
- client.setAccept("text/s1").setContentType("");
- r = client.doPut(url, "").getResponseAsString();
- assertEquals("s1/p2", r);
-
- client.setAccept("").setContentType("text/p1");
- r = client.doPut(url, "").getResponseAsString();
- assertEquals("s2/p1", r);
-
- client.setAccept("text/s1").setContentType("text/p1");
- r = client.doPut(url, "").getResponseAsString();
- assertEquals("s1/p1", r);
-
- client.setAccept("text/s2").setContentType("");
- r = client.doPut(url, "").getResponseAsString();
- assertEquals("s2/p2", r);
-
- client.setAccept("").setContentType("text/p2");
- r = client.doPut(url, "").getResponseAsString();
- assertEquals("s2/p2", r);
-
- client.setAccept("text/s2").setContentType("text/p2");
- r = client.doPut(url, "").getResponseAsString();
- assertEquals("s2/p2", r);
-
- try {
- client.setAccept("text/s3").setContentType("");
- r = client.doPut(url+"?noTrace=true", "").getResponseAsString();
- fail("Exception expected");
- } catch (RestCallException e) {
- checkErrorResponse(debug, e, SC_NOT_ACCEPTABLE,
- "Unsupported media-type in request header 'Accept': 'text/s3'",
- "Supported media-types: [text/s1, text/s2]"
- );
- }
-
- try {
- client.setAccept("").setContentType("text/p3");
- r = client.doPut(url+"?noTrace=true", "").getResponseAsString();
- fail("Exception expected");
- } catch (RestCallException e) {
- checkErrorResponse(debug, e, SC_UNSUPPORTED_MEDIA_TYPE,
- "Unsupported media-type in request header 'Content-Type': 'text/p3'",
- "Supported media-types: [text/p1, text/p2]"
- );
- }
-
- try {
- client.setAccept("text/s3").setContentType("text/p3");
- r = client.doPut(url+"?noTrace=true", "").getResponseAsString();
- fail("Exception expected");
- } catch (RestCallException e) {
- checkErrorResponse(debug, e, SC_UNSUPPORTED_MEDIA_TYPE,
- "Unsupported media-type in request header 'Content-Type': 'text/p3'",
- "Supported media-types: [text/p1, text/p2]"
- );
- }
-
- client.closeQuietly();
- }
-
- //====================================================================================================
- // Test that default Accept and Content-Type headers on servlet annotation are picked up
- // when @RestMethod.parsers/serializers annotations are used.
- //====================================================================================================
- @Test
- public void testRestMethodParsersSerializers() throws Exception {
- RestClient client = new TestRestClient(JsonSerializer.DEFAULT, JsonParser.DEFAULT);
- String r;
-
- String url = URL + "/testRestMethodParsersSerializers";
-
- try {
- client.setAccept("").setContentType("");
- r = client.doPut(url+"?noTrace=true", "").getResponseAsString();
- fail("Exception expected");
- } catch (RestCallException e) {
- checkErrorResponse(debug, e, SC_UNSUPPORTED_MEDIA_TYPE,
- "Unsupported media-type in request header 'Content-Type': 'text/p2'",
- "Supported media-types: [text/p3]"
- );
- }
-
- try {
- client.setAccept("text/s1").setContentType("");
- r = client.doPut(url+"?noTrace=true", "").getResponseAsString();
- fail("Exception expected");
- } catch (RestCallException e) {
- checkErrorResponse(debug, e, SC_UNSUPPORTED_MEDIA_TYPE,
- "Unsupported media-type in request header 'Content-Type': 'text/p2'",
- "Supported media-types: [text/p3]"
- );
- }
-
- try {
- client.setAccept("").setContentType("text/p1");
- r = client.doPut(url+"?noTrace=true", "").getResponseAsString();
- fail("Exception expected");
- } catch (RestCallException e) {
- checkErrorResponse(debug, e, SC_UNSUPPORTED_MEDIA_TYPE,
- "Unsupported media-type in request header 'Content-Type': 'text/p1'",
- "Supported media-types: [text/p3]"
- );
- }
-
- try {
- client.setAccept("text/s1").setContentType("text/p1");
- r = client.doPut(url+"?noTrace=true", "").getResponseAsString();
- fail("Exception expected");
- } catch (RestCallException e) {
- checkErrorResponse(debug, e, SC_UNSUPPORTED_MEDIA_TYPE,
- "Unsupported media-type in request header 'Content-Type': 'text/p1'",
- "Supported media-types: [text/p3]"
- );
- }
-
- try {
- client.setAccept("text/s2").setContentType("");
- r = client.doPut(url+"?noTrace=true", "").getResponseAsString();
- fail("Exception expected");
- } catch (RestCallException e) {
- checkErrorResponse(debug, e, SC_UNSUPPORTED_MEDIA_TYPE,
- "Unsupported media-type in request header 'Content-Type': 'text/p2'",
- "Supported media-types: [text/p3]"
- );
- }
-
- try {
- client.setAccept("").setContentType("text/p2");
- r = client.doPut(url+"?noTrace=true", "").getResponseAsString();
- fail("Exception expected");
- } catch (RestCallException e) {
- checkErrorResponse(debug, e, SC_UNSUPPORTED_MEDIA_TYPE,
- "Unsupported media-type in request header 'Content-Type': 'text/p2'",
- "Supported media-types: [text/p3]"
- );
- }
-
- try {
- client.setAccept("text/s2").setContentType("text/p2");
- r = client.doPut(url+"?noTrace=true", "").getResponseAsString();
- fail("Exception expected");
- } catch (RestCallException e) {
- checkErrorResponse(debug, e, SC_UNSUPPORTED_MEDIA_TYPE,
- "Unsupported media-type in request header 'Content-Type': 'text/p2'",
- "Supported media-types: [text/p3]"
- );
- }
-
- try {
- client.setAccept("text/s3").setContentType("");
- r = client.doPut(url+"?noTrace=true", "").getResponseAsString();
- fail("Exception expected");
- } catch (RestCallException e) {
- checkErrorResponse(debug, e, SC_UNSUPPORTED_MEDIA_TYPE,
- "Unsupported media-type in request header 'Content-Type': 'text/p2'",
- "Supported media-types: [text/p3]"
- );
- }
-
- try {
- client.setAccept("").setContentType("text/p3");
- r = client.doPut(url+"?noTrace=true", "").getResponseAsString();
- fail("Exception expected");
- } catch (RestCallException e) {
- checkErrorResponse(debug, e, SC_NOT_ACCEPTABLE,
- "Unsupported media-type in request header 'Accept': 'text/s2'",
- "Supported media-types: [text/s3]"
- );
- }
-
- client.setAccept("text/s3").setContentType("text/p3");
- r = client.doPut(url, "").getResponseAsString();
- assertEquals("s3/p3", r);
-
- client.closeQuietly();
- }
-
- //====================================================================================================
- // Test that default Accept and Content-Type headers on servlet annotation are picked up
- // when @RestMethod.addParsers/addSerializers annotations are used.
- //====================================================================================================
- @Test
- public void testRestMethodAddParsersSerializers() throws Exception {
- RestClient client = new TestRestClient(JsonSerializer.DEFAULT, JsonParser.DEFAULT);
- String r;
-
- String url = URL + "/testRestMethodAddParsersSerializers";
-
- client.setAccept("").setContentType("");
- r = client.doPut(url, "").getResponseAsString();
- assertEquals("s2/p2", r);
-
- client.setAccept("text/s1").setContentType("");
- r = client.doPut(url, "").getResponseAsString();
- assertEquals("s1/p2", r);
-
- client.setAccept("").setContentType("text/p1");
- r = client.doPut(url, "").getResponseAsString();
- assertEquals("s2/p1", r);
-
- client.setAccept("text/s1").setContentType("text/p1");
- r = client.doPut(url, "").getResponseAsString();
- assertEquals("s1/p1", r);
-
- client.setAccept("text/s2").setContentType("");
- r = client.doPut(url, "").getResponseAsString();
- assertEquals("s2/p2", r);
-
- client.setAccept("").setContentType("text/p2");
- r = client.doPut(url, "").getResponseAsString();
- assertEquals("s2/p2", r);
-
- client.setAccept("text/s2").setContentType("text/p2");
- r = client.doPut(url, "").getResponseAsString();
- assertEquals("s2/p2", r);
-
- client.setAccept("text/s3").setContentType("");
- r = client.doPut(url, "").getResponseAsString();
- assertEquals("s3/p2", r);
-
- client.setAccept("").setContentType("text/p3");
- r = client.doPut(url, "").getResponseAsString();
- assertEquals("s2/p3", r);
-
- client.setAccept("text/s3").setContentType("text/p3");
- r = client.doPut(url, "").getResponseAsString();
- assertEquals("s3/p3", r);
-
- try {
- client.setAccept("").setContentType("text/p4");
- r = client.doPut(url+"?noTrace=true", "").getResponseAsString();
- fail("Exception expected");
- } catch (RestCallException e) {
- // Note that parsers defined on method are listed before parsers defined on class.
- checkErrorResponse(debug, e, SC_UNSUPPORTED_MEDIA_TYPE,
- "Unsupported media-type in request header 'Content-Type': 'text/p4'",
- "Supported media-types: [text/p3, text/p1, text/p2]"
- );
- }
-
- try {
- client.setAccept("text/s4").setContentType("");
- r = client.doPut(url+"?noTrace=true", "").getResponseAsString();
- fail("Exception expected");
- } catch (RestCallException e) {
- // Note that serializers defined on method are listed before serializers defined on class.
- checkErrorResponse(debug, e, SC_NOT_ACCEPTABLE,
- "Unsupported media-type in request header 'Accept': 'text/s4'",
- "Supported media-types: [text/s3, text/s1, text/s2]"
- );
- }
-
- client.closeQuietly();
- }
-
- //====================================================================================================
- // Various Accept incantations.
- //====================================================================================================
- @Test
- public void testAccept() throws Exception {
- RestClient client = new TestRestClient(JsonSerializer.DEFAULT, JsonParser.DEFAULT).setContentType("text/p1");
- String r;
-
- String url = URL + "/testAccept";
-
- // "*/*" should match the first serializer, not the default serializer.
- client.setAccept("*/*");
- r = client.doPut(url, "").getResponseAsString();
- assertEquals("s1/p1", r);
-
- // "text/*" should match the first serializer, not the default serializer.
- client.setAccept("text/*");
- r = client.doPut(url, "").getResponseAsString();
- assertEquals("s1/p1", r);
-
- try {
- client.setAccept("bad/*");
- r = client.doPut(url+"?noTrace=true", "").getResponseAsString();
- fail("Exception expected");
- } catch (RestCallException e) {
- checkErrorResponse(debug, e, SC_NOT_ACCEPTABLE,
- "Unsupported media-type in request header 'Accept': 'bad/*'",
- "Supported media-types: [text/s1, text/s2]"
- );
- }
-
- client.setAccept("bad/*,text/*");
- r = client.doPut(url, "").getResponseAsString();
- assertEquals("s1/p1", r);
-
- client.setAccept("text/*,bad/*");
- r = client.doPut(url, "").getResponseAsString();
- assertEquals("s1/p1", r);
-
- client.setAccept("text/s1;q=0.5,text/s2");
- r = client.doPut(url, "").getResponseAsString();
- assertEquals("s2/p1", r);
-
- client.setAccept("text/s1,text/s2;q=0.5");
- r = client.doPut(url, "").getResponseAsString();
- assertEquals("s1/p1", r);
-
- client.closeQuietly();
- }
-
- //====================================================================================================
- // Test that default Accept and Content-Type headers on method annotation are picked up
- // when @RestMethod.parsers/serializers annotations are used.
- //====================================================================================================
- @Test
- public void testRestMethodParserSerializerAnnotations() throws Exception {
- RestClient client = new TestRestClient(JsonSerializer.DEFAULT, JsonParser.DEFAULT);
- String r;
-
- String url = URL + "/testRestMethodParserSerializerAnnotations";
-
- client.setAccept("").setContentType("");
- r = client.doPut(url, "").getResponseAsString();
- assertEquals("s3/p3", r);
-
- try {
- client.setAccept("text/s1").setContentType("");
- r = client.doPut(url+"?noTrace=true", "").getResponseAsString();
- fail("Exception expected");
- } catch (RestCallException e) {
- checkErrorResponse(debug, e, SC_NOT_ACCEPTABLE,
- "Unsupported media-type in request header 'Accept': 'text/s1'",
- "Supported media-types: [text/s3]"
- );
- }
-
- try {
- client.setAccept("").setContentType("text/p1");
- r = client.doPut(url+"?noTrace=true", "").getResponseAsString();
- fail("Exception expected");
- } catch (RestCallException e) {
- checkErrorResponse(debug, e, SC_UNSUPPORTED_MEDIA_TYPE,
- "Unsupported media-type in request header 'Content-Type': 'text/p1'",
- "Supported media-types: [text/p3]"
- );
- }
-
- try {
- client.setAccept("text/s1").setContentType("text/p1");
- r = client.doPut(url+"?noTrace=true", "").getResponseAsString();
- fail("Exception expected");
- } catch (RestCallException e) {
- checkErrorResponse(debug, e, SC_UNSUPPORTED_MEDIA_TYPE,
- "Unsupported media-type in request header 'Content-Type': 'text/p1'",
- "Supported media-types: [text/p3]"
- );
- }
-
- try {
- client.setAccept("text/s2").setContentType("");
- r = client.doPut(url+"?noTrace=true", "").getResponseAsString();
- fail("Exception expected");
- } catch (RestCallException e) {
- checkErrorResponse(debug, e, SC_NOT_ACCEPTABLE,
- "Unsupported media-type in request header 'Accept': 'text/s2'",
- "Supported media-types: [text/s3]"
- );
- }
-
- try {
- client.setAccept("").setContentType("text/p2");
- r = client.doPut(url+"?noTrace=true", "").getResponseAsString();
- fail("Exception expected");
- } catch (RestCallException e) {
- checkErrorResponse(debug, e, SC_UNSUPPORTED_MEDIA_TYPE,
- "Unsupported media-type in request header 'Content-Type': 'text/p2'",
- "Supported media-types: [text/p3]"
- );
- }
-
- try {
- client.setAccept("text/s2").setContentType("text/p2");
- r = client.doPut(url+"?noTrace=true", "").getResponseAsString();
- fail("Exception expected");
- } catch (RestCallException e) {
- checkErrorResponse(debug, e, SC_UNSUPPORTED_MEDIA_TYPE,
- "Unsupported media-type in request header 'Content-Type': 'text/p2'",
- "Supported media-types: [text/p3]"
- );
- }
-
- client.setAccept("text/s3").setContentType("");
- r = client.doPut(url, "").getResponseAsString();
- assertEquals("s3/p3", r);
-
- client.setAccept("").setContentType("text/p3");
- r = client.doPut(url, "").getResponseAsString();
- assertEquals("s3/p3", r);
-
- client.setAccept("text/s3").setContentType("text/p3");
- r = client.doPut(url, "").getResponseAsString();
- assertEquals("s3/p3", r);
-
- client.closeQuietly();
- }
-
- //====================================================================================================
- // Test that default Accept and Content-Type headers on method annotation are picked up
- // when @RestMethod.addParsers/addSerializers annotations are used.
- //====================================================================================================
- @Test
- public void testRestMethodAddParsersSerializersAnnotations() throws Exception {
- RestClient client = new TestRestClient(JsonSerializer.DEFAULT, JsonParser.DEFAULT);
- String r;
-
- String url = URL + "/testRestMethodAddParsersSerializersAnnotations";
-
- client.setAccept("").setContentType("");
- r = client.doPut(url, "").getResponseAsString();
- assertEquals("s3/p3", r);
-
- client.setAccept("text/s1").setContentType("");
- r = client.doPut(url, "").getResponseAsString();
- assertEquals("s1/p3", r);
-
- client.setAccept("").setContentType("text/p1");
- r = client.doPut(url, "").getResponseAsString();
- assertEquals("s3/p1", r);
-
- client.setAccept("text/s1").setContentType("text/p1");
- r = client.doPut(url, "").getResponseAsString();
- assertEquals("s1/p1", r);
-
- client.setAccept("text/s2").setContentType("");
- r = client.doPut(url, "").getResponseAsString();
- assertEquals("s2/p3", r);
-
- client.setAccept("").setContentType("text/p2");
- r = client.doPut(url, "").getResponseAsString();
- assertEquals("s3/p2", r);
-
- client.setAccept("text/s2").setContentType("text/p2");
- r = client.doPut(url, "").getResponseAsString();
- assertEquals("s2/p2", r);
-
- client.setAccept("text/s3").setContentType("");
- r = client.doPut(url, "").getResponseAsString();
- assertEquals("s3/p3", r);
-
- client.setAccept("").setContentType("text/p3");
- r = client.doPut(url, "").getResponseAsString();
- assertEquals("s3/p3", r);
-
- client.setAccept("text/s3").setContentType("text/p3");
- r = client.doPut(url, "").getResponseAsString();
- assertEquals("s3/p3", r);
-
- client.closeQuietly();
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestErrorConditions.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestErrorConditions.java b/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestErrorConditions.java
deleted file mode 100755
index 760399a..0000000
--- a/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestErrorConditions.java
+++ /dev/null
@@ -1,220 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.server;
-
-import static javax.servlet.http.HttpServletResponse.*;
-import static org.apache.juneau.server.TestUtils.*;
-import static org.junit.Assert.*;
-
-import org.apache.juneau.*;
-import org.apache.juneau.client.*;
-import org.apache.juneau.json.*;
-import org.junit.*;
-
-
-public class CT_TestErrorConditions {
-
- private static String URL = "/testErrorConditions";
- private static boolean debug = false;
- private static RestClient client;
-
- @BeforeClass
- public static void beforeClass() {
- client = new TestRestClient(JsonSerializer.DEFAULT, JsonParser.DEFAULT);
- }
-
- @AfterClass
- public static void afterClass() {
- client.closeQuietly();
- }
- //====================================================================================================
- // Test non-existent properties
- //====================================================================================================
- @Test
- public void testNonExistentBeanProperties() throws Exception {
- String url = URL + "/testNonExistentBeanProperties";
-
- try {
- client.doPut(url + "?noTrace=true", new ObjectMap("{f2:'foo'}")).getResponseAsString();
- fail("Exception expected");
- } catch (RestCallException e) {
- checkErrorResponse(debug, e, SC_BAD_REQUEST,
- "Could not convert request body content to class type 'org.apache.juneau.server.TestErrorConditions$Test1' using parser 'org.apache.juneau.json.JsonParser'",
- "Unknown property 'f2' encountered while trying to parse into class 'org.apache.juneau.server.TestErrorConditions$Test1'");
- }
-
- try {
- client.doPut(url + "?noTrace=true", new ObjectMap("{f1:'foo', f2:'foo'}")).getResponseAsString();
- fail("Exception expected");
- } catch (RestCallException e) {
- checkErrorResponse(debug, e, SC_BAD_REQUEST,
- "Could not convert request body content to class type 'org.apache.juneau.server.TestErrorConditions$Test1' using parser 'org.apache.juneau.json.JsonParser'",
- "Unknown property 'f2' encountered while trying to parse into class 'org.apache.juneau.server.TestErrorConditions$Test1'");
- }
- }
-
- //====================================================================================================
- // Test trying to set properties to wrong data type
- //====================================================================================================
- @Test
- public void testWrongDataType() throws Exception {
- String url = URL + "/testWrongDataType";
- try {
- client.doPut(url + "?noTrace=true", new ObjectMap("{f1:'foo'}")).getResponseAsString();
- fail("Exception expected");
- } catch (RestCallException e) {
- checkErrorResponse(debug, e, SC_BAD_REQUEST,
- "Could not convert request body content to class type 'org.apache.juneau.server.TestErrorConditions$Test2' using parser 'org.apache.juneau.json.JsonParser'.",
- "Could not convert string 'foo' to class 'int'");
- }
- }
-
- //====================================================================================================
- // Test trying to parse into class with non-public no-arg constructor.
- //====================================================================================================
- @Test
- public void testParseIntoNonConstructableBean() throws Exception {
- String url = URL + "/testParseIntoNonConstructableBean";
- try {
- client.doPut(url + "?noTrace=true", new ObjectMap("{f1:1}")).getResponseAsString();
- fail("Exception expected");
- } catch (RestCallException e) {
- checkErrorResponse(debug, e, SC_BAD_REQUEST,
- "Class 'org.apache.juneau.server.TestErrorConditions$Test3a' could not be instantiated.");
- }
- }
-
- //====================================================================================================
- // Test trying to parse into non-static inner class
- //====================================================================================================
- @Test
- public void testParseIntoNonStaticInnerClass() throws Exception {
- String url = URL + "/testParseIntoNonStaticInnerClass";
- try {
- client.doPut(url + "?noTrace=true", new ObjectMap("{f1:1}")).getResponseAsString();
- fail("Exception expected");
- } catch (RestCallException e) {
- checkErrorResponse(debug, e, SC_BAD_REQUEST,
- "Class 'org.apache.juneau.server.TestErrorConditions$Test3b' could not be instantiated. Reason: 'No properties detected on bean class'");
- }
- }
-
- //====================================================================================================
- // Test trying to parse into non-public inner class
- //====================================================================================================
- @Test
- public void testParseIntoNonPublicInnerClass() throws Exception {
- String url = URL + "/testParseIntoNonPublicInnerClass";
- try {
- client.doPut(url + "?noTrace=true", new ObjectMap("{f1:1}")).getResponseAsString();
- fail("Exception expected");
- } catch (RestCallException e) {
- checkErrorResponse(debug, e, SC_BAD_REQUEST,
- "Class 'org.apache.juneau.server.TestErrorConditions$Test3b1' could not be instantiated",
- "Class is not public");
- }
- }
-
- //====================================================================================================
- // Test exception thrown during bean construction.
- //====================================================================================================
- @Test
- public void testThrownConstructorException() throws Exception {
- String url = URL + "/testThrownConstructorException";
- try {
- client.doPut(url + "?noTrace=true", "'foo'").getResponseAsString();
- fail("Exception expected");
- } catch (RestCallException e) {
- checkErrorResponse(debug, e, SC_BAD_REQUEST,
- "Could not convert request body content to class type 'org.apache.juneau.server.TestErrorConditions$Test3c' using parser 'org.apache.juneau.json.JsonParser'.",
- "Caused by (RuntimeException): Test error");
- }
- }
-
- //====================================================================================================
- // Test trying to set parameters to invalid types.
- //====================================================================================================
- @Test
- public void testSetParameterToInvalidTypes() throws Exception {
- String url = URL + "/testSetParameterToInvalidTypes";
- try {
- client.doPut(url + "/1?noTrace=true&p1=foo", "").getResponseAsString();
- fail("Exception expected");
- } catch (RestCallException e) {
- checkErrorResponse(debug, e, SC_BAD_REQUEST,
- "Could not convert PARAM 'p1' to type 'int' on method 'org.apache.juneau.server.TestErrorConditions.testSetParameterToInvalidTypes'");
- }
-
- try {
- client.doPut(url + "/foo?noTrace=true&p1=1", "").getResponseAsString();
- fail("Exception expected");
- } catch (RestCallException e) {
- checkErrorResponse(debug, e, SC_BAD_REQUEST,
- "Could not convert ATTR 'a1' to type 'int' on method 'org.apache.juneau.server.TestErrorConditions.testSetParameterToInvalidTypes'");
- }
-
- try {
- client.doPut(url + "/1?noTrace=true&p1=1", "").setHeader("h1", "foo").getResponseAsString();
- fail("Exception expected");
- } catch (RestCallException e) {
- checkErrorResponse(debug, e, SC_BAD_REQUEST,
- "Could not convert HEADER 'h1' to type 'int' on method 'org.apache.juneau.server.TestErrorConditions.testSetParameterToInvalidTypes'");
- }
- }
-
- //====================================================================================================
- // Test SC_NOT_FOUND & SC_METHOD_NOT_ALLOWED
- //====================================================================================================
- @Test
- public void test404and405() throws Exception {
- String url = URL + "/test404and405";
- try {
- client.doGet(URL + "/testNonExistent?noTrace=true").getResponseAsString();
- fail("Exception expected");
- } catch (RestCallException e) {
- checkErrorResponse(debug, e, SC_NOT_FOUND,
- "Method 'GET' not found on resource with matching pattern on path '/testNonExistent'");
- }
-
- try {
- client.doPut(url + "?noTrace=true", "").getResponseAsString();
- fail("Exception expected");
- } catch (RestCallException e) {
- checkErrorResponse(debug, e, SC_NOT_FOUND,
- "Method 'PUT' not found on resource with matching pattern on path '/test404and405'");
- }
-
- try {
- client.doPost(url + "?noTrace=true", "").getResponseAsString();
- fail("Exception expected");
- } catch (RestCallException e) {
- checkErrorResponse(debug, e, SC_METHOD_NOT_ALLOWED,
- "Method 'POST' not found on resource.");
- }
- }
-
- //====================================================================================================
- // Test SC_PRECONDITION_FAILED
- //====================================================================================================
- @Test
- public void test412() throws Exception {
- String url = URL + "/test412";
- try {
- client.doGet(url + "?noTrace=true").getResponseAsString();
- fail("Exception expected");
- } catch (RestCallException e) {
- checkErrorResponse(debug, e, SC_PRECONDITION_FAILED,
- "Method 'GET' not found on resource on path '/test412' with matching matcher.");
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestGroups.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestGroups.java b/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestGroups.java
deleted file mode 100755
index 4e43e5e..0000000
--- a/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestGroups.java
+++ /dev/null
@@ -1,122 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.server;
-
-import static javax.servlet.http.HttpServletResponse.*;
-import static org.apache.juneau.server.TestUtils.*;
-import static org.junit.Assert.*;
-
-import java.io.*;
-
-import org.apache.juneau.client.*;
-import org.apache.juneau.json.*;
-import org.junit.*;
-
-
-public class CT_TestGroups {
-
- private static String URL = "/testGroups";
- private static boolean debug = false;
-
- //====================================================================================================
- // Serializer defined on class.
- //====================================================================================================
- @Test
- public void testSerializerDefinedOnClass() throws Exception {
- RestClient client = new TestRestClient(JsonSerializer.DEFAULT, JsonParser.DEFAULT);
- String url = URL + "/testSerializerDefinedOnClass";
- String r;
-
- try {
- client.setContentType("text/p1");
- r = client.doGet(url+"?noTrace=true").getResponseAsString();
- fail("Exception expected");
- } catch (RestCallException e) {
- checkErrorResponse(debug, e, SC_NOT_ACCEPTABLE,
- "Unsupported media-type in request header 'Accept': 'application/json'",
- "Supported media-types: [text/s1, text/s2]"
- );
- }
-
- client.setAccept("text/s1").setContentType("");
- r = client.doGet(url).getResponseAsString();
- assertEquals("text/s,GET", r);
-
- client.setAccept("text/s2").setContentType("");
- r = client.doGet(url).getResponseAsString();
- assertEquals("text/s,GET", r);
-
- try {
- client.setAccept("text/s3").setContentType("");
- r = client.doGet(url+"?noTrace=true").getResponseAsString();
- assertEquals("text/s,GET", r);
- } catch (RestCallException e) {
- checkErrorResponse(debug, e, SC_NOT_ACCEPTABLE,
- "Unsupported media-type in request header 'Accept': 'text/s3'",
- "Supported media-types: [text/s1, text/s2]"
- );
- }
-
- try {
- client.setAccept("text/json").setContentType("text/p1");
- r = client.doPut(url+"?noTrace=true", new StringReader("foo")).getResponseAsString();
- fail("Exception expected");
- } catch (RestCallException e) {
- checkErrorResponse(debug, e, SC_NOT_ACCEPTABLE,
- "Unsupported media-type in request header 'Accept': 'text/json'",
- "Supported media-types: [text/s1, text/s2]"
- );
- }
-
- try {
- client.setAccept("text/s1").setContentType("text/json");
- r = client.doPut(url+"?noTrace=true", new StringReader("foo")).getResponseAsString();
- fail("Exception expected");
- } catch (RestCallException e) {
- checkErrorResponse(debug, e, SC_UNSUPPORTED_MEDIA_TYPE,
- "Unsupported media-type in request header 'Content-Type': 'text/json'",
- "Supported media-types: [text/p1, text/p2]"
- );
- }
-
- client.setContentType("text/p1").setAccept("text/s1");
- r = client.doPut(url, new StringReader("foo")).getResponseAsString();
- assertEquals("text/s,foo", r);
-
- client.setContentType("text/p2").setAccept("text/s2");
- r = client.doPut(url, new StringReader("foo")).getResponseAsString();
- assertEquals("text/s,foo", r);
-
- try {
- client.setContentType("text/p1").setAccept("text/s3");
- r = client.doPut(url+"?noTrace=true", new StringReader("foo")).getResponseAsString();
- } catch (RestCallException e) {
- checkErrorResponse(debug, e, SC_NOT_ACCEPTABLE,
- "Unsupported media-type in request header 'Accept': 'text/s3'",
- "Supported media-types: [text/s1, text/s2]"
- );
- }
-
- try {
- client.setContentType("text/p3").setAccept("text/s1");
- r = client.doPut(url+"?noTrace=true", new StringReader("foo")).getResponseAsString();
- } catch (RestCallException e) {
- checkErrorResponse(debug, e, SC_UNSUPPORTED_MEDIA_TYPE,
- "Unsupported media-type in request header 'Content-Type': 'text/p3'",
- "Supported media-types: [text/p1, text/p2]"
- );
- }
-
- client.closeQuietly();
- }
-}
[34/44] incubator-juneau git commit: Rename CT_* testcases.
Posted by ja...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestTransformsTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestTransformsTest.java b/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestTransformsTest.java
new file mode 100755
index 0000000..85be1e2
--- /dev/null
+++ b/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestTransformsTest.java
@@ -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.juneau.server;
+
+import static org.junit.Assert.*;
+
+import org.apache.juneau.client.*;
+import org.apache.juneau.json.*;
+import org.junit.*;
+
+public class TestTransformsTest {
+
+ private static String URL = "/testTransforms";
+
+ //====================================================================================================
+ // test1 - Test class transform overrides parent class transform
+ // Should return "A2-1".
+ //====================================================================================================
+ @Test
+ public void testClassTransformOverridesParentClassTransform() throws Exception {
+ RestClient client = new TestRestClient(JsonSerializer.DEFAULT, JsonParser.DEFAULT);
+ String r;
+ String url = URL + "/testClassTransformOverridesParentClassTransform";
+
+ r = client.doGet(url).getResponse(String.class);
+ assertEquals("A2-0", r);
+
+ r = client.doPut(url, "A2-1").getResponse(String.class);
+ assertEquals("A2-1", r);
+
+ r = client.doPut(url + "/A2-2", "").getResponse(String.class);
+ assertEquals("A2-2", r);
+
+ client.closeQuietly();
+ }
+
+ //====================================================================================================
+ // Test method transform overrides class transform
+ // Should return "A3-1".
+ //====================================================================================================
+ @Test
+ public void testMethodTransformOverridesClassTransform() throws Exception {
+ RestClient client = new TestRestClient(JsonSerializer.DEFAULT, JsonParser.DEFAULT);
+ String r;
+ String url = URL + "/testMethodTransformOverridesClassTransform";
+
+ r = client.doGet(url).getResponse(String.class);
+ assertEquals("A3-0", r);
+
+ r = client.doPut(url, "A3-1").getResponse(String.class);
+ assertEquals("A3-1", r);
+
+ r = client.doPut(url + "/A3-2", "").getResponse(String.class);
+ assertEquals("A3-2", r);
+
+ client.closeQuietly();
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestUrisTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestUrisTest.java b/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestUrisTest.java
new file mode 100755
index 0000000..4cf147e
--- /dev/null
+++ b/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestUrisTest.java
@@ -0,0 +1,918 @@
+/***************************************************************************************************************************
+ * 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.juneau.server;
+
+import static org.junit.Assert.*;
+
+import java.util.regex.*;
+
+import org.apache.juneau.*;
+import org.apache.juneau.client.*;
+import org.apache.juneau.json.*;
+import org.junit.*;
+
+/**
+ * Verifies that all the RestRequest.getXXX() methods involving URIs work correctly.
+ */
+public class TestUrisTest {
+
+ private static String URL2 = Constants.getServerTestUrl() + "/testuris"; // /jazz/juneau/sample/testuris
+ private static int port = getPort(Constants.getServerTestUrl()); // 9443
+ private static String path = Constants.getServerTestUri().getPath(); // /jazz/juneau/sample
+
+ //====================================================================================================
+ // testRoot - http://localhost:8080/sample/testuris
+ //====================================================================================================
+ @Test
+ public void testRoot() throws Exception {
+ RestClient client = new TestRestClient(JsonSerializer.DEFAULT, JsonParser.DEFAULT);
+ ObjectMap r;
+
+ //--------------------------------------------------------------------------------
+ // http://localhost:8080/sample/testuris
+ //--------------------------------------------------------------------------------
+ r = client.doGet("/testuris").getResponse(ObjectMap.class);
+ assertEquals("root.test1", r.getString("testMethod"));
+ assertNull(r.getString("pathInfo"));
+ assertNull(r.getString("pathRemainder"));
+ assertEquals(path + "/testuris", r.getString("requestURI"));
+ assertTrue(r.getString("requestURL").endsWith(port + path + "/testuris"));
+ // Same for servlet
+ assertEquals(path + "/testuris", r.getString("contextPath") + r.getString("servletPath")); // App may not have context path, but combination should always equal path.
+ assertEquals(URL2, r.getString("servletURI"));
+ assertTrue(r.getString("testURL1").endsWith(port + path + "/testuris/testURL"));
+ // Always the same
+ assertTrue(r.getString("testURL2").endsWith(port + "/testURL"));
+ assertEquals("http://testURL", r.getString("testURL3"));
+
+ //--------------------------------------------------------------------------------
+ // http://localhost:8080/sample/testuris/foo
+ //--------------------------------------------------------------------------------
+ r = client.doGet("/testuris/foo").getResponse(ObjectMap.class);
+ assertEquals("root.test1", r.getString("testMethod"));
+ assertEquals("/foo", r.getString("pathInfo"));
+ assertEquals("foo", r.getString("pathRemainder"));
+ assertEquals(path + "/testuris", r.getString("requestParentURI"));
+ assertEquals(path + "/testuris/foo", r.getString("requestURI"));
+ assertTrue(r.getString("requestURL").endsWith(port + path + "/testuris/foo"));
+ // Same for servlet
+ assertEquals(path + "/testuris", r.getString("contextPath") + r.getString("servletPath")); // App may not have context path, but combination should always equal path.
+ assertEquals(URL2, r.getString("servletURI"));
+ assertTrue(r.getString("testURL1").endsWith(port + path + "/testuris/testURL"));
+ // Always the same
+ assertTrue(r.getString("testURL2").endsWith(port + "/testURL"));
+ assertEquals("http://testURL", r.getString("testURL3"));
+
+ //--------------------------------------------------------------------------------
+ // http://localhost:8080/sample/testuris/foo/bar
+ //--------------------------------------------------------------------------------
+ r = client.doGet("/testuris/foo/bar").getResponse(ObjectMap.class);
+ assertEquals("root.test1", r.getString("testMethod"));
+ assertEquals("/foo/bar", r.getString("pathInfo"));
+ assertEquals("foo/bar", r.getString("pathRemainder"));
+ assertEquals(path + "/testuris/foo", r.getString("requestParentURI"));
+ assertEquals(path + "/testuris/foo/bar", r.getString("requestURI"));
+ assertTrue(r.getString("requestURL").endsWith(port + path + "/testuris/foo/bar"));
+ // Same for servlet
+ assertEquals(path + "/testuris", r.getString("contextPath") + r.getString("servletPath")); // App may not have context path, but combination should always equal path.
+ assertEquals(URL2, r.getString("servletURI"));
+ assertTrue(r.getString("testURL1").endsWith(port + path + "/testuris/testURL"));
+ // Always the same
+ assertTrue(r.getString("testURL2").endsWith(port + "/testURL"));
+ assertEquals("http://testURL", r.getString("testURL3"));
+
+ //--------------------------------------------------------------------------------
+ // http://localhost:8080/sample/testuris/foo/bar%2Fbaz
+ //--------------------------------------------------------------------------------
+ r = client.doGet("/testuris/foo/bar%2Fbaz").getResponse(ObjectMap.class);
+ assertEquals("root.test1", r.getString("testMethod"));
+ assertEquals("/foo/bar/baz", r.getString("pathInfo"));
+ assertEquals("foo/bar/baz", r.getString("pathRemainder"));
+ assertEquals(path + "/testuris/foo", r.getString("requestParentURI"));
+ assertEquals(path + "/testuris/foo/bar%2Fbaz", r.getString("requestURI"));
+ assertTrue(r.getString("requestURL").endsWith(port + path + "/testuris/foo/bar%2Fbaz"));
+ // Same for servlet
+ assertEquals(path + "/testuris", r.getString("contextPath") + r.getString("servletPath")); // App may not have context path, but combination should always equal path.
+ assertEquals(URL2, r.getString("servletURI"));
+ assertTrue(r.getString("testURL1").endsWith(port + path + "/testuris/testURL"));
+ // Always the same
+ assertTrue(r.getString("testURL2").endsWith(port + "/testURL"));
+ assertEquals("http://testURL", r.getString("testURL3"));
+
+ //--------------------------------------------------------------------------------
+ // http://localhost:8080/sample/testuris/test2
+ //--------------------------------------------------------------------------------
+ r = client.doGet("/testuris/test2").getResponse(ObjectMap.class);
+ assertEquals("root.test2", r.getString("testMethod"));
+ assertEquals("/test2", r.getString("pathInfo"));
+ assertNull(r.getString("pathRemainder"));
+ assertEquals(path + "/testuris", r.getString("requestParentURI"));
+ assertEquals(path + "/testuris/test2", r.getString("requestURI"));
+ assertTrue(r.getString("requestURL").endsWith(port + path + "/testuris/test2"));
+ // Same for servlet
+ assertEquals(path + "/testuris", r.getString("contextPath") + r.getString("servletPath")); // App may not have context path, but combination should always equal path.
+ assertEquals(URL2, r.getString("servletURI"));
+ assertTrue(r.getString("testURL1").endsWith(port + path + "/testuris/testURL"));
+ // Always the same
+ assertTrue(r.getString("testURL2").endsWith(port + "/testURL"));
+ assertEquals("http://testURL", r.getString("testURL3"));
+
+ //--------------------------------------------------------------------------------
+ // http://localhost:8080/sample/testuris/test2/foo
+ //--------------------------------------------------------------------------------
+ r = client.doGet("/testuris/test2/foo").getResponse(ObjectMap.class);
+ assertEquals("root.test2", r.getString("testMethod"));
+ assertEquals("/test2/foo", r.getString("pathInfo"));
+ assertEquals("foo", r.getString("pathRemainder"));
+ assertEquals(path + "/testuris/test2", r.getString("requestParentURI"));
+ assertEquals(path + "/testuris/test2/foo", r.getString("requestURI"));
+ assertTrue(r.getString("requestURL").endsWith(port + path + "/testuris/test2/foo"));
+ // Same for servlet
+ assertEquals(path + "/testuris", r.getString("contextPath") + r.getString("servletPath")); // App may not have context path, but combination should always equal path.
+ assertEquals(URL2, r.getString("servletURI"));
+ assertTrue(r.getString("testURL1").endsWith(port + path + "/testuris/testURL"));
+ // Always the same
+ assertTrue(r.getString("testURL2").endsWith(port + "/testURL"));
+ assertEquals("http://testURL", r.getString("testURL3"));
+
+ //--------------------------------------------------------------------------------
+ // http://localhost:8080/sample/testuris/test2/foo/bar
+ //--------------------------------------------------------------------------------
+ r = client.doGet("/testuris/test2/foo/bar").getResponse(ObjectMap.class);
+ assertEquals("root.test2", r.getString("testMethod"));
+ assertEquals("/test2/foo/bar", r.getString("pathInfo"));
+ assertEquals("foo/bar", r.getString("pathRemainder"));
+ assertEquals(path + "/testuris/test2/foo", r.getString("requestParentURI"));
+ assertEquals(path + "/testuris/test2/foo/bar", r.getString("requestURI"));
+ assertTrue(r.getString("requestURL").endsWith(port + path + "/testuris/test2/foo/bar"));
+ // Same for servlet
+ assertEquals(path + "/testuris", r.getString("contextPath") + r.getString("servletPath")); // App may not have context path, but combination should always equal path.
+ assertEquals(URL2, r.getString("servletURI"));
+ assertTrue(r.getString("testURL1").endsWith(port + path + "/testuris/testURL"));
+ // Always the same
+ assertTrue(r.getString("testURL2").endsWith(port + "/testURL"));
+ assertEquals("http://testURL", r.getString("testURL3"));
+
+ //--------------------------------------------------------------------------------
+ // http://localhost:8080/sample/testuris/test3%2Ftest3
+ //--------------------------------------------------------------------------------
+ r = client.doGet("/testuris/test3%2Ftest3").getResponse(ObjectMap.class);
+ assertEquals("root.test3", r.getString("testMethod"));
+ assertEquals("/test3/test3", r.getString("pathInfo"));
+ assertNull(r.getString("pathRemainder"));
+ assertEquals(path + "/testuris", r.getString("requestParentURI"));
+ assertEquals(path + "/testuris/test3%2Ftest3", r.getString("requestURI"));
+ assertTrue(r.getString("requestURL").endsWith(port + path + "/testuris/test3%2Ftest3"));
+ // Same for servlet
+ assertEquals(path + "/testuris", r.getString("contextPath") + r.getString("servletPath")); // App may not have context path, but combination should always equal path.
+ assertEquals(URL2, r.getString("servletURI"));
+ assertTrue(r.getString("testURL1").endsWith(port + path + "/testuris/testURL"));
+ // Always the same
+ assertTrue(r.getString("testURL2").endsWith(port + "/testURL"));
+ assertEquals("http://testURL", r.getString("testURL3"));
+
+ //--------------------------------------------------------------------------------
+ // http://localhost:8080/sample/testuris/test3%2Ftest3/foo
+ //--------------------------------------------------------------------------------
+ r = client.doGet("/testuris/test3%2Ftest3/foo").getResponse(ObjectMap.class);
+ assertEquals("root.test3", r.getString("testMethod"));
+ assertEquals("/test3/test3/foo", r.getString("pathInfo"));
+ assertEquals("foo", r.getString("pathRemainder"));
+ assertEquals(path + "/testuris/test3%2Ftest3", r.getString("requestParentURI"));
+ assertEquals(path + "/testuris/test3%2Ftest3/foo", r.getString("requestURI"));
+ assertTrue(r.getString("requestURL").endsWith(port + path + "/testuris/test3%2Ftest3/foo"));
+ // Same for servlet
+ assertEquals(path + "/testuris", r.getString("contextPath") + r.getString("servletPath")); // App may not have context path, but combination should always equal path.
+ assertEquals(URL2, r.getString("servletURI"));
+ assertTrue(r.getString("testURL1").endsWith(port + path + "/testuris/testURL"));
+ // Always the same
+ assertTrue(r.getString("testURL2").endsWith(port + "/testURL"));
+ assertEquals("http://testURL", r.getString("testURL3"));
+
+ //--------------------------------------------------------------------------------
+ // http://localhost:8080/sample/testuris/test3%2Ftest3/foo/bar
+ //--------------------------------------------------------------------------------
+ r = client.doGet("/testuris/test3%2Ftest3/foo/bar").getResponse(ObjectMap.class);
+ assertEquals("root.test3", r.getString("testMethod"));
+ assertEquals("/test3/test3/foo/bar", r.getString("pathInfo"));
+ assertEquals("foo/bar", r.getString("pathRemainder"));
+ assertEquals(path + "/testuris/test3%2Ftest3/foo", r.getString("requestParentURI"));
+ assertEquals(path + "/testuris/test3%2Ftest3/foo/bar", r.getString("requestURI"));
+ assertTrue(r.getString("requestURL").endsWith(port + path + "/testuris/test3%2Ftest3/foo/bar"));
+ // Same for servlet
+ assertEquals(path + "/testuris", r.getString("contextPath") + r.getString("servletPath")); // App may not have context path, but combination should always equal path.
+ assertEquals(URL2, r.getString("servletURI"));
+ assertTrue(r.getString("testURL1").endsWith(port + path + "/testuris/testURL"));
+ // Always the same
+ assertTrue(r.getString("testURL2").endsWith(port + "/testURL"));
+ assertEquals("http://testURL", r.getString("testURL3"));
+
+ //--------------------------------------------------------------------------------
+ // http://localhost:8080/sample/testuris/test3%2Ftest3/foo/bar%2Fbaz
+ //--------------------------------------------------------------------------------
+ r = client.doGet("/testuris/test3%2Ftest3/foo/bar%2Fbaz").getResponse(ObjectMap.class);
+ assertEquals("root.test3", r.getString("testMethod"));
+ assertEquals("/test3/test3/foo/bar/baz", r.getString("pathInfo"));
+ assertEquals("foo/bar/baz", r.getString("pathRemainder"));
+ assertEquals(path + "/testuris/test3%2Ftest3/foo", r.getString("requestParentURI"));
+ assertEquals(path + "/testuris/test3%2Ftest3/foo/bar%2Fbaz", r.getString("requestURI"));
+ assertTrue(r.getString("requestURL").endsWith(port + path + "/testuris/test3%2Ftest3/foo/bar%2Fbaz"));
+ // Same for servlet
+ assertEquals(path + "/testuris", r.getString("contextPath") + r.getString("servletPath")); // App may not have context path, but combination should always equal path.
+ assertEquals(URL2, r.getString("servletURI"));
+ assertTrue(r.getString("testURL1").endsWith(port + path + "/testuris/testURL"));
+ // Always the same
+ assertTrue(r.getString("testURL2").endsWith(port + "/testURL"));
+ assertEquals("http://testURL", r.getString("testURL3"));
+
+ //--------------------------------------------------------------------------------
+ // http://localhost:8080/sample/testuris/test4/test4
+ //--------------------------------------------------------------------------------
+ r = client.doGet("/testuris/test4/test4").getResponse(ObjectMap.class);
+ assertEquals("root.test4", r.getString("testMethod"));
+ assertEquals("/test4/test4", r.getString("pathInfo"));
+ assertNull(r.getString("pathRemainder"));
+ assertEquals(path + "/testuris/test4", r.getString("requestParentURI"));
+ assertEquals(path + "/testuris/test4/test4", r.getString("requestURI"));
+ assertTrue(r.getString("requestURL").endsWith(port + path + "/testuris/test4/test4"));
+ // Same for servlet
+ assertEquals(path + "/testuris", r.getString("contextPath") + r.getString("servletPath")); // App may not have context path, but combination should always equal path.
+ assertEquals(URL2, r.getString("servletURI"));
+ assertTrue(r.getString("testURL1").endsWith(port + path + "/testuris/testURL"));
+ // Always the same
+ assertTrue(r.getString("testURL2").endsWith(port + "/testURL"));
+ assertEquals("http://testURL", r.getString("testURL3"));
+
+ //--------------------------------------------------------------------------------
+ // http://localhost:8080/sample/testuris/test4/test4/foo
+ //--------------------------------------------------------------------------------
+ r = client.doGet("/testuris/test4/test4/foo").getResponse(ObjectMap.class);
+ assertEquals("root.test4", r.getString("testMethod"));
+ assertEquals("/test4/test4/foo", r.getString("pathInfo"));
+ assertEquals("foo", r.getString("pathRemainder"));
+ assertEquals(path + "/testuris/test4/test4", r.getString("requestParentURI"));
+ assertEquals(path + "/testuris/test4/test4/foo", r.getString("requestURI"));
+ assertTrue(r.getString("requestURL").endsWith(port + path + "/testuris/test4/test4/foo"));
+ // Same for servlet
+ assertEquals(path + "/testuris", r.getString("contextPath") + r.getString("servletPath")); // App may not have context path, but combination should always equal path.
+ assertEquals(URL2, r.getString("servletURI"));
+ assertTrue(r.getString("testURL1").endsWith(port + path + "/testuris/testURL"));
+ // Always the same
+ assertTrue(r.getString("testURL2").endsWith(port + "/testURL"));
+ assertEquals("http://testURL", r.getString("testURL3"));
+
+ //--------------------------------------------------------------------------------
+ // http://localhost:8080/sample/testuris/test4/test4/foo/bar
+ //--------------------------------------------------------------------------------
+ r = client.doGet("/testuris/test4/test4/foo/bar").getResponse(ObjectMap.class);
+ assertEquals("root.test4", r.getString("testMethod"));
+ assertEquals("/test4/test4/foo/bar", r.getString("pathInfo"));
+ assertEquals("foo/bar", r.getString("pathRemainder"));
+ assertEquals(path + "/testuris/test4/test4/foo", r.getString("requestParentURI"));
+ assertEquals(path + "/testuris/test4/test4/foo/bar", r.getString("requestURI"));
+ assertTrue(r.getString("requestURL").endsWith(port + path + "/testuris/test4/test4/foo/bar"));
+ // Same for servlet
+ assertEquals(path + "/testuris", r.getString("contextPath") + r.getString("servletPath")); // App may not have context path, but combination should always equal path.
+ assertEquals(URL2, r.getString("servletURI"));
+ assertTrue(r.getString("testURL1").endsWith(port + path + "/testuris/testURL"));
+ // Always the same
+ assertTrue(r.getString("testURL2").endsWith(port + "/testURL"));
+ assertEquals("http://testURL", r.getString("testURL3"));
+
+ //--------------------------------------------------------------------------------
+ // http://localhost:8080/sample/testuris/test4/test4/foo/bar%2Fbaz
+ //--------------------------------------------------------------------------------
+ r = client.doGet("/testuris/test4/test4/foo/bar%2Fbaz").getResponse(ObjectMap.class);
+ assertEquals("root.test4", r.getString("testMethod"));
+ assertEquals("/test4/test4/foo/bar/baz", r.getString("pathInfo"));
+ assertEquals("foo/bar/baz", r.getString("pathRemainder"));
+ assertEquals(path + "/testuris/test4/test4/foo", r.getString("requestParentURI"));
+ assertEquals(path + "/testuris/test4/test4/foo/bar%2Fbaz", r.getString("requestURI"));
+ assertTrue(r.getString("requestURL").endsWith(port + path + "/testuris/test4/test4/foo/bar%2Fbaz"));
+ // Same for servlet
+ assertEquals(path + "/testuris", r.getString("contextPath") + r.getString("servletPath")); // App may not have context path, but combination should always equal path.
+ assertEquals(URL2, r.getString("servletURI"));
+ assertTrue(r.getString("testURL1").endsWith(port + path + "/testuris/testURL"));
+ // Always the same
+ assertTrue(r.getString("testURL2").endsWith(port + "/testURL"));
+ assertEquals("http://testURL", r.getString("testURL3"));
+
+ client.closeQuietly();
+ }
+
+ //====================================================================================================
+ // testChild - http://localhost:8080/sample/testuris/child
+ //====================================================================================================
+ @Test
+ public void testChild() throws Exception {
+ RestClient client = new TestRestClient(JsonSerializer.DEFAULT, JsonParser.DEFAULT);
+ ObjectMap r;
+
+ //--------------------------------------------------------------------------------
+ // http://localhost:8080/sample/testuris/child
+ //--------------------------------------------------------------------------------
+ r = client.doGet("/testuris/child").getResponse(ObjectMap.class);
+ assertEquals("child.test1", r.getString("testMethod"));
+ assertNull(r.getString("pathInfo"));
+ assertNull(r.getString("pathRemainder"));
+ assertEquals(path + "/testuris", r.getString("requestParentURI"));
+ assertEquals(path + "/testuris/child", r.getString("requestURI"));
+ assertTrue(r.getString("requestURL").endsWith(port + path + "/testuris/child"));
+ // Same for servlet
+ assertEquals(path + "/testuris/child", r.getString("contextPath") + r.getString("servletPath")); // App may not have context path, but combination should always equal path.
+ assertEquals(URL2 + "/child", r.getString("servletURI"));
+ assertTrue(r.getString("testURL1").endsWith(port + path + "/testuris/child/testURL"));
+ // Always the same
+ assertTrue(r.getString("testURL2").endsWith(port + "/testURL"));
+ assertEquals("http://testURL", r.getString("testURL3"));
+
+ //--------------------------------------------------------------------------------
+ // http://localhost:8080/sample/testuris/child/foo
+ //--------------------------------------------------------------------------------
+ r = client.doGet("/testuris/child/foo").getResponse(ObjectMap.class);
+ assertEquals("child.test1", r.getString("testMethod"));
+ assertEquals("/foo", r.getString("pathInfo"));
+ assertEquals("foo", r.getString("pathRemainder"));
+ assertEquals(path + "/testuris/child", r.getString("requestParentURI"));
+ assertEquals(path + "/testuris/child/foo", r.getString("requestURI"));
+ assertTrue(r.getString("requestURL").endsWith(port + path + "/testuris/child/foo"));
+ // Same for servlet
+ assertEquals(path + "/testuris/child", r.getString("contextPath") + r.getString("servletPath")); // App may not have context path, but combination should always equal path.
+ assertEquals(URL2 + "/child", r.getString("servletURI"));
+ assertTrue(r.getString("testURL1").endsWith(port + path + "/testuris/child/testURL"));
+ // Always the same
+ assertTrue(r.getString("testURL2").endsWith(port + "/testURL"));
+ assertEquals("http://testURL", r.getString("testURL3"));
+
+ //--------------------------------------------------------------------------------
+ // http://localhost:8080/sample/testuris/child/foo/bar
+ //--------------------------------------------------------------------------------
+ r = client.doGet("/testuris/child/foo/bar").getResponse(ObjectMap.class);
+ assertEquals("child.test1", r.getString("testMethod"));
+ assertEquals("/foo/bar", r.getString("pathInfo"));
+ assertEquals("foo/bar", r.getString("pathRemainder"));
+ assertEquals(path + "/testuris/child/foo", r.getString("requestParentURI"));
+ assertEquals(path + "/testuris/child/foo/bar", r.getString("requestURI"));
+ assertTrue(r.getString("requestURL").endsWith(port + path + "/testuris/child/foo/bar"));
+ // Same for servlet
+ assertEquals(path + "/testuris/child", r.getString("contextPath") + r.getString("servletPath")); // App may not have context path, but combination should always equal path.
+ assertEquals(URL2 + "/child", r.getString("servletURI"));
+ assertTrue(r.getString("testURL1").endsWith(port + path + "/testuris/child/testURL"));
+ // Always the same
+ assertTrue(r.getString("testURL2").endsWith(port + "/testURL"));
+ assertEquals("http://testURL", r.getString("testURL3"));
+
+ //--------------------------------------------------------------------------------
+ // http://localhost:8080/sample/testuris/child/foo/bar%2Fbaz
+ //--------------------------------------------------------------------------------
+ r = client.doGet("/testuris/child/foo/bar%2Fbaz").getResponse(ObjectMap.class);
+ assertEquals("child.test1", r.getString("testMethod"));
+ assertEquals("/foo/bar/baz", r.getString("pathInfo"));
+ assertEquals("foo/bar/baz", r.getString("pathRemainder"));
+ assertEquals(path + "/testuris/child/foo", r.getString("requestParentURI"));
+ assertEquals(path + "/testuris/child/foo/bar%2Fbaz", r.getString("requestURI"));
+ assertTrue(r.getString("requestURL").endsWith(port + path + "/testuris/child/foo/bar%2Fbaz"));
+ // Same for servlet
+ assertEquals(path + "/testuris/child", r.getString("contextPath") + r.getString("servletPath")); // App may not have context path, but combination should always equal path.
+ assertEquals(URL2 + "/child", r.getString("servletURI"));
+ assertTrue(r.getString("testURL1").endsWith(port + path + "/testuris/child/testURL"));
+ // Always the same
+ assertTrue(r.getString("testURL2").endsWith(port + "/testURL"));
+ assertEquals("http://testURL", r.getString("testURL3"));
+
+ //--------------------------------------------------------------------------------
+ // http://localhost:8080/sample/testuris/child/test2
+ //--------------------------------------------------------------------------------
+ r = client.doGet("/testuris/child/test2").getResponse(ObjectMap.class);
+ assertEquals("child.test2", r.getString("testMethod"));
+ assertEquals("/test2", r.getString("pathInfo"));
+ assertNull(r.getString("pathRemainder"));
+ assertEquals(path + "/testuris/child", r.getString("requestParentURI"));
+ assertEquals(path + "/testuris/child/test2", r.getString("requestURI"));
+ assertTrue(r.getString("requestURL").endsWith(port + path + "/testuris/child/test2"));
+ // Same for servlet
+ assertEquals(path + "/testuris/child", r.getString("contextPath") + r.getString("servletPath")); // App may not have context path, but combination should always equal path.
+ assertEquals(URL2 + "/child", r.getString("servletURI"));
+ assertTrue(r.getString("testURL1").endsWith(port + path + "/testuris/child/testURL"));
+ // Always the same
+ assertTrue(r.getString("testURL2").endsWith(port + "/testURL"));
+ assertEquals("http://testURL", r.getString("testURL3"));
+
+ //--------------------------------------------------------------------------------
+ // http://localhost:8080/sample/testuris/child/test2/foo
+ //--------------------------------------------------------------------------------
+ r = client.doGet("/testuris/child/test2/foo").getResponse(ObjectMap.class);
+ assertEquals("child.test2", r.getString("testMethod"));
+ assertEquals("/test2/foo", r.getString("pathInfo"));
+ assertEquals("foo", r.getString("pathRemainder"));
+ assertEquals(path + "/testuris/child/test2", r.getString("requestParentURI"));
+ assertEquals(path + "/testuris/child/test2/foo", r.getString("requestURI"));
+ assertTrue(r.getString("requestURL").endsWith(port + path + "/testuris/child/test2/foo"));
+ // Same for servlet
+ assertEquals(path + "/testuris/child", r.getString("contextPath") + r.getString("servletPath")); // App may not have context path, but combination should always equal path.
+ assertEquals(URL2 + "/child", r.getString("servletURI"));
+ assertTrue(r.getString("testURL1").endsWith(port + path + "/testuris/child/testURL"));
+ // Always the same
+ assertTrue(r.getString("testURL2").endsWith(port + "/testURL"));
+ assertEquals("http://testURL", r.getString("testURL3"));
+
+ //--------------------------------------------------------------------------------
+ // http://localhost:8080/sample/testuris/child/test2/foo/bar
+ //--------------------------------------------------------------------------------
+ r = client.doGet("/testuris/child/test2/foo/bar").getResponse(ObjectMap.class);
+ assertEquals("child.test2", r.getString("testMethod"));
+ assertEquals("/test2/foo/bar", r.getString("pathInfo"));
+ assertEquals("foo/bar", r.getString("pathRemainder"));
+ assertEquals(path + "/testuris/child/test2/foo", r.getString("requestParentURI"));
+ assertEquals(path + "/testuris/child/test2/foo/bar", r.getString("requestURI"));
+ assertTrue(r.getString("requestURL").endsWith(port + path + "/testuris/child/test2/foo/bar"));
+ // Same for servlet
+ assertEquals(path + "/testuris/child", r.getString("contextPath") + r.getString("servletPath")); // App may not have context path, but combination should always equal path.
+ assertEquals(URL2 + "/child", r.getString("servletURI"));
+ assertTrue(r.getString("testURL1").endsWith(port + path + "/testuris/child/testURL"));
+ // Always the same
+ assertTrue(r.getString("testURL2").endsWith(port + "/testURL"));
+ assertEquals("http://testURL", r.getString("testURL3"));
+
+ //--------------------------------------------------------------------------------
+ // http://localhost:8080/sample/testuris/child/test2/foo/bar%2Fbaz
+ //--------------------------------------------------------------------------------
+ r = client.doGet("/testuris/child/test2/foo/bar%2Fbaz").getResponse(ObjectMap.class);
+ assertEquals("child.test2", r.getString("testMethod"));
+ assertEquals("/test2/foo/bar/baz", r.getString("pathInfo"));
+ assertEquals("foo/bar/baz", r.getString("pathRemainder"));
+ assertEquals(path + "/testuris/child/test2/foo", r.getString("requestParentURI"));
+ assertEquals(path + "/testuris/child/test2/foo/bar%2Fbaz", r.getString("requestURI"));
+ assertTrue(r.getString("requestURL").endsWith(port + path + "/testuris/child/test2/foo/bar%2Fbaz"));
+ // Same for servlet
+ assertEquals(path + "/testuris/child", r.getString("contextPath") + r.getString("servletPath")); // App may not have context path, but combination should always equal path.
+ assertEquals(URL2 + "/child", r.getString("servletURI"));
+ assertTrue(r.getString("testURL1").endsWith(port + path + "/testuris/child/testURL"));
+ // Always the same
+ assertTrue(r.getString("testURL2").endsWith(port + "/testURL"));
+ assertEquals("http://testURL", r.getString("testURL3"));
+
+ //--------------------------------------------------------------------------------
+ // http://localhost:8080/sample/testuris/child/test3%2Ftest3
+ //--------------------------------------------------------------------------------
+ r = client.doGet("/testuris/child/test3%2Ftest3").getResponse(ObjectMap.class);
+ assertEquals("child.test3", r.getString("testMethod"));
+ assertEquals("/test3/test3", r.getString("pathInfo"));
+ assertNull(r.getString("pathRemainder"));
+ assertEquals(path + "/testuris/child", r.getString("requestParentURI"));
+ assertEquals(path + "/testuris/child/test3%2Ftest3", r.getString("requestURI"));
+ assertTrue(r.getString("requestURL").endsWith(port + path + "/testuris/child/test3%2Ftest3"));
+ // Same for servlet
+ assertEquals(path + "/testuris/child", r.getString("contextPath") + r.getString("servletPath")); // App may not have context path, but combination should always equal path.
+ assertEquals(URL2 + "/child", r.getString("servletURI"));
+ assertTrue(r.getString("testURL1").endsWith(port + path + "/testuris/child/testURL"));
+ // Always the same
+ assertTrue(r.getString("testURL2").endsWith(port + "/testURL"));
+ assertEquals("http://testURL", r.getString("testURL3"));
+
+ //--------------------------------------------------------------------------------
+ // http://localhost:8080/sample/testuris/child/test3%2Ftest3/foo
+ //--------------------------------------------------------------------------------
+ r = client.doGet("/testuris/child/test3%2Ftest3/foo").getResponse(ObjectMap.class);
+ assertEquals("child.test3", r.getString("testMethod"));
+ assertEquals("/test3/test3/foo", r.getString("pathInfo"));
+ assertEquals("foo", r.getString("pathRemainder"));
+ assertEquals(path + "/testuris/child/test3%2Ftest3", r.getString("requestParentURI"));
+ assertEquals(path + "/testuris/child/test3%2Ftest3/foo", r.getString("requestURI"));
+ assertTrue(r.getString("requestURL").endsWith(port + path + "/testuris/child/test3%2Ftest3/foo"));
+ // Same for servlet
+ assertEquals(path + "/testuris/child", r.getString("contextPath") + r.getString("servletPath")); // App may not have context path, but combination should always equal path.
+ assertEquals(URL2 + "/child", r.getString("servletURI"));
+ assertTrue(r.getString("testURL1").endsWith(port + path + "/testuris/child/testURL"));
+ // Always the same
+ assertTrue(r.getString("testURL2").endsWith(port + "/testURL"));
+ assertEquals("http://testURL", r.getString("testURL3"));
+
+ //--------------------------------------------------------------------------------
+ // http://localhost:8080/sample/testuris/child/test3%2Ftest3/foo/bar
+ //--------------------------------------------------------------------------------
+ r = client.doGet("/testuris/child/test3%2Ftest3/foo/bar").getResponse(ObjectMap.class);
+ assertEquals("child.test3", r.getString("testMethod"));
+ assertEquals("/test3/test3/foo/bar", r.getString("pathInfo"));
+ assertEquals("foo/bar", r.getString("pathRemainder"));
+ assertEquals(path + "/testuris/child/test3%2Ftest3/foo", r.getString("requestParentURI"));
+ assertEquals(path + "/testuris/child/test3%2Ftest3/foo/bar", r.getString("requestURI"));
+ assertTrue(r.getString("requestURL").endsWith(port + path + "/testuris/child/test3%2Ftest3/foo/bar"));
+ // Same for servlet
+ assertEquals(path + "/testuris/child", r.getString("contextPath") + r.getString("servletPath")); // App may not have context path, but combination should always equal path.
+ assertEquals(URL2 + "/child", r.getString("servletURI"));
+ assertTrue(r.getString("testURL1").endsWith(port + path + "/testuris/child/testURL"));
+ // Always the same
+ assertTrue(r.getString("testURL2").endsWith(port + "/testURL"));
+ assertEquals("http://testURL", r.getString("testURL3"));
+
+ //--------------------------------------------------------------------------------
+ // http://localhost:8080/sample/testuris/child/test3%2Ftest3/foo/bar%2Fbaz
+ //--------------------------------------------------------------------------------
+ r = client.doGet("/testuris/child/test3%2Ftest3/foo/bar%2Fbaz").getResponse(ObjectMap.class);
+ assertEquals("child.test3", r.getString("testMethod"));
+ assertEquals("/test3/test3/foo/bar/baz", r.getString("pathInfo"));
+ assertEquals("foo/bar/baz", r.getString("pathRemainder"));
+ assertEquals(path + "/testuris/child/test3%2Ftest3/foo", r.getString("requestParentURI"));
+ assertEquals(path + "/testuris/child/test3%2Ftest3/foo/bar%2Fbaz", r.getString("requestURI"));
+ assertTrue(r.getString("requestURL").endsWith(port + path + "/testuris/child/test3%2Ftest3/foo/bar%2Fbaz"));
+ // Same for servlet
+ assertEquals(path + "/testuris/child", r.getString("contextPath") + r.getString("servletPath")); // App may not have context path, but combination should always equal path.
+ assertEquals(URL2 + "/child", r.getString("servletURI"));
+ assertTrue(r.getString("testURL1").endsWith(port + path + "/testuris/child/testURL"));
+ // Always the same
+ assertTrue(r.getString("testURL2").endsWith(port + "/testURL"));
+ assertEquals("http://testURL", r.getString("testURL3"));
+
+ //--------------------------------------------------------------------------------
+ // http://localhost:8080/sample/testuris/child/test4/test4
+ //--------------------------------------------------------------------------------
+ r = client.doGet("/testuris/child/test4/test4").getResponse(ObjectMap.class);
+ assertEquals("child.test4", r.getString("testMethod"));
+ assertEquals("/test4/test4", r.getString("pathInfo"));
+ assertNull(r.getString("pathRemainder"));
+ assertEquals(path + "/testuris/child/test4", r.getString("requestParentURI"));
+ assertEquals(path + "/testuris/child/test4/test4", r.getString("requestURI"));
+ assertTrue(r.getString("requestURL").endsWith(port + path + "/testuris/child/test4/test4"));
+ // Same for servlet
+ assertEquals(path + "/testuris/child", r.getString("contextPath") + r.getString("servletPath")); // App may not have context path, but combination should always equal path.
+ assertEquals(URL2 + "/child", r.getString("servletURI"));
+ assertTrue(r.getString("testURL1").endsWith(port + path + "/testuris/child/testURL"));
+ // Always the same
+ assertTrue(r.getString("testURL2").endsWith(port + "/testURL"));
+ assertEquals("http://testURL", r.getString("testURL3"));
+
+ //--------------------------------------------------------------------------------
+ // http://localhost:8080/sample/testuris/child/test4/test4/foo
+ //--------------------------------------------------------------------------------
+ r = client.doGet("/testuris/child/test4/test4/foo").getResponse(ObjectMap.class);
+ assertEquals("child.test4", r.getString("testMethod"));
+ assertEquals("/test4/test4/foo", r.getString("pathInfo"));
+ assertEquals("foo", r.getString("pathRemainder"));
+ assertEquals(path + "/testuris/child/test4/test4", r.getString("requestParentURI"));
+ assertEquals(path + "/testuris/child/test4/test4/foo", r.getString("requestURI"));
+ assertTrue(r.getString("requestURL").endsWith(port + path + "/testuris/child/test4/test4/foo"));
+ // Same for servlet
+ assertEquals(path + "/testuris/child", r.getString("contextPath") + r.getString("servletPath")); // App may not have context path, but combination should always equal path.
+ assertEquals(URL2 + "/child", r.getString("servletURI"));
+ assertTrue(r.getString("testURL1").endsWith(port + path + "/testuris/child/testURL"));
+ // Always the same
+ assertTrue(r.getString("testURL2").endsWith(port + "/testURL"));
+ assertEquals("http://testURL", r.getString("testURL3"));
+
+ //--------------------------------------------------------------------------------
+ // http://localhost:8080/sample/testuris/child/test4/test4/foo/bar
+ //--------------------------------------------------------------------------------
+ r = client.doGet("/testuris/child/test4/test4/foo/bar").getResponse(ObjectMap.class);
+ assertEquals("child.test4", r.getString("testMethod"));
+ assertEquals("/test4/test4/foo/bar", r.getString("pathInfo"));
+ assertEquals("foo/bar", r.getString("pathRemainder"));
+ assertEquals(path + "/testuris/child/test4/test4/foo", r.getString("requestParentURI"));
+ assertEquals(path + "/testuris/child/test4/test4/foo/bar", r.getString("requestURI"));
+ assertTrue(r.getString("requestURL").endsWith(port + path + "/testuris/child/test4/test4/foo/bar"));
+ // Same for servlet
+ assertEquals(path + "/testuris/child", r.getString("contextPath") + r.getString("servletPath")); // App may not have context path, but combination should always equal path.
+ assertEquals(URL2 + "/child", r.getString("servletURI"));
+ assertTrue(r.getString("testURL1").endsWith(port + path + "/testuris/child/testURL"));
+ // Always the same
+ assertTrue(r.getString("testURL2").endsWith(port + "/testURL"));
+ assertEquals("http://testURL", r.getString("testURL3"));
+
+ //--------------------------------------------------------------------------------
+ // http://localhost:8080/sample/testuris/child/test4/test4/foo/bar%2Fbaz
+ //--------------------------------------------------------------------------------
+ r = client.doGet("/testuris/child/test4/test4/foo/bar%2Fbaz").getResponse(ObjectMap.class);
+ assertEquals("child.test4", r.getString("testMethod"));
+ assertEquals("/test4/test4/foo/bar/baz", r.getString("pathInfo"));
+ assertEquals("foo/bar/baz", r.getString("pathRemainder"));
+ assertEquals(path + "/testuris/child/test4/test4/foo", r.getString("requestParentURI"));
+ assertEquals(path + "/testuris/child/test4/test4/foo/bar%2Fbaz", r.getString("requestURI"));
+ assertTrue(r.getString("requestURL").endsWith(port + path + "/testuris/child/test4/test4/foo/bar%2Fbaz"));
+ // Same for servlet
+ assertEquals(path + "/testuris/child", r.getString("contextPath") + r.getString("servletPath")); // App may not have context path, but combination should always equal path.
+ assertEquals(URL2 + "/child", r.getString("servletURI"));
+ assertTrue(r.getString("testURL1").endsWith(port + path + "/testuris/child/testURL"));
+ // Always the same
+ assertTrue(r.getString("testURL2").endsWith(port + "/testURL"));
+ assertEquals("http://testURL", r.getString("testURL3"));
+
+ client.closeQuietly();
+ }
+
+ //====================================================================================================
+ // testGrandChild - http://localhost:8080/sample/testuris/child/grandchild
+ //====================================================================================================
+ @Test
+ public void testGrandChild() throws Exception {
+ RestClient client = new TestRestClient(JsonSerializer.DEFAULT, JsonParser.DEFAULT);
+ ObjectMap r;
+
+ //--------------------------------------------------------------------------------
+ // http://localhost:8080/sample/testuris/child
+ //--------------------------------------------------------------------------------
+ r = client.doGet("/testuris/child/grandchild").getResponse(ObjectMap.class);
+ assertEquals("grandchild.test1", r.getString("testMethod"));
+ assertNull(r.getString("pathInfo"));
+ assertNull(r.getString("pathRemainder"));
+ assertEquals(path + "/testuris/child", r.getString("requestParentURI"));
+ assertEquals(path + "/testuris/child/grandchild", r.getString("requestURI"));
+ assertTrue(r.getString("requestURL").endsWith(port + path + "/testuris/child/grandchild"));
+ // Same for servlet
+ assertEquals(path + "/testuris/child/grandchild", r.getString("contextPath") + r.getString("servletPath")); // App may not have context path, but combination should always equal path.
+ assertEquals(URL2 + "/child/grandchild", r.getString("servletURI"));
+ assertTrue(r.getString("testURL1").endsWith(port + path + "/testuris/child/grandchild/testURL"));
+ // Always the same
+ assertTrue(r.getString("testURL2").endsWith(port + "/testURL"));
+ assertEquals("http://testURL", r.getString("testURL3"));
+
+ //--------------------------------------------------------------------------------
+ // http://localhost:8080/sample/testuris/child/foo
+ //--------------------------------------------------------------------------------
+ r = client.doGet("/testuris/child/grandchild/foo").getResponse(ObjectMap.class);
+ assertEquals("grandchild.test1", r.getString("testMethod"));
+ assertEquals("/foo", r.getString("pathInfo"));
+ assertEquals("foo", r.getString("pathRemainder"));
+ assertEquals(path + "/testuris/child/grandchild", r.getString("requestParentURI"));
+ assertEquals(path + "/testuris/child/grandchild/foo", r.getString("requestURI"));
+ assertTrue(r.getString("requestURL").endsWith(port + path + "/testuris/child/grandchild/foo"));
+ // Same for servlet
+ assertEquals(path + "/testuris/child/grandchild", r.getString("contextPath") + r.getString("servletPath")); // App may not have context path, but combination should always equal path.
+ assertEquals(URL2 + "/child/grandchild", r.getString("servletURI"));
+ assertTrue(r.getString("testURL1").endsWith(port + path + "/testuris/child/grandchild/testURL"));
+ // Always the same
+ assertTrue(r.getString("testURL2").endsWith(port + "/testURL"));
+ assertEquals("http://testURL", r.getString("testURL3"));
+
+ //--------------------------------------------------------------------------------
+ // http://localhost:8080/sample/testuris/child/foo/bar
+ //--------------------------------------------------------------------------------
+ r = client.doGet("/testuris/child/grandchild/foo/bar").getResponse(ObjectMap.class);
+ assertEquals("grandchild.test1", r.getString("testMethod"));
+ assertEquals("/foo/bar", r.getString("pathInfo"));
+ assertEquals("foo/bar", r.getString("pathRemainder"));
+ assertEquals(path + "/testuris/child/grandchild/foo", r.getString("requestParentURI"));
+ assertEquals(path + "/testuris/child/grandchild/foo/bar", r.getString("requestURI"));
+ assertTrue(r.getString("requestURL").endsWith(port + path + "/testuris/child/grandchild/foo/bar"));
+ // Same for servlet
+ assertEquals(path + "/testuris/child/grandchild", r.getString("contextPath") + r.getString("servletPath")); // App may not have context path, but combination should always equal path.
+ assertEquals(URL2 + "/child/grandchild", r.getString("servletURI"));
+ assertTrue(r.getString("testURL1").endsWith(port + path + "/testuris/child/grandchild/testURL"));
+ // Always the same
+ assertTrue(r.getString("testURL2").endsWith(port + "/testURL"));
+ assertEquals("http://testURL", r.getString("testURL3"));
+
+ //--------------------------------------------------------------------------------
+ // http://localhost:8080/sample/testuris/child/foo/bar%2Fbaz
+ //--------------------------------------------------------------------------------
+ r = client.doGet("/testuris/child/grandchild/foo/bar%2Fbaz").getResponse(ObjectMap.class);
+ assertEquals("grandchild.test1", r.getString("testMethod"));
+ assertEquals("/foo/bar/baz", r.getString("pathInfo"));
+ assertEquals("foo/bar/baz", r.getString("pathRemainder"));
+ assertEquals(path + "/testuris/child/grandchild/foo", r.getString("requestParentURI"));
+ assertEquals(path + "/testuris/child/grandchild/foo/bar%2Fbaz", r.getString("requestURI"));
+ assertTrue(r.getString("requestURL").endsWith(port + path + "/testuris/child/grandchild/foo/bar%2Fbaz"));
+ // Same for servlet
+ assertEquals(path + "/testuris/child/grandchild", r.getString("contextPath") + r.getString("servletPath")); // App may not have context path, but combination should always equal path.
+ assertEquals(URL2 + "/child/grandchild", r.getString("servletURI"));
+ assertTrue(r.getString("testURL1").endsWith(port + path + "/testuris/child/grandchild/testURL"));
+ // Always the same
+ assertTrue(r.getString("testURL2").endsWith(port + "/testURL"));
+ assertEquals("http://testURL", r.getString("testURL3"));
+
+ //--------------------------------------------------------------------------------
+ // http://localhost:8080/sample/testuris/child/test2
+ //--------------------------------------------------------------------------------
+ r = client.doGet("/testuris/child/grandchild/test2").getResponse(ObjectMap.class);
+ assertEquals("grandchild.test2", r.getString("testMethod"));
+ assertEquals("/test2", r.getString("pathInfo"));
+ assertNull(r.getString("pathRemainder"));
+ assertEquals(path + "/testuris/child/grandchild", r.getString("requestParentURI"));
+ assertEquals(path + "/testuris/child/grandchild/test2", r.getString("requestURI"));
+ assertTrue(r.getString("requestURL").endsWith(port + path + "/testuris/child/grandchild/test2"));
+ // Same for servlet
+ assertEquals(path + "/testuris/child/grandchild", r.getString("contextPath") + r.getString("servletPath")); // App may not have context path, but combination should always equal path.
+ assertEquals(URL2 + "/child/grandchild", r.getString("servletURI"));
+ assertTrue(r.getString("testURL1").endsWith(port + path + "/testuris/child/grandchild/testURL"));
+ // Always the same
+ assertTrue(r.getString("testURL2").endsWith(port + "/testURL"));
+ assertEquals("http://testURL", r.getString("testURL3"));
+
+ //--------------------------------------------------------------------------------
+ // http://localhost:8080/sample/testuris/child/test2/foo
+ //--------------------------------------------------------------------------------
+ r = client.doGet("/testuris/child/grandchild/test2/foo").getResponse(ObjectMap.class);
+ assertEquals("grandchild.test2", r.getString("testMethod"));
+ assertEquals("/test2/foo", r.getString("pathInfo"));
+ assertEquals("foo", r.getString("pathRemainder"));
+ assertEquals(path + "/testuris/child/grandchild/test2", r.getString("requestParentURI"));
+ assertEquals(path + "/testuris/child/grandchild/test2/foo", r.getString("requestURI"));
+ assertTrue(r.getString("requestURL").endsWith(port + path + "/testuris/child/grandchild/test2/foo"));
+ // Same for servlet
+ assertEquals(path + "/testuris/child/grandchild", r.getString("contextPath") + r.getString("servletPath")); // App may not have context path, but combination should always equal path.
+ assertEquals(URL2 + "/child/grandchild", r.getString("servletURI"));
+ assertTrue(r.getString("testURL1").endsWith(port + path + "/testuris/child/grandchild/testURL"));
+ // Always the same
+ assertTrue(r.getString("testURL2").endsWith(port + "/testURL"));
+ assertEquals("http://testURL", r.getString("testURL3"));
+
+ //--------------------------------------------------------------------------------
+ // http://localhost:8080/sample/testuris/child/test2/foo/bar
+ //--------------------------------------------------------------------------------
+ r = client.doGet("/testuris/child/grandchild/test2/foo/bar").getResponse(ObjectMap.class);
+ assertEquals("grandchild.test2", r.getString("testMethod"));
+ assertEquals("/test2/foo/bar", r.getString("pathInfo"));
+ assertEquals("foo/bar", r.getString("pathRemainder"));
+ assertEquals(path + "/testuris/child/grandchild/test2/foo", r.getString("requestParentURI"));
+ assertEquals(path + "/testuris/child/grandchild/test2/foo/bar", r.getString("requestURI"));
+ assertTrue(r.getString("requestURL").endsWith(port + path + "/testuris/child/grandchild/test2/foo/bar"));
+ // Same for servlet
+ assertEquals(path + "/testuris/child/grandchild", r.getString("contextPath") + r.getString("servletPath")); // App may not have context path, but combination should always equal path.
+ assertEquals(URL2 + "/child/grandchild", r.getString("servletURI"));
+ assertTrue(r.getString("testURL1").endsWith(port + path + "/testuris/child/grandchild/testURL"));
+ // Always the same
+ assertTrue(r.getString("testURL2").endsWith(port + "/testURL"));
+ assertEquals("http://testURL", r.getString("testURL3"));
+
+ //--------------------------------------------------------------------------------
+ // http://localhost:8080/sample/testuris/child/test2/foo/bar%2Fbaz
+ //--------------------------------------------------------------------------------
+ r = client.doGet("/testuris/child/grandchild/test2/foo/bar%2Fbaz").getResponse(ObjectMap.class);
+ assertEquals("grandchild.test2", r.getString("testMethod"));
+ assertEquals("/test2/foo/bar/baz", r.getString("pathInfo"));
+ assertEquals("foo/bar/baz", r.getString("pathRemainder"));
+ assertEquals(path + "/testuris/child/grandchild/test2/foo", r.getString("requestParentURI"));
+ assertEquals(path + "/testuris/child/grandchild/test2/foo/bar%2Fbaz", r.getString("requestURI"));
+ assertTrue(r.getString("requestURL").endsWith(port + path + "/testuris/child/grandchild/test2/foo/bar%2Fbaz"));
+ // Same for servlet
+ assertEquals(path + "/testuris/child/grandchild", r.getString("contextPath") + r.getString("servletPath")); // App may not have context path, but combination should always equal path.
+ assertEquals(URL2 + "/child/grandchild", r.getString("servletURI"));
+ assertTrue(r.getString("testURL1").endsWith(port + path + "/testuris/child/grandchild/testURL"));
+ // Always the same
+ assertTrue(r.getString("testURL2").endsWith(port + "/testURL"));
+ assertEquals("http://testURL", r.getString("testURL3"));
+
+ //--------------------------------------------------------------------------------
+ // http://localhost:8080/sample/testuris/child/test3%2Ftest3
+ //--------------------------------------------------------------------------------
+ r = client.doGet("/testuris/child/grandchild/test3%2Ftest3").getResponse(ObjectMap.class);
+ assertEquals("grandchild.test3", r.getString("testMethod"));
+ assertEquals("/test3/test3", r.getString("pathInfo"));
+ assertNull(r.getString("pathRemainder"));
+ assertEquals(path + "/testuris/child/grandchild", r.getString("requestParentURI"));
+ assertEquals(path + "/testuris/child/grandchild/test3%2Ftest3", r.getString("requestURI"));
+ assertTrue(r.getString("requestURL").endsWith(port + path + "/testuris/child/grandchild/test3%2Ftest3"));
+ // Same for servlet
+ assertEquals(path + "/testuris/child/grandchild", r.getString("contextPath") + r.getString("servletPath")); // App may not have context path, but combination should always equal path.
+ assertEquals(URL2 + "/child/grandchild", r.getString("servletURI"));
+ assertTrue(r.getString("testURL1").endsWith(port + path + "/testuris/child/grandchild/testURL"));
+ // Always the same
+ assertTrue(r.getString("testURL2").endsWith(port + "/testURL"));
+ assertEquals("http://testURL", r.getString("testURL3"));
+
+ //--------------------------------------------------------------------------------
+ // http://localhost:8080/sample/testuris/child/test3%2Ftest3/foo
+ //--------------------------------------------------------------------------------
+ r = client.doGet("/testuris/child/grandchild/test3%2Ftest3/foo").getResponse(ObjectMap.class);
+ assertEquals("grandchild.test3", r.getString("testMethod"));
+ assertEquals("/test3/test3/foo", r.getString("pathInfo"));
+ assertEquals("foo", r.getString("pathRemainder"));
+ assertEquals(path + "/testuris/child/grandchild/test3%2Ftest3", r.getString("requestParentURI"));
+ assertEquals(path + "/testuris/child/grandchild/test3%2Ftest3/foo", r.getString("requestURI"));
+ assertTrue(r.getString("requestURL").endsWith(port + path + "/testuris/child/grandchild/test3%2Ftest3/foo"));
+ // Same for servlet
+ assertEquals(path + "/testuris/child/grandchild", r.getString("contextPath") + r.getString("servletPath")); // App may not have context path, but combination should always equal path.
+ assertEquals(URL2 + "/child/grandchild", r.getString("servletURI"));
+ assertTrue(r.getString("testURL1").endsWith(port + path + "/testuris/child/grandchild/testURL"));
+ // Always the same
+ assertTrue(r.getString("testURL2").endsWith(port + "/testURL"));
+ assertEquals("http://testURL", r.getString("testURL3"));
+
+ //--------------------------------------------------------------------------------
+ // http://localhost:8080/sample/testuris/child/test3%2Ftest3/foo/bar
+ //--------------------------------------------------------------------------------
+ r = client.doGet("/testuris/child/grandchild/test3%2Ftest3/foo/bar").getResponse(ObjectMap.class);
+ assertEquals("grandchild.test3", r.getString("testMethod"));
+ assertEquals("/test3/test3/foo/bar", r.getString("pathInfo"));
+ assertEquals("foo/bar", r.getString("pathRemainder"));
+ assertEquals(path + "/testuris/child/grandchild/test3%2Ftest3/foo", r.getString("requestParentURI"));
+ assertEquals(path + "/testuris/child/grandchild/test3%2Ftest3/foo/bar", r.getString("requestURI"));
+ assertTrue(r.getString("requestURL").endsWith(port + path + "/testuris/child/grandchild/test3%2Ftest3/foo/bar"));
+ // Same for servlet
+ assertEquals(path + "/testuris/child/grandchild", r.getString("contextPath") + r.getString("servletPath")); // App may not have context path, but combination should always equal path.
+ assertEquals(URL2 + "/child/grandchild", r.getString("servletURI"));
+ assertTrue(r.getString("testURL1").endsWith(port + path + "/testuris/child/grandchild/testURL"));
+ // Always the same
+ assertTrue(r.getString("testURL2").endsWith(port + "/testURL"));
+ assertEquals("http://testURL", r.getString("testURL3"));
+
+ //--------------------------------------------------------------------------------
+ // http://localhost:8080/sample/testuris/child/test3%2Ftest3/foo/bar%2Fbaz
+ //--------------------------------------------------------------------------------
+ r = client.doGet("/testuris/child/grandchild/test3%2Ftest3/foo/bar%2Fbaz").getResponse(ObjectMap.class);
+ assertEquals("grandchild.test3", r.getString("testMethod"));
+ assertEquals("/test3/test3/foo/bar/baz", r.getString("pathInfo"));
+ assertEquals("foo/bar/baz", r.getString("pathRemainder"));
+ assertEquals(path + "/testuris/child/grandchild/test3%2Ftest3/foo", r.getString("requestParentURI"));
+ assertEquals(path + "/testuris/child/grandchild/test3%2Ftest3/foo/bar%2Fbaz", r.getString("requestURI"));
+ assertTrue(r.getString("requestURL").endsWith(port + path + "/testuris/child/grandchild/test3%2Ftest3/foo/bar%2Fbaz"));
+ // Same for servlet
+ assertEquals(path + "/testuris/child/grandchild", r.getString("contextPath") + r.getString("servletPath")); // App may not have context path, but combination should always equal path.
+ assertEquals(URL2 + "/child/grandchild", r.getString("servletURI"));
+ assertTrue(r.getString("testURL1").endsWith(port + path + "/testuris/child/grandchild/testURL"));
+ // Always the same
+ assertTrue(r.getString("testURL2").endsWith(port + "/testURL"));
+ assertEquals("http://testURL", r.getString("testURL3"));
+
+ //--------------------------------------------------------------------------------
+ // http://localhost:8080/sample/testuris/child/test4/test4
+ //--------------------------------------------------------------------------------
+ r = client.doGet("/testuris/child/grandchild/test4/test4").getResponse(ObjectMap.class);
+ assertEquals("grandchild.test4", r.getString("testMethod"));
+ assertEquals("/test4/test4", r.getString("pathInfo"));
+ assertNull(r.getString("pathRemainder"));
+ assertEquals(path + "/testuris/child/grandchild/test4", r.getString("requestParentURI"));
+ assertEquals(path + "/testuris/child/grandchild/test4/test4", r.getString("requestURI"));
+ assertTrue(r.getString("requestURL").endsWith(port + path + "/testuris/child/grandchild/test4/test4"));
+ // Same for servlet
+ assertEquals(path + "/testuris/child/grandchild", r.getString("contextPath") + r.getString("servletPath")); // App may not have context path, but combination should always equal path.
+ assertEquals(URL2 + "/child/grandchild", r.getString("servletURI"));
+ assertTrue(r.getString("testURL1").endsWith(port + path + "/testuris/child/grandchild/testURL"));
+ // Always the same
+ assertTrue(r.getString("testURL2").endsWith(port + "/testURL"));
+ assertEquals("http://testURL", r.getString("testURL3"));
+
+ //--------------------------------------------------------------------------------
+ // http://localhost:8080/sample/testuris/child/test4/test4/foo
+ //--------------------------------------------------------------------------------
+ r = client.doGet("/testuris/child/grandchild/test4/test4/foo").getResponse(ObjectMap.class);
+ assertEquals("grandchild.test4", r.getString("testMethod"));
+ assertEquals("/test4/test4/foo", r.getString("pathInfo"));
+ assertEquals("foo", r.getString("pathRemainder"));
+ assertEquals(path + "/testuris/child/grandchild/test4/test4", r.getString("requestParentURI"));
+ assertEquals(path + "/testuris/child/grandchild/test4/test4/foo", r.getString("requestURI"));
+ assertTrue(r.getString("requestURL").endsWith(port + path + "/testuris/child/grandchild/test4/test4/foo"));
+ // Same for servlet
+ assertEquals(path + "/testuris/child/grandchild", r.getString("contextPath") + r.getString("servletPath")); // App may not have context path, but combination should always equal path.
+ assertEquals(URL2 + "/child/grandchild", r.getString("servletURI"));
+ assertTrue(r.getString("testURL1").endsWith(port + path + "/testuris/child/grandchild/testURL"));
+ // Always the same
+ assertTrue(r.getString("testURL2").endsWith(port + "/testURL"));
+ assertEquals("http://testURL", r.getString("testURL3"));
+
+ //--------------------------------------------------------------------------------
+ // http://localhost:8080/sample/testuris/child/test4/test4/foo/bar
+ //--------------------------------------------------------------------------------
+ r = client.doGet("/testuris/child/grandchild/test4/test4/foo/bar").getResponse(ObjectMap.class);
+ assertEquals("grandchild.test4", r.getString("testMethod"));
+ assertEquals("/test4/test4/foo/bar", r.getString("pathInfo"));
+ assertEquals("foo/bar", r.getString("pathRemainder"));
+ assertEquals(path + "/testuris/child/grandchild/test4/test4/foo", r.getString("requestParentURI"));
+ assertEquals(path + "/testuris/child/grandchild/test4/test4/foo/bar", r.getString("requestURI"));
+ assertTrue(r.getString("requestURL").endsWith(port + path + "/testuris/child/grandchild/test4/test4/foo/bar"));
+ // Same for servlet
+ assertEquals(path + "/testuris/child/grandchild", r.getString("contextPath") + r.getString("servletPath")); // App may not have context path, but combination should always equal path.
+ assertEquals(URL2 + "/child/grandchild", r.getString("servletURI"));
+ assertTrue(r.getString("testURL1").endsWith(port + path + "/testuris/child/grandchild/testURL"));
+ // Always the same
+ assertTrue(r.getString("testURL2").endsWith(port + "/testURL"));
+ assertEquals("http://testURL", r.getString("testURL3"));
+
+ //--------------------------------------------------------------------------------
+ // http://localhost:8080/sample/testuris/child/test4/test4/foo/bar%2Fbaz
+ //--------------------------------------------------------------------------------
+ r = client.doGet("/testuris/child/grandchild/test4/test4/foo/bar%2Fbaz").getResponse(ObjectMap.class);
+ assertEquals("grandchild.test4", r.getString("testMethod"));
+ assertEquals("/test4/test4/foo/bar/baz", r.getString("pathInfo"));
+ assertEquals("foo/bar/baz", r.getString("pathRemainder"));
+ assertEquals(path + "/testuris/child/grandchild/test4/test4/foo", r.getString("requestParentURI"));
+ assertEquals(path + "/testuris/child/grandchild/test4/test4/foo/bar%2Fbaz", r.getString("requestURI"));
+ assertTrue(r.getString("requestURL").endsWith(port + path + "/testuris/child/grandchild/test4/test4/foo/bar%2Fbaz"));
+ // Same for servlet
+ assertEquals(path + "/testuris/child/grandchild", r.getString("contextPath") + r.getString("servletPath")); // App may not have context path, but combination should always equal path.
+ assertEquals(URL2 + "/child/grandchild", r.getString("servletURI"));
+ assertTrue(r.getString("testURL1").endsWith(port + path + "/testuris/child/grandchild/testURL"));
+ // Always the same
+ assertTrue(r.getString("testURL2").endsWith(port + "/testURL"));
+ assertEquals("http://testURL", r.getString("testURL3"));
+
+ client.closeQuietly();
+ }
+
+ private static int getPort(String url) {
+ Pattern p = Pattern.compile("\\:(\\d{2,5})");
+ Matcher m = p.matcher(url);
+ if (m.find())
+ return Integer.parseInt(m.group(1));
+ return -1;
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestUrlContentTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestUrlContentTest.java b/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestUrlContentTest.java
new file mode 100755
index 0000000..fab63a6
--- /dev/null
+++ b/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestUrlContentTest.java
@@ -0,0 +1,74 @@
+/***************************************************************************************************************************
+ * 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.juneau.server;
+
+import static org.junit.Assert.*;
+
+import org.apache.juneau.client.*;
+import org.junit.*;
+
+public class TestUrlContentTest {
+
+ private static String URL = "/testUrlContent";
+ private static RestClient client;
+
+ @BeforeClass
+ public static void beforeClass() {
+ client = new TestRestClient().setHeader("Accept", "text/plain");
+ }
+
+ @AfterClass
+ public static void afterClass() {
+ client.closeQuietly();
+ }
+
+ //====================================================================================================
+ // Test URL &Content parameter containing a String
+ //====================================================================================================
+ @Test
+ public void testString() throws Exception {
+ String r;
+ r = client.doGet(URL + "/testString?content=\'xxx\'&Content-Type=text/json").getResponseAsString();
+ assertEquals("class=java.lang.String, value=xxx", r);
+ }
+
+ //====================================================================================================
+ // Test URL &Content parameter containing an Enum
+ //====================================================================================================
+ @Test
+ public void testEnum() throws Exception {
+ String r;
+ r = client.doGet(URL + "/testEnum?content='X1'&Content-Type=text/json").getResponseAsString();
+ assertEquals("class=org.apache.juneau.server.TestUrlContent$TestEnum, value=X1", r);
+ }
+
+ //====================================================================================================
+ // Test URL &Content parameter containing a Bean
+ //====================================================================================================
+ @Test
+ public void testBean() throws Exception {
+ String r;
+ r = client.doGet(URL + "/testBean?content=%7Bf1:1,f2:'foobar'%7D&Content-Type=text/json").getResponseAsString();
+ assertEquals("class=org.apache.juneau.server.TestUrlContent$TestBean, value={f1:1,f2:'foobar'}", r);
+ }
+
+ //====================================================================================================
+ // Test URL &Content parameter containing an int
+ //====================================================================================================
+ @Test
+ public void testInt() throws Exception {
+ String r;
+ r = client.doGet(URL + "/testInt?content=123&Content-Type=text/json").getResponseAsString();
+ assertEquals("class=java.lang.Integer, value=123", r);
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/UrlPathPatternTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/UrlPathPatternTest.java b/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/UrlPathPatternTest.java
new file mode 100755
index 0000000..09b782d
--- /dev/null
+++ b/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/UrlPathPatternTest.java
@@ -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.juneau.server;
+
+import static org.junit.Assert.*;
+
+import java.util.*;
+
+import org.apache.juneau.json.*;
+import org.junit.*;
+
+public class UrlPathPatternTest {
+ @Test
+ public void testComparison() throws Exception {
+ List<UrlPathPattern> l = new LinkedList<UrlPathPattern>();
+
+ l.add(new UrlPathPattern("/foo"));
+ l.add(new UrlPathPattern("/foo/*"));
+ l.add(new UrlPathPattern("/foo/bar"));
+ l.add(new UrlPathPattern("/foo/bar/*"));
+ l.add(new UrlPathPattern("/foo/{id}"));
+ l.add(new UrlPathPattern("/foo/{id}/*"));
+ l.add(new UrlPathPattern("/foo/{id}/bar"));
+ l.add(new UrlPathPattern("/foo/{id}/bar/*"));
+
+ Collections.sort(l);
+ assertEquals("['/foo/bar','/foo/bar/*','/foo/{id}/bar','/foo/{id}/bar/*','/foo/{id}','/foo/{id}/*','/foo','/foo/*']", JsonSerializer.DEFAULT_LAX.serialize(l));
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/AnnotationsTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/AnnotationsTest.java b/org.apache.juneau/src/test/java/org/apache/juneau/AnnotationsTest.java
new file mode 100755
index 0000000..016b4c1
--- /dev/null
+++ b/org.apache.juneau/src/test/java/org/apache/juneau/AnnotationsTest.java
@@ -0,0 +1,82 @@
+/***************************************************************************************************************************
+ * 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.juneau;
+
+import static org.apache.juneau.TestUtils.*;
+import static org.junit.Assert.*;
+
+import org.apache.juneau.annotation.*;
+import org.junit.*;
+
+
+@SuppressWarnings({"rawtypes"})
+public class AnnotationsTest {
+
+ //====================================================================================================
+ // Bean with explicitly specified properties.
+ //====================================================================================================
+ @Test
+ public void testBeanWithExplicitProperties() throws Exception {
+ BeanContext bc = BeanContext.DEFAULT;
+ BeanMap bm = null;
+
+ // Basic test
+ bm = bc.newBeanMap(Person1.class).load("{age:21,name:'foobar'}");
+ assertNotNull(bm);
+ assertNotNull(bm.getBean());
+ assertEquals(bm.get("age"), 21);
+ assertEquals(bm.get("name"), "foobar");
+
+ bm.put("age", 65);
+ bm.put("name", "futbol");
+ assertEquals(bm.get("age"), 65);
+ assertEquals(bm.get("name"), "futbol");
+ }
+
+ /** Class with explicitly specified properties */
+ @Bean(properties = { "age", "name" })
+ public static class Person1 {
+ public int age;
+ private String name;
+ public String getName() {
+ return name;
+ }
+ public void setName(String name) {
+ this.name = name;
+ }
+ }
+
+ //====================================================================================================
+ // Private/protected/default fields should be ignored.
+ //====================================================================================================
+ @Test
+ public void testForOnlyPublicFields() throws Exception {
+ BeanContext bc = BeanContext.DEFAULT;
+ BeanMap bm = null;
+
+ // Make sure only public fields are detected
+ bm = bc.newBeanMap(A.class).load("{publicField:123}");
+ assertNotNull("F1", bm);
+ assertNotNull("F2", bm.getBean());
+ assertObjectEquals("{publicField:123}", bm.getBean());
+
+ }
+
+ public static class A {
+ public int publicField;
+ protected int protectedField;
+ @SuppressWarnings("unused")
+ private int privateField;
+ int defaultField;
+ }
+}
\ No newline at end of file
[24/44] incubator-juneau git commit: Rename CT_* testcases.
Posted by ja...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/CT_RoundTripPrimitivesBeans.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/CT_RoundTripPrimitivesBeans.java b/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/CT_RoundTripPrimitivesBeans.java
deleted file mode 100755
index b8234fc..0000000
--- a/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/CT_RoundTripPrimitivesBeans.java
+++ /dev/null
@@ -1,367 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.a.rttests;
-
-import static org.junit.Assert.*;
-
-import java.util.*;
-
-import org.apache.juneau.parser.*;
-import org.apache.juneau.serializer.*;
-import org.junit.*;
-
-/**
- * Tests designed to serialize and parse objects to make sure we end up
- * with the same objects for all serializers and parsers.
- */
-@SuppressWarnings({"unchecked","serial"})
-public class CT_RoundTripPrimitivesBeans extends RoundTripTest {
-
- public CT_RoundTripPrimitivesBeans(String label, Serializer s, Parser p, int flags) throws Exception {
- super(label, s, p, flags);
- }
-
- //====================================================================================================
- // testPrimitivesBean
- //====================================================================================================
- @Test
- public void testPrimitivesBean() throws Exception {
- PrimitivesBean t = new PrimitivesBean().init();
- t = roundTrip(t, PrimitivesBean.class);
-
- // primitives
- assertEquals(true, t.pBoolean);
- assertEquals(1, t.pByte);
- assertEquals('a', t.pChar);
- assertEquals(2, t.pShort);
- assertEquals(3, t.pInt);
- assertEquals(4l, t.pLong);
- assertEquals(5f, t.pFloat, 0.1f);
- assertEquals(6d, t.pDouble, 0.1f);
-
- // uninitialized primitives
- assertEquals(false, t.puBoolean);
- assertEquals(0, t.puByte);
- assertEquals((char)0, t.puChar);
- assertEquals(0, t.puShort);
- assertEquals(0, t.puInt);
- assertEquals(0l, t.puLong);
- assertEquals(0f, t.puFloat, 0.1f);
- assertEquals(0d, t.puDouble, 0.1f);
-
- // primitive arrays
- assertEquals(false, t.paBoolean[1][0]);
- assertEquals(2, t.paByte[1][0]);
- assertEquals('b', t.paChar[1][0]);
- assertEquals(2, t.paShort[1][0]);
- assertEquals(2, t.paInt[1][0]);
- assertEquals(2l, t.paLong[1][0]);
- assertEquals(2f, t.paFloat[1][0], 0.1f);
- assertEquals(2d, t.paDouble[1][0], 0.1f);
- assertNull(t.paBoolean[2]);
- assertNull(t.paByte[2]);
- assertNull(t.paChar[2]);
- assertNull(t.paShort[2]);
- assertNull(t.paInt[2]);
- assertNull(t.paLong[2]);
- assertNull(t.paFloat[2]);
- assertNull(t.paDouble[2]);
-
- // uninitialized primitive arrays
- assertNull(t.pauBoolean);
- assertNull(t.pauByte);
- assertNull(t.pauChar);
- assertNull(t.pauShort);
- assertNull(t.pauInt);
- assertNull(t.pauLong);
- assertNull(t.pauFloat);
- assertNull(t.pauDouble);
-
- // anonymous list of primitive arrays
- assertEquals(true, t.palBoolean.get(0)[0]);
- assertEquals(1, t.palByte.get(0)[0]);
- assertEquals('a', t.palChar.get(0)[0]);
- assertEquals(1, t.palShort.get(0)[0]);
- assertEquals(1, t.palInt.get(0)[0]);
- assertEquals(1l, t.palLong.get(0)[0]);
- assertEquals(1f, t.palFloat.get(0)[0], 0.1f);
- assertEquals(1d, t.palDouble.get(0)[0], 0.1f);
- assertNull(t.palBoolean.get(1));
- assertNull(t.palByte.get(1));
- assertNull(t.palChar.get(1));
- assertNull(t.palShort.get(1));
- assertNull(t.palInt.get(1));
- assertNull(t.palLong.get(1));
- assertNull(t.palFloat.get(1));
- assertNull(t.palDouble.get(1));
-
- // regular list of primitive arrays
- assertEquals(true, t.plBoolean.get(0)[0]);
- assertEquals(1, t.plByte.get(0)[0]);
- assertEquals('a', t.plChar.get(0)[0]);
- assertEquals(1, t.plShort.get(0)[0]);
- assertEquals(1, t.plInt.get(0)[0]);
- assertEquals(1l, t.plLong.get(0)[0]);
- assertEquals(1f, t.plFloat.get(0)[0], 0.1f);
- assertEquals(1d, t.plDouble.get(0)[0], 0.1f);
- assertNull(t.plBoolean.get(1));
- assertNull(t.plByte.get(1));
- assertNull(t.plChar.get(1));
- assertNull(t.plShort.get(1));
- assertNull(t.plInt.get(1));
- assertNull(t.plLong.get(1));
- assertNull(t.plFloat.get(1));
- assertNull(t.plDouble.get(1));
- }
-
- public static class PrimitivesBean {
-
- // primitives
- public boolean pBoolean;
- public byte pByte;
- public char pChar;
- public short pShort;
- public int pInt;
- public long pLong;
- public float pFloat;
- public double pDouble;
-
- // uninitialized primitives
- public boolean puBoolean;
- public byte puByte;
- public char puChar;
- public short puShort;
- public int puInt;
- public long puLong;
- public float puFloat;
- public double puDouble;
-
- // primitive arrays
- public boolean[][] paBoolean;
- public byte[][] paByte;
- public char[][] paChar;
- public short[][] paShort;
- public int[][] paInt;
- public long[][] paLong;
- public float[][] paFloat;
- public double[][] paDouble;
-
- // uninitialized primitive arrays
- public boolean[][] pauBoolean;
- public byte[][] pauByte;
- public char[][] pauChar;
- public short[][] pauShort;
- public int[][] pauInt;
- public long[][] pauLong;
- public float[][] pauFloat;
- public double[][] pauDouble;
-
- // Regular lists of primitives
- public List<boolean[]> plBoolean;
- public List<byte[]> plByte;
- public List<char[]> plChar;
- public List<short[]> plShort;
- public List<int[]> plInt;
- public List<long[]> plLong;
- public List<float[]> plFloat;
- public List<double[]> plDouble;
-
- // Anonymous list of primitives
- public List<boolean[]> palBoolean;
- public List<byte[]> palByte;
- public List<char[]> palChar;
- public List<short[]> palShort;
- public List<int[]> palInt;
- public List<long[]> palLong;
- public List<float[]> palFloat;
- public List<double[]> palDouble;
-
- public PrimitivesBean init() {
- // primitives
- pBoolean = true;
- pByte = 1;
- pChar = 'a';
- pShort = 2;
- pInt = 3;
- pLong = 4l;
- pFloat = 5f;
- pDouble = 6d;
-
- // primitive arrays
- paBoolean = new boolean[][]{{true},{false},null};
- paByte = new byte[][]{{1},{2},null};
- paChar = new char[][]{{'a'},{'b'},null};
- paShort = new short[][]{{1},{2},null};
- paInt = new int[][]{{1},{2},null};
- paLong = new long[][]{{1},{2},null};
- paFloat = new float[][]{{1},{2},null};
- paDouble = new double[][]{{1},{2},null};
-
- // Regular lists of primitives
- plBoolean = new ArrayList<boolean[]>() {{
- add(new boolean[]{true}); add(null);
- }};
- plByte = new ArrayList<byte[]>() {{
- add(new byte[]{1}); add(null);
- }};
- plChar = new ArrayList<char[]>() {{
- add(new char[]{'a'}); add(null);
- }};
- plShort = new ArrayList<short[]>() {{
- add(new short[]{1}); add(null);
- }};
- plInt = new ArrayList<int[]>() {{
- add(new int[]{1}); add(null);
- }};
- plLong = new ArrayList<long[]>() {{
- add(new long[]{1}); add(null);
- }};
- plFloat = new ArrayList<float[]>() {{
- add(new float[]{1}); add(null);
- }};
- plDouble = new ArrayList<double[]>() {{
- add(new double[]{1}); add(null);
- }};
-
- // Anonymous list of primitives
- palBoolean = new ArrayList<boolean[]>();
- palBoolean.add(new boolean[]{true});
- palBoolean.add(null);
- palByte = new ArrayList<byte[]>();
- palByte.add(new byte[]{1});
- palByte.add(null);
- palChar = new ArrayList<char[]>();
- palChar.add(new char[]{'a'});
- palChar.add(null);
- palShort = new ArrayList<short[]>();
- palShort.add(new short[]{1});
- palShort.add(null);
- palInt = new ArrayList<int[]>();
- palInt.add(new int[]{1});
- palInt.add(null);
- palLong = new ArrayList<long[]>();
- palLong.add(new long[]{1});
- palLong.add(null);
- palFloat = new ArrayList<float[]>();
- palFloat.add(new float[]{1});
- palFloat.add(null);
- palDouble = new ArrayList<double[]>();
- palDouble.add(new double[]{1});
- palDouble.add(null);
- return this;
- }
- }
-
- //====================================================================================================
- // List of PrimitivesBean
- //====================================================================================================
- @Test
- public void testPrimitivesBeanList() throws Exception {
- List<PrimitivesBean> t = new ArrayList<PrimitivesBean>() {{
- add(new PrimitivesBean().init());
- add(null);
- add(new PrimitivesBean().init());
- }};
- if (p == null)
- return;
- t = roundTrip(t, p.getBeanContext().getCollectionClassMeta(List.class, PrimitivesBean.class));
-
- PrimitivesBean t2 = t.get(2);
-
- // primitives
- assertEquals(true, t2.pBoolean);
- assertEquals(1, t2.pByte);
- assertEquals('a', t2.pChar);
- assertEquals(2, t2.pShort);
- assertEquals(3, t2.pInt);
- assertEquals(4l, t2.pLong);
- assertEquals(5f, t2.pFloat, 0.1f);
- assertEquals(6d, t2.pDouble, 0.1f);
-
- // uninitialized primitives
- assertEquals(false, t2.puBoolean);
- assertEquals(0, t2.puByte);
- assertEquals((char)0, t2.puChar);
- assertEquals(0, t2.puShort);
- assertEquals(0, t2.puInt);
- assertEquals(0l, t2.puLong);
- assertEquals(0f, t2.puFloat, 0.1f);
- assertEquals(0d, t2.puDouble, 0.1f);
-
- // primitive arrays
- assertEquals(false, t2.paBoolean[1][0]);
- assertEquals(2, t2.paByte[1][0]);
- assertEquals('b', t2.paChar[1][0]);
- assertEquals(2, t2.paShort[1][0]);
- assertEquals(2, t2.paInt[1][0]);
- assertEquals(2l, t2.paLong[1][0]);
- assertEquals(2f, t2.paFloat[1][0], 0.1f);
- assertEquals(2d, t2.paDouble[1][0], 0.1f);
- assertNull(t2.paBoolean[2]);
- assertNull(t2.paByte[2]);
- assertNull(t2.paChar[2]);
- assertNull(t2.paShort[2]);
- assertNull(t2.paInt[2]);
- assertNull(t2.paLong[2]);
- assertNull(t2.paFloat[2]);
- assertNull(t2.paDouble[2]);
-
- // uninitialized primitive arrays
- assertNull(t2.pauBoolean);
- assertNull(t2.pauByte);
- assertNull(t2.pauChar);
- assertNull(t2.pauShort);
- assertNull(t2.pauInt);
- assertNull(t2.pauLong);
- assertNull(t2.pauFloat);
- assertNull(t2.pauDouble);
-
- // anonymous list of primitive arrays
- assertEquals(true, t2.palBoolean.get(0)[0]);
- assertEquals(1, t2.palByte.get(0)[0]);
- assertEquals('a', t2.palChar.get(0)[0]);
- assertEquals(1, t2.palShort.get(0)[0]);
- assertEquals(1, t2.palInt.get(0)[0]);
- assertEquals(1l, t2.palLong.get(0)[0]);
- assertEquals(1f, t2.palFloat.get(0)[0], 0.1f);
- assertEquals(1d, t2.palDouble.get(0)[0], 0.1f);
- assertNull(t2.palBoolean.get(1));
- assertNull(t2.palByte.get(1));
- assertNull(t2.palChar.get(1));
- assertNull(t2.palShort.get(1));
- assertNull(t2.palInt.get(1));
- assertNull(t2.palLong.get(1));
- assertNull(t2.palFloat.get(1));
- assertNull(t2.palDouble.get(1));
-
- // regular list of primitive arrays
- assertEquals(true, t2.plBoolean.get(0)[0]);
- assertEquals(1, t2.plByte.get(0)[0]);
- assertEquals('a', t2.plChar.get(0)[0]);
- assertEquals(1, t2.plShort.get(0)[0]);
- assertEquals(1, t2.plInt.get(0)[0]);
- assertEquals(1l, t2.plLong.get(0)[0]);
- assertEquals(1f, t2.plFloat.get(0)[0], 0.1f);
- assertEquals(1d, t2.plDouble.get(0)[0], 0.1f);
- assertNull(t2.plBoolean.get(1));
- assertNull(t2.plByte.get(1));
- assertNull(t2.plChar.get(1));
- assertNull(t2.plShort.get(1));
- assertNull(t2.plInt.get(1));
- assertNull(t2.plLong.get(1));
- assertNull(t2.plFloat.get(1));
- assertNull(t2.plDouble.get(1));
-
- assertNull(t.get(1));
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/CT_RoundTripReadOnlyBeans.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/CT_RoundTripReadOnlyBeans.java b/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/CT_RoundTripReadOnlyBeans.java
deleted file mode 100755
index cb4c40a..0000000
--- a/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/CT_RoundTripReadOnlyBeans.java
+++ /dev/null
@@ -1,100 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.a.rttests;
-
-import static org.junit.Assert.*;
-
-import org.apache.juneau.annotation.*;
-import org.apache.juneau.parser.*;
-import org.apache.juneau.serializer.*;
-import org.junit.*;
-
-/**
- * Tests designed to serialize and parse objects to make sure we end up
- * with the same objects for all serializers and parsers.
- */
-public class CT_RoundTripReadOnlyBeans extends RoundTripTest {
-
- public CT_RoundTripReadOnlyBeans(String label, Serializer s, Parser p, int flags) throws Exception {
- super(label, s, p, flags);
- }
-
- //====================================================================================================
- // test
- //====================================================================================================
- @Test
- public void test() throws Exception {
- B t1 = new B(1, "a"), t2 = new B(2, "b");
- A t3 = new A(t1, t2);
-
- t3 = roundTrip(t3, A.class);
- assertEquals(1, t3.getF1().getF1());
- assertEquals("a", t3.getF1().getF2());
- assertEquals(2, t3.getF2().getF1());
- assertEquals("b", t3.getF2().getF2());
- }
-
- public static class A {
- private B f1;
- private final B f2;
-
- @BeanConstructor(properties={"f2"})
- public A(B f2) {
- this.f2 = f2;
- }
-
- public A(B f1, B f2) {
- this.f1 = f1;
- this.f2 = f2;
- }
-
- public B getF1() {
- return f1;
- }
-
- public void setF1(B f1) {
- this.f1 = f1;
- }
-
- public B getF2() {
- return f2;
- }
- }
-
- public static class B {
- private int f1;
- private final String f2;
-
- @BeanConstructor(properties={"f2"})
- public B(String sField) {
- this.f2 = sField;
- }
-
- public B(int iField, String sField) {
- this.f1 = iField;
- this.f2 = sField;
- }
-
- public int getF1() {
- return f1;
- }
-
- public void setF1(int f1) {
- this.f1 = f1;
- }
-
- public String getF2() {
- return f2;
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/CT_RoundTripSimpleObjects.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/CT_RoundTripSimpleObjects.java b/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/CT_RoundTripSimpleObjects.java
deleted file mode 100755
index 305021a..0000000
--- a/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/CT_RoundTripSimpleObjects.java
+++ /dev/null
@@ -1,750 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.a.rttests;
-
-import static org.junit.Assert.*;
-
-import java.util.*;
-
-import org.apache.juneau.*;
-import org.apache.juneau.parser.*;
-import org.apache.juneau.serializer.*;
-import org.junit.*;
-
-/**
- * Tests designed to serialize and parse objects to make sure we end up
- * with the same objects for all serializers and parsers.
- */
-@SuppressWarnings({ "unchecked", "rawtypes" })
-public class CT_RoundTripSimpleObjects extends RoundTripTest {
-
- public CT_RoundTripSimpleObjects(String label, Serializer s, Parser p, int flags) throws Exception {
- super(label, s, p, flags);
- }
-
- //====================================================================================================
- // testNull
- //====================================================================================================
- @Test
- public void testNull() throws Exception {
- String t = null;
- t = roundTrip(t);
- assertNull(t);
- }
-
- //====================================================================================================
- // testString
- //====================================================================================================
- @Test
- public void testString() throws Exception {
- String t = "foobar";
- t = roundTrip(t);
- assertEquals("foobar", t);
- t = "";
- t = roundTrip(t);
- assertEquals("", t);
- }
-
- //====================================================================================================
- // testStringArray
- //====================================================================================================
- @Test
- public void testStringArray() throws Exception {
- String[] t = {"foo", null, "null", ""};
- t = roundTrip(t, String[].class);
- assertEquals("foo", t[0]);
- assertNull(t[1]);
- assertEquals("null", t[2]);
- assertEquals("", t[3]);
- }
-
- //====================================================================================================
- // testString2dArray
- //====================================================================================================
- @Test
- public void testString2dArray() throws Exception {
- String[][] t = {{"foo", null, "null", ""},null};
- t = roundTrip(t, String[][].class);
- assertEquals("foo", t[0][0]);
- assertNull(t[0][1]);
- assertEquals("null", t[0][2]);
- assertEquals("", t[0][3]);
- assertNull(t[1]);
- }
-
- //====================================================================================================
- // testInt
- //====================================================================================================
- @Test
- public void testInt() throws Exception {
- int t = 123;
- t = roundTrip(t);
- assertEquals(123, t);
- }
-
- //====================================================================================================
- // testIntArray
- //====================================================================================================
- @Test
- public void testIntArray() throws Exception {
- int[] t = roundTrip(new int[]{1,2,3}, int[].class);
- assertEquals(1, t[0]);
- assertEquals(2, t[1]);
- assertEquals(3, t[2]);
- }
-
- //====================================================================================================
- // testInt2dArray
- //====================================================================================================
- @Test
- public void testInt2dArray() throws Exception {
- int[][] t = {{1,2,3},null};
- t = roundTrip(t, int[][].class);
- assertEquals(1, t[0][0]);
- assertEquals(2, t[0][1]);
- assertEquals(3, t[0][2]);
- assertNull(t[1]);
- }
-
- //====================================================================================================
- // testInt3dArray
- //====================================================================================================
- @Test
- public void testInt3dArray() throws Exception {
- int[][][] t = {{{1,2,3},{4,5,6},null},null};
- t = roundTrip(t, int[][][].class);
- assertEquals(1, t[0][0][0]);
- assertEquals(2, t[0][0][1]);
- assertEquals(3, t[0][0][2]);
- assertEquals(4, t[0][1][0]);
- assertEquals(5, t[0][1][1]);
- assertEquals(6, t[0][1][2]);
- assertNull(t[0][2]);
- assertNull(t[1]);
- }
-
- //====================================================================================================
- // testBoolean
- //====================================================================================================
- @Test
- public void testBoolean() throws Exception {
- boolean t = true;
- t = roundTrip(t);
- assertTrue(t);
- t = false;
- t = roundTrip(t);
- assertFalse(t);
- }
-
- //====================================================================================================
- // testBooleanArray
- //====================================================================================================
- @Test
- public void testBooleanArray() throws Exception {
- boolean[] t = {true,false};
- t = roundTrip(t, boolean[].class);
- assertTrue(t[0]);
- assertFalse(t[1]);
- }
-
- //====================================================================================================
- // testBoolean2dArray
- //====================================================================================================
- @Test
- public void testBoolean2dArray() throws Exception {
- boolean[][] t = {{true,false},null};
- t = roundTrip(t, boolean[][].class);
- assertTrue(t[0][0]);
- assertFalse(t[0][1]);
- assertNull(t[1]);
- }
-
- //====================================================================================================
- // testChar
- //====================================================================================================
- @Test
- public void testChar() throws Exception {
- char t = 'a';
- t = roundTrip(t, char.class);
- assertEquals('a', t);
- }
-
- //====================================================================================================
- // testCharArray
- //====================================================================================================
- @Test
- public void testCharArray() throws Exception {
- char[] t = {'a',0};
- t = roundTrip(t, char[].class);
- assertEquals('a', t[0]);
- assertEquals(0, t[1]);
- }
-
- //====================================================================================================
- // testChar2dArray
- //====================================================================================================
- @Test
- public void testChar2dArray() throws Exception {
- char[][] t = {{'a',0},null};
- t = roundTrip(t, char[][].class);
- assertEquals('a', t[0][0]);
- assertEquals(0, t[0][1]);
- assertNull(t[1]);
- }
-
- //====================================================================================================
- // testFloat
- //====================================================================================================
- @Test
- public void testFloat() throws Exception {
- float t = 1f;
- t = roundTrip(t, float.class);
- assertEquals(1f, t, 0.1f);
- }
-
- //====================================================================================================
- // testFloatArray
- //====================================================================================================
- @Test
- public void testFloatArray() throws Exception {
- float[] t = {1f};
- t = roundTrip(t, float[].class);
- assertEquals(1f, t[0], 0.1f);
- }
-
- //====================================================================================================
- // testFloat2dArray
- //====================================================================================================
- @Test
- public void testFloat2dArray() throws Exception {
- float[][] t = {{1f},null};
- t = roundTrip(t, float[][].class);
- assertEquals(1f, t[0][0], 0.1f);
- assertNull(t[1]);
- }
-
- //====================================================================================================
- // testDouble
- //====================================================================================================
- @Test
- public void testDouble() throws Exception {
- double t = 1d;
- t = roundTrip(t, double.class);
- assertEquals(1d, t, 0.1f);
- }
-
- //====================================================================================================
- // testDoubleArray
- //====================================================================================================
- @Test
- public void testDoubleArray() throws Exception {
- double[] t = {1d};
- t = roundTrip(t, double[].class);
- assertEquals(1d, t[0], 0.1f);
- }
-
- //====================================================================================================
- // testDouble2dArray
- //====================================================================================================
- @Test
- public void testDouble2dArray() throws Exception {
- double[][] t = {{1d},null};
- t = roundTrip(t, double[][].class);
- assertEquals(1d, t[0][0], 0.1f);
- assertNull(t[1]);
- }
-
- //====================================================================================================
- // testLong
- //====================================================================================================
- @Test
- public void testLong() throws Exception {
- long t = 1l;
- t = roundTrip(t, long.class);
- assertEquals(1l, t);
- }
-
- //====================================================================================================
- // testLongArray
- //====================================================================================================
- @Test
- public void testLongArray() throws Exception {
- long[] t = {1l};
- t = roundTrip(t, long[].class);
- assertEquals(1l, t[0]);
- }
-
- //====================================================================================================
- // testLong2dArray
- //====================================================================================================
- @Test
- public void testLong2dArray() throws Exception {
- long[][] t = {{1l},null};
- t = roundTrip(t, long[][].class);
- assertEquals(1l, t[0][0]);
- assertNull(t[1]);
- }
-
- //====================================================================================================
- // testShort
- //====================================================================================================
- @Test
- public void testShort() throws Exception {
- short t = (short)1;
- t = roundTrip(t, short.class);
- assertEquals(1l, t);
- }
-
- //====================================================================================================
- // testShortArray
- //====================================================================================================
- @Test
- public void testShortArray() throws Exception {
- short[] t = {(short)1};
- t = roundTrip(t, short[].class);
- assertEquals(1l, t[0]);
- }
-
- //====================================================================================================
- // testShort2dArray
- //====================================================================================================
- @Test
- public void testShort2dArray() throws Exception {
- short[][] t = {{(short)1},null};
- t = roundTrip(t, short[][].class);
- assertEquals((short)1, t[0][0]);
- assertNull(t[1]);
- }
-
- //====================================================================================================
- // testInteger
- //====================================================================================================
- @Test
- public void testInteger() throws Exception {
- Integer t = 123;
- t = roundTrip(t, Integer.class);
- assertEquals(new Integer(123), t);
- }
-
- //====================================================================================================
- // testIntegerArray
- //====================================================================================================
- @Test
- public void testIntegerArray() throws Exception {
- Integer[] t = {123, null};
- t = roundTrip(t, Integer[].class);
- assertEquals(new Integer(123), t[0]);
- assertNull(t[1]);
- }
-
- //====================================================================================================
- // testInteger2dArray
- //====================================================================================================
- @Test
- public void testInteger2dArray() throws Exception {
- Integer[][] t = {{123,null},null};
- t = roundTrip(t, Integer[][].class);
- assertEquals(new Integer(123), t[0][0]);
- assertNull(t[0][1]);
- assertNull(t[1]);
- }
-
- //====================================================================================================
- // testInteger3dArray
- //====================================================================================================
- @Test
- public void testInteger3dArray() throws Exception {
- Integer[][][] t = {{{123,null},null},null};
- t = roundTrip(t, Integer[][][].class);
- assertEquals(new Integer(123), t[0][0][0]);
- assertNull(t[0][0][1]);
- assertNull(t[0][1]);
- assertNull(t[1]);
- }
-
- //====================================================================================================
- // testBooleanObject
- //====================================================================================================
- @Test
- public void testBooleanObject() throws Exception {
- Boolean t = Boolean.TRUE;
- t = roundTrip(t, Boolean.class);
- assertTrue(t);
- t = Boolean.FALSE;
- t = roundTrip(t, Boolean.class);
- assertFalse(t);
- }
-
- //====================================================================================================
- // testBooleanObjectArray
- //====================================================================================================
- @Test
- public void testBooleanObjectArray() throws Exception {
- Boolean[] t = {true,false,null};
- t = roundTrip(t, Boolean[].class);
- assertTrue(t[0]);
- assertFalse(t[1]);
- assertNull(t[2]);
- }
-
- //====================================================================================================
- // testBooleanObject2dArray
- //====================================================================================================
- @Test
- public void testBooleanObject2dArray() throws Exception {
- Boolean[][] t = {{true,false,null},null};
- t = roundTrip(t, Boolean[][].class);
- assertTrue(t[0][0]);
- assertFalse(t[0][1]);
- assertNull(t[0][2]);
- assertNull(t[1]);
- }
-
- //====================================================================================================
- // testCharacter
- //====================================================================================================
- @Test
- public void testCharacter() throws Exception {
- Character t = 'a';
- t = roundTrip(t, Character.class);
- assertEquals(new Character('a'), t);
- }
-
- //====================================================================================================
- // testCharacterArray
- //====================================================================================================
- @Test
- public void testCharacterArray() throws Exception {
- Character[] t = {'a',null};
- t = roundTrip(t, Character[].class);
- assertEquals(new Character('a'), t[0]);
- assertNull(t[1]);
- }
-
- //====================================================================================================
- // testCharacter2dArray
- //====================================================================================================
- @Test
- public void testCharacter2dArray() throws Exception {
- Character[][] t = {{'a',null},null};
- t = roundTrip(t, Character[][].class);
- assertEquals(new Character('a'), t[0][0]);
- assertNull(t[0][1]);
- assertNull(t[1]);
- }
-
- //====================================================================================================
- // testFloatObject
- //====================================================================================================
- @Test
- public void testFloatObject() throws Exception {
- Float t = 1f;
- t = roundTrip(t, Float.class);
- assertEquals(new Float(1f), t);
- }
-
- //====================================================================================================
- // testFloatObjectArray
- //====================================================================================================
- @Test
- public void testFloatObjectArray() throws Exception {
- Float[] t = {1f, null};
- t = roundTrip(t, Float[].class);
- assertEquals(new Float(1f), t[0]);
- assertNull(t[1]);
- }
-
- //====================================================================================================
- // testFloatObject2dArray
- //====================================================================================================
- @Test
- public void testFloatObject2dArray() throws Exception {
- Float[][] t = {{1f,null},null};
- t = roundTrip(t, Float[][].class);
- assertEquals(new Float(1f), t[0][0]);
- assertNull(t[0][1]);
- assertNull(t[1]);
- }
-
- //====================================================================================================
- // testDoubleObject
- //====================================================================================================
- @Test
- public void testDoubleObject() throws Exception {
- Double t = 1d;
- t = roundTrip(t, Double.class);
- assertEquals(new Double(1d), t);
- }
-
- //====================================================================================================
- // testDoubleObjectArray
- //====================================================================================================
- @Test
- public void testDoubleObjectArray() throws Exception {
- Double[] t = {1d,null};
- t = roundTrip(t, Double[].class);
- assertEquals(new Double(1d), t[0]);
- assertNull(t[1]);
- }
-
- //====================================================================================================
- // testDoubleObject2dArray
- //====================================================================================================
- @Test
- public void testDoubleObject2dArray() throws Exception {
- Double[][] t = {{1d,null},null};
- t = roundTrip(t, Double[][].class);
- assertEquals(new Double(1d), t[0][0]);
- assertNull(t[0][1]);
- assertNull(t[1]);
- }
-
- //====================================================================================================
- // testLongObject
- //====================================================================================================
- @Test
- public void testLongObject() throws Exception {
- Long t = 1l;
- t = roundTrip(t, Long.class);
- assertEquals(new Long(1l), t);
- }
-
- //====================================================================================================
- // testLongObjectArray
- //====================================================================================================
- @Test
- public void testLongObjectArray() throws Exception {
- Long[] t = {1l, null};
- t = roundTrip(t, Long[].class);
- assertEquals(new Long(1l), t[0]);
- assertNull(t[1]);
- }
-
- //====================================================================================================
- // testLongObject2dArray
- //====================================================================================================
- @Test
- public void testLongObject2dArray() throws Exception {
- Long[][] t = {{1l,null},null};
- t = roundTrip(t, Long[][].class);
- assertEquals(new Long(1l), t[0][0]);
- assertNull(t[0][1]);
- assertNull(t[1]);
- }
-
- //====================================================================================================
- // testShortObject
- //====================================================================================================
- @Test
- public void testShortObject() throws Exception {
- Short t = (short)1;
- t = roundTrip(t, Short.class);
- assertEquals(new Short((short)1), t);
- }
-
- //====================================================================================================
- // testShortObjectArray
- //====================================================================================================
- @Test
- public void testShortObjectArray() throws Exception {
- Short[] t = {(short)1,null};
- t = roundTrip(t, Short[].class);
- assertEquals(new Short((short)1), t[0]);
- assertNull(t[1]);
- }
-
- //====================================================================================================
- // testShortObject2dArray
- //====================================================================================================
- @Test
- public void testShortObject2dArray() throws Exception {
- Short[][] t = {{(short)1,null},null};
- t = roundTrip(t, Short[][].class);
- assertEquals(new Short((short)1), t[0][0]);
- assertNull(t[0][1]);
- assertNull(t[1]);
- }
-
- //====================================================================================================
- // testObjectMap
- //====================================================================================================
- @Test
- public void testObjectMap() throws Exception {
- ObjectMap t = new ObjectMap("{a:'b',c:123,d:false,e:null,f:[123,'abc',true,false,null]}");
- t = roundTrip(t);
- assertEquals("b", t.get("a"));
- assertEquals(123, t.get("c"));
- assertEquals(false, t.get("d"));
- assertNull(t.get("e"));
- List l = (List)t.get("f");
- assertEquals(123, l.get(0));
- assertEquals("abc", l.get(1));
- assertEquals(true, l.get(2));
- assertEquals(false, l.get(3));
- assertNull(l.get(4));
- }
-
- //====================================================================================================
- // testObjectList
- //====================================================================================================
- @Test
- public void testObjectList() throws Exception {
- ObjectList t = new ObjectList("['abc',123,true,false,null,{a:'b'}]");
- t = roundTrip(t);
- assertEquals("abc", t.get(0));
- assertEquals(123, t.get(1));
- assertEquals(true, t.get(2));
- assertEquals(false, t.get(3));
- assertNull(t.get(4));
- Map m = (Map)t.get(5);
- assertEquals("b", m.get("a"));
- }
-
- //====================================================================================================
- // testTreeMap
- //====================================================================================================
- @Test
- public void testTreeMap() throws Exception {
- TreeMap t = new TreeMap();
- t.put("a", 1);
- t.put("b", 2);
- t.put("c", 3);
- t = roundTrip(t, TreeMap.class);
- assertEquals(1, t.get("a"));
- assertEquals(2, t.get("b"));
- assertEquals(3, t.get("c"));
-
- t = new TreeMap();
- t.put("a", true);
- t.put("b", false);
- t.put("c", null);
- t.put("d", "foo");
- t.put("null", "baz");
- t.put("a\"a", "a\"a");
- t.put("b'b", "b'b");
- t.put("\"cc\"", "\"cc\"");
- t.put("'dd'", "'dd'");
- t = roundTrip(t, TreeMap.class);
- assertEquals(true, t.get("a"));
- assertEquals(false, t.get("b"));
- assertNull(t.get("c"));
- assertEquals("foo", t.get("d"));
- assertEquals("baz", t.get("null"));
- assertEquals("a\"a", t.get("a\"a"));
- assertEquals("b'b", t.get("b'b"));
- assertEquals("\"cc\"", t.get("\"cc\""));
- assertEquals("'dd'", t.get("'dd'"));
- }
-
- //====================================================================================================
- // testLinkedHashMap
- //====================================================================================================
- @Test
- public void testLinkedHashMap() throws Exception {
- LinkedHashMap t = new LinkedHashMap();
- t.put("a", true);
- t.put("b", false);
- t.put("c", null);
- t.put("d", "foo");
- t.put(null, "bar");
- t.put("null", "null");
- t.put("true", "true");
- t.put("false", "false");
- t.put("a\"a", "a\"a");
- t.put("b'b", "b'b");
- t.put("\"cc\"", "\"cc\"");
- t.put("'dd'", "'dd'");
- t.put("<ee>", "<ee>");
- t.put("<ff/>", "<ff/>");
- t.put("</gg>", "</gg>");
- t.put("<>", "<>");
- t.put("{}", "{}");
- t.put("[]", "[]");
- t.put("&", "&");
- t.put("?", "?");
- t.put("/", "/");
- t.put("\b", "\b");
- t.put("\\b", "\\b");
- t.put("\n", "\n");
- t.put("\\n", "\\n");
- t.put("\t", "\t");
- t.put("\\t", "\\t");
- t.put("\f", "\f");
- t.put("\\f", "\\f");
- t.put("\\", "\\");
- t.put("\\\\", "\\\\");
- t.put("\u2345", "\u2345");
- t.put("\\u2345", "\\u2345");
- t.put("\\\u2345", "\\\u2345");
- t.put("<>{}[]&?/\b\n\t\f\\\\\u2345", "<>{}[]&?/\b\n\t\f\\\\\u2345");
- t = roundTrip(t, LinkedHashMap.class);
- assertEquals(true, t.get("a"));
- assertEquals(false, t.get("b"));
- assertNull(t.get("c"));
- assertEquals("foo", t.get("d"));
- assertEquals("bar", t.get(null));
- assertEquals("null", t.get("null"));
- assertEquals("true", t.get("true"));
- assertEquals("false", t.get("false"));
- assertEquals("a\"a", t.get("a\"a"));
- assertEquals("b'b", t.get("b'b"));
- assertEquals("\"cc\"", t.get("\"cc\""));
- assertEquals("'dd'", t.get("'dd'"));
- assertEquals("<ee>", t.get("<ee>"));
- assertEquals("<ff/>", t.get("<ff/>"));
- assertEquals("</gg>", t.get("</gg>"));
- assertEquals("<>", t.get("<>"));
- assertEquals("{}", t.get("{}"));
- assertEquals("[]", t.get("[]"));
- assertEquals("&", t.get("&"));
- assertEquals("?", t.get("?"));
- assertEquals("/", t.get("/"));
- assertEquals("\b", t.get("\b"));
- assertEquals("\\b", t.get("\\b"));
- assertEquals("\n", t.get("\n"));
- assertEquals("\\n", t.get("\\n"));
- assertEquals("\t", t.get("\t"));
- assertEquals("\\t", t.get("\\t"));
- assertEquals("\f", t.get("\f"));
- assertEquals("\\f", t.get("\\f"));
- assertEquals("\\", t.get("\\"));
- assertEquals("\\\\", t.get("\\\\"));
- assertEquals("\u2345", t.get("\u2345"));
- assertEquals("\\u2345", t.get("\\u2345"));
- assertEquals("\\\u2345", t.get("\\\u2345"));
- assertEquals("<>{}[]&?/\b\n\t\f\\\\\u2345", t.get("<>{}[]&?/\b\n\t\f\\\\\u2345"));
- }
-
- //====================================================================================================
- // testVector
- //====================================================================================================
- @Test
- public void testVector() throws Exception {
- Vector<Integer> t = new Vector<Integer>();
- t.add(1);
- t.add(2);
- t.add(3);
- t = roundTripCollection(t, Vector.class, Integer.class);
- }
-
- //====================================================================================================
- // testNull
- //====================================================================================================
- @Test
- public void testExtendedUnicode() throws Exception {
- // Test 4-byte UTF-8 character
- String t = "\U00024b62\U00024b62";
- t = roundTrip(t);
- assertEquals("\U00024b62\U00024b62", t);
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/CT_RoundTripToObjectMaps.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/CT_RoundTripToObjectMaps.java b/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/CT_RoundTripToObjectMaps.java
deleted file mode 100755
index 384e06e..0000000
--- a/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/CT_RoundTripToObjectMaps.java
+++ /dev/null
@@ -1,78 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.a.rttests;
-
-import static org.junit.Assert.*;
-
-import java.util.*;
-
-import org.apache.juneau.*;
-import org.apache.juneau.parser.*;
-import org.apache.juneau.serializer.*;
-import org.junit.*;
-
-
-
-/**
- * Tests designed to serialize and parse objects to make sure we end up
- * with the same objects for all serializers and parsers.
- */
-public class CT_RoundTripToObjectMaps extends RoundTripTest {
-
- public CT_RoundTripToObjectMaps(String label, Serializer s, Parser p, int flags) throws Exception {
- super(label, s, p, flags);
- }
-
- //====================================================================================================
- // Class with X(ObjectMap) constructor and toObjectMap() method.
- //====================================================================================================
- @SuppressWarnings({ "serial", "unchecked" })
- @Test
- public void test() throws Exception {
- A a = new A(new ObjectMap("{f1:'a',f2:2}"));
- a = roundTrip(a, A.class);
- assertEquals("a", a.f1);
- assertEquals(2, a.f2);
-
- A[] aa = new A[]{a};
- aa = roundTrip(aa, A[].class);
- assertEquals(1, aa.length);
- assertEquals("a", aa[0].f1);
- assertEquals(2, aa[0].f2);
-
- List<A> a2 = new ArrayList<A>(){{add(new A(new ObjectMap("{f1:'a',f2:2}")));}};
- a2 = roundTrip(a2, BeanContext.DEFAULT.getCollectionClassMeta(List.class, A.class));
- assertEquals(1, a2.size());
- assertEquals("a", a2.get(0).f1);
- assertEquals(2, a2.get(0).f2);
-
- Map<String,A> a3 = new LinkedHashMap<String,A>(){{put("a", new A(new ObjectMap("{f1:'a',f2:2}")));}};
- a3 = roundTrip(a3, BeanContext.DEFAULT.getMapClassMeta(Map.class, String.class, A.class));
- assertEquals(1, a3.size());
- assertEquals("a", a3.get("a").f1);
- assertEquals(2, a3.get("a").f2);
- }
-
- public static class A {
- private String f1;
- private int f2;
- public A(ObjectMap m) {
- this.f1 = m.getString("f1");
- this.f2 = m.getInt("f2");
- }
- public ObjectMap toObjectMap() {
- return new ObjectMap().append("f1",f1).append("f2",f2);
- }
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/CT_RoundTripTransformBeans.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/CT_RoundTripTransformBeans.java b/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/CT_RoundTripTransformBeans.java
deleted file mode 100755
index 3a118c8..0000000
--- a/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/CT_RoundTripTransformBeans.java
+++ /dev/null
@@ -1,382 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.a.rttests;
-
-import static org.junit.Assert.*;
-
-import java.io.*;
-import java.util.*;
-
-import javax.xml.datatype.*;
-
-import org.apache.juneau.*;
-import org.apache.juneau.annotation.*;
-import org.apache.juneau.annotation.Transform;
-import org.apache.juneau.json.*;
-import org.apache.juneau.parser.*;
-import org.apache.juneau.serializer.*;
-import org.apache.juneau.transform.*;
-import org.apache.juneau.transforms.*;
-import org.junit.*;
-
-/**
- * Tests designed to serialize and parse objects to make sure we end up
- * with the same objects for all serializers and parsers.
- */
-@SuppressWarnings({"unchecked","rawtypes","hiding","serial"})
-public class CT_RoundTripTransformBeans extends RoundTripTest {
-
- public CT_RoundTripTransformBeans(String label, Serializer s, Parser p, int flags) throws Exception {
- super(label, s, p, flags);
- }
-
- //====================================================================================================
- // testTransformBeans1
- //====================================================================================================
- @Test
- public void testTransformBeans1() throws Exception {
- Class<?>[] f = {
- ByteArrayBase64Transform.class,
- CalendarTransform.ISO8601DTZ.class,
- DateTransform.ISO8601DTZ.class
- };
- s.addTransforms(f);
- if (p != null)
- p.addTransforms(f);
- A t = new A().init();
- t = roundTrip(t, A.class);
-
- // ByteArrayBase64Transform
- assertEquals(3, t.fByte[3]);
- assertNull(t.fnByte);
- assertEquals(5, t.faByte[2][1]);
- assertEquals(6, t.flByte.get(1)[2]);
- assertNull(t.flByte.get(2));
- assertEquals(6, t.fmByte.get("bar")[2]);
- assertNull(t.fmByte.get("baz"));
-
- // CalendarTransform
- t.fCalendar.setTimeZone(TimeZone.getTimeZone("GMT"));
- assertEquals(2001, t.fCalendar.get(Calendar.YEAR));
- assertEquals(01, t.fCalendar.get(Calendar.MONTH));
- assertEquals(02, t.fCalendar.get(Calendar.DATE));
- assertEquals(03, t.fCalendar.get(Calendar.HOUR));
- assertEquals(04, t.fCalendar.get(Calendar.MINUTE));
- assertEquals(05, t.fCalendar.get(Calendar.SECOND));
-
- t.faCalendar[0].setTimeZone(TimeZone.getTimeZone("GMT"));
- assertEquals(2001, t.faCalendar[0].get(Calendar.YEAR));
- assertEquals(01, t.faCalendar[0].get(Calendar.MONTH));
- assertEquals(02, t.faCalendar[0].get(Calendar.DATE));
- assertEquals(03, t.faCalendar[0].get(Calendar.HOUR));
- assertEquals(04, t.faCalendar[0].get(Calendar.MINUTE));
- assertEquals(05, t.faCalendar[0].get(Calendar.SECOND));
- assertNull(t.fnCalendar);
- assertNull(t.fn2Calendar);
-
- // DateTransform
- assertEquals(1000, t.fDate.getTime());
- assertNull(t.fnDate);
- assertEquals(3000, t.faDate[2].getTime());
- assertEquals(4000, t.flDate.get(0).getTime());
- assertNull(t.flDate.get(1));
- assertEquals(5000, t.fmDate.get("foo").getTime());
- assertNull(t.fmDate.get("bar"));
- }
-
- public static class A {
-
- // Test ByteArrayBase64Transform
- public byte[] fByte;
- public byte[] fnByte;
- public byte[][] faByte;
- public List<byte[]> flByte;
- public Map<String,byte[]> fmByte;
-
- public GregorianCalendar fCalendar;
- public GregorianCalendar fnCalendar;
- public Calendar fn2Calendar;
- public GregorianCalendar[] faCalendar;
-
- public Date fDate;
- public Date fnDate;
- public Date[] faDate;
- public List<Date> flDate;
- public Map<String,Date> fmDate;
-
- public A init() {
- fByte = new byte[]{0,1,2,3};
- fnByte = null;
- faByte = new byte[][]{{0,1},{2,3},{4,5}};
- flByte = new ArrayList<byte[]>() {{
- add(new byte[]{1,2,3});
- add(new byte[]{4,5,6});
- add(null);
- }};
- fmByte = new LinkedHashMap<String,byte[]>() {{
- put("foo", new byte[]{1,2,3});
- put("bar", new byte[]{4,5,6});
- put("baz", null);
- }};
-
- fCalendar = new GregorianCalendar() {{
- set(2001, 01, 02, 03, 04, 05);
- setTimeZone(TimeZone.getTimeZone("GMT"));
- }};
- fnCalendar = null;
- fn2Calendar = null;
- faCalendar = new GregorianCalendar[]{
- new GregorianCalendar() {{
- set(2001, 01, 02, 03, 04, 05);
- setTimeZone(TimeZone.getTimeZone("GMT"));
- }}
- };
-
- fDate = new Date(1000);
- fnDate = null;
- faDate = new Date[]{
- new Date(1000), new Date(2000), new Date(3000)
- };
- flDate = new ArrayList<Date>() {{
- add(new Date(4000));
- add(null);
- }};
- fmDate = new LinkedHashMap<String,Date>() {{
- put("foo", new Date(5000));
- put("bar", null);
- }};
- return this;
- }
- }
-
-
- //====================================================================================================
- // testTransformBeans2
- //====================================================================================================
- @Test
- public void testTransformBeans2() throws Exception {
- Class<?>[] f = {
- ByteArrayBase64Transform.class,
- CalendarTransform.Medium.class,
- DateTransform.RFC2822DT.class,
- };
- s.addTransforms(f);
- if (p != null)
- p.addTransforms(f);
- A t = new A().init();
- t = roundTrip(t, A.class);
-
- // ByteArrayBase64Transform
- assertEquals(3, t.fByte[3]);
- assertNull(t.fnByte);
- assertEquals(5, t.faByte[2][1]);
- assertEquals(6, t.flByte.get(1)[2]);
- assertNull(t.flByte.get(2));
- assertEquals(6, t.fmByte.get("bar")[2]);
- assertNull(t.fmByte.get("baz"));
-
- // CalendarTransform
- t.fCalendar.setTimeZone(TimeZone.getTimeZone("GMT"));
- assertEquals(2001, t.fCalendar.get(Calendar.YEAR));
- assertEquals(01, t.fCalendar.get(Calendar.MONTH));
- // Note: We lose precision on the following because of the transform type.
- //assertEquals(02, b.fCalendar.get(Calendar.DATE));
- //assertEquals(03, b.fCalendar.get(Calendar.HOUR));
- //assertEquals(04, b.fCalendar.get(Calendar.MINUTE));
- //assertEquals(05, b.fCalendar.get(Calendar.SECOND));
-
- t.faCalendar[0].setTimeZone(TimeZone.getTimeZone("GMT"));
- assertEquals(2001, t.faCalendar[0].get(Calendar.YEAR));
- assertEquals(01, t.faCalendar[0].get(Calendar.MONTH));
- // Note: We lose precision on the following because of the transform type.
- //assertEquals(02, b.faCalendar[0].get(Calendar.DATE));
- //assertEquals(03, b.faCalendar[0].get(Calendar.HOUR));
- //assertEquals(04, b.faCalendar[0].get(Calendar.MINUTE));
- //assertEquals(05, b.faCalendar[0].get(Calendar.SECOND));
- assertNull(t.fnCalendar);
- assertNull(t.fn2Calendar);
-
- // DateTransform
- assertEquals(1000, t.fDate.getTime());
- assertNull(t.fnDate);
- assertEquals(3000, t.faDate[2].getTime());
- assertEquals(4000, t.flDate.get(0).getTime());
- assertNull(t.flDate.get(1));
- assertEquals(5000, t.fmDate.get("foo").getTime());
- assertNull(t.fmDate.get("bar"));
- }
-
- //====================================================================================================
- // testTransform - Bean.transform annotation
- //====================================================================================================
- @Test
- public void testTransform() throws Exception {
- B t = new B();
- t.f1 = "bar";
- t = roundTrip(t, B.class);
-
- assertEquals("bar", t.f1);
- }
-
- @Transform(BTransform.class)
- public static class B {
- public String f1;
- }
-
- public static class BTransform extends PojoTransform<B,String> {
- @Override /* PojoTransform */
- public String transform(B o) throws SerializeException {
- return o.f1;
- }
- @Override /* PojoTransform */
- public B normalize(String f, ClassMeta<?> hint) throws ParseException {
- B b1 = new B();
- b1.f1 = f;
- return b1;
- }
- }
-
- //====================================================================================================
- // testXMLGregorianCalendar - Test XMLGregorianCalendarTransform class.
- //====================================================================================================
- @Test
- public void testXMLGregorianCalendar() throws Exception {
-
- if (isValidationOnly())
- return;
-
- GregorianCalendar gc = new GregorianCalendar();
- XMLGregorianCalendar c = DatatypeFactory.newInstance().newXMLGregorianCalendar(gc);
-
- Serializer s = getSerializer().clone().addTransforms(XMLGregorianCalendarTransform.class);
- Parser p = getParser().clone().addTransforms(XMLGregorianCalendarTransform.class);
-
- Object r = s.serialize(c);
- XMLGregorianCalendar c2 = p.parse(r, XMLGregorianCalendar.class);
- assertEquals(c, c2);
- }
-
- //====================================================================================================
- // testSubTypeWithGenerics
- //====================================================================================================
- @Test
- public void testSubTypeWithGenerics() throws Exception {
- JsonSerializer s = JsonSerializer.DEFAULT;
-
- C1 c1 = C3.create();
- String r = s.serialize(c1);
- assertEquals("{\"type\":\"C3\",\"f1\":{\"f2\":\"f2\",\"f3\":3}}", r);
- }
-
-
- @Bean(
- subTypeProperty="type",
- subTypes={
- @BeanSubType(id="C3", type=C3.class)
- }
- )
- public static interface C1<T> extends Serializable {
- void setF1(T f1);
- T getF1();
- }
-
- public abstract static class C2<T> implements C1<T> {
- protected T f1;
-
- @Override /* C1 */
- public void setF1(T f1) {
- this.f1 = f1;
- }
-
- @Override /* C1 */
- public T getF1() {
- return f1;
- }
- }
-
- public static class C3<T> extends C2<T> {
-
- public static C3 create() {
- C3 c3 = new C3<Object>();
- CDTO cdto = new CDTO();
- cdto.f2 = "f2";
- cdto.f3 = 3;
- c3.f1 = cdto;
- return c3;
- }
-
- @Override /* C1 */
- public void setF1(T f1) {
- this.f1 = f1;
- }
-
- @Override /* C1 */
- public T getF1() {
- return f1;
- }
- }
-
- public static class CDTO {
- public String f2;
- public int f3;
- }
-
-
- //====================================================================================================
- // Surrogate transforms
- //====================================================================================================
- @Test
- public void testSurrogateTransform() throws Exception {
- addTransforms(D2.class);
-
- JsonSerializer s = new JsonSerializer.Simple().addTransforms(D2.class);
- JsonParser p = new JsonParser().addTransforms(D2.class);
- Object r;
- D1 d1 = D1.create();
-
- r = s.serialize(d1);
- assertEquals("{f2:'f1'}", r);
-
- d1 = p.parse(r, D1.class);
- assertEquals("f1", d1.f1);
-
- r = getSerializer().serialize(d1);
- assertTrue(TestUtils.toString(r).contains("f2"));
-
- d1 = roundTrip(d1, D1.class);
- }
-
- public static class D1 {
- public String f1;
-
- public static D1 create() {
- D1 d1 = new D1();
- d1.f1 = "f1";
- return d1;
- }
- }
-
- public static class D2 {
- public String f2;
- public D2(D1 d1) {
- f2 = d1.f1;
- }
- public D2() {
- }
- public static D1 valueOf(D2 d2) {
- D1 d1 = new D1();
- d1.f1 = d2.f2;
- return d1;
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/CT_RoundTripTrimStrings.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/CT_RoundTripTrimStrings.java b/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/CT_RoundTripTrimStrings.java
deleted file mode 100755
index cdd56c8..0000000
--- a/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/CT_RoundTripTrimStrings.java
+++ /dev/null
@@ -1,98 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.a.rttests;
-
-import static org.apache.juneau.TestUtils.*;
-
-import org.apache.juneau.*;
-import org.apache.juneau.parser.*;
-import org.apache.juneau.serializer.*;
-import org.junit.*;
-
-
-/**
- * Tests for the {@link SerializerContext#SERIALIZER_trimStrings} and {@link ParserContext#PARSER_trimStrings}.
- */
-public class CT_RoundTripTrimStrings extends RoundTripTest {
-
- public CT_RoundTripTrimStrings(String label, Serializer s, Parser p, int flags) throws Exception {
- super(label, s, p, flags);
- }
-
- //====================================================================================================
- // test
- //====================================================================================================
- @SuppressWarnings("hiding")
- @Test
- public void test() throws Exception {
- if (isValidationOnly())
- return;
- Serializer s = getSerializer();
- Parser p = getParser();
- Object in, a, e;
-
- Serializer s2 = s.clone().setProperty(SerializerContext.SERIALIZER_trimStrings, true);
- Parser p2 = p.clone().setProperty(ParserContext.PARSER_trimStrings, true);
-
- in = " foo bar ";
- e = "foo bar";
- a = p.parse(s2.serialize(in), String.class);
- assertEqualObjects(e, a);
- a = p2.parse(s.serialize(in), String.class);
- assertEqualObjects(e, a);
-
- in = new ObjectMap("{' foo ': ' bar '}");
- e = new ObjectMap("{foo:'bar'}");
- a = p.parse(s2.serialize(in), ObjectMap.class);
- assertEqualObjects(e, a);
- a = p2.parse(s.serialize(in), ObjectMap.class);
- assertEqualObjects(e, a);
-
- in = new ObjectList("[' foo ', {' foo ': ' bar '}]");
- e = new ObjectList("['foo',{foo:'bar'}]");
- a = p.parse(s2.serialize(in), ObjectList.class);
- assertEqualObjects(e, a);
- a = p2.parse(s.serialize(in), ObjectList.class);
- assertEqualObjects(e, a);
-
- in = new A().init1();
- e = new A().init2();
- a = p.parse(s2.serialize(in), A.class);
- assertEqualObjects(e, a);
- a = p2.parse(s.serialize(in), A.class);
- assertEqualObjects(e, a);
- }
-
- public static class A {
- public String f1;
- public String[] f2;
- public ObjectList f3;
- public ObjectMap f4;
-
- public A init1() throws Exception {
- f1 = " f1 ";
- f2 = new String[]{" f2a ", " f2b "};
- f3 = new ObjectList("[' f3a ',' f3b ']");
- f4 = new ObjectMap("{' foo ':' bar '}");
- return this;
- }
-
- public A init2() throws Exception {
- f1 = "f1";
- f2 = new String[]{"f2a", "f2b"};
- f3 = new ObjectList("['f3a','f3b']");
- f4 = new ObjectMap("{'foo':'bar'}");
- return this;
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/RoundTripAddClassAttrsTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/RoundTripAddClassAttrsTest.java b/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/RoundTripAddClassAttrsTest.java
new file mode 100755
index 0000000..7f5658f
--- /dev/null
+++ b/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/RoundTripAddClassAttrsTest.java
@@ -0,0 +1,349 @@
+/***************************************************************************************************************************
+ * 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.juneau.a.rttests;
+
+import static org.apache.juneau.BeanContext.*;
+import static org.apache.juneau.a.rttests.RoundTripTest.Flags.*;
+import static org.apache.juneau.serializer.SerializerContext.*;
+import static org.junit.Assert.*;
+
+import java.util.*;
+
+import org.apache.juneau.html.*;
+import org.apache.juneau.jena.*;
+import org.apache.juneau.json.*;
+import org.apache.juneau.msgpack.*;
+import org.apache.juneau.parser.*;
+import org.apache.juneau.serializer.*;
+import org.apache.juneau.urlencoding.*;
+import org.apache.juneau.xml.*;
+import org.junit.*;
+import org.junit.runners.*;
+
+
+/**
+ * Tests designed to serialize and parse objects to make sure we end up
+ * with the same objects for all serializers and parsers.
+ */
+public class RoundTripAddClassAttrsTest extends RoundTripTest {
+
+ @Parameterized.Parameters
+ public static Collection<Object[]> getPairs() {
+ return Arrays.asList(new Object[][] {
+ { /* 0 */
+ "JsonSerializer.DEFAULT/JsonParser.DEFAULT",
+ new JsonSerializer().setProperty(SERIALIZER_addClassAttrs, true).setClassLoader(RoundTripAddClassAttrsTest.class.getClassLoader()),
+ new JsonParser().setProperty(BEAN_useInterfaceProxies, false).setClassLoader(RoundTripAddClassAttrsTest.class.getClassLoader()),
+ 0
+ },
+ { /* 1 */
+ "JsonSerializer.DEFAULT_LAX/JsonParser.DEFAULT",
+ new JsonSerializer.Simple().setProperty(SERIALIZER_addClassAttrs, true).setClassLoader(RoundTripAddClassAttrsTest.class.getClassLoader()),
+ new JsonParser().setProperty(BEAN_useInterfaceProxies, false).setClassLoader(RoundTripAddClassAttrsTest.class.getClassLoader()),
+ 0
+ },
+ { /* 2 */
+ "JsonSerializer.DEFAULT_SQ/JsonParser.DEFAULT",
+ new JsonSerializer.Simple().setProperty(SERIALIZER_addClassAttrs, true).setClassLoader(RoundTripAddClassAttrsTest.class.getClassLoader()),
+ new JsonParser().setProperty(BEAN_useInterfaceProxies, false).setClassLoader(RoundTripAddClassAttrsTest.class.getClassLoader()),
+ 0
+ },
+ { /* 3 */
+ "XmlSerializer.DEFAULT/XmlParser.DEFAULT",
+ new XmlSerializer.XmlJson().setProperty(SERIALIZER_addClassAttrs, true).setClassLoader(RoundTripAddClassAttrsTest.class.getClassLoader()),
+ new XmlParser().setProperty(BEAN_useInterfaceProxies, false).setClassLoader(RoundTripAddClassAttrsTest.class.getClassLoader()),
+ CHECK_XML_WHITESPACE | VALIDATE_XML
+ },
+ { /* 4 */
+ "HtmlSerializer.DEFAULT/HtmlParser.DEFAULT",
+ new HtmlSerializer().setProperty(SERIALIZER_addClassAttrs, true).setClassLoader(RoundTripAddClassAttrsTest.class.getClassLoader()),
+ new HtmlParser().setProperty(BEAN_useInterfaceProxies, false).setClassLoader(RoundTripAddClassAttrsTest.class.getClassLoader()),
+ CHECK_XML_WHITESPACE
+ },
+ { /* 5 */
+ "UonSerializer.DEFAULT_ENCODING/UonParser.DEFAULT_DECODING",
+ new UonSerializer.Encoding().setProperty(SERIALIZER_addClassAttrs, true).setClassLoader(RoundTripAddClassAttrsTest.class.getClassLoader()),
+ new UonParser.Decoding().setProperty(BEAN_useInterfaceProxies, false).setClassLoader(RoundTripAddClassAttrsTest.class.getClassLoader()),
+ 0
+ },
+ { /* 6 */
+ "UonSerializer.DEFAULT/UonParser.DEFAULT",
+ new UonSerializer().setProperty(SERIALIZER_addClassAttrs, true).setClassLoader(RoundTripAddClassAttrsTest.class.getClassLoader()),
+ new UonParser().setProperty(BEAN_useInterfaceProxies, false).setClassLoader(RoundTripAddClassAttrsTest.class.getClassLoader()),
+ 0
+ },
+ { /* 7 */
+ "UrlEncodingSerializer.DEFAULT/UrlEncodingParser.DEFAULT",
+ new UrlEncodingSerializer().setProperty(SERIALIZER_addClassAttrs, true).setClassLoader(RoundTripAddClassAttrsTest.class.getClassLoader()),
+ new UrlEncodingParser().setProperty(BEAN_useInterfaceProxies, false).setClassLoader(RoundTripAddClassAttrsTest.class.getClassLoader()),
+ 0
+ },
+ { /* 8 */
+ "RdfSerializer.Xml/RdfParser.Xml",
+ new RdfSerializer.Xml().setProperty(SERIALIZER_addClassAttrs, true).setClassLoader(RoundTripAddClassAttrsTest.class.getClassLoader()),
+ new RdfParser.Xml().setProperty(BEAN_useInterfaceProxies, false).setClassLoader(RoundTripAddClassAttrsTest.class.getClassLoader()),
+ 0
+ },
+ { /* 9 */
+ "MsgPackSerializer.DEFAULT/MsgPackParser.DEFAULT",
+ new MsgPackSerializer().setProperty(SERIALIZER_addClassAttrs, true).setClassLoader(RoundTripAddClassAttrsTest.class.getClassLoader()),
+ new MsgPackParser().setProperty(BEAN_useInterfaceProxies, false).setClassLoader(RoundTripAddClassAttrsTest.class.getClassLoader()),
+ 0
+ }
+ });
+ }
+
+ public RoundTripAddClassAttrsTest(String label, Serializer s, Parser p, int flags) throws Exception {
+ super(label, s, p, flags);
+ }
+
+ //====================================================================================================
+ // testBean
+ //====================================================================================================
+ @Test
+ public void testBean() throws Exception {
+ A t = new A("foo");
+ AA ta;
+ IA ti;
+
+ t = roundTrip(t, A.class);
+ assertEquals("foo", t.getF1());
+
+ ta = roundTrip(t, AA.class);
+ assertEquals("foo", ta.getF1());
+
+ ti = roundTrip(t, IA.class);
+ assertEquals("foo", ti.getF1());
+
+ t = (A)roundTrip(t, Object.class);
+ assertEquals("foo", t.getF1());
+ }
+
+ public static interface IA {
+ public String getF1();
+ public void setF1(String f1);
+ }
+
+ public static abstract class AA implements IA {
+ }
+
+ public static class A extends AA {
+ private String f1;
+
+ @Override /* AA */
+ public String getF1() {
+ return f1;
+ }
+ @Override /* AA */
+ public void setF1(String f1) {
+ this.f1 = f1;
+ }
+
+ public A() {}
+ public A(String f1) {
+ this.f1 = f1;
+ }
+ }
+
+ //====================================================================================================
+ // testBeanArray
+ //====================================================================================================
+ @Test
+ public void testBeanArray() throws Exception {
+ A[] t = {new A("foo")};
+ AA[] ta;
+ IA[] ti;
+
+ t = roundTrip(t, A[].class);
+ assertEquals("foo", t[0].getF1());
+
+ ta = roundTrip(t, AA[].class);
+ assertEquals("foo", ta[0].getF1());
+
+ ti = roundTrip(t, IA[].class);
+ assertEquals("foo", ti[0].getF1());
+
+ t = (A[])roundTrip(t, Object.class);
+ assertEquals("foo", t[0].getF1());
+ }
+
+ //====================================================================================================
+ // testBeanWithBeanProps
+ //====================================================================================================
+ @Test
+ public void testBeanWithBeanProps() throws Exception {
+ B t = new B("foo");
+ t = roundTrip(t, B.class);
+ assertEquals("foo", t.f2a.getF1());
+ assertEquals("foo", t.f2b.getF1());
+ assertEquals("foo", t.f2c.getF1());
+ assertEquals("foo", ((A)t.f2d).getF1());
+
+ t = (B)roundTrip(t, Object.class);
+ assertEquals("foo", t.f2a.getF1());
+ assertEquals("foo", t.f2b.getF1());
+ assertEquals("foo", t.f2c.getF1());
+ assertEquals("foo", ((A)t.f2d).getF1());
+ }
+
+ public static class B {
+ public A f2a;
+ public AA f2b;
+ public IA f2c;
+ public Object f2d;
+ public B() {}
+ public B(String f1) {
+ f2d = f2c = f2b = f2a = new A(f1);
+ }
+ }
+
+ //====================================================================================================
+ // testMapsWithTypeParams - Maps with type parameters should not have class attributes on entries.
+ //====================================================================================================
+ @Test
+ public void testMapsWithTypeParams() throws Exception {
+ C t = new C("foo");
+ t = roundTrip(t, C.class);
+ assertEquals("foo", t.f3a.get("foo").getF1());
+ assertEquals("foo", t.f3b.get("foo").getF1());
+ assertEquals("foo", t.f3c.get("foo").getF1());
+ assertEquals("foo", t.f3d.get("foo").getF1());
+
+ t = (C)roundTrip(t, Object.class);
+ assertEquals("foo", t.f3a.get("foo").getF1());
+ assertEquals("foo", t.f3b.get("foo").getF1());
+ assertEquals("foo", t.f3c.get("foo").getF1());
+ assertEquals("foo", t.f3d.get("foo").getF1());
+ }
+
+ public static class C {
+ public Map<String,A> f3a = new HashMap<String,A>();
+ public Map<String,A> f3b = new HashMap<String,A>();
+ public Map<String,A> f3c = new HashMap<String,A>();
+ public Map<String,A> f3d = new HashMap<String,A>();
+
+ public C(){}
+ public C(String f1) {
+ A b = new A(f1);
+ f3a.put("foo", b);
+ f3b.put("foo", b);
+ f3c.put("foo", b);
+ f3d.put("foo", b);
+ }
+ }
+
+ //====================================================================================================
+ // testMapsWithoutTypeParams - Maps without type parameters should have class attributes on entries.
+ //====================================================================================================
+ @Test
+ public void testMapsWithoutTypeParams() throws Exception {
+ D t = new D("foo");
+ t = roundTrip(t, D.class);
+ assertEquals("foo", t.f4a[0].getF1());
+ assertEquals("foo", t.f4b[0].getF1());
+ assertEquals("foo", t.f4c[0].getF1());
+ assertEquals("foo", ((A)t.f4d[0]).getF1());
+
+ t = (D)roundTrip(t, Object.class);
+ assertEquals("foo", t.f4a[0].getF1());
+ assertEquals("foo", t.f4b[0].getF1());
+ assertEquals("foo", t.f4c[0].getF1());
+ assertEquals("foo", ((A)t.f4d[0]).getF1());
+ }
+
+ public static class D {
+ public A[] f4a;
+ public AA[] f4b;
+ public IA[] f4c;
+ public Object[] f4d;
+
+ public D(){}
+ public D(String f1) {
+ A b = new A(f1);
+ f4a = new A[]{b};
+ f4b = new AA[]{b};
+ f4c = new IA[]{b};
+ f4d = new Object[]{b};
+ }
+ }
+
+ //====================================================================================================
+ // testBeanWithListProps
+ //====================================================================================================
+ @Test
+ public void testBeanWithListProps() throws Exception {
+ E t = new E("foo");
+ t = roundTrip(t, E.class);
+ assertEquals("foo", t.f5a.get(0).getF1());
+ assertEquals("foo", t.f5b.get(0).getF1());
+ assertEquals("foo", t.f5c.get(0).getF1());
+ assertEquals("foo", ((A)t.f5d.get(0)).getF1());
+
+ t = (E)roundTrip(t, Object.class);
+ assertEquals("foo", t.f5a.get(0).getF1());
+ assertEquals("foo", t.f5b.get(0).getF1());
+ assertEquals("foo", t.f5c.get(0).getF1());
+ assertEquals("foo", ((A)t.f5d.get(0)).getF1());
+ }
+
+ public static class E {
+ public List<A> f5a = new LinkedList<A>();
+ public List<AA> f5b = new LinkedList<AA>();
+ public List<IA> f5c = new LinkedList<IA>();
+ public List<Object> f5d = new LinkedList<Object>();
+
+ public E(){}
+ public E(String f1) {
+ A b = new A(f1);
+ f5a.add(b);
+ f5b.add(b);
+ f5c.add(b);
+ f5d.add(b);
+ }
+ }
+
+ //====================================================================================================
+ // testBeanWithListOfArraysProps
+ //====================================================================================================
+ @Test
+ public void testBeanWithListOfArraysProps() throws Exception {
+ F t = new F("foo");
+ t = roundTrip(t, F.class);
+ assertEquals("foo", t.f6a.get(0)[0].getF1());
+ assertEquals("foo", t.f6b.get(0)[0].getF1());
+ assertEquals("foo", t.f6c.get(0)[0].getF1());
+ assertEquals("foo", ((A)t.f6d.get(0)[0]).getF1());
+
+ t = (F)roundTrip(t, Object.class);
+ assertEquals("foo", t.f6a.get(0)[0].getF1());
+ assertEquals("foo", t.f6b.get(0)[0].getF1());
+ assertEquals("foo", t.f6c.get(0)[0].getF1());
+ assertEquals("foo", ((A)t.f6d.get(0)[0]).getF1());
+ }
+
+ public static class F {
+ public List<A[]> f6a = new LinkedList<A[]>();
+ public List<AA[]> f6b = new LinkedList<AA[]>();
+ public List<IA[]> f6c = new LinkedList<IA[]>();
+ public List<Object[]> f6d = new LinkedList<Object[]>();
+
+ public F(){}
+ public F(String f1) {
+ A[] b = {new A(f1)};
+ f6a.add(b);
+ f6b.add(b);
+ f6c.add(b);
+ f6d.add(b);
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/RoundTripBeanInheritanceTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/RoundTripBeanInheritanceTest.java b/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/RoundTripBeanInheritanceTest.java
new file mode 100755
index 0000000..6495a10
--- /dev/null
+++ b/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/RoundTripBeanInheritanceTest.java
@@ -0,0 +1,220 @@
+/***************************************************************************************************************************
+ * 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.juneau.a.rttests;
+
+import static org.apache.juneau.TestUtils.*;
+import static org.junit.Assert.*;
+
+import org.apache.juneau.*;
+import org.apache.juneau.json.*;
+import org.apache.juneau.parser.*;
+import org.apache.juneau.serializer.*;
+import org.junit.*;
+
+
+
+/**
+ * Tests designed to serialize and parse objects to make sure we end up
+ * with the same objects for all serializers and parsers.
+ */
+public class RoundTripBeanInheritanceTest extends RoundTripTest {
+
+ public RoundTripBeanInheritanceTest(String label, Serializer s, Parser p, int flags) throws Exception {
+ super(label, s, p, flags);
+ }
+
+ //====================================================================================================
+ // testBeanInheritance
+ //====================================================================================================
+ @Test
+ public void testBeanInheritance() throws Exception {
+
+ // Skip tests that just return the same object.
+ if (returnOriginalObject)
+ return;
+
+ A2 t1 = new A2(), t2;
+ t1.init();
+ t2 = roundTrip(t1, A2.class);
+ assertEqualObjects(t1, t2);
+
+ A3 t3 = new A3();
+ t3.init();
+ try {
+ ClassMeta<?> cm = BeanContext.DEFAULT.getClassMeta(A3.class);
+ assertEquals("No properties detected on bean class", cm.getNotABeanReason());
+ roundTrip(t3, A3.class);
+ fail("Exception expected");
+ } catch (ParseException e) {
+ } catch (SerializeException e) {
+ } catch (InvalidDataConversionException e) {}
+ }
+
+
+ public static abstract class A1 {
+ protected String x = null;
+ protected String y = null;
+ protected String z = null;
+
+ public A1() {
+ this.x = null;
+ this.y = null;
+ this.z = null;
+ }
+
+ public A1(String x, String y, String z) {
+ this.x = x;
+ this.y = y;
+ this.z = z;
+ }
+
+ public void setX(String x) {
+ this.x = x;
+ }
+
+ public void setY(String y) {
+ this.y = y;
+ }
+
+ public void setZ(String z) {
+ this.z = z;
+ }
+
+ @Override /* Object */
+ public String toString() {
+ return ("A1(x: " + this.x + ", y: " + this.y + ", z: " + this.z + ")");
+ }
+
+ public A1 init() {
+ x = null;
+ y = "";
+ z = "z";
+ return this;
+ }
+ }
+
+ public static class A2 extends A1 {
+ public A2() {
+ super();
+ }
+
+ public A2(String x, String y, String z) {
+ super(x, y, z);
+ }
+
+ public String getX() {
+ return this.x;
+ }
+
+ public String getY() {
+ return this.y;
+ }
+
+ public String getZ() {
+ return this.z;
+ }
+ }
+
+ // This is not supposed to be a valid bean since it has no getters defined.
+ public static class A3 extends A1 {
+ public A3() {
+ super();
+ }
+
+ public A3(String x, String y, String z) {
+ super(x, y, z);
+ }
+
+ public String isX() {
+ throw new RuntimeException("Should not be called!");
+ }
+
+ public String isY() {
+ throw new RuntimeException("Should not be called!");
+ }
+
+ public String isZ() {
+ throw new RuntimeException("Should not be called!");
+ }
+ }
+
+ //====================================================================================================
+ // testBeanInheritance2
+ //====================================================================================================
+ @Test
+ public void testBeanInheritance2() throws Exception {
+ B1 t1 = new B1().init(), t2;
+ t2 = roundTrip(t1, B1.class);
+ assertEqualObjects(t1, t2);
+ }
+
+ public static class B1 extends B2 {
+ private A2 f4;
+
+ public A2 getF4() {
+ return this.f4;
+ }
+
+ public void setF4(A2 f4) {
+ this.f4 = f4;
+ }
+
+ @Override /* Object */
+ public String toString() {
+ return super.toString() + " / " + this.f4;
+ }
+
+ public B1 init() {
+ setF1("A1");
+ setF2(101);
+ setF3(false);
+ setF4((A2)new A2().init());
+ return this;
+ }
+ }
+
+ public static class B2 {
+ private String f1 = null;
+ private int f2 = -1;
+ private boolean f3 = false;
+
+ public String getF1() {
+ return this.f1;
+ }
+
+ public void setF1(String f1) {
+ this.f1 = f1;
+ }
+
+ public int getF2() {
+ return this.f2;
+ }
+
+ public void setF2(int f2) {
+ this.f2 = f2;
+ }
+
+ public boolean isF3() {
+ return this.f3;
+ }
+
+ public void setF3(boolean f3) {
+ this.f3 = f3;
+ }
+
+ @Override /* Object */
+ public String toString() {
+ return ("B2(f1: " + this.getF1() + ", f2: " + this.getF2() + ")");
+ }
+ }
+}
[20/44] incubator-juneau git commit: Rename CT_* testcases.
Posted by ja...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/html/CommonTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/html/CommonTest.java b/org.apache.juneau/src/test/java/org/apache/juneau/html/CommonTest.java
new file mode 100755
index 0000000..462ceea
--- /dev/null
+++ b/org.apache.juneau/src/test/java/org/apache/juneau/html/CommonTest.java
@@ -0,0 +1,564 @@
+/***************************************************************************************************************************
+ * 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.juneau.html;
+
+import static org.apache.juneau.BeanContext.*;
+import static org.apache.juneau.TestUtils.*;
+import static org.apache.juneau.html.HtmlSerializerContext.*;
+import static org.apache.juneau.serializer.SerializerContext.*;
+import static org.junit.Assert.*;
+
+import java.net.*;
+import java.net.URI;
+import java.util.*;
+
+import org.apache.juneau.*;
+import org.apache.juneau.annotation.*;
+import org.apache.juneau.serializer.*;
+import org.apache.juneau.testbeans.*;
+import org.apache.juneau.xml.*;
+import org.junit.*;
+
+@SuppressWarnings("serial")
+public class CommonTest {
+
+ //====================================================================================================
+ // Trim nulls from beans
+ //====================================================================================================
+ @Test
+ public void testTrimNullsFromBeans() throws Exception {
+ HtmlSerializer s = new HtmlSerializer.Sq();
+ HtmlParser p = HtmlParser.DEFAULT;
+ A t1 = A.create(), t2;
+
+ s.setProperty(SERIALIZER_trimNullProperties, false);
+ String r = s.serialize(t1);
+ assertEquals("<table type='object'><tr><th><string>key</string></th><th><string>value</string></th></tr><tr><td><string>s1</string></td><td><null/></td></tr><tr><td><string>s2</string></td><td><string>s2</string></td></tr></table>", r);
+ t2 = p.parse(r, A.class);
+ assertEqualObjects(t1, t2);
+
+ s.setProperty(SERIALIZER_trimNullProperties, true);
+ r = s.serialize(t1);
+ assertEquals("<table type='object'><tr><th><string>key</string></th><th><string>value</string></th></tr><tr><td><string>s2</string></td><td><string>s2</string></td></tr></table>", r);
+ t2 = p.parse(r, A.class);
+ assertEqualObjects(t1, t2);
+ }
+
+ public static class A {
+ public String s1, s2;
+
+ public static A create() {
+ A t = new A();
+ t.s2 = "s2";
+ return t;
+ }
+ }
+
+ //====================================================================================================
+ // Trim empty maps
+ //====================================================================================================
+ @Test
+ public void testTrimEmptyMaps() throws Exception {
+ HtmlSerializer s = new HtmlSerializer.Sq();
+ HtmlParser p = HtmlParser.DEFAULT;
+ B t1 = B.create(), t2;
+ String r;
+
+ s.setProperty(SERIALIZER_trimEmptyMaps, false);
+ r = s.serialize(t1);
+ assertEquals("<table type='object'><tr><th><string>key</string></th><th><string>value</string></th></tr><tr><td><string>f1</string></td><td><table type='object'><tr><th><string>key</string></th><th><string>value</string></th></tr></table></td></tr><tr><td><string>f2</string></td><td><table type='object'><tr><th><string>key</string></th><th><string>value</string></th></tr><tr><td><string>f2a</string></td><td><null/></td></tr><tr><td><string>f2b</string></td><td><table type='object'><tr><th><string>key</string></th><th><string>value</string></th></tr><tr><td><string>s2</string></td><td><string>s2</string></td></tr></table></td></tr></table></td></tr></table>", r);
+ t2 = p.parse(r, B.class);
+ assertEqualObjects(t1, t2);
+
+ s.setProperty(SERIALIZER_trimEmptyMaps, true);
+ r = s.serialize(t1);
+ assertEquals("<table type='object'><tr><th><string>key</string></th><th><string>value</string></th></tr><tr><td><string>f2</string></td><td><table type='object'><tr><th><string>key</string></th><th><string>value</string></th></tr><tr><td><string>f2a</string></td><td><null/></td></tr><tr><td><string>f2b</string></td><td><table type='object'><tr><th><string>key</string></th><th><string>value</string></th></tr><tr><td><string>s2</string></td><td><string>s2</string></td></tr></table></td></tr></table></td></tr></table>", r);
+ t2 = p.parse(r, B.class);
+ assertNull(t2.f1);
+ }
+
+ public static class B {
+ public TreeMap<String,A> f1, f2;
+
+ public static B create() {
+ B t = new B();
+ t.f1 = new TreeMap<String,A>();
+ t.f2 = new TreeMap<String,A>(){{put("f2a",null);put("f2b",A.create());}};
+ return t;
+ }
+ }
+
+ //====================================================================================================
+ // Trim empty lists
+ //====================================================================================================
+ @Test
+ public void testTrimEmptyLists() throws Exception {
+ HtmlSerializer s = new HtmlSerializer.Sq();
+ HtmlParser p = HtmlParser.DEFAULT;
+ C t1 = C.create(), t2;
+ String r;
+
+ s.setProperty(SERIALIZER_trimEmptyLists, false);
+ r = s.serialize(t1);
+ assertEquals("<table type='object'><tr><th><string>key</string></th><th><string>value</string></th></tr><tr><td><string>f1</string></td><td><ul></ul></td></tr><tr><td><string>f2</string></td><td><table type='array'><tr><th>s1</th><th>s2</th></tr><tr><null/></tr><tr><td><null/></td><td><string>s2</string></td></tr></table></td></tr></table>", r);
+ t2 = p.parse(r, C.class);
+ assertEqualObjects(t1, t2);
+
+ s.setProperty(SERIALIZER_trimEmptyLists, true);
+ r = s.serialize(t1);
+ assertEquals("<table type='object'><tr><th><string>key</string></th><th><string>value</string></th></tr><tr><td><string>f2</string></td><td><table type='array'><tr><th>s1</th><th>s2</th></tr><tr><null/></tr><tr><td><null/></td><td><string>s2</string></td></tr></table></td></tr></table>", r);
+ t2 = p.parse(r, C.class);
+ assertNull(t2.f1);
+ }
+
+ public static class C {
+ public List<A> f1, f2;
+
+ public static C create() {
+ C t = new C();
+ t.f1 = new LinkedList<A>();
+ t.f2 = new LinkedList<A>(){{add(null);add(A.create());}};
+ return t;
+ }
+ }
+
+ //====================================================================================================
+ // Trim empty arrays
+ //====================================================================================================
+ @Test
+ public void testTrimEmptyArrays() throws Exception {
+ HtmlSerializer s = new HtmlSerializer.Sq();
+ HtmlParser p = HtmlParser.DEFAULT;
+ D t1 = D.create(), t2;
+ String r;
+
+ s.setProperty(SERIALIZER_trimEmptyLists, false);
+ r = s.serialize(t1);
+ assertEquals("<table type='object'><tr><th><string>key</string></th><th><string>value</string></th></tr><tr><td><string>f1</string></td><td><ul></ul></td></tr><tr><td><string>f2</string></td><td><table type='array'><tr><th>s1</th><th>s2</th></tr><tr><null/></tr><tr><td><null/></td><td><string>s2</string></td></tr></table></td></tr></table>", r);
+ t2 = p.parse(r, D.class);
+ assertEqualObjects(t1, t2);
+
+ s.setProperty(SERIALIZER_trimEmptyLists, true);
+ r = s.serialize(t1);
+ assertEquals("<table type='object'><tr><th><string>key</string></th><th><string>value</string></th></tr><tr><td><string>f2</string></td><td><table type='array'><tr><th>s1</th><th>s2</th></tr><tr><null/></tr><tr><td><null/></td><td><string>s2</string></td></tr></table></td></tr></table>", r);
+ t2 = p.parse(r, D.class);
+ assertNull(t2.f1);
+ }
+
+ public static class D {
+ public A[] f1, f2;
+
+ public static D create() {
+ D t = new D();
+ t.f1 = new A[]{};
+ t.f2 = new A[]{null, A.create()};
+ return t;
+ }
+ }
+
+ //====================================================================================================
+ // @BeanProperty.properties annotation.
+ //====================================================================================================
+ @Test
+ public void testBeanPropertyProperties() throws Exception {
+ HtmlSerializer s = HtmlSerializer.DEFAULT_SQ;
+ E1 t = new E1();
+ String r;
+
+ r = s.serialize(t);
+ assertEquals("<table type='object'><tr><th><string>key</string></th><th><string>value</string></th></tr><tr><td><string>x1</string></td><td><table type='object'><tr><th><string>key</string></th><th><string>value</string></th></tr><tr><td><string>f1</string></td><td><number>1</number></td></tr></table></td></tr><tr><td><string>x2</string></td><td><table type='object'><tr><th><string>key</string></th><th><string>value</string></th></tr><tr><td><string>f1</string></td><td><number>1</number></td></tr></table></td></tr><tr><td><string>x3</string></td><td><table type='array'><tr><th>f1</th></tr><tr><td><number>1</number></td></tr></table></td></tr><tr><td><string>x4</string></td><td><table type='array'><tr><th>f1</th></tr><tr><td><number>1</number></td></tr></table></td></tr><tr><td><string>x5</string></td><td><table type='array'><tr><th>f1</th></tr><tr><td><number>1</number></td></tr></table></td></tr><tr><td><string>x6</string></td><td><table type='array'><tr><th>f1</th></tr><tr><td><
number>1</number></td></tr></table></td></tr></table>", r);
+ r = s.getSchemaSerializer().serialize(new E1());
+ assertTrue(r.indexOf("f2") == -1);
+ }
+
+ public static class E1 {
+ @BeanProperty(properties={"f1"}) public E2 x1 = new E2();
+ @BeanProperty(properties={"f1"}) public Map<String,Integer> x2 = new LinkedHashMap<String,Integer>() {{
+ put("f1",1); put("f2",2);
+ }};
+ @BeanProperty(properties={"f1"}) public E2[] x3 = {new E2()};
+ @BeanProperty(properties={"f1"}) public List<E2> x4 = new LinkedList<E2>() {{
+ add(new E2());
+ }};
+ @BeanProperty(properties={"f1"}) public ObjectMap[] x5 = {new ObjectMap().append("f1",1).append("f2",2)};
+ @BeanProperty(properties={"f1"}) public List<ObjectMap> x6 = new LinkedList<ObjectMap>() {{
+ add(new ObjectMap().append("f1",1).append("f2",2));
+ }};
+ }
+
+ public static class E2 {
+ public int f1 = 1;
+ public int f2 = 2;
+ }
+
+ //====================================================================================================
+ // @BeanProperty.properties annotation on list of beans.
+ //====================================================================================================
+ @Test
+ public void testBeanPropertyPropertiesOnListOfBeans() throws Exception {
+ HtmlSerializer s = HtmlSerializer.DEFAULT_SQ;
+ List<F> l = new LinkedList<F>();
+ F t = new F();
+ t.x1.add(new F());
+ l.add(t);
+ String html = s.serialize(l);
+ assertEquals("<table type='array'><tr><th>x1</th><th>x2</th></tr><tr><td><table type='array'><tr><th>x2</th></tr><tr><td><number>2</number></td></tr></table></td><td><number>2</number></td></tr></table>", html);
+ }
+
+ public static class F {
+ @BeanProperty(properties={"x2"}) public List<F> x1 = new LinkedList<F>();
+ public int x2 = 2;
+ }
+
+ //====================================================================================================
+ // Test that URLs and URIs are serialized and parsed correctly.
+ //====================================================================================================
+ @Test
+ public void testURIAttr() throws Exception {
+ HtmlSerializer s = HtmlSerializer.DEFAULT_SQ;
+ HtmlParser p = HtmlParser.DEFAULT;
+
+ G t = new G();
+ t.uri = new URI("http://uri");
+ t.f1 = new URI("http://f1");
+ t.f2 = new URL("http://f2");
+
+ String html = s.serialize(t);
+ t = p.parse(html, G.class);
+ assertEquals("http://uri", t.uri.toString());
+ assertEquals("http://f1", t.f1.toString());
+ assertEquals("http://f2", t.f2.toString());
+ }
+
+ public static class G {
+ @BeanProperty(beanUri=true) public URI uri;
+ public URI f1;
+ public URL f2;
+ }
+
+ //====================================================================================================
+ // Test URIs with URI_CONTEXT and URI_AUTHORITY
+ //====================================================================================================
+ @Test
+ public void testUris() throws Exception {
+ HtmlSerializer s = new HtmlSerializer.Sq().setProperty(HTML_uriAnchorText, PROPERTY_NAME).setProperty(SERIALIZER_useIndentation, false);
+ TestURI t = new TestURI();
+ String r;
+ String expected;
+
+ s.setProperty(SERIALIZER_relativeUriBase, null);
+ r = strip(s.serialize(t));
+ expected = ""
+ +"\n[f0]=<a href='f0/x0'>f0</a>"
+ +"\n[f1]=<a href='f1/x1'>f1</a>"
+ +"\n[f2]=<a href='/f2/x2'>f2</a>"
+ +"\n[f3]=<a href='http://www.ibm.com/f3/x3'>f3</a>"
+ +"\n[f4]=<a href='f4/x4'>f4</a>"
+ +"\n[f5]=<a href='/f5/x5'>f5</a>"
+ +"\n[f6]=<a href='http://www.ibm.com/f6/x6'>f6</a>"
+ +"\n[f7]=<a href='http://www.ibm.com/f7/x7'>f7</a>"
+ +"\n[f8]=<a href='f8/x8'>f8</a>"
+ +"\n[f9]=<a href='f9/x9'>f9</a>"
+ +"\n[fa]=<a href='http://www.ibm.com/fa/xa#MY_LABEL'>fa</a>"
+ +"\n[fb]=<a href='http://www.ibm.com/fb/xb?label=MY_LABEL&foo=bar'>MY_LABEL</a>"
+ +"\n[fc]=<a href='http://www.ibm.com/fc/xc?foo=bar&label=MY_LABEL'>MY_LABEL</a>"
+ +"\n[fd]=<a href='http://www.ibm.com/fd/xd?label2=MY_LABEL&foo=bar'>fd</a>"
+ +"\n[fe]=<a href='http://www.ibm.com/fe/xe?foo=bar&label2=MY_LABEL'>fe</a>"
+ ;
+ assertEquals(expected, r);
+
+ s.setProperty(SERIALIZER_relativeUriBase, ""); // Same as null.
+ r = strip(s.serialize(t));
+ expected = ""
+ +"\n[f0]=<a href='f0/x0'>f0</a>"
+ +"\n[f1]=<a href='f1/x1'>f1</a>"
+ +"\n[f2]=<a href='/f2/x2'>f2</a>"
+ +"\n[f3]=<a href='http://www.ibm.com/f3/x3'>f3</a>"
+ +"\n[f4]=<a href='f4/x4'>f4</a>"
+ +"\n[f5]=<a href='/f5/x5'>f5</a>"
+ +"\n[f6]=<a href='http://www.ibm.com/f6/x6'>f6</a>"
+ +"\n[f7]=<a href='http://www.ibm.com/f7/x7'>f7</a>"
+ +"\n[f8]=<a href='f8/x8'>f8</a>"
+ +"\n[f9]=<a href='f9/x9'>f9</a>"
+ +"\n[fa]=<a href='http://www.ibm.com/fa/xa#MY_LABEL'>fa</a>"
+ +"\n[fb]=<a href='http://www.ibm.com/fb/xb?label=MY_LABEL&foo=bar'>MY_LABEL</a>"
+ +"\n[fc]=<a href='http://www.ibm.com/fc/xc?foo=bar&label=MY_LABEL'>MY_LABEL</a>"
+ +"\n[fd]=<a href='http://www.ibm.com/fd/xd?label2=MY_LABEL&foo=bar'>fd</a>"
+ +"\n[fe]=<a href='http://www.ibm.com/fe/xe?foo=bar&label2=MY_LABEL'>fe</a>"
+ ;
+ assertEquals(expected, r);
+
+ s.setProperty(SERIALIZER_relativeUriBase, "/cr");
+ r = strip(s.serialize(t));
+ expected = ""
+ +"\n[f0]=<a href='/cr/f0/x0'>f0</a>"
+ +"\n[f1]=<a href='/cr/f1/x1'>f1</a>"
+ +"\n[f2]=<a href='/f2/x2'>f2</a>"
+ +"\n[f3]=<a href='http://www.ibm.com/f3/x3'>f3</a>"
+ +"\n[f4]=<a href='/cr/f4/x4'>f4</a>"
+ +"\n[f5]=<a href='/f5/x5'>f5</a>"
+ +"\n[f6]=<a href='http://www.ibm.com/f6/x6'>f6</a>"
+ +"\n[f7]=<a href='http://www.ibm.com/f7/x7'>f7</a>"
+ +"\n[f8]=<a href='/cr/f8/x8'>f8</a>"
+ +"\n[f9]=<a href='/cr/f9/x9'>f9</a>"
+ +"\n[fa]=<a href='http://www.ibm.com/fa/xa#MY_LABEL'>fa</a>"
+ +"\n[fb]=<a href='http://www.ibm.com/fb/xb?label=MY_LABEL&foo=bar'>MY_LABEL</a>"
+ +"\n[fc]=<a href='http://www.ibm.com/fc/xc?foo=bar&label=MY_LABEL'>MY_LABEL</a>"
+ +"\n[fd]=<a href='http://www.ibm.com/fd/xd?label2=MY_LABEL&foo=bar'>fd</a>"
+ +"\n[fe]=<a href='http://www.ibm.com/fe/xe?foo=bar&label2=MY_LABEL'>fe</a>"
+ ;
+ assertEquals(expected, r);
+
+ s.setProperty(SERIALIZER_relativeUriBase, "/cr/"); // Same as above
+ r = strip(s.serialize(t));
+ expected = ""
+ +"\n[f0]=<a href='/cr/f0/x0'>f0</a>"
+ +"\n[f1]=<a href='/cr/f1/x1'>f1</a>"
+ +"\n[f2]=<a href='/f2/x2'>f2</a>"
+ +"\n[f3]=<a href='http://www.ibm.com/f3/x3'>f3</a>"
+ +"\n[f4]=<a href='/cr/f4/x4'>f4</a>"
+ +"\n[f5]=<a href='/f5/x5'>f5</a>"
+ +"\n[f6]=<a href='http://www.ibm.com/f6/x6'>f6</a>"
+ +"\n[f7]=<a href='http://www.ibm.com/f7/x7'>f7</a>"
+ +"\n[f8]=<a href='/cr/f8/x8'>f8</a>"
+ +"\n[f9]=<a href='/cr/f9/x9'>f9</a>"
+ +"\n[fa]=<a href='http://www.ibm.com/fa/xa#MY_LABEL'>fa</a>"
+ +"\n[fb]=<a href='http://www.ibm.com/fb/xb?label=MY_LABEL&foo=bar'>MY_LABEL</a>"
+ +"\n[fc]=<a href='http://www.ibm.com/fc/xc?foo=bar&label=MY_LABEL'>MY_LABEL</a>"
+ +"\n[fd]=<a href='http://www.ibm.com/fd/xd?label2=MY_LABEL&foo=bar'>fd</a>"
+ +"\n[fe]=<a href='http://www.ibm.com/fe/xe?foo=bar&label2=MY_LABEL'>fe</a>"
+ ;
+ assertEquals(expected, r);
+
+ s.setProperty(SERIALIZER_relativeUriBase, "/");
+ r = strip(s.serialize(t));
+ expected = ""
+ +"\n[f0]=<a href='/f0/x0'>f0</a>"
+ +"\n[f1]=<a href='/f1/x1'>f1</a>"
+ +"\n[f2]=<a href='/f2/x2'>f2</a>"
+ +"\n[f3]=<a href='http://www.ibm.com/f3/x3'>f3</a>"
+ +"\n[f4]=<a href='/f4/x4'>f4</a>"
+ +"\n[f5]=<a href='/f5/x5'>f5</a>"
+ +"\n[f6]=<a href='http://www.ibm.com/f6/x6'>f6</a>"
+ +"\n[f7]=<a href='http://www.ibm.com/f7/x7'>f7</a>"
+ +"\n[f8]=<a href='/f8/x8'>f8</a>"
+ +"\n[f9]=<a href='/f9/x9'>f9</a>"
+ +"\n[fa]=<a href='http://www.ibm.com/fa/xa#MY_LABEL'>fa</a>"
+ +"\n[fb]=<a href='http://www.ibm.com/fb/xb?label=MY_LABEL&foo=bar'>MY_LABEL</a>"
+ +"\n[fc]=<a href='http://www.ibm.com/fc/xc?foo=bar&label=MY_LABEL'>MY_LABEL</a>"
+ +"\n[fd]=<a href='http://www.ibm.com/fd/xd?label2=MY_LABEL&foo=bar'>fd</a>"
+ +"\n[fe]=<a href='http://www.ibm.com/fe/xe?foo=bar&label2=MY_LABEL'>fe</a>"
+ ;
+ assertEquals(expected, r);
+
+ s.setProperty(SERIALIZER_relativeUriBase, null);
+
+ s.setProperty(SERIALIZER_absolutePathUriBase, "http://foo");
+ r = strip(s.serialize(t));
+ expected = ""
+ +"\n[f0]=<a href='f0/x0'>f0</a>"
+ +"\n[f1]=<a href='f1/x1'>f1</a>"
+ +"\n[f2]=<a href='http://foo/f2/x2'>f2</a>"
+ +"\n[f3]=<a href='http://www.ibm.com/f3/x3'>f3</a>"
+ +"\n[f4]=<a href='f4/x4'>f4</a>"
+ +"\n[f5]=<a href='http://foo/f5/x5'>f5</a>"
+ +"\n[f6]=<a href='http://www.ibm.com/f6/x6'>f6</a>"
+ +"\n[f7]=<a href='http://www.ibm.com/f7/x7'>f7</a>"
+ +"\n[f8]=<a href='f8/x8'>f8</a>"
+ +"\n[f9]=<a href='f9/x9'>f9</a>"
+ +"\n[fa]=<a href='http://www.ibm.com/fa/xa#MY_LABEL'>fa</a>"
+ +"\n[fb]=<a href='http://www.ibm.com/fb/xb?label=MY_LABEL&foo=bar'>MY_LABEL</a>"
+ +"\n[fc]=<a href='http://www.ibm.com/fc/xc?foo=bar&label=MY_LABEL'>MY_LABEL</a>"
+ +"\n[fd]=<a href='http://www.ibm.com/fd/xd?label2=MY_LABEL&foo=bar'>fd</a>"
+ +"\n[fe]=<a href='http://www.ibm.com/fe/xe?foo=bar&label2=MY_LABEL'>fe</a>"
+ ;
+ assertEquals(expected, r);
+
+ s.setProperty(SERIALIZER_absolutePathUriBase, "http://foo/");
+ r = strip(s.serialize(t));
+ expected = ""
+ +"\n[f0]=<a href='f0/x0'>f0</a>"
+ +"\n[f1]=<a href='f1/x1'>f1</a>"
+ +"\n[f2]=<a href='http://foo/f2/x2'>f2</a>"
+ +"\n[f3]=<a href='http://www.ibm.com/f3/x3'>f3</a>"
+ +"\n[f4]=<a href='f4/x4'>f4</a>"
+ +"\n[f5]=<a href='http://foo/f5/x5'>f5</a>"
+ +"\n[f6]=<a href='http://www.ibm.com/f6/x6'>f6</a>"
+ +"\n[f7]=<a href='http://www.ibm.com/f7/x7'>f7</a>"
+ +"\n[f8]=<a href='f8/x8'>f8</a>"
+ +"\n[f9]=<a href='f9/x9'>f9</a>"
+ +"\n[fa]=<a href='http://www.ibm.com/fa/xa#MY_LABEL'>fa</a>"
+ +"\n[fb]=<a href='http://www.ibm.com/fb/xb?label=MY_LABEL&foo=bar'>MY_LABEL</a>"
+ +"\n[fc]=<a href='http://www.ibm.com/fc/xc?foo=bar&label=MY_LABEL'>MY_LABEL</a>"
+ +"\n[fd]=<a href='http://www.ibm.com/fd/xd?label2=MY_LABEL&foo=bar'>fd</a>"
+ +"\n[fe]=<a href='http://www.ibm.com/fe/xe?foo=bar&label2=MY_LABEL'>fe</a>"
+ ;
+ assertEquals(expected, r);
+
+ s.setProperty(SERIALIZER_absolutePathUriBase, ""); // Same as null.
+ r = strip(s.serialize(t));
+ expected = ""
+ +"\n[f0]=<a href='f0/x0'>f0</a>"
+ +"\n[f1]=<a href='f1/x1'>f1</a>"
+ +"\n[f2]=<a href='/f2/x2'>f2</a>"
+ +"\n[f3]=<a href='http://www.ibm.com/f3/x3'>f3</a>"
+ +"\n[f4]=<a href='f4/x4'>f4</a>"
+ +"\n[f5]=<a href='/f5/x5'>f5</a>"
+ +"\n[f6]=<a href='http://www.ibm.com/f6/x6'>f6</a>"
+ +"\n[f7]=<a href='http://www.ibm.com/f7/x7'>f7</a>"
+ +"\n[f8]=<a href='f8/x8'>f8</a>"
+ +"\n[f9]=<a href='f9/x9'>f9</a>"
+ +"\n[fa]=<a href='http://www.ibm.com/fa/xa#MY_LABEL'>fa</a>"
+ +"\n[fb]=<a href='http://www.ibm.com/fb/xb?label=MY_LABEL&foo=bar'>MY_LABEL</a>"
+ +"\n[fc]=<a href='http://www.ibm.com/fc/xc?foo=bar&label=MY_LABEL'>MY_LABEL</a>"
+ +"\n[fd]=<a href='http://www.ibm.com/fd/xd?label2=MY_LABEL&foo=bar'>fd</a>"
+ +"\n[fe]=<a href='http://www.ibm.com/fe/xe?foo=bar&label2=MY_LABEL'>fe</a>"
+ ;
+ assertEquals(expected, r);
+ }
+
+ private String strip(String html) {
+ return html
+ .replace("<table type='object'><tr><th><string>key</string></th><th><string>value</string></th></tr>", "")
+ .replace("</table>", "")
+ .replace("<tr><td><string>", "\n[")
+ .replace("</string></td><td>", "]=")
+ .replace("</td></tr>", "");
+ }
+
+ //====================================================================================================
+ // Validate that you cannot update properties on locked serializer.
+ //====================================================================================================
+ @Test
+ public void testLockedSerializer() throws Exception {
+ HtmlSerializer s = new HtmlSerializer().lock();
+ try {
+ s.setProperty(XmlSerializerContext.XML_enableNamespaces, true);
+ fail("Locked exception not thrown");
+ } catch (LockedException e) {}
+ try {
+ s.setProperty(SerializerContext.SERIALIZER_addClassAttrs, true);
+ fail("Locked exception not thrown");
+ } catch (LockedException e) {}
+ try {
+ s.setProperty(BeanContext.BEAN_beanMapPutReturnsOldValue, true);
+ fail("Locked exception not thrown");
+ } catch (LockedException e) {}
+ }
+
+ //====================================================================================================
+ // Recursion
+ //====================================================================================================
+ @Test
+ public void testRecursion() throws Exception {
+ HtmlSerializer s = new HtmlSerializer.Sq();
+
+ R1 r1 = new R1();
+ R2 r2 = new R2();
+ R3 r3 = new R3();
+ r1.r2 = r2;
+ r2.r3 = r3;
+ r3.r1 = r1;
+
+ // No recursion detection
+ try {
+ s.serialize(r1);
+ fail("Exception expected!");
+ } catch (Exception e) {
+ String msg = e.getLocalizedMessage();
+ assertTrue(msg.contains("It's recommended you use the SerializerContext.SERIALIZER_detectRecursions setting to help locate the loop."));
+ }
+
+ // Recursion detection, no ignore
+ s.setProperty(SERIALIZER_detectRecursions, true);
+ try {
+ s.serialize(r1);
+ fail("Exception expected!");
+ } catch (Exception e) {
+ String msg = e.getLocalizedMessage();
+ assertTrue(msg.contains("[0]<noname>:org.apache.juneau.html.CommonTest$R1"));
+ assertTrue(msg.contains("->[1]r2:org.apache.juneau.html.CommonTest$R2"));
+ assertTrue(msg.contains("->[2]r3:org.apache.juneau.html.CommonTest$R3"));
+ assertTrue(msg.contains("->[3]r1:org.apache.juneau.html.CommonTest$R1"));
+ }
+
+ s.setProperty(SERIALIZER_ignoreRecursions, true);
+ assertEquals("<table type='object'><tr><th><string>key</string></th><th><string>value</string></th></tr><tr><td><string>name</string></td><td><string>foo</string></td></tr><tr><td><string>r2</string></td><td><table type='object'><tr><th><string>key</string></th><th><string>value</string></th></tr><tr><td><string>name</string></td><td><string>bar</string></td></tr><tr><td><string>r3</string></td><td><table type='object'><tr><th><string>key</string></th><th><string>value</string></th></tr><tr><td><string>name</string></td><td><string>baz</string></td></tr></table></td></tr></table></td></tr></table>",
+ s.serialize(r1));
+
+ // Make sure this doesn't blow up.
+ s.getSchemaSerializer().serialize(r1);
+ }
+
+ public static class R1 {
+ public String name = "foo";
+ public R2 r2;
+ }
+ public static class R2 {
+ public String name = "bar";
+ public R3 r3;
+ }
+ public static class R3 {
+ public String name = "baz";
+ public R1 r1;
+ }
+
+ //====================================================================================================
+ // Basic bean
+ //====================================================================================================
+ @Test
+ public void testBasicBean() throws Exception {
+ WriterSerializer s = new HtmlSerializer.Sq().setProperty(SERIALIZER_trimNullProperties, false).setProperty(BEAN_sortProperties, true);
+
+ J a = new J();
+ a.setF1("J");
+ a.setF2(100);
+ a.setF3(true);
+ assertEquals("<table type='object'><tr><th><string>key</string></th><th><string>value</string></th></tr><tr><td><string>f1</string></td><td><string>J</string></td></tr><tr><td><string>f2</string></td><td><number>100</number></td></tr><tr><td><string>f3</string></td><td><boolean>true</boolean></td></tr></table>", s.serialize(a));
+ }
+
+ public static class J {
+ private String f1 = null;
+ private int f2 = -1;
+ private boolean f3 = false;
+
+ public String getF1() {
+ return this.f1;
+ }
+
+ public void setF1(String f1) {
+ this.f1 = f1;
+ }
+
+ public int getF2() {
+ return this.f2;
+ }
+
+ public void setF2(int f2) {
+ this.f2 = f2;
+ }
+
+ public boolean isF3() {
+ return this.f3;
+ }
+
+ public void setF3(boolean f3) {
+ this.f3 = f3;
+ }
+
+ @Override /* Object */
+ public String toString() {
+ return ("J(f1: " + this.getF1() + ", f2: " + this.getF2() + ")");
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/html/HtmlTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/html/HtmlTest.java b/org.apache.juneau/src/test/java/org/apache/juneau/html/HtmlTest.java
new file mode 100755
index 0000000..4cf5dfe
--- /dev/null
+++ b/org.apache.juneau/src/test/java/org/apache/juneau/html/HtmlTest.java
@@ -0,0 +1,389 @@
+/***************************************************************************************************************************
+ * 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.juneau.html;
+
+import static org.apache.juneau.html.HtmlSerializerContext.*;
+import static org.apache.juneau.serializer.SerializerContext.*;
+import static org.junit.Assert.*;
+
+import java.util.*;
+
+import org.apache.juneau.*;
+import org.apache.juneau.annotation.*;
+import org.apache.juneau.annotation.Transform;
+import org.apache.juneau.html.annotation.*;
+import org.apache.juneau.serializer.*;
+import org.apache.juneau.testbeans.*;
+import org.apache.juneau.transform.*;
+import org.junit.*;
+
+public class HtmlTest {
+
+ //====================================================================================================
+ // Verifies that lists of maps/beans are converted to tables correctly.
+ //====================================================================================================
+ @Test
+ public void testTables1() throws Exception {
+ HtmlSerializer s = HtmlSerializer.DEFAULT_SQ;
+ Object[] t;
+ String html;
+
+ t = new Object[] {new A1(), new A1()};
+ html = s.serialize(t);
+ assertEquals("<table type='array'><tr><th>f1</th></tr><tr><td><string>f1</string></td></tr><tr><td><string>f1</string></td></tr></table>", html);
+
+ t = new Object[] {new A1(), new A2()};
+ html = s.serialize(t);
+ assertEquals("<table type='array'><tr><th>f1</th></tr><tr><td><string>f1</string></td></tr><tr><td><string>f1</string></td></tr></table>", html);
+
+ t = new Object[] {new A1(), new ObjectMap("{f1:'f1'}")};
+ html = s.serialize(t);
+ assertEquals("<table type='array'><tr><th>f1</th></tr><tr><td><string>f1</string></td></tr><tr><td><string>f1</string></td></tr></table>", html);
+
+ t = new Object[] {new ObjectMap("{f1:'f1'}"), new A1()};
+ html = s.serialize(t);
+ assertEquals("<table type='array'><tr><th>f1</th></tr><tr><td><string>f1</string></td></tr><tr><td><string>f1</string></td></tr></table>", html);
+
+ // This should be serialized as a list since the objects have different properties.
+ t = new Object[] {new A1(), new ObjectMap("{f2:'f2'}")};
+ html = s.serialize(t);
+ assertEquals("<ul><li><table type='object'><tr><th><string>key</string></th><th><string>value</string></th></tr><tr><td><string>f1</string></td><td><string>f1</string></td></tr></table></li><li><table type='object'><tr><th><string>key</string></th><th><string>value</string></th></tr><tr><td><string>f2</string></td><td><string>f2</string></td></tr></table></li></ul>", html);
+
+ // Tables with some beans with @Bean#properties annotations.
+ t = new Object[] {new A1(), new A3()};
+ html = s.serialize(t);
+ assertEquals("<table type='array'><tr><th>f1</th></tr><tr><td><string>f1</string></td></tr><tr><td><string>f1</string></td></tr></table>", html);
+
+ t = new Object[] {new A3(), new A1()};
+ html = s.serialize(t);
+ assertEquals("<table type='array'><tr><th>f1</th></tr><tr><td><string>f1</string></td></tr><tr><td><string>f1</string></td></tr></table>", html);
+
+ // Tables with some beans with @Bean#transforms annotations.
+ t = new Object[] {new A4(), new A1()};
+ html = s.serialize(t);
+ assertEquals("<table type='array'><tr><th>f1</th></tr><tr><td><string>f1</string></td></tr><tr><td><string>f1</string></td></tr></table>", html);
+
+ t = new Object[] {new A1(), new A4()};
+ html = s.serialize(t);
+ assertEquals("<table type='array'><tr><th>f1</th></tr><tr><td><string>f1</string></td></tr><tr><td><string>f1</string></td></tr></table>", html);
+
+ t = new Object[] {new A5(), new A1()};
+ html = s.serialize(t);
+ assertEquals("<table type='array'><tr><th>f1</th></tr><tr><td><string>f1</string></td></tr><tr><td><string>f1</string></td></tr></table>", html);
+
+ t = new Object[] {new A1(), new A5()};
+ html = s.serialize(t);
+ assertEquals("<table type='array'><tr><th>f1</th></tr><tr><td><string>f1</string></td></tr><tr><td><string>f1</string></td></tr></table>", html);
+ }
+
+ public static class A1 {
+ public String f1 = "f1";
+ }
+
+ public static class A2 {
+ public String f1 = "f1";
+ }
+
+ @Bean(properties="f1")
+ public static class A3 {
+ public String f1 = "f1";
+ public String f2 = "f2";
+ }
+
+ @Transform(A4Transform.class)
+ public static class A4 {
+ public String f2 = "f2";
+ }
+
+ public static class A4Transform extends PojoTransform<A4,A1> {
+ @Override /* PojoTransform */
+ public A1 transform(A4 o) throws SerializeException {
+ return new A1();
+ }
+ }
+
+ @Transform(A5Transform.class)
+ public static class A5 {
+ public String f2 = "f2";
+ }
+
+ public static class A5Transform extends PojoTransform<A5,ObjectMap> {
+ @Override /* PojoTransform */
+ public ObjectMap transform(A5 o) {
+ return new ObjectMap().append("f1", "f1");
+ }
+ }
+
+ //====================================================================================================
+ // Test URI_ANCHOR_SET options
+ //====================================================================================================
+ @Test
+ public void testAnchorTextOptions() throws Exception {
+ HtmlSerializer s = new HtmlSerializer.Sq();
+ TestURI t = new TestURI();
+ String r;
+ String expected = null;
+
+ s.setProperty(HTML_uriAnchorText, TO_STRING);
+ r = strip(s.serialize(t));
+ expected = ""
+ +"\n[f0]=<a href='f0/x0'>f0/x0</a>"
+ +"\n[f1]=<a href='f1/x1'>f1/x1</a>"
+ +"\n[f2]=<a href='/f2/x2'>/f2/x2</a>"
+ +"\n[f3]=<a href='http://www.ibm.com/f3/x3'>http://www.ibm.com/f3/x3</a>"
+ +"\n[f4]=<a href='f4/x4'>f4/x4</a>"
+ +"\n[f5]=<a href='/f5/x5'>/f5/x5</a>"
+ +"\n[f6]=<a href='http://www.ibm.com/f6/x6'>http://www.ibm.com/f6/x6</a>"
+ +"\n[f7]=<a href='http://www.ibm.com/f7/x7'>http://www.ibm.com/f7/x7</a>"
+ +"\n[f8]=<a href='f8/x8'>f8/x8</a>"
+ +"\n[f9]=<a href='f9/x9'>f9/x9</a>"
+ +"\n[fa]=<a href='http://www.ibm.com/fa/xa#MY_LABEL'>http://www.ibm.com/fa/xa#MY_LABEL</a>"
+ +"\n[fb]=<a href='http://www.ibm.com/fb/xb?label=MY_LABEL&foo=bar'>MY_LABEL</a>"
+ +"\n[fc]=<a href='http://www.ibm.com/fc/xc?foo=bar&label=MY_LABEL'>MY_LABEL</a>"
+ +"\n[fd]=<a href='http://www.ibm.com/fd/xd?label2=MY_LABEL&foo=bar'>http://www.ibm.com/fd/xd?label2=MY_LABEL&foo=bar</a>"
+ +"\n[fe]=<a href='http://www.ibm.com/fe/xe?foo=bar&label2=MY_LABEL'>http://www.ibm.com/fe/xe?foo=bar&label2=MY_LABEL</a>";
+ assertEquals(expected, r);
+
+ s.setProperty(SERIALIZER_absolutePathUriBase, "http://myhost");
+ s.setProperty(SERIALIZER_relativeUriBase, "/cr");
+ s.setProperty(HTML_uriAnchorText, TO_STRING);
+ r = strip(s.serialize(t));
+ expected = ""
+ +"\n[f0]=<a href='/cr/f0/x0'>f0/x0</a>"
+ +"\n[f1]=<a href='/cr/f1/x1'>f1/x1</a>"
+ +"\n[f2]=<a href='http://myhost/f2/x2'>/f2/x2</a>"
+ +"\n[f3]=<a href='http://www.ibm.com/f3/x3'>http://www.ibm.com/f3/x3</a>"
+ +"\n[f4]=<a href='/cr/f4/x4'>f4/x4</a>"
+ +"\n[f5]=<a href='http://myhost/f5/x5'>/f5/x5</a>"
+ +"\n[f6]=<a href='http://www.ibm.com/f6/x6'>http://www.ibm.com/f6/x6</a>"
+ +"\n[f7]=<a href='http://www.ibm.com/f7/x7'>http://www.ibm.com/f7/x7</a>"
+ +"\n[f8]=<a href='/cr/f8/x8'>f8/x8</a>"
+ +"\n[f9]=<a href='/cr/f9/x9'>f9/x9</a>"
+ +"\n[fa]=<a href='http://www.ibm.com/fa/xa#MY_LABEL'>http://www.ibm.com/fa/xa#MY_LABEL</a>"
+ +"\n[fb]=<a href='http://www.ibm.com/fb/xb?label=MY_LABEL&foo=bar'>MY_LABEL</a>"
+ +"\n[fc]=<a href='http://www.ibm.com/fc/xc?foo=bar&label=MY_LABEL'>MY_LABEL</a>"
+ +"\n[fd]=<a href='http://www.ibm.com/fd/xd?label2=MY_LABEL&foo=bar'>http://www.ibm.com/fd/xd?label2=MY_LABEL&foo=bar</a>"
+ +"\n[fe]=<a href='http://www.ibm.com/fe/xe?foo=bar&label2=MY_LABEL'>http://www.ibm.com/fe/xe?foo=bar&label2=MY_LABEL</a>";
+ assertEquals(expected, r);
+
+ s.setProperty(HTML_uriAnchorText, URI);
+ r = strip(s.serialize(t));
+ expected = ""
+ +"\n[f0]=<a href='/cr/f0/x0'>/cr/f0/x0</a>"
+ +"\n[f1]=<a href='/cr/f1/x1'>/cr/f1/x1</a>"
+ +"\n[f2]=<a href='http://myhost/f2/x2'>http://myhost/f2/x2</a>"
+ +"\n[f3]=<a href='http://www.ibm.com/f3/x3'>http://www.ibm.com/f3/x3</a>"
+ +"\n[f4]=<a href='/cr/f4/x4'>/cr/f4/x4</a>"
+ +"\n[f5]=<a href='http://myhost/f5/x5'>http://myhost/f5/x5</a>"
+ +"\n[f6]=<a href='http://www.ibm.com/f6/x6'>http://www.ibm.com/f6/x6</a>"
+ +"\n[f7]=<a href='http://www.ibm.com/f7/x7'>http://www.ibm.com/f7/x7</a>"
+ +"\n[f8]=<a href='/cr/f8/x8'>/cr/f8/x8</a>"
+ +"\n[f9]=<a href='/cr/f9/x9'>/cr/f9/x9</a>"
+ +"\n[fa]=<a href='http://www.ibm.com/fa/xa#MY_LABEL'>http://www.ibm.com/fa/xa#MY_LABEL</a>"
+ +"\n[fb]=<a href='http://www.ibm.com/fb/xb?label=MY_LABEL&foo=bar'>MY_LABEL</a>"
+ +"\n[fc]=<a href='http://www.ibm.com/fc/xc?foo=bar&label=MY_LABEL'>MY_LABEL</a>"
+ +"\n[fd]=<a href='http://www.ibm.com/fd/xd?label2=MY_LABEL&foo=bar'>http://www.ibm.com/fd/xd?label2=MY_LABEL&foo=bar</a>"
+ +"\n[fe]=<a href='http://www.ibm.com/fe/xe?foo=bar&label2=MY_LABEL'>http://www.ibm.com/fe/xe?foo=bar&label2=MY_LABEL</a>";
+ assertEquals(expected, r);
+
+ s.setProperty(HTML_uriAnchorText, LAST_TOKEN);
+ r = strip(s.serialize(t));
+ expected = ""
+ +"\n[f0]=<a href='/cr/f0/x0'>x0</a>"
+ +"\n[f1]=<a href='/cr/f1/x1'>x1</a>"
+ +"\n[f2]=<a href='http://myhost/f2/x2'>x2</a>"
+ +"\n[f3]=<a href='http://www.ibm.com/f3/x3'>x3</a>"
+ +"\n[f4]=<a href='/cr/f4/x4'>x4</a>"
+ +"\n[f5]=<a href='http://myhost/f5/x5'>x5</a>"
+ +"\n[f6]=<a href='http://www.ibm.com/f6/x6'>x6</a>"
+ +"\n[f7]=<a href='http://www.ibm.com/f7/x7'>x7</a>"
+ +"\n[f8]=<a href='/cr/f8/x8'>x8</a>"
+ +"\n[f9]=<a href='/cr/f9/x9'>x9</a>"
+ +"\n[fa]=<a href='http://www.ibm.com/fa/xa#MY_LABEL'>xa</a>"
+ +"\n[fb]=<a href='http://www.ibm.com/fb/xb?label=MY_LABEL&foo=bar'>MY_LABEL</a>"
+ +"\n[fc]=<a href='http://www.ibm.com/fc/xc?foo=bar&label=MY_LABEL'>MY_LABEL</a>"
+ +"\n[fd]=<a href='http://www.ibm.com/fd/xd?label2=MY_LABEL&foo=bar'>xd</a>"
+ +"\n[fe]=<a href='http://www.ibm.com/fe/xe?foo=bar&label2=MY_LABEL'>xe</a>";
+ assertEquals(expected, r);
+
+ s.setProperty(HTML_uriAnchorText, URI_ANCHOR);
+ r = strip(s.serialize(t));
+ expected = ""
+ +"\n[f0]=<a href='/cr/f0/x0'>f0/x0</a>"
+ +"\n[f1]=<a href='/cr/f1/x1'>f1/x1</a>"
+ +"\n[f2]=<a href='http://myhost/f2/x2'>/f2/x2</a>"
+ +"\n[f3]=<a href='http://www.ibm.com/f3/x3'>http://www.ibm.com/f3/x3</a>"
+ +"\n[f4]=<a href='/cr/f4/x4'>f4/x4</a>"
+ +"\n[f5]=<a href='http://myhost/f5/x5'>/f5/x5</a>"
+ +"\n[f6]=<a href='http://www.ibm.com/f6/x6'>http://www.ibm.com/f6/x6</a>"
+ +"\n[f7]=<a href='http://www.ibm.com/f7/x7'>http://www.ibm.com/f7/x7</a>"
+ +"\n[f8]=<a href='/cr/f8/x8'>f8/x8</a>"
+ +"\n[f9]=<a href='/cr/f9/x9'>f9/x9</a>"
+ +"\n[fa]=<a href='http://www.ibm.com/fa/xa#MY_LABEL'>MY_LABEL</a>"
+ +"\n[fb]=<a href='http://www.ibm.com/fb/xb?label=MY_LABEL&foo=bar'>MY_LABEL</a>"
+ +"\n[fc]=<a href='http://www.ibm.com/fc/xc?foo=bar&label=MY_LABEL'>MY_LABEL</a>"
+ +"\n[fd]=<a href='http://www.ibm.com/fd/xd?label2=MY_LABEL&foo=bar'>http://www.ibm.com/fd/xd?label2=MY_LABEL&foo=bar</a>"
+ +"\n[fe]=<a href='http://www.ibm.com/fe/xe?foo=bar&label2=MY_LABEL'>http://www.ibm.com/fe/xe?foo=bar&label2=MY_LABEL</a>";
+ assertEquals(expected, r);
+
+ s.setProperty(HTML_labelParameter, "label2");
+ r = strip(s.serialize(t));
+ expected = ""
+ +"\n[f0]=<a href='/cr/f0/x0'>f0/x0</a>"
+ +"\n[f1]=<a href='/cr/f1/x1'>f1/x1</a>"
+ +"\n[f2]=<a href='http://myhost/f2/x2'>/f2/x2</a>"
+ +"\n[f3]=<a href='http://www.ibm.com/f3/x3'>http://www.ibm.com/f3/x3</a>"
+ +"\n[f4]=<a href='/cr/f4/x4'>f4/x4</a>"
+ +"\n[f5]=<a href='http://myhost/f5/x5'>/f5/x5</a>"
+ +"\n[f6]=<a href='http://www.ibm.com/f6/x6'>http://www.ibm.com/f6/x6</a>"
+ +"\n[f7]=<a href='http://www.ibm.com/f7/x7'>http://www.ibm.com/f7/x7</a>"
+ +"\n[f8]=<a href='/cr/f8/x8'>f8/x8</a>"
+ +"\n[f9]=<a href='/cr/f9/x9'>f9/x9</a>"
+ +"\n[fa]=<a href='http://www.ibm.com/fa/xa#MY_LABEL'>MY_LABEL</a>"
+ +"\n[fb]=<a href='http://www.ibm.com/fb/xb?label=MY_LABEL&foo=bar'>http://www.ibm.com/fb/xb?label=MY_LABEL&foo=bar</a>"
+ +"\n[fc]=<a href='http://www.ibm.com/fc/xc?foo=bar&label=MY_LABEL'>http://www.ibm.com/fc/xc?foo=bar&label=MY_LABEL</a>"
+ +"\n[fd]=<a href='http://www.ibm.com/fd/xd?label2=MY_LABEL&foo=bar'>MY_LABEL</a>"
+ +"\n[fe]=<a href='http://www.ibm.com/fe/xe?foo=bar&label2=MY_LABEL'>MY_LABEL</a>";
+ assertEquals(expected, r);
+
+ s.setProperty(HTML_detectLinksInStrings, false);
+ r = strip(s.serialize(t));
+ expected = ""
+ +"\n[f0]=<a href='/cr/f0/x0'>f0/x0</a>"
+ +"\n[f1]=<a href='/cr/f1/x1'>f1/x1</a>"
+ +"\n[f2]=<a href='http://myhost/f2/x2'>/f2/x2</a>"
+ +"\n[f3]=<a href='http://www.ibm.com/f3/x3'>http://www.ibm.com/f3/x3</a>"
+ +"\n[f4]=<a href='/cr/f4/x4'>f4/x4</a>"
+ +"\n[f5]=<a href='http://myhost/f5/x5'>/f5/x5</a>"
+ +"\n[f6]=<a href='http://www.ibm.com/f6/x6'>http://www.ibm.com/f6/x6</a>"
+ +"\n[f7]=<a href='http://www.ibm.com/f7/x7'>http://www.ibm.com/f7/x7</a>"
+ +"\n[f8]=<a href='/cr/f8/x8'>f8/x8</a>"
+ +"\n[f9]=<a href='/cr/f9/x9'>f9/x9</a>"
+ +"\n[fa]=<string>http://www.ibm.com/fa/xa#MY_LABEL</string>"
+ +"\n[fb]=<string>http://www.ibm.com/fb/xb?label=MY_LABEL&foo=bar</string>"
+ +"\n[fc]=<string>http://www.ibm.com/fc/xc?foo=bar&label=MY_LABEL</string>"
+ +"\n[fd]=<string>http://www.ibm.com/fd/xd?label2=MY_LABEL&foo=bar</string>"
+ +"\n[fe]=<string>http://www.ibm.com/fe/xe?foo=bar&label2=MY_LABEL</string>";
+ assertEquals(expected, r);
+
+ s.setProperty(HTML_detectLinksInStrings, true);
+ s.setProperty(HTML_lookForLabelParameters, false);
+ r = strip(s.serialize(t));
+ expected = ""
+ +"\n[f0]=<a href='/cr/f0/x0'>f0/x0</a>"
+ +"\n[f1]=<a href='/cr/f1/x1'>f1/x1</a>"
+ +"\n[f2]=<a href='http://myhost/f2/x2'>/f2/x2</a>"
+ +"\n[f3]=<a href='http://www.ibm.com/f3/x3'>http://www.ibm.com/f3/x3</a>"
+ +"\n[f4]=<a href='/cr/f4/x4'>f4/x4</a>"
+ +"\n[f5]=<a href='http://myhost/f5/x5'>/f5/x5</a>"
+ +"\n[f6]=<a href='http://www.ibm.com/f6/x6'>http://www.ibm.com/f6/x6</a>"
+ +"\n[f7]=<a href='http://www.ibm.com/f7/x7'>http://www.ibm.com/f7/x7</a>"
+ +"\n[f8]=<a href='/cr/f8/x8'>f8/x8</a>"
+ +"\n[f9]=<a href='/cr/f9/x9'>f9/x9</a>"
+ +"\n[fa]=<a href='http://www.ibm.com/fa/xa#MY_LABEL'>MY_LABEL</a>"
+ +"\n[fb]=<a href='http://www.ibm.com/fb/xb?label=MY_LABEL&foo=bar'>http://www.ibm.com/fb/xb?label=MY_LABEL&foo=bar</a>"
+ +"\n[fc]=<a href='http://www.ibm.com/fc/xc?foo=bar&label=MY_LABEL'>http://www.ibm.com/fc/xc?foo=bar&label=MY_LABEL</a>"
+ +"\n[fd]=<a href='http://www.ibm.com/fd/xd?label2=MY_LABEL&foo=bar'>http://www.ibm.com/fd/xd?label2=MY_LABEL&foo=bar</a>"
+ +"\n[fe]=<a href='http://www.ibm.com/fe/xe?foo=bar&label2=MY_LABEL'>http://www.ibm.com/fe/xe?foo=bar&label2=MY_LABEL</a>";
+ assertEquals(expected, r);
+ }
+
+ private String strip(String html) {
+ return html
+ .replace("<table type='object'><tr><th><string>key</string></th><th><string>value</string></th></tr>", "")
+ .replace("</table>", "")
+ .replace("<tr><td><string>", "\n[")
+ .replace("</string></td><td>", "]=")
+ .replace("</td></tr>", "");
+ }
+
+ //====================================================================================================
+ // Test @Html.asPlainText annotation on classes and fields
+ //====================================================================================================
+ @Test
+ public void testHtmlAnnotationAsPlainText() throws Exception {
+ HtmlSerializer s = new HtmlSerializer.Sq();
+ Object o = null;
+ String r;
+
+ o = new B1();
+ r = s.serialize(o);
+ assertEquals("<test>", r);
+
+ o = new B2();
+ r = s.serialize(o);
+ assertEquals("<table type='object'><tr><th><string>key</string></th><th><string>value</string></th></tr><tr><td><string>f1</string></td><td><f1></td></tr></table>", r);
+ }
+
+ @Html(asPlainText=true)
+ public static class B1 {
+ public String f1 = "<f1>";
+ @Override /* Object */
+ public String toString() {
+ return "<test>";
+ }
+ }
+
+ public static class B2 {
+ @Html(asPlainText=true)
+ public String f1 = "<f1>";
+ }
+
+ //====================================================================================================
+ // Test @Html.asXml annotation on classes and fields
+ //====================================================================================================
+ @Test
+ public void testHtmlAnnotationAsXml() throws Exception {
+ HtmlSerializer s = new HtmlSerializer.Sq();
+ Object o = null;
+ String r;
+
+ o = new C1();
+ r = s.serialize(o);
+ assertEquals("<object><f1><f1></f1></object>", r);
+
+ o = new C2();
+ r = s.serialize(o);
+ assertEquals("<table type='object'><tr><th><string>key</string></th><th><string>value</string></th></tr><tr><td><string>f1</string></td><td><string><f1></string></td></tr></table>", r);
+ }
+
+ @Html(asXml=true)
+ public static class C1 {
+ public String f1 = "<f1>";
+ }
+
+ public static class C2 {
+ @Html(asXml=true)
+ public String f1 = "<f1>";
+ }
+
+ //====================================================================================================
+ // Test @Html.noTableHeaders
+ //====================================================================================================
+ @Test
+ public void testNoTableHeaders() throws Exception {
+ HtmlSerializer s = new HtmlSerializer.Sq();
+ Object o = null;
+ String r;
+
+ Map m = new MyMap();
+ m.put("foo", "bar");
+ o = new ObjectList().append(m);
+ r = s.serialize(o);
+ assertEquals("<ul><li><table type='object'><tr><td><string>foo</string></td><td><string>bar</string></td></tr></table></li></ul>", r);
+ }
+
+ @Html(noTables=true, noTableHeaders=true)
+ public static class MyMap extends LinkedHashMap<String,String> {}
+
+}
\ No newline at end of file
[42/44] incubator-juneau git commit: Rename CT_* testcases.
Posted by ja...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestGzip.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestGzip.java b/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestGzip.java
deleted file mode 100755
index 954186e..0000000
--- a/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestGzip.java
+++ /dev/null
@@ -1,344 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.server;
-
-import static javax.servlet.http.HttpServletResponse.*;
-import static org.apache.juneau.server.TestUtils.*;
-import static org.junit.Assert.*;
-
-import java.io.*;
-import java.util.zip.*;
-
-import org.apache.http.impl.client.*;
-import org.apache.juneau.client.*;
-import org.apache.juneau.internal.*;
-import org.junit.*;
-
-/**
- * Test Accept-Encoding and Content-Encoding handling.
- *
- * Note: WAS does automatic gzip decompression on http request messages, so we have to invent
- * our own 'mycoding' compression.
- */
-public class CT_TestGzip {
-
- private static boolean debug = false;
-
- private static String testGzipOff = "/testGzipOff";
- private static String testGzipOn = "/testGzipOn";
-
- // Converts string into a GZipped input stream.
- private static InputStream compress(String contents) throws Exception {
- ByteArrayOutputStream baos = new ByteArrayOutputStream(contents.length()>>1);
- GZIPOutputStream gos = new GZIPOutputStream(baos);
- gos.write(contents.getBytes());
- gos.finish();
- gos.close();
- return new ByteArrayInputStream(baos.toByteArray());
- }
-
- private static String decompress(InputStream is) throws Exception {
- return IOUtils.read(new GZIPInputStream(is));
- }
-
- //====================================================================================================
- // Test with no compression enabled.
- //====================================================================================================
- @Test
- public void testGzipOff() throws Exception {
- RestClient c = new TestRestClient().setAccept("text/plain").setContentType("text/plain");
- RestCall r;
- String url = testGzipOff;
-
- // *** GET ***
-
- r = c.doGet(url);
- assertEquals("foo", r.getResponseAsString());
-
- r = c.doGet(url).setHeader("Accept-Encoding", "");
- assertEquals("foo", r.getResponseAsString());
-
- r = c.doGet(url).setHeader("Accept-Encoding", "*");
- assertEquals("foo", r.getResponseAsString());
-
- r = c.doGet(url).setHeader("Accept-Encoding", "identity");
- assertEquals("foo", r.getResponseAsString());
-
- // Should match identity.
- r = c.doGet(url).setHeader("Accept-Encoding", "mycoding");
- assertEquals("foo", r.getResponseAsString());
-
- // Shouldn't match.
- try {
- r = c.doGet(url+"?noTrace=true").setHeader("Accept-Encoding", "mycoding,identity;q=0").connect();
- fail("Exception expected");
- } catch (RestCallException e) {
- checkErrorResponse(debug, e, SC_NOT_ACCEPTABLE,
- "Unsupported encoding in request header 'Accept-Encoding': 'mycoding,identity;q=0'",
- "Supported codings: [identity]"
- );
- }
-
- // Shouldn't match.
- try {
- c.doGet(url+"?noTrace=true").setHeader("Accept-Encoding", "mycoding,*;q=0").connect();
- fail("Exception expected");
- } catch (RestCallException e) {
- checkErrorResponse(debug, e, SC_NOT_ACCEPTABLE,
- "Unsupported encoding in request header 'Accept-Encoding': 'mycoding,*;q=0'",
- "Supported codings: [identity]"
- );
- }
-
- // Should match identity
- r = c.doGet(url).setHeader("Accept-Encoding", "identity;q=0.8,mycoding;q=0.6");
- assertEquals("foo", r.getResponseAsString());
-
- // Should match identity
- r = c.doGet(url).setHeader("Accept-Encoding", "mycoding;q=0.8,identity;q=0.6");
- assertEquals("foo", r.getResponseAsString());
-
- // Should match identity
- r = c.doGet(url).setHeader("Accept-Encoding", "mycoding;q=0.8,*;q=0.6");
- assertEquals("foo", r.getResponseAsString());
-
- // Should match identity
- r = c.doGet(url).setHeader("Accept-Encoding", "*;q=0.8,myencoding;q=0.6");
- assertEquals("foo", r.getResponseAsString());
-
- // Shouldn't match
- try {
- c.doGet(url+"?noTrace=true").setHeader("Accept-Encoding", "identity;q=0").connect();
- fail("Exception expected");
- } catch (RestCallException e) {
- checkErrorResponse(debug, e, SC_NOT_ACCEPTABLE,
- "Unsupported encoding in request header 'Accept-Encoding': 'identity;q=0'",
- "Supported codings: [identity]"
- );
- }
-
- // Shouldn't match
- try {
- c.doGet(url+"?noTrace=true").setHeader("Accept-Encoding", "identity;q=0.0").connect();
- fail("Exception expected");
- } catch (RestCallException e) {
- checkErrorResponse(debug, e, SC_NOT_ACCEPTABLE,
- "Unsupported encoding in request header 'Accept-Encoding': 'identity;q=0.0'",
- "Supported codings: [identity]"
- );
- }
-
- // Shouldn't match
- try {
- c.doGet(url+"?noTrace=true").setHeader("Accept-Encoding", "*;q=0").connect();
- fail("Exception expected");
- } catch (RestCallException e) {
- checkErrorResponse(debug, e, SC_NOT_ACCEPTABLE,
- "Unsupported encoding in request header 'Accept-Encoding': '*;q=0'",
- "Supported codings: [identity]"
- );
- }
-
- // Shouldn't match
- try {
- c.doGet(url+"?noTrace=true").setHeader("Accept-Encoding", "*;q=0.0").connect();
- fail("Exception expected");
- } catch (RestCallException e) {
- checkErrorResponse(debug, e, SC_NOT_ACCEPTABLE,
- "Unsupported encoding in request header 'Accept-Encoding': '*;q=0.0'",
- "Supported codings: [identity]"
- );
- }
-
-
- // *** PUT ***
-
- r = c.doPut(url, new StringReader("foo"));
- assertEquals("foo", r.getResponseAsString());
-
- r = c.doPut(url, new StringReader("foo")).setHeader("Content-Encoding", "");
- assertEquals("foo", r.getResponseAsString());
-
- r = c.doPut(url, new StringReader("foo")).setHeader("Content-Encoding", "identity");
- assertEquals("foo", r.getResponseAsString());
-
- try {
- c.doPut(url+"?noTrace=true", compress("foo")).setHeader("Content-Encoding", "mycoding").connect();
- fail("Exception expected");
- } catch (RestCallException e) {
- checkErrorResponse(debug, e, SC_UNSUPPORTED_MEDIA_TYPE,
- "Unsupported encoding in request header 'Content-Encoding': 'mycoding'",
- "Supported codings: [identity]"
- );
- }
-
- c.closeQuietly();
- }
-
- //====================================================================================================
- // Test with compression enabled.
- //====================================================================================================
- @Test
- public void testGzipOn() throws Exception {
-
- // Create a client that disables content compression support so that we can get the gzipped content directly.
- CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(TestRestClient.getSSLSocketFactory()).disableContentCompression().build();
-
- RestClient c = new TestRestClient(httpClient).setAccept("text/plain").setContentType("text/plain");
- RestCall r;
- String url = testGzipOn;
-
- // *** GET ***
-
- r = c.doGet(url);
- assertEquals("foo", r.getResponseAsString());
-
- r = c.doGet(url).setHeader("Accept-Encoding", "");
- assertEquals("foo", r.getResponseAsString());
-
- r = c.doGet(url).setHeader("Accept-Encoding", "*");
- assertEquals("foo", decompress(r.getInputStream()));
-
- r = c.doGet(url).setHeader("Accept-Encoding", "identity");
- assertEquals("foo", r.getResponseAsString());
-
- // Should match identity.
- r = c.doGet(url).setHeader("Accept-Encoding", "mycoding");
- assertEquals("foo", decompress(r.getInputStream()));
-
- r = c.doGet(url).setHeader("Accept-Encoding", "mycoding,identity;q=0").connect();
- assertEquals("foo", decompress(r.getInputStream()));
-
- r = c.doGet(url).setHeader("Accept-Encoding", "mycoding,*;q=0").connect();
- assertEquals("foo", decompress(r.getInputStream()));
-
- // Should match identity
- r = c.doGet(url).setHeader("Accept-Encoding", "identity;q=0.8,mycoding;q=0.6");
- assertEquals("foo", r.getResponseAsString());
-
- // Should match mycoding
- r = c.doGet(url).setHeader("Accept-Encoding", "mycoding;q=0.8,identity;q=0.6");
- assertEquals("foo", decompress(r.getInputStream()));
-
- // Should match mycoding
- r = c.doGet(url).setHeader("Accept-Encoding", "mycoding;q=0.8,*;q=0.6");
- assertEquals("foo", decompress(r.getInputStream()));
-
- // Should match identity
- r = c.doGet(url).setHeader("Accept-Encoding", "*;q=0.8,myencoding;q=0.6");
- assertEquals("foo", decompress(r.getInputStream()));
-
- // Shouldn't match
- try {
- c.doGet(url+"?noTrace=true").setHeader("Accept-Encoding", "identity;q=0").connect();
- fail("Exception expected");
- } catch (RestCallException e) {
- checkErrorResponse(debug, e, SC_NOT_ACCEPTABLE,
- "Unsupported encoding in request header 'Accept-Encoding': 'identity;q=0'",
- "Supported codings: [mycoding, identity]"
- );
- }
-
- // Shouldn't match
- try {
- c.doGet(url+"?noTrace=true").setHeader("Accept-Encoding", "identity;q=0.0").connect();
- fail("Exception expected");
- } catch (RestCallException e) {
- checkErrorResponse(debug, e, SC_NOT_ACCEPTABLE,
- "Unsupported encoding in request header 'Accept-Encoding': 'identity;q=0.0'",
- "Supported codings: [mycoding, identity]"
- );
- }
-
- // Shouldn't match
- try {
- c.doGet(url+"?noTrace=true").setHeader("Accept-Encoding", "*;q=0").connect();
- fail("Exception expected");
- } catch (RestCallException e) {
- checkErrorResponse(debug, e, SC_NOT_ACCEPTABLE,
- "Unsupported encoding in request header 'Accept-Encoding': '*;q=0'",
- "Supported codings: [mycoding, identity]"
- );
- }
-
- // Shouldn't match
- try {
- c.doGet(url+"?noTrace=true").setHeader("Accept-Encoding", "*;q=0.0").connect();
- fail("Exception expected");
- } catch (RestCallException e) {
- checkErrorResponse(debug, e, SC_NOT_ACCEPTABLE,
- "Unsupported encoding in request header 'Accept-Encoding': '*;q=0.0'",
- "Supported codings: [mycoding, identity]"
- );
- }
-
-
- // *** PUT ***
-
- r = c.doPut(url, new StringReader("foo"));
- assertEquals("foo", r.getResponseAsString());
-
- r = c.doPut(url, new StringReader("foo")).setHeader("Content-Encoding", "");
- assertEquals("foo", r.getResponseAsString());
-
- r = c.doPut(url, new StringReader("foo")).setHeader("Content-Encoding", "identity");
- assertEquals("foo", r.getResponseAsString());
-
- r = c.doPut(url, compress("foo")).setHeader("Content-Encoding", "mycoding");
- assertEquals("foo", r.getResponseAsString());
-
- c.closeQuietly();
- }
-
- //====================================================================================================
- // Test with compression enabled but with servlet using output stream directly.
- //====================================================================================================
- @Test
- public void testGzipOnDirect() throws Exception {
- // Create a client that disables content compression support so that we can get the gzipped content directly.
- CloseableHttpClient httpClient = HttpClientBuilder.create().setSSLSocketFactory(TestRestClient.getSSLSocketFactory()).build();
- RestClient c = new TestRestClient(httpClient).setAccept("text/plain").setContentType("text/plain");
- RestCall r = null;
- String s = null;
-
- // res.getOutputStream() called....should bypass encoding.
- r = c.doGet(testGzipOn + "/direct").setHeader("Accept-Encoding", "mycoding");
- s = r.getResponseAsString();
- assertEquals("test", s);
- assertTrue(r.getResponse().getHeaders("Content-Type")[0].getValue().contains("text/direct")); // Should get header set manually.
- assertEquals(0, r.getResponse().getHeaders("Content-Encoding").length); // Should not be set.
-
- // res.getWriter() called....should bypass encoding.
- r = c.doGet(testGzipOn + "/direct2").setHeader("Accept-Encoding", "mycoding");
- s = r.getResponseAsString();
- assertEquals("test", s);
- assertEquals(0, r.getResponse().getHeaders("Content-Encoding").length); // Should not be set.
-
- // res.getNegotiateWriter() called....should NOT bypass encoding.
- r = c.doGet(testGzipOn + "/direct3").setHeader("Accept-Encoding", "mycoding");
- try {
- assertEquals("mycoding", r.getResponse().getHeaders("content-encoding")[0].getValue());
- } catch (RestCallException e) {
- // OK - HttpClient doesn't know what mycoding is.
- // Newer versions of HttpClient ignore this condition.
- }
-
- // res.getNegotiateWriter() called but @RestMethod(encoders={})...should bypass encoding.
- r = c.doGet(testGzipOn + "/direct4").setHeader("Accept-Encoding", "mycoding");
- s = r.getResponseAsString();
- assertEquals("test", s);
- assertEquals(0, r.getResponse().getHeaders("Content-Encoding").length); // Should not be set.
-
- c.closeQuietly();
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestInheritance.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestInheritance.java b/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestInheritance.java
deleted file mode 100755
index e9f0fb7..0000000
--- a/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestInheritance.java
+++ /dev/null
@@ -1,128 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.server;
-
-import static org.junit.Assert.*;
-
-import org.apache.juneau.client.*;
-import org.apache.juneau.json.*;
-import org.junit.*;
-
-public class CT_TestInheritance {
-
- private static RestClient client;
-
- @BeforeClass
- public static void beforeClass() {
- client = new TestRestClient();
- }
-
- @AfterClass
- public static void afterClass() {
- client.closeQuietly();
- }
-
- //====================================================================================================
- // Test serializer inheritance.
- //====================================================================================================
- @Test
- public void testSerializers() throws Exception {
- String r;
- String url = "/testInheritanceSerializers";
- r = client.doGet(url + "/test1").getResponseAsString();
- assertEquals("['text/s3','text/s4','text/s1','text/s2']", r);
-
- r = client.doGet(url + "/test2").getResponseAsString();
- assertEquals("['text/s5']", r);
-
- r = client.doGet(url + "/test3").getResponseAsString();
- assertEquals("['text/s5','text/s3','text/s4','text/s1','text/s2']", r);
- }
-
- //====================================================================================================
- // Test parser inheritance.
- //====================================================================================================
- @Test
- public void testParsers() throws Exception {
- String r;
- String url = "/testInheritanceParsers";
- r = client.doGet(url + "/test1").getResponseAsString();
- assertEquals("['text/p3','text/p4','text/p1','text/p2']", r);
-
- r = client.doGet(url + "/test2").getResponseAsString();
- assertEquals("['text/p5']", r);
-
- r = client.doGet(url + "/test3").getResponseAsString();
- assertEquals("['text/p5','text/p3','text/p4','text/p1','text/p2']", r);
- }
-
- //====================================================================================================
- // Test encoder inheritance.
- //====================================================================================================
- @Test
- public void testEncoders() throws Exception {
- String url = "/testInheritanceEncoders";
- String r = client.doGet(url + "/test").getResponseAsString();
- assertEquals("['e3','e4','e1','e2','identity']", r);
- }
-
- //====================================================================================================
- // Test filter inheritance.
- //====================================================================================================
- @Test
- @SuppressWarnings("hiding")
- public void testTransforms() throws Exception {
- RestClient client = new TestRestClient(JsonSerializer.class, JsonParser.class).setAccept("text/json+simple");
- String r;
- String url = "/testInheritanceTransforms";
-
- r = client.doGet(url + "/test1").getResponseAsString();
- assertEquals("['F1','F2','Foo3']", r);
-
- r = client.doGet(url + "/test2").getResponseAsString();
- assertEquals("['F1','F2','F3']", r);
-
- r = client.doGet(url + "/test3").getResponseAsString();
- assertEquals("['F1','F2','F3']", r);
-
- r = client.doGet(url + "/test4").getResponseAsString();
- assertEquals("['Foo1','Foo2','F3']", r);
-
- r = client.doGet(url + "/test5").getResponseAsString();
- assertEquals("['F1','F2','F3']", r);
-
- client.closeQuietly();
- }
-
- //====================================================================================================
- // Test properties inheritance.
- //====================================================================================================
- @Test
- @SuppressWarnings("hiding")
- public void testProperties() throws Exception {
- RestClient client = new TestRestClient(JsonSerializer.class, JsonParser.class).setAccept("text/json+simple");
- String r;
- String url = "/testInheritanceProperties";
-
- r = client.doGet(url + "/test1").getResponseAsString();
- assertEquals("{p1:'v1',p2:'v2a',p3:'v3',p4:'v4'}", r);
-
- r = client.doGet(url + "/test2?override").getResponseAsString();
- assertEquals("{p1:'x',p2:'x',p3:'x',p4:'x',p5:'x'}", r);
-
- r = client.doGet(url + "/test2").getResponseAsString();
- assertEquals("{p1:'v1',p2:'v2a',p3:'v3',p4:'v4a',p5:'v5'}", r);
-
- client.closeQuietly();
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestLargePojos.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestLargePojos.java b/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestLargePojos.java
deleted file mode 100755
index dfbc494..0000000
--- a/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestLargePojos.java
+++ /dev/null
@@ -1,83 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.server;
-
-import org.apache.juneau.client.*;
-import org.apache.juneau.html.*;
-import org.apache.juneau.json.*;
-import org.apache.juneau.urlencoding.*;
-import org.apache.juneau.xml.*;
-import org.junit.*;
-
-@Ignore
-public class CT_TestLargePojos {
-
- private static String URL = "/testLargePojos";
- boolean debug = false;
-
- //====================================================================================================
- // Test how long it takes to serialize/parse various content types.
- //====================================================================================================
- @Test
- public void test() throws Exception {
- LargePojo p;
- long t;
- RestClient c;
-
- System.err.println("\n---Testing JSON---");
- c = new TestRestClient(JsonSerializer.class, JsonParser.class);
- for (int i = 1; i <= 3; i++) {
- t = System.currentTimeMillis();
- p = c.doGet(URL).getResponse(LargePojo.class);
- System.err.println("Download: ["+(System.currentTimeMillis() - t)+"] ms");
- t = System.currentTimeMillis();
- c.doPut(URL, p).run();
- System.err.println("Upload: ["+(System.currentTimeMillis() - t)+"] ms");
- }
-
- System.err.println("\n---Testing XML---");
- c = new TestRestClient(XmlSerializer.class, XmlParser.class);
- for (int i = 1; i <= 3; i++) {
- t = System.currentTimeMillis();
- p = c.doGet(URL).getResponse(LargePojo.class);
- System.err.println("Download: ["+(System.currentTimeMillis() - t)+"] ms");
- t = System.currentTimeMillis();
- c.doPut(URL, p).run();
- System.err.println("Upload: ["+(System.currentTimeMillis() - t)+"] ms");
- }
-
- System.err.println("\n---Testing HTML---");
- c = new TestRestClient(HtmlSerializer.class, HtmlParser.class).setAccept("text/html+stripped");
- for (int i = 1; i <= 3; i++) {
- t = System.currentTimeMillis();
- p = c.doGet(URL).getResponse(LargePojo.class);
- System.err.println("Download: ["+(System.currentTimeMillis() - t)+"] ms");
- t = System.currentTimeMillis();
- c.doPut(URL, p).run();
- System.err.println("Upload: ["+(System.currentTimeMillis() - t)+"] ms");
- }
-
- System.err.println("\n---Testing UrlEncoding---");
- c = new TestRestClient(UonSerializer.class, UonParser.class);
- for (int i = 1; i <= 3; i++) {
- t = System.currentTimeMillis();
- p = c.doGet(URL).getResponse(LargePojo.class);
- System.err.println("Download: ["+(System.currentTimeMillis() - t)+"] ms");
- t = System.currentTimeMillis();
- c.doPut(URL, p).run();
- System.err.println("Upload: ["+(System.currentTimeMillis() - t)+"] ms");
- }
-
- c.closeQuietly();
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestMessages.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestMessages.java b/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestMessages.java
deleted file mode 100755
index 563ece7..0000000
--- a/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestMessages.java
+++ /dev/null
@@ -1,47 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.server;
-
-import static org.apache.juneau.server.TestUtils.*;
-
-import java.util.*;
-
-import org.apache.juneau.client.*;
-import org.apache.juneau.json.*;
-import org.junit.*;
-
-/**
- * Validates that resource bundles can be defined on both parent and child classes.
- */
-public class CT_TestMessages {
-
- //====================================================================================================
- // Return contents of resource bundle.
- //====================================================================================================
- @SuppressWarnings("rawtypes")
- @Test
- public void test() throws Exception {
- RestClient client = new TestRestClient(JsonSerializer.class,JsonParser.class);
-
- // Parent resource should just pick up values from its bundle.
- TreeMap r = client.doGet("/testMessages/test").getResponse(TreeMap.class);
- assertObjectEquals("{key1:'value1a',key2:'value2a'}", r);
-
- // Child resource should pick up values from both parent and child,
- // ordered child before parent.
- r = client.doGet("/testMessages2/test").getResponse(TreeMap.class);
- assertObjectEquals("{key1:'value1a',key2:'value2b',key3:'value3b'}", r);
-
- client.closeQuietly();
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestNls.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestNls.java b/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestNls.java
deleted file mode 100755
index 6bd4372..0000000
--- a/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestNls.java
+++ /dev/null
@@ -1,170 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.server;
-
-import static org.junit.Assert.*;
-
-import org.apache.juneau.*;
-import org.apache.juneau.client.*;
-import org.apache.juneau.json.*;
-import org.junit.*;
-
-public class CT_TestNls {
-
- private static String URL = "/testNls";
-
- // ====================================================================================================
- // test1 - Pull labels from annotations only.
- // ====================================================================================================
- @Test
- public void test1() throws Exception {
- RestClient client = new TestRestClient(JsonSerializer.DEFAULT, JsonParser.DEFAULT);
- ObjectMap r = null;
- String expected = null;
-
- // Labels all pulled from annotations.
- r = client.doOptions(URL + "/test1").getResponse(ObjectMap.class);
- assertEquals("Test1.a", r.getString("label"));
- assertEquals("Test1.b", r.getString("description"));
- r = r.getObjectList("methods").getObjectMap(0);
- assertEquals("test1", r.getString("javaMethod"));
- assertEquals("POST", r.getString("httpMethod"));
- expected = "[{category:'attr',name:'a',description:'Test1.d'},{category:'attr',name:'a2',description:'Test1.h'},{category:'attr',name:'e'},{category:'content',name:'',description:'Test1.f'},{category:'foo',name:'bar',description:'Test1.k'},{category:'header',name:'D',description:'Test1.g'},{category:'header',name:'D2',description:'Test1.j'},{category:'header',name:'g'},{category:'param',name:'b',description:'Test1.e'},{category:'param',name:'b2',description:'Test1.i'},{category:'param',name:'f'}]";
- assertEquals(expected, r.getObjectList("input").toString());
- expected = "[{status:200,description:'OK',output:[]},{status:201,description:'Test1.l',output:[{category:'foo',name:'bar',description:'Test1.m'}]}]";
- assertEquals(expected, r.getObjectList("responses").toString());
-
- client.closeQuietly();
- }
-
- // ====================================================================================================
- // test2 - Pull labels from resource bundles only - simple keys.
- // ====================================================================================================
- @Test
- public void test2() throws Exception {
- RestClient client = new TestRestClient(JsonSerializer.DEFAULT, JsonParser.DEFAULT);
- ObjectMap r = null;
- String expected = null;
-
- // Labels all pulled from annotations.
- r = client.doOptions(URL + "/test2").getResponse(ObjectMap.class);
- assertEquals("Test2.a", r.getString("label"));
- assertEquals("Test2.b", r.getString("description"));
- r = r.getObjectList("methods").getObjectMap(0);
- assertEquals("test2", r.getString("javaMethod"));
- assertEquals("POST", r.getString("httpMethod"));
- expected = "[{category:'attr',name:'a',description:'Test2.d'},{category:'attr',name:'a2',description:'Test2.h'},{category:'attr',name:'e'},{category:'content',name:'',description:'Test2.f'},{category:'foo',name:'bar',description:'Test2.k'},{category:'header',name:'D',description:'Test2.g'},{category:'header',name:'D2',description:'Test2.j'},{category:'header',name:'g'},{category:'param',name:'b',description:'Test2.e'},{category:'param',name:'b2',description:'Test2.i'},{category:'param',name:'f'}]";
- assertEquals(expected, r.getObjectList("input").toString());
- expected = "[{status:200,description:'OK2',output:[]},{status:201,description:'Test2.l',output:[{category:'foo',name:'bar',description:'Test2.m'}]}]";
- assertEquals(expected, r.getObjectList("responses").toString());
-
- client.closeQuietly();
- }
-
- // ====================================================================================================
- // test3 - Pull labels from resource bundles only - keys with class names.
- // ====================================================================================================
- @Test
- public void test3() throws Exception {
- RestClient client = new TestRestClient(JsonSerializer.DEFAULT, JsonParser.DEFAULT);
- ObjectMap r = null;
- String expected = null;
-
- // Labels all pulled from annotations.
- r = client.doOptions(URL + "/test3").getResponse(ObjectMap.class);
- assertEquals("Test3.a", r.getString("label"));
- assertEquals("Test3.b", r.getString("description"));
- r = r.getObjectList("methods").getObjectMap(1);
- assertEquals("test3", r.getString("javaMethod"));
- assertEquals("POST", r.getString("httpMethod"));
- expected = "[{category:'attr',name:'a',description:'Test3.d'},{category:'attr',name:'a2',description:'Test3.h'},{category:'attr',name:'e'},{category:'content',name:'',description:'Test3.f'},{category:'foo',name:'bar',description:'Test3.k'},{category:'header',name:'D',description:'Test3.g'},{category:'header',name:'D2',description:'Test3.j'},{category:'header',name:'g'},{category:'param',name:'b',description:'Test3.e'},{category:'param',name:'b2',description:'Test3.i'},{category:'param',name:'f'}]";
- assertEquals(expected, r.getObjectList("input").toString());
- expected = "[{status:200,description:'OK3',output:[]},{status:201,description:'Test3.l',output:[{category:'foo',name:'bar',description:'Test3.m'}]}]";
- assertEquals(expected, r.getObjectList("responses").toString());
-
- client.closeQuietly();
- }
-
- // ====================================================================================================
- // test4 - Pull labels from resource bundles only. Values have localized variables to resolve.
- // ====================================================================================================
- @Test
- public void test4() throws Exception {
- RestClient client = new TestRestClient(JsonSerializer.DEFAULT, JsonParser.DEFAULT);
- ObjectMap r = null;
- String expected = null;
-
- // Labels all pulled from annotations.
- r = client.doOptions(URL + "/test4").getResponse(ObjectMap.class);
- assertEquals("baz", r.getString("label"));
- assertEquals("baz", r.getString("description"));
- r = r.getObjectList("methods").getObjectMap(0);
- assertEquals("test4", r.getString("javaMethod"));
- assertEquals("POST", r.getString("httpMethod"));
- expected = "[{category:'attr',name:'a',description:'baz'},{category:'attr',name:'a2',description:'baz'},{category:'attr',name:'e'},{category:'content',name:'',description:'baz'},{category:'foo',name:'bar',description:'baz'},{category:'header',name:'D',description:'baz'},{category:'header',name:'D2',description:'baz'},{category:'header',name:'g'},{category:'param',name:'b',description:'baz'},{category:'param',name:'b2',description:'baz'},{category:'param',name:'f'}]";
- assertEquals(expected, r.getObjectList("input").toString());
- expected = "[{status:200,description:'foobazfoobazfoo',output:[]},{status:201,description:'baz',output:[{category:'foo',name:'bar',description:'baz'}]}]";
- assertEquals(expected, r.getObjectList("responses").toString());
-
- client.closeQuietly();
- }
-
- // ====================================================================================================
- // test5 - Pull labels from resource bundles only. Values have request variables to resolve.
- // ====================================================================================================
- @Test
- public void test5() throws Exception {
- RestClient client = new TestRestClient(JsonSerializer.DEFAULT, JsonParser.DEFAULT);
- ObjectMap r = null;
- String expected = null;
-
- // Labels all pulled from annotations.
- r = client.doOptions(URL + "/test5").getResponse(ObjectMap.class);
- assertEquals("baz2", r.getString("label"));
- assertEquals("baz2", r.getString("description"));
- r = r.getObjectList("methods").getObjectMap(0);
- assertEquals("test5", r.getString("javaMethod"));
- assertEquals("POST", r.getString("httpMethod"));
- expected = "[{category:'attr',name:'a',description:'baz2'},{category:'attr',name:'a2',description:'baz2'},{category:'attr',name:'e'},{category:'content',name:'',description:'baz2'},{category:'foo',name:'bar',description:'baz2'},{category:'header',name:'D',description:'baz2'},{category:'header',name:'D2',description:'baz2'},{category:'header',name:'g'},{category:'param',name:'b',description:'baz2'},{category:'param',name:'b2',description:'baz2'},{category:'param',name:'f'}]";
- assertEquals(expected, r.getObjectList("input").toString());
- expected = "[{status:200,description:'foobaz2foobaz2foo',output:[]},{status:201,description:'baz2',output:[{category:'foo',name:'bar',description:'baz2'}]}]";
- assertEquals(expected, r.getObjectList("responses").toString());
-
- client.closeQuietly();
- }
-
- // ====================================================================================================
- // test6 - Pull labels from annotations only, but annotations contain variables.
- // ====================================================================================================
- @Test
- public void test6() throws Exception {
- RestClient client = new TestRestClient(JsonSerializer.DEFAULT, JsonParser.DEFAULT);
- ObjectMap r = null;
- String expected = null;
-
- // Labels all pulled from annotations.
- r = client.doOptions(URL + "/test6").getResponse(ObjectMap.class);
- assertEquals("baz", r.getString("label"));
- assertEquals("baz", r.getString("description"));
- r = r.getObjectList("methods").getObjectMap(0);
- assertEquals("test6", r.getString("javaMethod"));
- assertEquals("POST", r.getString("httpMethod"));
- expected = "[{category:'attr',name:'a',description:'baz'},{category:'attr',name:'a2',description:'baz'},{category:'attr',name:'e'},{category:'content',name:'',description:'baz'},{category:'foo',name:'bar',description:'baz'},{category:'header',name:'D',description:'baz'},{category:'header',name:'D2',description:'baz'},{category:'header',name:'g'},{category:'param',name:'b',description:'baz'},{category:'param',name:'b2',description:'baz'},{category:'param',name:'f'}]";
- assertEquals(expected, r.getObjectList("input").toString());
- expected = "[{status:200,description:'OK',output:[]},{status:201,description:'baz',output:[{category:'foo',name:'bar',description:'baz'}]}]";
- assertEquals(expected, r.getObjectList("responses").toString());
-
- client.closeQuietly();
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestNlsProperty.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestNlsProperty.java b/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestNlsProperty.java
deleted file mode 100755
index f8c0a1f..0000000
--- a/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestNlsProperty.java
+++ /dev/null
@@ -1,48 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.server;
-
-import static org.junit.Assert.*;
-
-import org.apache.juneau.client.*;
-import org.apache.juneau.plaintext.*;
-import org.junit.*;
-
-public class CT_TestNlsProperty {
-
- private static String URL = "/testNlsProperty";
-
- //====================================================================================================
- // Test getting an NLS property defined on a class.
- //====================================================================================================
- @Test
- public void testInheritedFromClass() throws Exception {
- RestClient client = new TestRestClient(PlainTextSerializer.class, PlainTextParser.class);
- String r = client.doGet(URL + "/testInheritedFromClass").getResponseAsString();
- assertEquals("value1", r);
-
- client.closeQuietly();
- }
-
- //====================================================================================================
- // Test getting an NLS property defined on a method.
- //====================================================================================================
- @Test
- public void testInheritedFromMethod() throws Exception {
- RestClient client = new TestRestClient(PlainTextSerializer.class, PlainTextParser.class);
- String r = client.doGet(URL + "/testInheritedFromMethod").getResponseAsString();
- assertEquals("value2", r);
-
- client.closeQuietly();
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestNoParserInput.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestNoParserInput.java b/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestNoParserInput.java
deleted file mode 100755
index 06b03e0..0000000
--- a/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestNoParserInput.java
+++ /dev/null
@@ -1,70 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.server;
-
-import static javax.servlet.http.HttpServletResponse.*;
-import static org.apache.juneau.server.TestUtils.*;
-import static org.junit.Assert.*;
-
-import org.apache.juneau.client.*;
-import org.apache.juneau.plaintext.*;
-import org.junit.*;
-
-public class CT_TestNoParserInput {
-
- private static String URL = "/testNoParserInput";
- private static boolean debug = false;
-
- //====================================================================================================
- // @Content annotated InputStream.
- //====================================================================================================
- @Test
- public void testInputStream() throws Exception {
- RestClient client = new TestRestClient(PlainTextSerializer.class, PlainTextParser.class);
- String r = client.doPut(URL + "/testInputStream", "foo").getResponseAsString();
- assertEquals("foo", r);
-
- client.closeQuietly();
- }
-
- //====================================================================================================
- // @Content annotated Reader.
- //====================================================================================================
- @Test
- public void testReader() throws Exception {
- RestClient client = new TestRestClient(PlainTextSerializer.class, PlainTextParser.class);
- String r = client.doPut(URL + "/testReader", "foo").getResponseAsString();
- assertEquals("foo", r);
-
- client.closeQuietly();
- }
-
- //====================================================================================================
- // @Content annotated PushbackReader.
- // This should always fail since the servlet reader is not a pushback reader.
- //====================================================================================================
- @Test
- public void testPushbackReader() throws Exception {
- RestClient client = new TestRestClient(PlainTextSerializer.class, PlainTextParser.class);
- try {
- client.doPut(URL + "/testPushbackReader?noTrace=true", "foo").getResponseAsString();
- fail("Exception expected");
- } catch (RestCallException e) {
- checkErrorResponse(debug, e, SC_BAD_REQUEST,
- "Invalid argument type passed to the following method:",
- "'public java.lang.String org.apache.juneau.server.TestNoParserInput.testPushbackReader(java.io.PushbackReader) throws java.lang.Exception'");
- }
-
- client.closeQuietly();
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestOnPostCall.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestOnPostCall.java b/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestOnPostCall.java
deleted file mode 100755
index 92a62cc..0000000
--- a/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestOnPostCall.java
+++ /dev/null
@@ -1,121 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.server;
-
-import static org.junit.Assert.*;
-
-import java.io.*;
-
-import org.apache.juneau.client.*;
-import org.junit.*;
-
-public class CT_TestOnPostCall {
-
- private static String URL = "/testOnPostCall";
-
- //====================================================================================================
- // Properties overridden via properties annotation.
- //====================================================================================================
- @Test
- public void testPropertiesOverridenByAnnotation() throws Exception {
- RestClient client = new TestRestClient().setAccept("text/s1");
- String url = URL + "/testPropertiesOverridenByAnnotation";
- String r;
- RestCall rc;
-
- r = client.doPut(url, new StringReader("")).getResponseAsString();
- assertEquals("p1=sp1,p2=xp2,p3=mp3,p4=xp4,p5=xp5,contentType=text/s1", r);
-
- r = client.doPut(url, new StringReader("")).setHeader("Override-Accept", "text/s2").getResponseAsString();
- assertEquals("p1=sp1,p2=xp2,p3=mp3,p4=xp4,p5=xp5,contentType=text/s2", r);
-
- rc = client.doPut(url, new StringReader("")).setHeader("Override-Content-Type", "text/s3").connect();
- r = rc.getResponseAsString();
- assertEquals("p1=sp1,p2=xp2,p3=mp3,p4=xp4,p5=xp5,contentType=text/s1", r);
- assertTrue(rc.getResponse().getFirstHeader("Content-Type").getValue().startsWith("text/s3"));
-
- client.closeQuietly();
- }
-
- //====================================================================================================
- // Properties overridden via properties annotation. Default Accept header.
- //====================================================================================================
- @Test
- public void testPropertiesOverridenByAnnotationDefaultAccept() throws Exception {
- RestClient client = new TestRestClient().setAccept("");
- String url = URL + "/testPropertiesOverridenByAnnotation";
- String r;
- RestCall rc;
-
- r = client.doPut(url, new StringReader("")).getResponseAsString();
- assertEquals("p1=sp1,p2=xp2,p3=mp3,p4=xp4,p5=xp5,contentType=text/s2", r);
-
- r = client.doPut(url, new StringReader("")).setHeader("Override-Accept", "text/s3").getResponseAsString();
- assertEquals("p1=sp1,p2=xp2,p3=mp3,p4=xp4,p5=xp5,contentType=text/s3", r);
-
- rc = client.doPut(url, new StringReader("")).setHeader("Override-Content-Type", "text/s3").connect();
- r = rc.getResponseAsString();
- assertEquals("p1=sp1,p2=xp2,p3=mp3,p4=xp4,p5=xp5,contentType=text/s2", r);
- assertTrue(rc.getResponse().getFirstHeader("Content-Type").getValue().startsWith("text/s3"));
-
- client.closeQuietly();
- }
-
- //====================================================================================================
- // Properties overridden programmatically.
- //====================================================================================================
- @Test
- public void testPropertiesOverriddenProgramatically() throws Exception {
- RestClient client = new TestRestClient().setAccept("text/s1");
- String url = URL + "/testPropertiesOverriddenProgramatically";
- String r;
- RestCall rc;
-
- r = client.doPut(url, new StringReader("")).getResponseAsString();
- assertEquals("p1=sp1,p2=xp2,p3=pp3,p4=xp4,p5=xp5,contentType=text/s1", r);
-
- r = client.doPut(url, new StringReader("")).setHeader("Override-Accept", "text/s2").getResponseAsString();
- assertEquals("p1=sp1,p2=xp2,p3=pp3,p4=xp4,p5=xp5,contentType=text/s2", r);
-
- rc = client.doPut(url, new StringReader("")).setHeader("Override-Content-Type", "text/s3").connect();
- r = rc.getResponseAsString();
- assertEquals("p1=sp1,p2=xp2,p3=pp3,p4=xp4,p5=xp5,contentType=text/s1", r);
- assertTrue(rc.getResponse().getFirstHeader("Content-Type").getValue().startsWith("text/s3"));
-
- client.closeQuietly();
- }
-
- //====================================================================================================
- // Properties overridden programmatically. Default Accept header.
- //====================================================================================================
- @Test
- public void testPropertiesOverriddenProgramaticallyDefaultAccept() throws Exception {
- RestClient client = new TestRestClient().setAccept("");
- String url = URL + "/testPropertiesOverriddenProgramatically";
- String r;
- RestCall rc;
-
- r = client.doPut(url, new StringReader("")).getResponseAsString();
- assertEquals("p1=sp1,p2=xp2,p3=pp3,p4=xp4,p5=xp5,contentType=text/s2", r);
-
- r = client.doPut(url, new StringReader("")).setHeader("Override-Accept", "text/s3").getResponseAsString();
- assertEquals("p1=sp1,p2=xp2,p3=pp3,p4=xp4,p5=xp5,contentType=text/s3", r);
-
- rc = client.doPut(url, new StringReader("")).setHeader("Override-Content-Type", "text/s3").connect();
- r = rc.getResponseAsString();
- assertEquals("p1=sp1,p2=xp2,p3=pp3,p4=xp4,p5=xp5,contentType=text/s2", r);
- assertTrue(rc.getResponse().getFirstHeader("Content-Type").getValue().startsWith("text/s3"));
-
- client.closeQuietly();
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestOnPreCall.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestOnPreCall.java b/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestOnPreCall.java
deleted file mode 100755
index 6c52d2b..0000000
--- a/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestOnPreCall.java
+++ /dev/null
@@ -1,61 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.server;
-
-import static org.junit.Assert.*;
-
-import java.io.*;
-
-import org.apache.juneau.client.*;
-import org.junit.*;
-
-public class CT_TestOnPreCall {
-
- private static String URL = "/testOnPreCall";
-
- //====================================================================================================
- // Properties overridden via properties annotation.
- //====================================================================================================
- @Test
- public void testPropertiesOverriddenByAnnotation() throws Exception {
- RestClient client = new TestRestClient().setContentType("text/a1").setAccept("text/plain");
- String url = URL + "/testPropertiesOverriddenByAnnotation";
- String r;
-
- r = client.doPut(url, new StringReader("")).getResponseAsString();
- assertEquals("p1=sp1,p2=xp2,p3=mp3,p4=xp4,p5=xp5,contentType=text/a1", r);
-
- r = client.doPut(url, new StringReader("")).setHeader("Override-Content-Type", "text/a2").getResponseAsString();
- assertEquals("p1=sp1,p2=xp2,p3=mp3,p4=xp4,p5=xp5,contentType=text/a2", r);
-
- client.closeQuietly();
- }
-
- //====================================================================================================
- // Properties overridden programmatically.
- //====================================================================================================
- @Test
- public void testPropertiesOverriddenProgrammatically() throws Exception {
- RestClient client = new TestRestClient().setContentType("text/a1").setAccept("text/plain");
- String url = URL + "/testPropertiesOverriddenProgrammatically";
- String r;
-
- r = client.doPut(url, new StringReader("")).getResponseAsString();
- assertEquals("p1=sp1,p2=xp2,p3=pp3,p4=pp4,p5=xp5,contentType=text/a1", r);
-
- r = client.doPut(url, new StringReader("")).setHeader("Override-Content-Type", "text/a2").getResponseAsString();
- assertEquals("p1=sp1,p2=xp2,p3=pp3,p4=pp4,p5=xp5,contentType=text/a2", r);
-
- client.closeQuietly();
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestOptionsWithoutNls.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestOptionsWithoutNls.java b/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestOptionsWithoutNls.java
deleted file mode 100755
index d55bd80..0000000
--- a/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestOptionsWithoutNls.java
+++ /dev/null
@@ -1,51 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.server;
-
-import static org.junit.Assert.*;
-
-import org.apache.juneau.client.*;
-import org.apache.juneau.json.*;
-import org.apache.juneau.server.labels.*;
-import org.junit.*;
-
-public class CT_TestOptionsWithoutNls {
-
- private static String URL = "/testOptionsWithoutNls";
-
- //====================================================================================================
- // Should get to the options page without errors
- //====================================================================================================
- @Test
- public void testOptions() throws Exception {
- RestClient client = new TestRestClient(JsonSerializer.DEFAULT, JsonParser.DEFAULT);
- RestCall r = client.doOptions(URL + "/testOptions");
- ResourceOptions o = r.getResponse(ResourceOptions.class);
- assertEquals("", o.getDescription());
-
- client.closeQuietly();
- }
-
- //====================================================================================================
- // Missing resource bundle should cause {!!x} string.
- //====================================================================================================
- @Test
- public void testMissingResourceBundle() throws Exception {
- RestClient client = new TestRestClient(JsonSerializer.DEFAULT, JsonParser.DEFAULT);
- RestCall r = client.doGet(URL + "/testMissingResourceBundle");
- String o = r.getResponse(String.class);
- assertEquals("{!!bad}", o);
-
- client.closeQuietly();
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestOverlappingMethods.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestOverlappingMethods.java b/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestOverlappingMethods.java
deleted file mode 100755
index 5c0942a..0000000
--- a/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestOverlappingMethods.java
+++ /dev/null
@@ -1,170 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.server;
-
-import static javax.servlet.http.HttpServletResponse.*;
-import static org.apache.juneau.server.TestUtils.*;
-import static org.junit.Assert.*;
-
-import org.apache.juneau.client.*;
-import org.junit.*;
-
-public class CT_TestOverlappingMethods {
-
- private static String URL = "/testOverlappingMethods";
- private static boolean debug = false;
-
- //====================================================================================================
- // Overlapping guards
- //====================================================================================================
- @Test
- public void testOverlappingGuards1() throws Exception {
- RestClient client = new TestRestClient().setHeader("Accept", "text/plain");
- String r;
- String url = URL + "/testOverlappingGuards1";
-
- r = client.doGet(url + "?t1=1").getResponseAsString();
- assertEquals("test1_doGet", r);
-
- try {
- client.doGet(url + "?noTrace=true").connect();
- fail("Exception expected");
- } catch (RestCallException e) {
- checkErrorResponse(debug, e, SC_FORBIDDEN, "Access denied by guard");
- }
-
- client.closeQuietly();
- }
-
- //====================================================================================================
- // Overlapping guards
- //====================================================================================================
- @Test
- public void testOverlappingGuards2() throws Exception {
- RestClient client = new TestRestClient().setHeader("Accept", "text/plain");
- String r;
- String url = URL + "/testOverlappingGuards2";
- try {
- client.doGet(url + "?noTrace=true").connect();
- fail("Exception expected");
- } catch (RestCallException e) {
- checkErrorResponse(debug, e, SC_FORBIDDEN, "Access denied by guard");
- }
-
- try {
- client.doGet(url + "?t1=1&noTrace=true").connect();
- fail("Exception expected");
- } catch (RestCallException e) {
- checkErrorResponse(debug, e, SC_FORBIDDEN, "Access denied by guard");
- }
-
- try {
- client.doGet(url + "?t2=2&noTrace=true").connect();
- fail("Exception expected");
- } catch (RestCallException e) {
- checkErrorResponse(debug, e, SC_FORBIDDEN, "Access denied by guard");
- }
-
- r = client.doGet(url + "?t1=1&t2=2").getResponseAsString();
- assertEquals("test2_doGet", r);
-
- client.closeQuietly();
- }
-
- //====================================================================================================
- // Overlapping matchers
- //====================================================================================================
- @Test
- public void testOverlappingMatchers1() throws Exception {
- RestClient client = new TestRestClient().setHeader("Accept", "text/plain");
- String r;
- String url = URL + "/testOverlappingMatchers1";
-
- r = client.doGet(url + "?t1=1").getResponseAsString();
- assertEquals("test3a", r);
-
- r = client.doGet(url + "?t2=2").getResponseAsString();
- assertEquals("test3b", r);
-
- r = client.doGet(url).getResponseAsString();
- assertEquals("test3c", r);
-
- client.closeQuietly();
- }
-
- //====================================================================================================
- // Overlapping matchers
- //====================================================================================================
- @Test
- public void testOverlappingMatchers2() throws Exception {
- RestClient client = new TestRestClient().setHeader("Accept", "text/plain");
- String r;
- String url = URL + "/testOverlappingMatchers2";
-
- r = client.doGet(url + "?t1=1").getResponseAsString();
- assertEquals("test4b", r);
-
- r = client.doGet(url + "?t2=2").getResponseAsString();
- assertEquals("test4b", r);
-
- r = client.doGet(url + "?t1=1&t2=2").getResponseAsString();
- assertEquals("test4b", r);
-
- r = client.doGet(url + "?tx=x").getResponseAsString();
- assertEquals("test4a", r);
-
- client.closeQuietly();
- }
-
- //====================================================================================================
- // Overlapping URL patterns
- //====================================================================================================
- @Test
- public void testOverlappingUrlPatterns() throws Exception {
- RestClient client = new TestRestClient().setHeader("Accept", "text/plain");
- String r;
- String url = URL + "/testOverlappingUrlPatterns";
-
- // [/test5] = [test5a]
- // [/test5/*] = [test5b] -- Cannot get called.
- // [/test5/foo] = [test5c]
- // [/test5/foo/*] = [test5d]
- // [/test5/{id}] = [test5e]
- // [/test5/{id}/*] = [test5f]
- // [/test5/{id}/foo] = [test5g]
- // [/test5/{id}/foo/*] = [test5h]
-
- r = client.doGet(url).getResponseAsString();
- assertEquals("test5a", r);
-
- r = client.doGet(url + "/foo").getResponseAsString();
- assertEquals("test5c", r);
-
- r = client.doGet(url + "/foo/x").getResponseAsString();
- assertEquals("test5d", r);
-
- r = client.doGet(url + "/x").getResponseAsString();
- assertEquals("test5e", r);
-
- r = client.doGet(url + "/x/x").getResponseAsString();
- assertEquals("test5f", r);
-
- r = client.doGet(url + "/x/foo").getResponseAsString();
- assertEquals("test5g", r);
-
- r = client.doGet(url + "/x/foo/x").getResponseAsString();
- assertEquals("test5h", r);
-
- client.closeQuietly();
- }
-}
[35/44] incubator-juneau git commit: Rename CT_* testcases.
Posted by ja...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestPathsTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestPathsTest.java b/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestPathsTest.java
new file mode 100755
index 0000000..01f0eef
--- /dev/null
+++ b/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestPathsTest.java
@@ -0,0 +1,1368 @@
+/***************************************************************************************************************************
+ * 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.juneau.server;
+
+import static org.junit.Assert.*;
+
+import org.apache.juneau.*;
+import org.apache.juneau.client.*;
+import org.apache.juneau.json.*;
+import org.junit.*;
+
+public class TestPathsTest {
+
+ private static String URL = "/testPaths";
+
+ //====================================================================================================
+ // Basic tests
+ //====================================================================================================
+ @Test
+ public void testBasic() throws Exception {
+ RestClient client = new TestRestClient(JsonSerializer.DEFAULT, JsonParser.DEFAULT);
+ ObjectMap r;
+ String url;
+
+ // [/test/testPaths]
+ // {
+ // pathInfo:null,
+ // pathInfoUndecoded:null,
+ // pathInfoParts:[],
+ // pathRemainder:null,
+ // pathRemainderUndecoded:null,
+ // requestURI:'/jazz/juneau/test/testPaths',
+ // requestParentURI:'/jazz/juneau/test',
+ // requestURL:'https://localhost:9443/jazz/juneau/test/testPaths',
+ // servletPath:'/juneau/test/testPaths',
+ // relativeServletURI:'/jazz/juneau/test/testPaths',
+ // pathRemainder2:null
+ // }
+ url = URL;
+ r = client.doGet(url).getResponse(ObjectMap.class);
+ assertNull(r.getString("pathInfo"));
+ assertNull(r.getString("pathInfoUndecoded"));
+ assertEquals("[]", r.getObjectList("pathInfoParts").toString());
+ assertNull(r.getString("pathRemainder"));
+ assertNull(r.getString("pathRemainderUndecoded"));
+ assertNull(r.getString("pathRemainder2"));
+ assertTrue(r.getString("requestURI").endsWith("/testPaths"));
+ assertTrue(r.getString("requestParentURI").endsWith("/"));
+ assertTrue(r.getString("requestURL").endsWith("/testPaths"));
+ assertTrue(r.getString("servletPath").endsWith("/testPaths"));
+ assertTrue(r.getString("servletURI").endsWith("/testPaths"));
+ assertTrue(r.getString("relativeServletURI").endsWith("/testPaths"));
+ assertEquals(1, (int)r.getInt("method"));
+
+
+ // [/test/testPaths/]
+ // {
+ // pathInfo: '/',
+ // pathInfoUndecoded: '/',
+ // pathInfoParts: [
+ // ],
+ // pathRemainder: '',
+ // pathRemainderUndecoded: '',
+ // requestURI: '/jazz/juneau/test/testPaths/',
+ // requestParentURI: '/jazz/juneau/test',
+ // requestURL: 'https://localhost:9443/jazz/juneau/test/testPaths/',
+ // servletPath: '/juneau/test/testPaths',
+ // relativeServletURI: '/jazz/juneau/test/testPaths',
+ // pathRemainder2: ''
+ // }
+ url = URL + '/';
+ r = client.doGet(url).getResponse(ObjectMap.class);
+ assertEquals("/", r.getString("pathInfo"));
+ assertEquals("/", r.getString("pathInfoUndecoded"));
+ assertEquals("[]", r.getObjectList("pathInfoParts").toString());
+ assertEquals("", r.getString("pathRemainder"));
+ assertEquals("", r.getString("pathRemainderUndecoded"));
+ assertEquals("", r.getString("pathRemainder2"));
+ assertTrue(r.getString("requestURI").endsWith("/testPaths/"));
+ assertTrue(r.getString("requestParentURI").endsWith("/"));
+ assertTrue(r.getString("requestURL").endsWith("/testPaths/"));
+ assertTrue(r.getString("servletPath").endsWith("/testPaths"));
+ assertTrue(r.getString("servletURI").endsWith("/testPaths"));
+ assertTrue(r.getString("relativeServletURI").endsWith("/testPaths"));
+ assertEquals(1, (int)r.getInt("method"));
+
+ // [/test/testPaths//]
+ // {
+ // pathInfo: '//',
+ // pathInfoParts: [''],
+ // pathRemainder: '/',
+ // requestURI: '/jazz/juneau/test/testPaths//',
+ // requestParentURI: '/jazz/juneau/test',
+ // requestURL: 'https://localhost:9443/jazz/juneau/test/testPaths//',
+ // servletPath: '/juneau/test/testPaths',
+ // relativeServletURI: '/jazz/juneau/test/testPaths',
+ // pathRemainder2: '/'
+ // }
+ url = URL + "//";
+ r = client.doGet(url).getResponse(ObjectMap.class);
+ assertEquals("//", r.getString("pathInfo"));
+ assertEquals("['']", r.getObjectList("pathInfoParts").toString());
+ assertEquals("/", r.getString("pathRemainder"));
+ assertEquals("/", r.getString("pathRemainder2"));
+ assertTrue(r.getString("requestURI").endsWith("/testPaths//"));
+ assertTrue(r.getString("requestParentURI").endsWith("/"));
+ assertTrue(r.getString("requestURL").endsWith("/testPaths//"));
+ assertTrue(r.getString("servletPath").endsWith("/testPaths"));
+ assertTrue(r.getString("servletURI").endsWith("/testPaths"));
+ assertTrue(r.getString("relativeServletURI").endsWith("/testPaths"));
+ assertEquals(1, (int)r.getInt("method"));
+
+ // [/test/testPaths///]
+ // {
+ // pathInfo: '///',
+ // pathInfoParts: ['',''],
+ // pathRemainder: '//',
+ // requestURI: '/jazz/juneau/test/testPaths///',
+ // requestParentURI: '/jazz/juneau/test',
+ // requestURL: 'https://localhost:9443/jazz/juneau/test/testPaths///',
+ // servletPath: '/juneau/test/testPaths',
+ // relativeServletURI: '/jazz/juneau/test/testPaths',
+ // pathRemainder2: '//'
+ // }
+ url = URL + "///";
+ r = client.doGet(url).getResponse(ObjectMap.class);
+ assertEquals("///", r.getString("pathInfo"));
+ assertEquals("['','']", r.getObjectList("pathInfoParts").toString());
+ assertEquals("//", r.getString("pathRemainder"));
+ assertEquals("//", r.getString("pathRemainder2"));
+ assertTrue(r.getString("requestURI").endsWith("/testPaths///"));
+ assertTrue(r.getString("requestParentURI").endsWith("/"));
+ assertTrue(r.getString("requestURL").endsWith("/testPaths///"));
+ assertTrue(r.getString("servletPath").endsWith("/testPaths"));
+ assertTrue(r.getString("servletURI").endsWith("/testPaths"));
+ assertTrue(r.getString("relativeServletURI").endsWith("/testPaths"));
+ assertEquals(1, (int)r.getInt("method"));
+
+ // [/test/testPaths/foo/bar]
+ // {
+ // pathInfo: '/foo/bar',
+ // pathInfoParts: [
+ // 'foo',
+ // 'bar'
+ // ],
+ // pathRemainder: 'foo/bar',
+ // requestURI: '/jazz/juneau/test/testPaths/foo/bar',
+ // requestParentURI: '/jazz/juneau/test/testPaths/foo',
+ // requestURL: 'https://localhost:9443/jazz/juneau/test/testPaths/foo/bar',
+ // servletPath: '/juneau/test/testPaths',
+ // relativeServletURI: '/jazz/juneau/test/testPaths',
+ // pathRemainder2: 'foo/bar'
+ // }
+ url = URL + "/foo/bar";
+ r = client.doGet(url).getResponse(ObjectMap.class);
+ assertEquals("/foo/bar", r.getString("pathInfo"));
+ assertEquals("['foo','bar']", r.getObjectList("pathInfoParts").toString());
+ assertEquals("foo/bar", r.getString("pathRemainder"));
+ assertEquals("foo/bar", r.getString("pathRemainder2"));
+ assertTrue(r.getString("requestURI").endsWith("/testPaths/foo/bar"));
+ assertTrue(r.getString("requestParentURI").endsWith("/testPaths/foo"));
+ assertTrue(r.getString("requestURL").endsWith("/testPaths/foo/bar"));
+ assertTrue(r.getString("servletPath").endsWith("/testPaths"));
+ assertTrue(r.getString("servletURI").endsWith("/testPaths"));
+ assertTrue(r.getString("relativeServletURI").endsWith("/testPaths"));
+ assertEquals(1, (int)r.getInt("method"));
+
+ // [/test/testPaths/foo/bar/]
+ // {
+ // pathInfo: '/foo/bar/',
+ // pathInfoParts: [
+ // 'foo',
+ // 'bar'
+ // ],
+ // pathRemainder: 'foo/bar/',
+ // requestURI: '/jazz/juneau/test/testPaths/foo/bar/',
+ // requestParentURI: '/jazz/juneau/test/testPaths/foo',
+ // requestURL: 'https://localhost:9443/jazz/juneau/test/testPaths/foo/bar/',
+ // servletPath: '/juneau/test/testPaths',
+ // relativeServletURI: '/jazz/juneau/test/testPaths',
+ // pathRemainder2: 'foo/bar/'
+ // }
+ url = URL + "/foo/bar/";
+ r = client.doGet(url).getResponse(ObjectMap.class);
+ assertEquals("/foo/bar/", r.getString("pathInfo"));
+ assertEquals("['foo','bar']", r.getObjectList("pathInfoParts").toString());
+ assertEquals("foo/bar/", r.getString("pathRemainder"));
+ assertEquals("foo/bar/", r.getString("pathRemainder2"));
+ assertTrue(r.getString("requestURI").endsWith("/testPaths/foo/bar/"));
+ assertTrue(r.getString("requestParentURI").endsWith("/testPaths/foo"));
+ assertTrue(r.getString("requestURL").endsWith("/testPaths/foo/bar/"));
+ assertTrue(r.getString("servletPath").endsWith("/testPaths"));
+ assertTrue(r.getString("servletURI").endsWith("/testPaths"));
+ assertTrue(r.getString("relativeServletURI").endsWith("/testPaths"));
+ assertEquals(1, (int)r.getInt("method"));
+
+ // [/test/testPaths//foo//bar//]
+ // {
+ // pathInfo: '//foo//bar//',
+ // pathInfoParts: [
+ // '',
+ // 'foo',
+ // '',
+ // 'bar',
+ // ''
+ // ],
+ // pathRemainder: '/foo//bar//',
+ // requestURI: '/jazz/juneau/test/testPaths//foo//bar//',
+ // requestParentURI: '/jazz/juneau/test/testPaths//foo',
+ // requestURL: 'https://localhost:9443/jazz/juneau/test/testPaths//foo//bar//',
+ // servletPath: '/juneau/test/testPaths',
+ // relativeServletURI: '/jazz/juneau/test/testPaths',
+ // pathRemainder2: '/foo//bar//'
+ // }
+ url = URL + "//foo//bar//";
+ r = client.doGet(url).getResponse(ObjectMap.class);
+ assertEquals("//foo//bar//", r.getString("pathInfo"));
+ assertEquals("['','foo','','bar','']", r.getObjectList("pathInfoParts").toString());
+ assertEquals("/foo//bar//", r.getString("pathRemainder"));
+ assertEquals("/foo//bar//", r.getString("pathRemainder2"));
+ assertTrue(r.getString("requestURI").endsWith("/testPaths//foo//bar//"));
+ assertTrue(r.getString("requestParentURI").endsWith("/testPaths//foo/"));
+ assertTrue(r.getString("requestURL").endsWith("/testPaths//foo//bar//"));
+ assertTrue(r.getString("servletPath").endsWith("/testPaths"));
+ assertTrue(r.getString("servletURI").endsWith("/testPaths"));
+ assertTrue(r.getString("relativeServletURI").endsWith("/testPaths"));
+ assertEquals(1, (int)r.getInt("method"));
+
+ // [/test/testPaths/foo%2Fbar]
+ // {
+ // pathInfo: '/foo//bar',
+ // pathInfoUndecoded: '/foo%2F%2Fbar',
+ // pathInfoParts: [
+ // 'foo//bar'
+ // ],
+ // pathRemainder: 'foo//bar',
+ // pathRemainderUndecoded: 'foo%2F%2Fbar',
+ // requestURI: '/jazz/juneau/test/testPaths/foo%2F%2Fbar',
+ // requestParentURI: '/jazz/juneau/test/testPaths',
+ // requestURL: 'https://localhost:9443/jazz/juneau/test/testPaths/foo%2F%2Fbar',
+ // servletPath: '/juneau/test/testPaths',
+ // servletURI: 'https://localhost:9443/jazz/juneau/test/testPaths',
+ // servletParentURI: 'https://localhost:9443/jazz/juneau/test',
+ // relativeServletURI: '/jazz/juneau/test/testPaths',
+ // pathRemainder2: 'foo//bar',
+ // method: 1
+ // }
+ url = URL + "/foo%2F%2Fbar";
+ r = client.doGet(url).getResponse(ObjectMap.class);
+ assertEquals("/foo//bar", r.getString("pathInfo"));
+ assertEquals("/foo%2F%2Fbar", r.getString("pathInfoUndecoded"));
+ assertEquals("['foo//bar']", r.getObjectList("pathInfoParts").toString());
+ assertEquals("foo//bar", r.getString("pathRemainder"));
+ assertEquals("foo%2F%2Fbar", r.getString("pathRemainderUndecoded"));
+ assertEquals("foo//bar", r.getString("pathRemainder2"));
+ assertTrue(r.getString("requestURI").endsWith("/testPaths/foo%2F%2Fbar"));
+ assertTrue(r.getString("requestParentURI").endsWith("/testPaths"));
+ assertTrue(r.getString("requestURL").endsWith("/testPaths/foo%2F%2Fbar"));
+ assertTrue(r.getString("servletPath").endsWith("/testPaths"));
+ assertTrue(r.getString("servletURI").endsWith("/testPaths"));
+ assertTrue(r.getString("relativeServletURI").endsWith("/testPaths"));
+ assertEquals(1, (int)r.getInt("method"));
+
+ // [/test/testPaths//foo%2Fbar//]
+ // {
+ // pathInfo: '//foo//bar//',
+ // pathInfoUndecoded: '//foo%2F%2Fbar//',
+ // pathInfoParts: [
+ // '',
+ // 'foo//bar',
+ // ''
+ // ],
+ // pathRemainder: '/foo//bar//',
+ // pathRemainderUndecoded: '/foo%2F%2Fbar//',
+ // requestURI: '/jazz/juneau/test/testPaths//foo%2F%2Fbar//',
+ // requestParentURI: '/jazz/juneau/test/testPaths/',
+ // requestURL: 'https://localhost:9443/jazz/juneau/test/testPaths//foo%2F%2Fbar//',
+ // servletPath: '/juneau/test/testPaths',
+ // servletURI: 'https://localhost:9443/jazz/juneau/test/testPaths',
+ // servletParentURI: 'https://localhost:9443/jazz/juneau/test',
+ // relativeServletURI: '/jazz/juneau/test/testPaths',
+ // pathRemainder2: '/foo//bar//',
+ // method: 1
+ // }
+ url = URL + "//foo%2F%2Fbar//";
+ r = client.doGet(url).getResponse(ObjectMap.class);
+ assertEquals("//foo//bar//", r.getString("pathInfo"));
+ assertEquals("//foo%2F%2Fbar//", r.getString("pathInfoUndecoded"));
+ assertEquals("['','foo//bar','']", r.getObjectList("pathInfoParts").toString());
+ assertEquals("/foo//bar//", r.getString("pathRemainder"));
+ assertEquals("/foo%2F%2Fbar//", r.getString("pathRemainderUndecoded"));
+ assertEquals("/foo//bar//", r.getString("pathRemainder2"));
+ assertTrue(r.getString("requestURI").endsWith("/testPaths//foo%2F%2Fbar//"));
+ assertTrue(r.getString("requestParentURI").endsWith("/testPaths/"));
+ assertTrue(r.getString("requestURL").endsWith("/testPaths//foo%2F%2Fbar//"));
+ assertTrue(r.getString("servletPath").endsWith("/testPaths"));
+ assertTrue(r.getString("servletURI").endsWith("/testPaths"));
+ assertTrue(r.getString("relativeServletURI").endsWith("/testPaths"));
+ assertEquals(1, (int)r.getInt("method"));
+
+ // [/test/testPaths/test2]
+ // {
+ // pathInfo: '/test2',
+ // pathInfoParts: [
+ // 'test2'
+ // ],
+ // pathRemainder: null,
+ // requestURI: '/jazz/juneau/test/testPaths/test2',
+ // requestParentURI: '/jazz/juneau/test/testPaths',
+ // requestURL: 'https://localhost:9443/jazz/juneau/test/testPaths/test2',
+ // servletPath: '/juneau/test/testPaths',
+ // servletURI: 'https://localhost:9443/jazz/juneau/test/testPaths',
+ // servletParentURI: 'https://localhost:9443/jazz/juneau/test',
+ // relativeServletURI: '/jazz/juneau/test/testPaths',
+ // pathRemainder2: null,
+ // method: 2
+ // }
+ url = URL + "/test2";
+ r = client.doGet(url).getResponse(ObjectMap.class);
+ assertEquals("/test2", r.getString("pathInfo"));
+ assertEquals("['test2']", r.getObjectList("pathInfoParts").toString());
+ assertNull(r.getString("pathRemainder"));
+ assertNull(r.getString("pathRemainder2"));
+ assertTrue(r.getString("requestURI").endsWith("/testPaths/test2"));
+ assertTrue(r.getString("requestParentURI").endsWith("/testPaths"));
+ assertTrue(r.getString("requestURL").endsWith("/testPaths/test2"));
+ assertTrue(r.getString("servletPath").endsWith("/testPaths"));
+ assertTrue(r.getString("servletURI").endsWith("/testPaths"));
+ assertTrue(r.getString("relativeServletURI").endsWith("/testPaths"));
+ assertEquals(2, (int)r.getInt("method"));
+
+
+ // [/test/testPaths/test2/]
+ // {
+ // pathInfo: '/test2/',
+ // pathInfoParts: [
+ // 'test2'
+ // ],
+ // pathRemainder: '',
+ // requestURI: '/jazz/juneau/test/testPaths/test2/',
+ // requestParentURI: '/jazz/juneau/test/testPaths',
+ // requestURL: 'https://localhost:9443/jazz/juneau/test/testPaths/test2/',
+ // servletPath: '/juneau/test/testPaths',
+ // servletURI: 'https://localhost:9443/jazz/juneau/test/testPaths',
+ // servletParentURI: 'https://localhost:9443/jazz/juneau/test',
+ // relativeServletURI: '/jazz/juneau/test/testPaths',
+ // pathRemainder2: '',
+ // method: 2
+ // }
+ url = URL + "/test2/";
+ r = client.doGet(url).getResponse(ObjectMap.class);
+ assertEquals("/test2/", r.getString("pathInfo"));
+ assertEquals("['test2']", r.getObjectList("pathInfoParts").toString());
+ assertEquals("", r.getString("pathRemainder"));
+ assertEquals("", r.getString("pathRemainder2"));
+ assertTrue(r.getString("requestURI").endsWith("/testPaths/test2/"));
+ assertTrue(r.getString("requestParentURI").endsWith("/testPaths"));
+ assertTrue(r.getString("requestURL").endsWith("/testPaths/test2/"));
+ assertTrue(r.getString("servletPath").endsWith("/testPaths"));
+ assertTrue(r.getString("servletURI").endsWith("/testPaths"));
+ assertTrue(r.getString("relativeServletURI").endsWith("/testPaths"));
+ assertEquals(2, (int)r.getInt("method"));
+
+ // [/test/testPaths/test2//]
+ // {
+ // pathInfo: '/test2//',
+ // pathInfoParts: [
+ // 'test2',
+ // ''
+ // ],
+ // pathRemainder: '/',
+ // requestURI: '/jazz/juneau/test/testPaths/test2//',
+ // requestParentURI: '/jazz/juneau/test/testPaths',
+ // requestURL: 'https://localhost:9443/jazz/juneau/test/testPaths/test2//',
+ // servletPath: '/juneau/test/testPaths',
+ // servletURI: 'https://localhost:9443/jazz/juneau/test/testPaths',
+ // servletParentURI: 'https://localhost:9443/jazz/juneau/test',
+ // relativeServletURI: '/jazz/juneau/test/testPaths',
+ // pathRemainder2: '/',
+ // method: 2
+ // }
+ url = URL + "/test2//";
+ r = client.doGet(url).getResponse(ObjectMap.class);
+ assertEquals("/test2//", r.getString("pathInfo"));
+ assertEquals("['test2','']", r.getObjectList("pathInfoParts").toString());
+ assertEquals("/", r.getString("pathRemainder"));
+ assertEquals("/", r.getString("pathRemainder2"));
+ assertTrue(r.getString("requestURI").endsWith("/testPaths/test2//"));
+ assertTrue(r.getString("requestParentURI").endsWith("/testPaths"));
+ assertTrue(r.getString("requestURL").endsWith("/testPaths/test2//"));
+ assertTrue(r.getString("servletPath").endsWith("/testPaths"));
+ assertTrue(r.getString("servletURI").endsWith("/testPaths"));
+ assertTrue(r.getString("relativeServletURI").endsWith("/testPaths"));
+ assertEquals(2, (int)r.getInt("method"));
+
+ // [/test/testPaths/test2///]
+ // {
+ // pathInfo: '/test2///',
+ // pathInfoParts: [
+ // 'test2',
+ // '',
+ // ''
+ // ],
+ // pathRemainder: '//',
+ // requestURI: '/jazz/juneau/test/testPaths/test2///',
+ // requestParentURI: '/jazz/juneau/test/testPaths',
+ // requestURL: 'https://localhost:9443/jazz/juneau/test/testPaths/test2///',
+ // servletPath: '/juneau/test/testPaths',
+ // servletURI: 'https://localhost:9443/jazz/juneau/test/testPaths',
+ // servletParentURI: 'https://localhost:9443/jazz/juneau/test',
+ // relativeServletURI: '/jazz/juneau/test/testPaths',
+ // pathRemainder2: '//',
+ // method: 2
+ // }
+ url = URL + "/test2///";
+ r = client.doGet(url).getResponse(ObjectMap.class);
+ assertEquals("/test2///", r.getString("pathInfo"));
+ assertEquals("['test2','','']", r.getObjectList("pathInfoParts").toString());
+ assertEquals("//", r.getString("pathRemainder"));
+ assertEquals("//", r.getString("pathRemainder2"));
+ assertTrue(r.getString("requestURI").endsWith("/testPaths/test2///"));
+ assertTrue(r.getString("requestParentURI").endsWith("/testPaths"));
+ assertTrue(r.getString("requestURL").endsWith("/testPaths/test2///"));
+ assertTrue(r.getString("servletPath").endsWith("/testPaths"));
+ assertTrue(r.getString("servletURI").endsWith("/testPaths"));
+ assertTrue(r.getString("relativeServletURI").endsWith("/testPaths"));
+ assertEquals(2, (int)r.getInt("method"));
+
+ // [/test/testPaths/test2/foo/bar]
+ // {
+ // pathInfo: '/test2/foo/bar',
+ // pathInfoParts: [
+ // 'test2',
+ // 'foo',
+ // 'bar'
+ // ],
+ // pathRemainder: 'foo/bar',
+ // requestURI: '/jazz/juneau/test/testPaths/test2/foo/bar',
+ // requestParentURI: '/jazz/juneau/test/testPaths/test2/foo',
+ // requestURL: 'https://localhost:9443/jazz/juneau/test/testPaths/test2/foo/bar',
+ // servletPath: '/juneau/test/testPaths',
+ // servletURI: 'https://localhost:9443/jazz/juneau/test/testPaths',
+ // servletParentURI: 'https://localhost:9443/jazz/juneau/test',
+ // relativeServletURI: '/jazz/juneau/test/testPaths',
+ // pathRemainder2: 'foo/bar',
+ // method: 2
+ // }
+ url = URL + "/test2/foo/bar";
+ r = client.doGet(url).getResponse(ObjectMap.class);
+ assertEquals("/test2/foo/bar", r.getString("pathInfo"));
+ assertEquals("['test2','foo','bar']", r.getObjectList("pathInfoParts").toString());
+ assertEquals("foo/bar", r.getString("pathRemainder"));
+ assertEquals("foo/bar", r.getString("pathRemainder2"));
+ assertTrue(r.getString("requestURI").endsWith("/testPaths/test2/foo/bar"));
+ assertTrue(r.getString("requestParentURI").endsWith("/testPaths/test2/foo"));
+ assertTrue(r.getString("requestURL").endsWith("/testPaths/test2/foo/bar"));
+ assertTrue(r.getString("servletPath").endsWith("/testPaths"));
+ assertTrue(r.getString("servletURI").endsWith("/testPaths"));
+ assertTrue(r.getString("relativeServletURI").endsWith("/testPaths"));
+ assertEquals(2, (int)r.getInt("method"));
+
+ // [/test/testPaths/test2/foo/bar/]
+ // {
+ // pathInfo: '/test2/foo/bar/',
+ // pathInfoParts: [
+ // 'test2',
+ // 'foo',
+ // 'bar'
+ // ],
+ // pathRemainder: 'foo/bar/',
+ // requestURI: '/jazz/juneau/test/testPaths/test2/foo/bar/',
+ // requestParentURI: '/jazz/juneau/test/testPaths/test2/foo',
+ // requestURL: 'https://localhost:9443/jazz/juneau/test/testPaths/test2/foo/bar/',
+ // servletPath: '/juneau/test/testPaths',
+ // servletURI: 'https://localhost:9443/jazz/juneau/test/testPaths',
+ // servletParentURI: 'https://localhost:9443/jazz/juneau/test',
+ // relativeServletURI: '/jazz/juneau/test/testPaths',
+ // pathRemainder2: 'foo/bar/',
+ // method: 2
+ // }
+ url = URL + "/test2/foo/bar/";
+ r = client.doGet(url).getResponse(ObjectMap.class);
+ assertEquals("/test2/foo/bar/", r.getString("pathInfo"));
+ assertEquals("['test2','foo','bar']", r.getObjectList("pathInfoParts").toString());
+ assertEquals("foo/bar/", r.getString("pathRemainder"));
+ assertEquals("foo/bar/", r.getString("pathRemainder2"));
+ assertTrue(r.getString("requestURI").endsWith("/testPaths/test2/foo/bar/"));
+ assertTrue(r.getString("requestParentURI").endsWith("/testPaths/test2/foo"));
+ assertTrue(r.getString("requestURL").endsWith("/testPaths/test2/foo/bar/"));
+ assertTrue(r.getString("servletPath").endsWith("/testPaths"));
+ assertTrue(r.getString("servletURI").endsWith("/testPaths"));
+ assertTrue(r.getString("relativeServletURI").endsWith("/testPaths"));
+ assertEquals(2, (int)r.getInt("method"));
+
+ // [/test/testPaths/test2//foo//bar//]
+ // {
+ // pathInfo: '/test2//foo//bar//',
+ // pathInfoParts: [
+ // 'test2',
+ // '',
+ // 'foo',
+ // '',
+ // 'bar',
+ // ''
+ // ],
+ // pathRemainder: '/foo//bar//',
+ // requestURI: '/jazz/juneau/test/testPaths/test2//foo//bar//',
+ // requestParentURI: '/jazz/juneau/test/testPaths/test2//foo/',
+ // requestURL: 'https://localhost:9443/jazz/juneau/test/testPaths/test2//foo//bar//',
+ // servletPath: '/juneau/test/testPaths',
+ // servletURI: 'https://localhost:9443/jazz/juneau/test/testPaths',
+ // servletParentURI: 'https://localhost:9443/jazz/juneau/test',
+ // relativeServletURI: '/jazz/juneau/test/testPaths',
+ // pathRemainder2: '/foo//bar//',
+ // method: 2
+ // }
+ url = URL + "/test2//foo//bar//";
+ r = client.doGet(url).getResponse(ObjectMap.class);
+ assertEquals("/test2//foo//bar//", r.getString("pathInfo"));
+ assertEquals("['test2','','foo','','bar','']", r.getObjectList("pathInfoParts").toString());
+ assertEquals("/foo//bar//", r.getString("pathRemainder"));
+ assertEquals("/foo//bar//", r.getString("pathRemainder2"));
+ assertTrue(r.getString("requestURI").endsWith("/testPaths/test2//foo//bar//"));
+ assertTrue(r.getString("requestParentURI").endsWith("/testPaths/test2//foo/"));
+ assertTrue(r.getString("requestURL").endsWith("/testPaths/test2//foo//bar//"));
+ assertTrue(r.getString("servletPath").endsWith("/testPaths"));
+ assertTrue(r.getString("servletURI").endsWith("/testPaths"));
+ assertTrue(r.getString("relativeServletURI").endsWith("/testPaths"));
+ assertEquals(2, (int)r.getInt("method"));
+
+ // [/test/testPaths/test2/foo%2Fbar]
+ // {
+ // pathInfo: '/test2/foo//bar',
+ // pathInfoUndecoded: '/test2/foo%2F%2Fbar',
+ // pathInfoParts: [
+ // 'test2',
+ // 'foo//bar'
+ // ],
+ // pathRemainder: 'foo//bar',
+ // pathRemainderUndecoded: 'foo%2F%2Fbar',
+ // requestURI: '/jazz/juneau/test/testPaths/test2/foo%2F%2Fbar',
+ // requestParentURI: '/jazz/juneau/test/testPaths/test2',
+ // requestURL: 'https://localhost:9443/jazz/juneau/test/testPaths/test2/foo%2F%2Fbar',
+ // servletPath: '/juneau/test/testPaths',
+ // servletURI: 'https://localhost:9443/jazz/juneau/test/testPaths',
+ // servletParentURI: 'https://localhost:9443/jazz/juneau/test',
+ // relativeServletURI: '/jazz/juneau/test/testPaths',
+ // pathRemainder2: 'foo//bar',
+ // method: 2
+ // }
+ url = URL + "/test2/foo%2F%2Fbar";
+ r = client.doGet(url).getResponse(ObjectMap.class);
+ assertEquals("/test2/foo//bar", r.getString("pathInfo"));
+ assertEquals("/test2/foo%2F%2Fbar", r.getString("pathInfoUndecoded"));
+ assertEquals("['test2','foo//bar']", r.getObjectList("pathInfoParts").toString());
+ assertEquals("foo//bar", r.getString("pathRemainder"));
+ assertEquals("foo%2F%2Fbar", r.getString("pathRemainderUndecoded"));
+ assertEquals("foo//bar", r.getString("pathRemainder2"));
+ assertTrue(r.getString("requestURI").endsWith("/testPaths/test2/foo%2F%2Fbar"));
+ assertTrue(r.getString("requestParentURI").endsWith("/testPaths/test2"));
+ assertTrue(r.getString("requestURL").endsWith("/testPaths/test2/foo%2F%2Fbar"));
+ assertTrue(r.getString("servletPath").endsWith("/testPaths"));
+ assertTrue(r.getString("servletURI").endsWith("/testPaths"));
+ assertTrue(r.getString("relativeServletURI").endsWith("/testPaths"));
+ assertEquals(2, (int)r.getInt("method"));
+
+ // [/test/testPaths/test2//foo%2Fbar//]
+ // {
+ // pathInfo: '/test2//foo//bar//',
+ // pathInfoUndecoded: '/test2//foo%2F%2Fbar//',
+ // pathInfoParts: [
+ // 'test2',
+ // '',
+ // 'foo//bar',
+ // ''
+ // ],
+ // pathRemainder: '/foo//bar//',
+ // pathRemainderUndecoded: '/foo%2F%2Fbar//',
+ // requestURI: '/jazz/juneau/test/testPaths/test2//foo%2F%2Fbar//',
+ // requestParentURI: '/jazz/juneau/test/testPaths/test2/',
+ // requestURL: 'https://localhost:9443/jazz/juneau/test/testPaths/test2//foo%2F%2Fbar//',
+ // servletPath: '/juneau/test/testPaths',
+ // servletURI: 'https://localhost:9443/jazz/juneau/test/testPaths',
+ // servletParentURI: 'https://localhost:9443/jazz/juneau/test',
+ // relativeServletURI: '/jazz/juneau/test/testPaths',
+ // pathRemainder2: '/foo//bar//',
+ // method: 2
+ // }
+ url = URL + "/test2//foo%2F%2Fbar//";
+ r = client.doGet(url).getResponse(ObjectMap.class);
+ assertEquals("/test2//foo//bar//", r.getString("pathInfo"));
+ assertEquals("/test2//foo%2F%2Fbar//", r.getString("pathInfoUndecoded"));
+ assertEquals("['test2','','foo//bar','']", r.getObjectList("pathInfoParts").toString());
+ assertEquals("/foo//bar//", r.getString("pathRemainder"));
+ assertEquals("/foo%2F%2Fbar//", r.getString("pathRemainderUndecoded"));
+ assertEquals("/foo//bar//", r.getString("pathRemainder2"));
+ assertTrue(r.getString("requestURI").endsWith("/testPaths/test2//foo%2F%2Fbar//"));
+ assertTrue(r.getString("requestParentURI").endsWith("/testPaths/test2/"));
+ assertTrue(r.getString("requestURL").endsWith("/testPaths/test2//foo%2F%2Fbar//"));
+ assertTrue(r.getString("servletPath").endsWith("/testPaths"));
+ assertTrue(r.getString("servletURI").endsWith("/testPaths"));
+ assertTrue(r.getString("relativeServletURI").endsWith("/testPaths"));
+ assertEquals(2, (int)r.getInt("method"));
+
+ // [/test/testPaths/a]
+ // {
+ // pathInfo: null,
+ // pathInfoParts: [
+ // ],
+ // pathRemainder: null,
+ // requestURI: '/jazz/juneau/test/testPaths/a',
+ // requestParentURI: '/jazz/juneau/test/testPaths',
+ // requestURL: 'https://localhost:9443/jazz/juneau/test/testPaths/a',
+ // servletPath: '/juneau/test/testPaths/a',
+ // servletURI: 'https://localhost:9443/jazz/juneau/test/testPaths/a',
+ // servletParentURI: 'https://localhost:9443/jazz/juneau/test/testPaths',
+ // relativeServletURI: '/jazz/juneau/test/testPaths/a',
+ // pathRemainder2: null,
+ // method: 3
+ // }
+ url = URL + "/a";
+ r = client.doGet(url).getResponse(ObjectMap.class);
+ assertNull(r.getString("pathInfo"));
+ assertEquals("[]", r.getObjectList("pathInfoParts").toString());
+ assertNull(r.getString("pathRemainder"));
+ assertNull(r.getString("pathRemainder2"));
+ assertTrue(r.getString("requestURI").endsWith("/testPaths/a"));
+ assertTrue(r.getString("requestParentURI").endsWith("/testPaths"));
+ assertTrue(r.getString("requestURL").endsWith("/testPaths/a"));
+ assertTrue(r.getString("servletPath").endsWith("/testPaths/a"));
+ assertTrue(r.getString("servletURI").endsWith("/testPaths/a"));
+ assertTrue(r.getString("servletParentURI").endsWith("/testPaths"));
+ assertTrue(r.getString("relativeServletURI").endsWith("/testPaths/a"));
+ assertEquals(3, (int)r.getInt("method"));
+
+ // [/test/testPaths/a/]
+ // {
+ // pathInfo: '/',
+ // pathInfoParts: [
+ // ],
+ // pathRemainder: '',
+ // requestURI: '/jazz/juneau/test/testPaths/a/',
+ // requestParentURI: '/jazz/juneau/test/testPaths',
+ // requestURL: 'https://localhost:9443/jazz/juneau/test/testPaths/a/',
+ // servletPath: '/juneau/test/testPaths/a',
+ // servletURI: 'https://localhost:9443/jazz/juneau/test/testPaths/a',
+ // servletParentURI: 'https://localhost:9443/jazz/juneau/test/testPaths',
+ // relativeServletURI: '/jazz/juneau/test/testPaths/a',
+ // pathRemainder2: '',
+ // method: 3
+ // }
+ url = URL + "/a/";
+ r = client.doGet(url).getResponse(ObjectMap.class);
+ assertEquals("/", r.getString("pathInfo"));
+ assertEquals("[]", r.getObjectList("pathInfoParts").toString());
+ assertEquals("", r.getString("pathRemainder"));
+ assertEquals("", r.getString("pathRemainder2"));
+ assertTrue(r.getString("requestURI").endsWith("/testPaths/a/"));
+ assertTrue(r.getString("requestParentURI").endsWith("/testPaths"));
+ assertTrue(r.getString("requestURL").endsWith("/testPaths/a/"));
+ assertTrue(r.getString("servletPath").endsWith("/testPaths/a"));
+ assertTrue(r.getString("servletURI").endsWith("/testPaths/a"));
+ assertTrue(r.getString("servletParentURI").endsWith("/testPaths"));
+ assertTrue(r.getString("relativeServletURI").endsWith("/testPaths/a"));
+ assertEquals(3, (int)r.getInt("method"));
+
+ // [/test/testPaths/a//]
+ // {
+ // pathInfo: '//',
+ // pathInfoParts: [
+ // ''
+ // ],
+ // pathRemainder: '/',
+ // requestURI: '/jazz/juneau/test/testPaths/a//',
+ // requestParentURI: '/jazz/juneau/test/testPaths',
+ // requestURL: 'https://localhost:9443/jazz/juneau/test/testPaths/a//',
+ // servletPath: '/juneau/test/testPaths/a',
+ // servletURI: 'https://localhost:9443/jazz/juneau/test/testPaths/a',
+ // servletParentURI: 'https://localhost:9443/jazz/juneau/test/testPaths',
+ // relativeServletURI: '/jazz/juneau/test/testPaths/a',
+ // pathRemainder2: '/',
+ // method: 3
+ // }
+ url = URL + "/a//";
+ r = client.doGet(url).getResponse(ObjectMap.class);
+ assertEquals("//", r.getString("pathInfo"));
+ assertEquals("['']", r.getObjectList("pathInfoParts").toString());
+ assertEquals("/", r.getString("pathRemainder"));
+ assertEquals("/", r.getString("pathRemainder2"));
+ assertTrue(r.getString("requestURI").endsWith("/testPaths/a//"));
+ assertTrue(r.getString("requestParentURI").endsWith("/testPaths"));
+ assertTrue(r.getString("requestURL").endsWith("/testPaths/a//"));
+ assertTrue(r.getString("servletPath").endsWith("/testPaths/a"));
+ assertTrue(r.getString("servletURI").endsWith("/testPaths/a"));
+ assertTrue(r.getString("servletParentURI").endsWith("/testPaths"));
+ assertTrue(r.getString("relativeServletURI").endsWith("/testPaths/a"));
+ assertEquals(3, (int)r.getInt("method"));
+
+ // [/test/testPaths/a///]
+ // {
+ // pathInfo: '///',
+ // pathInfoParts: [
+ // '',
+ // ''
+ // ],
+ // pathRemainder: '//',
+ // requestURI: '/jazz/juneau/test/testPaths/a///',
+ // requestParentURI: '/jazz/juneau/test/testPaths',
+ // requestURL: 'https://localhost:9443/jazz/juneau/test/testPaths/a///',
+ // servletPath: '/juneau/test/testPaths/a',
+ // servletURI: 'https://localhost:9443/jazz/juneau/test/testPaths/a',
+ // servletParentURI: 'https://localhost:9443/jazz/juneau/test/testPaths',
+ // relativeServletURI: '/jazz/juneau/test/testPaths/a',
+ // pathRemainder2: '//',
+ // method: 3
+ // }
+ url = URL + "/a///";
+ r = client.doGet(url).getResponse(ObjectMap.class);
+ assertEquals("///", r.getString("pathInfo"));
+ assertEquals("['','']", r.getObjectList("pathInfoParts").toString());
+ assertEquals("//", r.getString("pathRemainder"));
+ assertEquals("//", r.getString("pathRemainder2"));
+ assertTrue(r.getString("requestURI").endsWith("/testPaths/a///"));
+ assertTrue(r.getString("requestParentURI").endsWith("/testPaths"));
+ assertTrue(r.getString("requestURL").endsWith("/testPaths/a///"));
+ assertTrue(r.getString("servletPath").endsWith("/testPaths/a"));
+ assertTrue(r.getString("servletURI").endsWith("/testPaths/a"));
+ assertTrue(r.getString("servletParentURI").endsWith("/testPaths"));
+ assertTrue(r.getString("relativeServletURI").endsWith("/testPaths/a"));
+ assertEquals(3, (int)r.getInt("method"));
+
+ // [/test/testPaths/a/foo/bar]
+ // {
+ // pathInfo: '/foo/bar',
+ // pathInfoParts: [
+ // 'foo',
+ // 'bar'
+ // ],
+ // pathRemainder: 'foo/bar',
+ // requestURI: '/jazz/juneau/test/testPaths/a/foo/bar',
+ // requestParentURI: '/jazz/juneau/test/testPaths/a/foo',
+ // requestURL: 'https://localhost:9443/jazz/juneau/test/testPaths/a/foo/bar',
+ // servletPath: '/juneau/test/testPaths/a',
+ // servletURI: 'https://localhost:9443/jazz/juneau/test/testPaths/a',
+ // servletParentURI: 'https://localhost:9443/jazz/juneau/test/testPaths',
+ // relativeServletURI: '/jazz/juneau/test/testPaths/a',
+ // pathRemainder2: 'foo/bar',
+ // method: 3
+ // }
+ url = URL + "/a/foo/bar";
+ r = client.doGet(url).getResponse(ObjectMap.class);
+ assertEquals("/foo/bar", r.getString("pathInfo"));
+ assertEquals("['foo','bar']", r.getObjectList("pathInfoParts").toString());
+ assertEquals("foo/bar", r.getString("pathRemainder"));
+ assertEquals("foo/bar", r.getString("pathRemainder2"));
+ assertTrue(r.getString("requestURI").endsWith("/testPaths/a/foo/bar"));
+ assertTrue(r.getString("requestParentURI").endsWith("/testPaths/a/foo"));
+ assertTrue(r.getString("requestURL").endsWith("/testPaths/a/foo/bar"));
+ assertTrue(r.getString("servletPath").endsWith("/testPaths/a"));
+ assertTrue(r.getString("servletURI").endsWith("/testPaths/a"));
+ assertTrue(r.getString("servletParentURI").endsWith("/testPaths"));
+ assertTrue(r.getString("relativeServletURI").endsWith("/testPaths/a"));
+ assertEquals(3, (int)r.getInt("method"));
+
+ // [/test/testPaths/a/foo/bar/]
+ // {
+ // pathInfo: '/foo/bar/',
+ // pathInfoParts: [
+ // 'foo',
+ // 'bar'
+ // ],
+ // pathRemainder: 'foo/bar/',
+ // requestURI: '/jazz/juneau/test/testPaths/a/foo/bar/',
+ // requestParentURI: '/jazz/juneau/test/testPaths/a/foo',
+ // requestURL: 'https://localhost:9443/jazz/juneau/test/testPaths/a/foo/bar/',
+ // servletPath: '/juneau/test/testPaths/a',
+ // servletURI: 'https://localhost:9443/jazz/juneau/test/testPaths/a',
+ // servletParentURI: 'https://localhost:9443/jazz/juneau/test/testPaths',
+ // relativeServletURI: '/jazz/juneau/test/testPaths/a',
+ // pathRemainder2: 'foo/bar/',
+ // method: 3
+ // }
+ url = URL + "/a/foo/bar/";
+ r = client.doGet(url).getResponse(ObjectMap.class);
+ assertEquals("/foo/bar/", r.getString("pathInfo"));
+ assertEquals("['foo','bar']", r.getObjectList("pathInfoParts").toString());
+ assertEquals("foo/bar/", r.getString("pathRemainder"));
+ assertEquals("foo/bar/", r.getString("pathRemainder2"));
+ assertTrue(r.getString("requestURI").endsWith("/testPaths/a/foo/bar/"));
+ assertTrue(r.getString("requestParentURI").endsWith("/testPaths/a/foo"));
+ assertTrue(r.getString("requestURL").endsWith("/testPaths/a/foo/bar/"));
+ assertTrue(r.getString("servletPath").endsWith("/testPaths/a"));
+ assertTrue(r.getString("servletURI").endsWith("/testPaths/a"));
+ assertTrue(r.getString("servletParentURI").endsWith("/testPaths"));
+ assertTrue(r.getString("relativeServletURI").endsWith("/testPaths/a"));
+ assertEquals(3, (int)r.getInt("method"));
+
+ // [/test/testPaths/a//foo//bar//]
+ // {
+ // pathInfo: '//foo//bar//',
+ // pathInfoParts: [
+ // '',
+ // 'foo',
+ // '',
+ // 'bar',
+ // ''
+ // ],
+ // pathRemainder: '/foo//bar//',
+ // requestURI: '/jazz/juneau/test/testPaths/a//foo//bar//',
+ // requestParentURI: '/jazz/juneau/test/testPaths/a//foo/',
+ // requestURL: 'https://localhost:9443/jazz/juneau/test/testPaths/a//foo//bar//',
+ // servletPath: '/juneau/test/testPaths/a',
+ // servletURI: 'https://localhost:9443/jazz/juneau/test/testPaths/a',
+ // servletParentURI: 'https://localhost:9443/jazz/juneau/test/testPaths',
+ // relativeServletURI: '/jazz/juneau/test/testPaths/a',
+ // pathRemainder2: '/foo//bar//',
+ // method: 3
+ // }
+ url = URL + "/a//foo//bar//";
+ r = client.doGet(url).getResponse(ObjectMap.class);
+ assertEquals("//foo//bar//", r.getString("pathInfo"));
+ assertEquals("['','foo','','bar','']", r.getObjectList("pathInfoParts").toString());
+ assertEquals("/foo//bar//", r.getString("pathRemainder"));
+ assertEquals("/foo//bar//", r.getString("pathRemainder2"));
+ assertTrue(r.getString("requestURI").endsWith("/testPaths/a//foo//bar//"));
+ assertTrue(r.getString("requestParentURI").endsWith("/testPaths/a//foo/"));
+ assertTrue(r.getString("requestURL").endsWith("/testPaths/a//foo//bar//"));
+ assertTrue(r.getString("servletPath").endsWith("/testPaths/a"));
+ assertTrue(r.getString("servletURI").endsWith("/testPaths/a"));
+ assertTrue(r.getString("servletParentURI").endsWith("/testPaths"));
+ assertTrue(r.getString("relativeServletURI").endsWith("/testPaths/a"));
+ assertEquals(3, (int)r.getInt("method"));
+
+ // [/test/testPaths/a/foo%2Fbar]
+ // {
+ // pathInfo: '/foo//bar',
+ // pathInfoUndecoded: '/foo%2F%2Fbar',
+ // pathInfoParts: [
+ // 'foo//bar'
+ // ],
+ // pathRemainder: 'foo//bar',
+ // pathRemainderUndecoded: 'foo%2F%2Fbar',
+ // requestURI: '/jazz/juneau/test/testPaths/a/foo%2F%2Fbar',
+ // requestParentURI: '/jazz/juneau/test/testPaths/a',
+ // requestURL: 'https://localhost:9443/jazz/juneau/test/testPaths/a/foo%2F%2Fbar',
+ // servletPath: '/juneau/test/testPaths/a',
+ // servletURI: 'https://localhost:9443/jazz/juneau/test/testPaths/a',
+ // servletParentURI: 'https://localhost:9443/jazz/juneau/test/testPaths',
+ // relativeServletURI: '/jazz/juneau/test/testPaths/a',
+ // pathRemainder2: 'foo//bar',
+ // method: 3
+ // }
+ url = URL + "/a/foo%2F%2Fbar";
+ r = client.doGet(url).getResponse(ObjectMap.class);
+ assertEquals("/foo//bar", r.getString("pathInfo"));
+ assertEquals("/foo%2F%2Fbar", r.getString("pathInfoUndecoded"));
+ assertEquals("['foo//bar']", r.getObjectList("pathInfoParts").toString());
+ assertEquals("foo//bar", r.getString("pathRemainder"));
+ assertEquals("foo%2F%2Fbar", r.getString("pathRemainderUndecoded"));
+ assertEquals("foo//bar", r.getString("pathRemainder2"));
+ assertTrue(r.getString("requestURI").endsWith("/testPaths/a/foo%2F%2Fbar"));
+ assertTrue(r.getString("requestParentURI").endsWith("/testPaths/a"));
+ assertTrue(r.getString("requestURL").endsWith("/testPaths/a/foo%2F%2Fbar"));
+ assertTrue(r.getString("servletPath").endsWith("/testPaths/a"));
+ assertTrue(r.getString("servletURI").endsWith("/testPaths/a"));
+ assertTrue(r.getString("servletParentURI").endsWith("/testPaths"));
+ assertTrue(r.getString("relativeServletURI").endsWith("/testPaths/a"));
+ assertEquals(3, (int)r.getInt("method"));
+
+ // [/test/testPaths/a//foo%2Fbar//]
+ // {
+ // pathInfo: '//foo//bar//',
+ // pathInfoUndecoded: '//foo%2F%2Fbar//',
+ // pathInfoParts: [
+ // '',
+ // 'foo//bar',
+ // ''
+ // ],
+ // pathRemainder: '/foo//bar//',
+ // pathRemainderUndecoded: '/foo%2F%2Fbar//',
+ // requestURI: '/jazz/juneau/test/testPaths/a//foo%2F%2Fbar//',
+ // requestParentURI: '/jazz/juneau/test/testPaths/a/',
+ // requestURL: 'https://localhost:9443/jazz/juneau/test/testPaths/a//foo%2F%2Fbar//',
+ // servletPath: '/juneau/test/testPaths/a',
+ // servletURI: 'https://localhost:9443/jazz/juneau/test/testPaths/a',
+ // servletParentURI: 'https://localhost:9443/jazz/juneau/test/testPaths',
+ // relativeServletURI: '/jazz/juneau/test/testPaths/a',
+ // pathRemainder2: '/foo//bar//',
+ // method: 3
+ // }
+ url = URL + "/a//foo%2F%2Fbar//";
+ r = client.doGet(url).getResponse(ObjectMap.class);
+ assertEquals("//foo//bar//", r.getString("pathInfo"));
+ assertEquals("//foo%2F%2Fbar//", r.getString("pathInfoUndecoded"));
+ assertEquals("['','foo//bar','']", r.getObjectList("pathInfoParts").toString());
+ assertEquals("/foo//bar//", r.getString("pathRemainder"));
+ assertEquals("/foo%2F%2Fbar//", r.getString("pathRemainderUndecoded"));
+ assertEquals("/foo//bar//", r.getString("pathRemainder2"));
+ assertTrue(r.getString("requestURI").endsWith("/testPaths/a//foo%2F%2Fbar//"));
+ assertTrue(r.getString("requestParentURI").endsWith("/testPaths/a/"));
+ assertTrue(r.getString("requestURL").endsWith("/testPaths/a//foo%2F%2Fbar//"));
+ assertTrue(r.getString("servletPath").endsWith("/testPaths/a"));
+ assertTrue(r.getString("servletURI").endsWith("/testPaths/a"));
+ assertTrue(r.getString("servletParentURI").endsWith("/testPaths"));
+ assertTrue(r.getString("relativeServletURI").endsWith("/testPaths/a"));
+ assertEquals(3, (int)r.getInt("method"));
+
+
+ // [/test/testPaths/a/test2]
+ // {
+ // pathInfo: '/test2',
+ // pathInfoParts: [
+ // 'test2'
+ // ],
+ // pathRemainder: null,
+ // requestURI: '/jazz/juneau/test/testPaths/a/test2',
+ // requestParentURI: '/jazz/juneau/test/testPaths/a',
+ // requestURL: 'https://localhost:9443/jazz/juneau/test/testPaths/a/test2',
+ // servletPath: '/juneau/test/testPaths/a',
+ // servletURI: 'https://localhost:9443/jazz/juneau/test/testPaths/a',
+ // servletParentURI: 'https://localhost:9443/jazz/juneau/test/testPaths',
+ // relativeServletURI: '/jazz/juneau/test/testPaths/a',
+ // pathRemainder2: null,
+ // method: 4
+ // }
+ url = URL + "/a/test2";
+ r = client.doGet(url).getResponse(ObjectMap.class);
+ assertEquals("/test2", r.getString("pathInfo"));
+ assertEquals("['test2']", r.getObjectList("pathInfoParts").toString());
+ assertNull(r.getString("pathRemainder"));
+ assertNull(r.getString("pathRemainder2"));
+ assertTrue(r.getString("requestURI").endsWith("/testPaths/a/test2"));
+ assertTrue(r.getString("requestParentURI").endsWith("/testPaths/a"));
+ assertTrue(r.getString("requestURL").endsWith("/testPaths/a/test2"));
+ assertTrue(r.getString("servletPath").endsWith("/testPaths/a"));
+ assertTrue(r.getString("servletURI").endsWith("/testPaths/a"));
+ assertTrue(r.getString("servletParentURI").endsWith("/testPaths"));
+ assertTrue(r.getString("relativeServletURI").endsWith("/testPaths/a"));
+ assertEquals(4, (int)r.getInt("method"));
+
+ // [/test/testPaths/a/test2/]
+ // {
+ // pathInfo: '/test2/',
+ // pathInfoParts: [
+ // 'test2'
+ // ],
+ // pathRemainder: '',
+ // requestURI: '/jazz/juneau/test/testPaths/a/test2/',
+ // requestParentURI: '/jazz/juneau/test/testPaths/a',
+ // requestURL: 'https://localhost:9443/jazz/juneau/test/testPaths/a/test2/',
+ // servletPath: '/juneau/test/testPaths/a',
+ // servletURI: 'https://localhost:9443/jazz/juneau/test/testPaths/a',
+ // servletParentURI: 'https://localhost:9443/jazz/juneau/test/testPaths',
+ // relativeServletURI: '/jazz/juneau/test/testPaths/a',
+ // pathRemainder2: '',
+ // method: 4
+ // }
+ url = URL + "/a/test2/";
+ r = client.doGet(url).getResponse(ObjectMap.class);
+ assertEquals("/test2/", r.getString("pathInfo"));
+ assertEquals("['test2']", r.getObjectList("pathInfoParts").toString());
+ assertEquals("", r.getString("pathRemainder"));
+ assertEquals("", r.getString("pathRemainder2"));
+ assertTrue(r.getString("requestURI").endsWith("/testPaths/a/test2/"));
+ assertTrue(r.getString("requestParentURI").endsWith("/testPaths/a"));
+ assertTrue(r.getString("requestURL").endsWith("/testPaths/a/test2/"));
+ assertTrue(r.getString("servletPath").endsWith("/testPaths/a"));
+ assertTrue(r.getString("servletURI").endsWith("/testPaths/a"));
+ assertTrue(r.getString("servletParentURI").endsWith("/testPaths"));
+ assertTrue(r.getString("relativeServletURI").endsWith("/testPaths/a"));
+ assertEquals(4, (int)r.getInt("method"));
+
+ // [/test/testPaths/a/test2//]
+ // {
+ // pathInfo: '/test2//',
+ // pathInfoParts: [
+ // 'test2',
+ // ''
+ // ],
+ // pathRemainder: '/',
+ // requestURI: '/jazz/juneau/test/testPaths/a/test2//',
+ // requestParentURI: '/jazz/juneau/test/testPaths/a',
+ // requestURL: 'https://localhost:9443/jazz/juneau/test/testPaths/a/test2//',
+ // servletPath: '/juneau/test/testPaths/a',
+ // servletURI: 'https://localhost:9443/jazz/juneau/test/testPaths/a',
+ // servletParentURI: 'https://localhost:9443/jazz/juneau/test/testPaths',
+ // relativeServletURI: '/jazz/juneau/test/testPaths/a',
+ // pathRemainder2: '/',
+ // method: 4
+ // }
+ url = URL + "/a/test2//";
+ r = client.doGet(url).getResponse(ObjectMap.class);
+ assertEquals("/test2//", r.getString("pathInfo"));
+ assertEquals("['test2','']", r.getObjectList("pathInfoParts").toString());
+ assertEquals("/", r.getString("pathRemainder"));
+ assertEquals("/", r.getString("pathRemainder2"));
+ assertTrue(r.getString("requestURI").endsWith("/testPaths/a/test2//"));
+ assertTrue(r.getString("requestParentURI").endsWith("/testPaths/a"));
+ assertTrue(r.getString("requestURL").endsWith("/testPaths/a/test2//"));
+ assertTrue(r.getString("servletPath").endsWith("/testPaths/a"));
+ assertTrue(r.getString("servletURI").endsWith("/testPaths/a"));
+ assertTrue(r.getString("servletParentURI").endsWith("/testPaths"));
+ assertTrue(r.getString("relativeServletURI").endsWith("/testPaths/a"));
+ assertEquals(4, (int)r.getInt("method"));
+
+ // [/test/testPaths/a/test2///]
+ // {
+ // pathInfo: '/test2///',
+ // pathInfoParts: [
+ // 'test2',
+ // '',
+ // ''
+ // ],
+ // pathRemainder: '//',
+ // requestURI: '/jazz/juneau/test/testPaths/a/test2///',
+ // requestParentURI: '/jazz/juneau/test/testPaths/a',
+ // requestURL: 'https://localhost:9443/jazz/juneau/test/testPaths/a/test2///',
+ // servletPath: '/juneau/test/testPaths/a',
+ // servletURI: 'https://localhost:9443/jazz/juneau/test/testPaths/a',
+ // servletParentURI: 'https://localhost:9443/jazz/juneau/test/testPaths',
+ // relativeServletURI: '/jazz/juneau/test/testPaths/a',
+ // pathRemainder2: '//',
+ // method: 4
+ // }
+ url = URL + "/a/test2///";
+ r = client.doGet(url).getResponse(ObjectMap.class);
+ assertEquals("/test2///", r.getString("pathInfo"));
+ assertEquals("['test2','','']", r.getObjectList("pathInfoParts").toString());
+ assertEquals("//", r.getString("pathRemainder"));
+ assertEquals("//", r.getString("pathRemainder2"));
+ assertTrue(r.getString("requestURI").endsWith("/testPaths/a/test2///"));
+ assertTrue(r.getString("requestParentURI").endsWith("/testPaths/a"));
+ assertTrue(r.getString("requestURL").endsWith("/testPaths/a/test2///"));
+ assertTrue(r.getString("servletPath").endsWith("/testPaths/a"));
+ assertTrue(r.getString("servletURI").endsWith("/testPaths/a"));
+ assertTrue(r.getString("servletParentURI").endsWith("/testPaths"));
+ assertTrue(r.getString("relativeServletURI").endsWith("/testPaths/a"));
+ assertEquals(4, (int)r.getInt("method"));
+
+ // [/test/testPaths/a/test2/foo/bar]
+ // {
+ // pathInfo: '/test2/foo/bar',
+ // pathInfoParts: [
+ // 'test2',
+ // 'foo',
+ // 'bar'
+ // ],
+ // pathRemainder: 'foo/bar',
+ // requestURI: '/jazz/juneau/test/testPaths/a/test2/foo/bar',
+ // requestParentURI: '/jazz/juneau/test/testPaths/a/test2/foo',
+ // requestURL: 'https://localhost:9443/jazz/juneau/test/testPaths/a/test2/foo/bar',
+ // servletPath: '/juneau/test/testPaths/a',
+ // servletURI: 'https://localhost:9443/jazz/juneau/test/testPaths/a',
+ // servletParentURI: 'https://localhost:9443/jazz/juneau/test/testPaths',
+ // relativeServletURI: '/jazz/juneau/test/testPaths/a',
+ // pathRemainder2: 'foo/bar',
+ // method: 4
+ // }
+ url = URL + "/a/test2/foo/bar";
+ r = client.doGet(url).getResponse(ObjectMap.class);
+ assertEquals("/test2/foo/bar", r.getString("pathInfo"));
+ assertEquals("['test2','foo','bar']", r.getObjectList("pathInfoParts").toString());
+ assertEquals("foo/bar", r.getString("pathRemainder"));
+ assertEquals("foo/bar", r.getString("pathRemainder2"));
+ assertTrue(r.getString("requestURI").endsWith("/testPaths/a/test2/foo/bar"));
+ assertTrue(r.getString("requestParentURI").endsWith("/testPaths/a/test2/foo"));
+ assertTrue(r.getString("requestURL").endsWith("/testPaths/a/test2/foo/bar"));
+ assertTrue(r.getString("servletPath").endsWith("/testPaths/a"));
+ assertTrue(r.getString("servletURI").endsWith("/testPaths/a"));
+ assertTrue(r.getString("servletParentURI").endsWith("/testPaths"));
+ assertTrue(r.getString("relativeServletURI").endsWith("/testPaths/a"));
+ assertEquals(4, (int)r.getInt("method"));
+
+ // [/test/testPaths/a/test2/foo/bar/]
+ // {
+ // pathInfo: '/test2/foo/bar/',
+ // pathInfoParts: [
+ // 'test2',
+ // 'foo',
+ // 'bar'
+ // ],
+ // pathRemainder: 'foo/bar/',
+ // requestURI: '/jazz/juneau/test/testPaths/a/test2/foo/bar/',
+ // requestParentURI: '/jazz/juneau/test/testPaths/a/test2/foo',
+ // requestURL: 'https://localhost:9443/jazz/juneau/test/testPaths/a/test2/foo/bar/',
+ // servletPath: '/juneau/test/testPaths/a',
+ // servletURI: 'https://localhost:9443/jazz/juneau/test/testPaths/a',
+ // servletParentURI: 'https://localhost:9443/jazz/juneau/test/testPaths',
+ // relativeServletURI: '/jazz/juneau/test/testPaths/a',
+ // pathRemainder2: 'foo/bar/',
+ // method: 4
+ // }
+ url = URL + "/a/test2/foo/bar/";
+ r = client.doGet(url).getResponse(ObjectMap.class);
+ assertEquals("/test2/foo/bar/", r.getString("pathInfo"));
+ assertEquals("['test2','foo','bar']", r.getObjectList("pathInfoParts").toString());
+ assertEquals("foo/bar/", r.getString("pathRemainder"));
+ assertEquals("foo/bar/", r.getString("pathRemainder2"));
+ assertTrue(r.getString("requestURI").endsWith("/testPaths/a/test2/foo/bar/"));
+ assertTrue(r.getString("requestParentURI").endsWith("/testPaths/a/test2/foo"));
+ assertTrue(r.getString("requestURL").endsWith("/testPaths/a/test2/foo/bar/"));
+ assertTrue(r.getString("servletPath").endsWith("/testPaths/a"));
+ assertTrue(r.getString("servletURI").endsWith("/testPaths/a"));
+ assertTrue(r.getString("servletParentURI").endsWith("/testPaths"));
+ assertTrue(r.getString("relativeServletURI").endsWith("/testPaths/a"));
+ assertEquals(4, (int)r.getInt("method"));
+
+ // [/test/testPaths/a/test2//foo//bar//]
+ // {
+ // pathInfo: '/test2//foo//bar//',
+ // pathInfoParts: [
+ // 'test2',
+ // '',
+ // 'foo',
+ // '',
+ // 'bar',
+ // ''
+ // ],
+ // pathRemainder: '/foo//bar//',
+ // requestURI: '/jazz/juneau/test/testPaths/a/test2//foo//bar//',
+ // requestParentURI: '/jazz/juneau/test/testPaths/a/test2//foo/',
+ // requestURL: 'https://localhost:9443/jazz/juneau/test/testPaths/a/test2//foo//bar//',
+ // servletPath: '/juneau/test/testPaths/a',
+ // servletURI: 'https://localhost:9443/jazz/juneau/test/testPaths/a',
+ // servletParentURI: 'https://localhost:9443/jazz/juneau/test/testPaths',
+ // relativeServletURI: '/jazz/juneau/test/testPaths/a',
+ // pathRemainder2: '/foo//bar//',
+ // method: 4
+ // }
+ url = URL + "/a/test2//foo//bar//";
+ r = client.doGet(url).getResponse(ObjectMap.class);
+ assertEquals("/test2//foo//bar//", r.getString("pathInfo"));
+ assertEquals("['test2','','foo','','bar','']", r.getObjectList("pathInfoParts").toString());
+ assertEquals("/foo//bar//", r.getString("pathRemainder"));
+ assertEquals("/foo//bar//", r.getString("pathRemainder2"));
+ assertTrue(r.getString("requestURI").endsWith("/testPaths/a/test2//foo//bar//"));
+ assertTrue(r.getString("requestParentURI").endsWith("/testPaths/a/test2//foo/"));
+ assertTrue(r.getString("requestURL").endsWith("/testPaths/a/test2//foo//bar//"));
+ assertTrue(r.getString("servletPath").endsWith("/testPaths/a"));
+ assertTrue(r.getString("servletURI").endsWith("/testPaths/a"));
+ assertTrue(r.getString("servletParentURI").endsWith("/testPaths"));
+ assertTrue(r.getString("relativeServletURI").endsWith("/testPaths/a"));
+ assertEquals(4, (int)r.getInt("method"));
+
+ // [/test/testPaths/a/test2/foo%2Fbar]
+ // {
+ // pathInfo: '/test2/foo//bar',
+ // pathInfoUndecoded: '/test2/foo%2F%2Fbar',
+ // pathInfoParts: [
+ // 'test2',
+ // 'foo//bar'
+ // ],
+ // pathRemainder: 'foo//bar',
+ // pathRemainderUndecoded: 'foo%2F%2Fbar',
+ // requestURI: '/jazz/juneau/test/testPaths/a/test2/foo%2F%2Fbar',
+ // requestParentURI: '/jazz/juneau/test/testPaths/a/test2',
+ // requestURL: 'https://localhost:9443/jazz/juneau/test/testPaths/a/test2/foo%2F%2Fbar',
+ // servletPath: '/juneau/test/testPaths/a',
+ // servletURI: 'https://localhost:9443/jazz/juneau/test/testPaths/a',
+ // servletParentURI: 'https://localhost:9443/jazz/juneau/test/testPaths',
+ // relativeServletURI: '/jazz/juneau/test/testPaths/a',
+ // pathRemainder2: 'foo//bar',
+ // method: 4
+ // }
+ url = URL + "/a/test2/foo%2F%2Fbar";
+ r = client.doGet(url).getResponse(ObjectMap.class);
+ assertEquals("/test2/foo//bar", r.getString("pathInfo"));
+ assertEquals("/test2/foo%2F%2Fbar", r.getString("pathInfoUndecoded"));
+ assertEquals("['test2','foo//bar']", r.getObjectList("pathInfoParts").toString());
+ assertEquals("foo//bar", r.getString("pathRemainder"));
+ assertEquals("foo%2F%2Fbar", r.getString("pathRemainderUndecoded"));
+ assertEquals("foo//bar", r.getString("pathRemainder2"));
+ assertTrue(r.getString("requestURI").endsWith("/testPaths/a/test2/foo%2F%2Fbar"));
+ assertTrue(r.getString("requestParentURI").endsWith("/testPaths/a/test2"));
+ assertTrue(r.getString("requestURL").endsWith("/testPaths/a/test2/foo%2F%2Fbar"));
+ assertTrue(r.getString("servletPath").endsWith("/testPaths/a"));
+ assertTrue(r.getString("servletURI").endsWith("/testPaths/a"));
+ assertTrue(r.getString("servletParentURI").endsWith("/testPaths"));
+ assertTrue(r.getString("relativeServletURI").endsWith("/testPaths/a"));
+ assertEquals(4, (int)r.getInt("method"));
+
+ // [/test/testPaths/a/test2//foo%2Fbar//]
+ // {
+ // pathInfo: '/test2//foo//bar//',
+ // pathInfoUndecoded: '/test2//foo%2F%2Fbar//',
+ // pathInfoParts: [
+ // 'test2',
+ // '',
+ // 'foo//bar',
+ // ''
+ // ],
+ // pathRemainder: '/foo//bar//',
+ // pathRemainderUndecoded: '/foo%2F%2Fbar//',
+ // requestURI: '/jazz/juneau/test/testPaths/a/test2//foo%2F%2Fbar//',
+ // requestParentURI: '/jazz/juneau/test/testPaths/a/test2/',
+ // requestURL: 'https://localhost:9443/jazz/juneau/test/testPaths/a/test2//foo%2F%2Fbar//',
+ // servletPath: '/juneau/test/testPaths/a',
+ // servletURI: 'https://localhost:9443/jazz/juneau/test/testPaths/a',
+ // servletParentURI: 'https://localhost:9443/jazz/juneau/test/testPaths',
+ // relativeServletURI: '/jazz/juneau/test/testPaths/a',
+ // pathRemainder2: '/foo//bar//',
+ // method: 4
+ // }
+ url = URL + "/a/test2//foo%2F%2Fbar//";
+ r = client.doGet(url).getResponse(ObjectMap.class);
+ assertEquals("/test2//foo//bar//", r.getString("pathInfo"));
+ assertEquals("/test2//foo%2F%2Fbar//", r.getString("pathInfoUndecoded"));
+ assertEquals("['test2','','foo//bar','']", r.getObjectList("pathInfoParts").toString());
+ assertEquals("/foo//bar//", r.getString("pathRemainder"));
+ assertEquals("/foo%2F%2Fbar//", r.getString("pathRemainderUndecoded"));
+ assertEquals("/foo//bar//", r.getString("pathRemainder2"));
+ assertTrue(r.getString("requestURI").endsWith("/testPaths/a/test2//foo%2F%2Fbar//"));
+ assertTrue(r.getString("requestParentURI").endsWith("/testPaths/a/test2/"));
+ assertTrue(r.getString("requestURL").endsWith("/testPaths/a/test2//foo%2F%2Fbar//"));
+ assertTrue(r.getString("servletPath").endsWith("/testPaths/a"));
+ assertTrue(r.getString("servletURI").endsWith("/testPaths/a"));
+ assertTrue(r.getString("servletParentURI").endsWith("/testPaths"));
+ assertTrue(r.getString("relativeServletURI").endsWith("/testPaths/a"));
+ assertEquals(4, (int)r.getInt("method"));
+
+ //--------------------------------------------------------------------------------
+ // Spaces
+ //--------------------------------------------------------------------------------
+ url = URL + "/%20";
+ r = client.doGet(url).getResponse(ObjectMap.class);
+ assertEquals("/ ", r.getString("pathInfo"));
+ assertEquals("/%20", r.getString("pathInfoUndecoded"));
+ assertEquals("[' ']", r.getObjectList("pathInfoParts").toString());
+ assertEquals(" ", r.getString("pathRemainder"));
+ assertEquals("%20", r.getString("pathRemainderUndecoded"));
+ assertEquals(" ", r.getString("pathRemainder2"));
+ assertTrue(r.getString("requestURI").endsWith("/testPaths/%20"));
+ assertTrue(r.getString("requestParentURI").endsWith("/testPaths"));
+ assertTrue(r.getString("requestURL").endsWith("/testPaths/%20"));
+ assertTrue(r.getString("servletPath").endsWith("/testPaths"));
+ assertTrue(r.getString("servletURI").endsWith("/testPaths"));
+ assertTrue(r.getString("relativeServletURI").endsWith("/testPaths"));
+ assertEquals(1, (int)r.getInt("method"));
+
+ url = URL + "/test2/%20";
+ r = client.doGet(url).getResponse(ObjectMap.class);
+ assertEquals("/test2/ ", r.getString("pathInfo"));
+ assertEquals("/test2/%20", r.getString("pathInfoUndecoded"));
+ assertEquals("['test2',' ']", r.getObjectList("pathInfoParts").toString());
+ assertEquals(" ", r.getString("pathRemainder"));
+ assertEquals("%20", r.getString("pathRemainderUndecoded"));
+ assertEquals(" ", r.getString("pathRemainder2"));
+ assertTrue(r.getString("requestURI").endsWith("/testPaths/test2/%20"));
+ assertTrue(r.getString("requestParentURI").endsWith("/testPaths/test2"));
+ assertTrue(r.getString("requestURL").endsWith("/testPaths/test2/%20"));
+ assertTrue(r.getString("servletPath").endsWith("/testPaths"));
+ assertTrue(r.getString("servletURI").endsWith("/testPaths"));
+ assertTrue(r.getString("relativeServletURI").endsWith("/testPaths"));
+ assertEquals(2, (int)r.getInt("method"));
+
+ url = URL + "/a/%20";
+ r = client.doGet(url).getResponse(ObjectMap.class);
+ assertEquals("/ ", r.getString("pathInfo"));
+ assertEquals("/%20", r.getString("pathInfoUndecoded"));
+ assertEquals("[' ']", r.getObjectList("pathInfoParts").toString());
+ assertEquals(" ", r.getString("pathRemainder"));
+ assertEquals("%20", r.getString("pathRemainderUndecoded"));
+ assertEquals(" ", r.getString("pathRemainder2"));
+ assertTrue(r.getString("requestURI").endsWith("/testPaths/a/%20"));
+ assertTrue(r.getString("requestParentURI").endsWith("/testPaths/a"));
+ assertTrue(r.getString("requestURL").endsWith("/testPaths/a/%20"));
+ assertTrue(r.getString("servletPath").endsWith("/testPaths/a"));
+ assertTrue(r.getString("servletURI").endsWith("/testPaths/a"));
+ assertTrue(r.getString("servletParentURI").endsWith("/testPaths"));
+ assertTrue(r.getString("relativeServletURI").endsWith("/testPaths/a"));
+ assertEquals(3, (int)r.getInt("method"));
+
+ url = URL + "/a/test2/%20";
+ r = client.doGet(url).getResponse(ObjectMap.class);
+ assertEquals("/test2/ ", r.getString("pathInfo"));
+ assertEquals("/test2/%20", r.getString("pathInfoUndecoded"));
+ assertEquals("['test2',' ']", r.getObjectList("pathInfoParts").toString());
+ assertEquals(" ", r.getString("pathRemainder"));
+ assertEquals("%20", r.getString("pathRemainderUndecoded"));
+ assertEquals(" ", r.getString("pathRemainder2"));
+ assertTrue(r.getString("requestURI").endsWith("/testPaths/a/test2/%20"));
+ assertTrue(r.getString("requestParentURI").endsWith("/testPaths/a/test2"));
+ assertTrue(r.getString("requestURL").endsWith("/testPaths/a/test2/%20"));
+ assertTrue(r.getString("servletPath").endsWith("/testPaths/a"));
+ assertTrue(r.getString("servletURI").endsWith("/testPaths/a"));
+ assertTrue(r.getString("servletParentURI").endsWith("/testPaths"));
+ assertTrue(r.getString("relativeServletURI").endsWith("/testPaths/a"));
+ assertEquals(4, (int)r.getInt("method"));
+
+ url = URL + "/+";
+ r = client.doGet(url).getResponse(ObjectMap.class);
+ assertEquals("/ ", r.getString("pathInfo"));
+ assertEquals("/+", r.getString("pathInfoUndecoded"));
+ assertEquals("[' ']", r.getObjectList("pathInfoParts").toString());
+ assertEquals(" ", r.getString("pathRemainder"));
+ assertEquals("+", r.getString("pathRemainderUndecoded"));
+ assertEquals(" ", r.getString("pathRemainder2"));
+ assertTrue(r.getString("requestURI").endsWith("/testPaths/+"));
+ assertTrue(r.getString("requestParentURI").endsWith("/testPaths"));
+ assertTrue(r.getString("requestURL").endsWith("/testPaths/+"));
+ assertTrue(r.getString("servletPath").endsWith("/testPaths"));
+ assertTrue(r.getString("servletURI").endsWith("/testPaths"));
+ assertTrue(r.getString("relativeServletURI").endsWith("/testPaths"));
+ assertEquals(1, (int)r.getInt("method"));
+
+ url = URL + "/test2/+";
+ r = client.doGet(url).getResponse(ObjectMap.class);
+ assertEquals("/test2/ ", r.getString("pathInfo"));
+ assertEquals("/test2/+", r.getString("pathInfoUndecoded"));
+ assertEquals("['test2',' ']", r.getObjectList("pathInfoParts").toString());
+ assertEquals(" ", r.getString("pathRemainder"));
+ assertEquals("+", r.getString("pathRemainderUndecoded"));
+ assertEquals(" ", r.getString("pathRemainder2"));
+ assertTrue(r.getString("requestURI").endsWith("/testPaths/test2/+"));
+ assertTrue(r.getString("requestParentURI").endsWith("/testPaths/test2"));
+ assertTrue(r.getString("requestURL").endsWith("/testPaths/test2/+"));
+ assertTrue(r.getString("servletPath").endsWith("/testPaths"));
+ assertTrue(r.getString("servletURI").endsWith("/testPaths"));
+ assertTrue(r.getString("relativeServletURI").endsWith("/testPaths"));
+ assertEquals(2, (int)r.getInt("method"));
+
+ url = URL + "/a/+";
+ r = client.doGet(url).getResponse(ObjectMap.class);
+ assertEquals("/ ", r.getString("pathInfo"));
+ assertEquals("/+", r.getString("pathInfoUndecoded"));
+ assertEquals("[' ']", r.getObjectList("pathInfoParts").toString());
+ assertEquals(" ", r.getString("pathRemainder"));
+ assertEquals("+", r.getString("pathRemainderUndecoded"));
+ assertEquals(" ", r.getString("pathRemainder2"));
+ assertTrue(r.getString("requestURI").endsWith("/testPaths/a/+"));
+ assertTrue(r.getString("requestParentURI").endsWith("/testPaths/a"));
+ assertTrue(r.getString("requestURL").endsWith("/testPaths/a/+"));
+ assertTrue(r.getString("servletPath").endsWith("/testPaths/a"));
+ assertTrue(r.getString("servletURI").endsWith("/testPaths/a"));
+ assertTrue(r.getString("servletParentURI").endsWith("/testPaths"));
+ assertTrue(r.getString("relativeServletURI").endsWith("/testPaths/a"));
+ assertEquals(3, (int)r.getInt("method"));
+
+ url = URL + "/a/test2/+";
+ r = client.doGet(url).getResponse(ObjectMap.class);
+ assertEquals("/test2/ ", r.getString("pathInfo"));
+ assertEquals("/test2/+", r.getString("pathInfoUndecoded"));
+ assertEquals("['test2',' ']", r.getObjectList("pathInfoParts").toString());
+ assertEquals(" ", r.getString("pathRemainder"));
+ assertEquals("+", r.getString("pathRemainderUndecoded"));
+ assertEquals(" ", r.getString("pathRemainder2"));
+ assertTrue(r.getString("requestURI").endsWith("/testPaths/a/test2/+"));
+ assertTrue(r.getString("requestParentURI").endsWith("/testPaths/a/test2"));
+ assertTrue(r.getString("requestURL").endsWith("/testPaths/a/test2/+"));
+ assertTrue(r.getString("servletPath").endsWith("/testPaths/a"));
+ assertTrue(r.getString("servletURI").endsWith("/testPaths/a"));
+ assertTrue(r.getString("servletParentURI").endsWith("/testPaths"));
+ assertTrue(r.getString("relativeServletURI").endsWith("/testPaths/a"));
+ assertEquals(4, (int)r.getInt("method"));
+
+ client.closeQuietly();
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestPropertiesTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestPropertiesTest.java b/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestPropertiesTest.java
new file mode 100755
index 0000000..4ed0a7b
--- /dev/null
+++ b/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestPropertiesTest.java
@@ -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.juneau.server;
+
+import static org.junit.Assert.*;
+
+import org.apache.juneau.client.*;
+import org.apache.juneau.json.*;
+import org.junit.*;
+
+public class TestPropertiesTest {
+
+ private static String URL = "/testProperties";
+
+ //====================================================================================================
+ // Properties defined on method.
+ //====================================================================================================
+ @Test
+ public void testPropertiesDefinedOnMethod() throws Exception {
+ RestClient client = new TestRestClient(JsonSerializer.DEFAULT, JsonParser.DEFAULT);
+ String r = client.doGet(URL + "/testPropertiesDefinedOnMethod").getResponseAsString();
+ assertTrue(r.matches("A1=a1,A2=c,B1=b1,B2=c,C=c,R1a=.*/testProperties/testPropertiesDefinedOnMethod,R1b=.*/testProperties,R2=bar,R3=baz,R4=a1,R5=c,R6=c"));
+
+ client.closeQuietly();
+ }
+
+ //====================================================================================================
+ // Make sure attributes/parameters/headers are available through ctx.getProperties().
+ //====================================================================================================
+ @Test
+ public void testProperties() throws Exception {
+ RestClient client = new TestRestClient(JsonSerializer.DEFAULT, JsonParser.DEFAULT);
+ String r = client.doGet(URL + "/testProperties/a1?P=p1").setHeader("H", "h1").getResponseAsString();
+ assertEquals("A=a1,P=p1,H=h1", r);
+
+ client.closeQuietly();
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestRestClientTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestRestClientTest.java b/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestRestClientTest.java
new file mode 100755
index 0000000..ed53dbb
--- /dev/null
+++ b/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestRestClientTest.java
@@ -0,0 +1,199 @@
+/***************************************************************************************************************************
+ * 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.juneau.server;
+
+import static org.apache.juneau.server.TestUtils.*;
+import static org.junit.Assert.*;
+
+import java.util.*;
+import java.util.regex.*;
+
+import org.apache.http.entity.*;
+import org.apache.juneau.client.*;
+import org.apache.juneau.json.*;
+import org.junit.*;
+
+public class TestRestClientTest {
+
+ private static String URL = "/testRestClient";
+
+ //====================================================================================================
+ // successPattern()
+ //====================================================================================================
+ @Test
+ public void testSuccessPattern() throws Exception {
+ RestClient c = new TestRestClient(JsonSerializer.DEFAULT, JsonParser.DEFAULT);
+ String r;
+ int rc;
+
+ r = c.doPost(URL, new StringEntity("xxxSUCCESSxxx")).successPattern("SUCCESS").getResponseAsString();
+ assertEquals("xxxSUCCESSxxx", r);
+ rc = c.doPost(URL, new StringEntity("xxxSUCCESSxxx")).successPattern("SUCCESS").run();
+ assertEquals(200, rc);
+
+ try {
+ r = c.doPost(URL, new StringEntity("xxxFAILURExxx")).successPattern("SUCCESS").getResponseAsString();
+ fail();
+ } catch (RestCallException e) {
+ assertEquals("Success pattern not detected.", e.getLocalizedMessage());
+ }
+
+ c.closeQuietly();
+ }
+
+ //====================================================================================================
+ // failurePattern()
+ //====================================================================================================
+ @Test
+ public void testFailurePattern() throws Exception {
+ RestClient c = new TestRestClient(JsonSerializer.DEFAULT, JsonParser.DEFAULT);
+ String r;
+ int rc;
+
+ r = c.doPost(URL, new StringEntity("xxxSUCCESSxxx")).failurePattern("FAILURE").getResponseAsString();
+ assertEquals("xxxSUCCESSxxx", r);
+ rc = c.doPost(URL, new StringEntity("xxxSUCCESSxxx")).failurePattern("FAILURE").run();
+ assertEquals(200, rc);
+
+ try {
+ r = c.doPost(URL, new StringEntity("xxxFAILURExxx")).failurePattern("FAILURE").getResponseAsString();
+ fail();
+ } catch (RestCallException e) {
+ assertEquals("Failure pattern detected.", e.getLocalizedMessage());
+ }
+
+ try {
+ r = c.doPost(URL, new StringEntity("xxxERRORxxx")).failurePattern("FAILURE|ERROR").getResponseAsString();
+ fail();
+ } catch (RestCallException e) {
+ assertEquals("Failure pattern detected.", e.getLocalizedMessage());
+ }
+
+ c.closeQuietly();
+ }
+
+ //====================================================================================================
+ // captureResponse()/getCapturedResponse()
+ //====================================================================================================
+ @Test
+ public void testCaptureResponse() throws Exception {
+ RestClient c = new TestRestClient(JsonSerializer.DEFAULT, JsonParser.DEFAULT);
+ RestCall rc = c.doPost(URL, new StringEntity("xxx")).captureResponse();
+
+ try {
+ rc.getCapturedResponse();
+ fail();
+ } catch (IllegalStateException e) {
+ assertEquals("This method cannot be called until the response has been consumed.", e.getLocalizedMessage());
+ }
+ rc.run();
+ assertEquals("xxx", rc.getCapturedResponse());
+ assertEquals("xxx", rc.getCapturedResponse());
+
+ rc = c.doPost(URL, new StringEntity("xxx")).captureResponse();
+ assertEquals("xxx", rc.getResponseAsString());
+ assertEquals("xxx", rc.getCapturedResponse());
+ assertEquals("xxx", rc.getCapturedResponse());
+
+ try {
+ rc.getResponseAsString();
+ fail();
+ } catch (IllegalStateException e) {
+ assertEquals("Method cannot be called. Response has already been consumed.", e.getLocalizedMessage());
+ }
+
+ c.closeQuietly();
+ }
+
+ //====================================================================================================
+ // addResponsePattern()
+ //====================================================================================================
+ @Test
+ public void testAddResponsePattern() throws Exception {
+ RestClient c = new TestRestClient(JsonSerializer.DEFAULT, JsonParser.DEFAULT);
+ String r;
+
+ final List<String> l = new ArrayList<String>();
+ ResponsePattern p = new ResponsePattern("x=(\\d+),y=(\\S+)") {
+ @Override
+ public void onMatch(RestCall restCall, Matcher m) throws RestCallException {
+ l.add(m.group(1)+'/'+m.group(2));
+ }
+ @Override
+ public void onNoMatch(RestCall restCall) throws RestCallException {
+ throw new RestCallException("Pattern not found!");
+ }
+ };
+
+ r = c.doPost(URL, new StringEntity("x=1,y=2")).addResponsePattern(p).getResponseAsString();
+ assertEquals("x=1,y=2", r);
+ assertObjectEquals("['1/2']", l);
+
+ l.clear();
+
+ r = c.doPost(URL, new StringEntity("x=1,y=2\nx=3,y=4")).addResponsePattern(p).getResponseAsString();
+ assertEquals("x=1,y=2\nx=3,y=4", r);
+ assertObjectEquals("['1/2','3/4']", l);
+
+ try {
+ c.doPost(URL, new StringEntity("x=1")).addResponsePattern(p).run();
+ fail();
+ } catch (RestCallException e) {
+ assertEquals("Pattern not found!", e.getLocalizedMessage());
+ assertEquals(0, e.getResponseCode());
+ }
+
+ // Two patterns!
+ ResponsePattern p1 = new ResponsePattern("x=(\\d+)") {
+ @Override
+ public void onMatch(RestCall restCall, Matcher m) throws RestCallException {
+ l.add("x="+m.group(1));
+ }
+ @Override
+ public void onNoMatch(RestCall restCall) throws RestCallException {
+ throw new RestCallException("Pattern x not found!");
+ }
+ };
+ ResponsePattern p2 = new ResponsePattern("y=(\\S+)") {
+ @Override
+ public void onMatch(RestCall restCall, Matcher m) throws RestCallException {
+ l.add("y="+m.group(1));
+ }
+ @Override
+ public void onNoMatch(RestCall restCall) throws RestCallException {
+ throw new RestCallException("Pattern y not found!");
+ }
+ };
+
+ l.clear();
+ r = c.doPost(URL, new StringEntity("x=1,y=2\nx=3,y=4")).addResponsePattern(p1).addResponsePattern(p2).getResponseAsString();
+ assertEquals("x=1,y=2\nx=3,y=4", r);
+ assertObjectEquals("['x=1','x=3','y=2','y=4']", l);
+
+ try {
+ c.doPost(URL, new StringEntity("x=1\nx=3")).addResponsePattern(p1).addResponsePattern(p2).getResponseAsString();
+ } catch (RestCallException e) {
+ assertEquals("Pattern y not found!", e.getLocalizedMessage());
+ assertEquals(0, e.getResponseCode());
+ }
+
+ try {
+ c.doPost(URL, new StringEntity("y=1\ny=3")).addResponsePattern(p1).addResponsePattern(p2).getResponseAsString();
+ } catch (RestCallException e) {
+ assertEquals("Pattern x not found!", e.getLocalizedMessage());
+ assertEquals(0, e.getResponseCode());
+ }
+
+ c.closeQuietly();
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestSerializersTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestSerializersTest.java b/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestSerializersTest.java
new file mode 100755
index 0000000..5a478b9
--- /dev/null
+++ b/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestSerializersTest.java
@@ -0,0 +1,152 @@
+/***************************************************************************************************************************
+ * 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.juneau.server;
+
+import static javax.servlet.http.HttpServletResponse.*;
+import static org.apache.juneau.server.TestUtils.*;
+import static org.junit.Assert.*;
+
+import org.apache.juneau.client.*;
+import org.apache.juneau.json.*;
+import org.junit.*;
+
+public class TestSerializersTest {
+
+ private static String URL = "/testSerializers";
+ private static boolean debug = false;
+ private static RestClient client;
+
+ @BeforeClass
+ public static void beforeClass() {
+ client = new TestRestClient(JsonSerializer.DEFAULT, JsonParser.DEFAULT);
+ }
+
+ @AfterClass
+ public static void afterClass() {
+ client.closeQuietly();
+ }
+
+ //====================================================================================================
+ // Serializer defined on class.
+ //====================================================================================================
+ @Test
+ public void testSerializerOnClass() throws Exception {
+ String url = URL + "/testSerializerOnClass";
+
+ client.setAccept("text/a");
+ String r = client.doGet(url).getResponseAsString();
+ assertEquals("text/a - test1", r);
+
+ try {
+ client.setAccept("text/b");
+ client.doGet(url + "?noTrace=true").getResponseAsString();
+ fail("Exception expected");
+ } catch (RestCallException e) {
+ checkErrorResponse(debug, e, SC_NOT_ACCEPTABLE,
+ "Unsupported media-type in request header 'Accept': 'text/b'",
+ "Supported media-types: [text/a, ");
+ }
+
+ client.setAccept("text/json");
+ r = client.doGet(url).getResponseAsString();
+ assertEquals("\"test1\"", r);
+ }
+
+ //====================================================================================================
+ // Serializer defined on method.
+ //====================================================================================================
+ @Test
+ public void testSerializerOnMethod() throws Exception {
+ String url = URL + "/testSerializerOnMethod";
+
+ try {
+ client.setAccept("text/a");
+ client.doGet(url + "?noTrace=true").getResponseAsString();
+ fail("Exception expected");
+ } catch (RestCallException e) {
+ checkErrorResponse(debug, e, SC_NOT_ACCEPTABLE,
+ "Unsupported media-type in request header 'Accept': 'text/a'",
+ "Supported media-types: [text/b]"
+ );
+ }
+
+ try {
+ client.setAccept("text/json");
+ client.doGet(url + "?noTrace=true").getResponseAsString();
+ fail("Exception expected");
+ } catch (RestCallException e) {
+ checkErrorResponse(debug, e, SC_NOT_ACCEPTABLE,
+ "Unsupported media-type in request header 'Accept': 'text/json'",
+ "Supported media-types: [text/b]"
+ );
+ }
+ }
+
+ //====================================================================================================
+ // Serializer overridden on method.
+ //====================================================================================================
+ @Test
+ public void testSerializerOverriddenOnMethod() throws Exception {
+ String url = URL + "/testSerializerOverriddenOnMethod";
+
+ client.setAccept("text/a");
+ String r = client.doGet(url).getResponseAsString();
+ assertEquals("text/c - test3", r);
+
+ client.setAccept("text/b");
+ r = client.doGet(url).getResponseAsString();
+ assertEquals("text/b - test3", r);
+
+ client.setAccept("text/json");
+ r = client.doGet(url).getResponseAsString();
+ assertEquals("\"test3\"", r);
+ }
+
+ //====================================================================================================
+ // Serializer with different Accept than Content-Type.
+ //====================================================================================================
+ @Test
+ public void testSerializerWithDifferentMediaTypes() throws Exception {
+ String url = URL + "/testSerializerWithDifferentMediaTypes";
+
+ client.setAccept("text/a");
+ String r = client.doGet(url).getResponseAsString();
+ assertEquals("text/d - test4", r);
+
+ client.setAccept("text/d");
+ r = client.doGet(url).getResponseAsString();
+ assertEquals("text/d - test4", r);
+
+ client.setAccept("text/json");
+ r = client.doGet(url).getResponseAsString();
+ assertEquals("\"test4\"", r);
+ }
+
+ //====================================================================================================
+ // Check for valid 406 error response.
+ //====================================================================================================
+ @Test
+ public void test406() throws Exception {
+ String url = URL + "/test406";
+
+ try {
+ client.setAccept("text/bad");
+ client.doGet(url + "?noTrace=true").getResponseAsString();
+ fail("Exception expected");
+ } catch (RestCallException e) {
+ checkErrorResponse(debug, e, SC_NOT_ACCEPTABLE,
+ "Unsupported media-type in request header 'Accept': 'text/bad'",
+ "Supported media-types: [text/a");
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestStaticFilesTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestStaticFilesTest.java b/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestStaticFilesTest.java
new file mode 100755
index 0000000..c605122
--- /dev/null
+++ b/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestStaticFilesTest.java
@@ -0,0 +1,56 @@
+/***************************************************************************************************************************
+ * 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.juneau.server;
+
+import static org.junit.Assert.*;
+
+import org.apache.juneau.client.*;
+import org.apache.juneau.plaintext.*;
+import org.junit.*;
+
+public class TestStaticFilesTest {
+
+ private static String URL = "/testStaticFiles";
+
+ //====================================================================================================
+ // Tests the @RestResource(staticFiles) annotation.
+ //====================================================================================================
+ @Test
+ public void testXdocs() throws Exception {
+ RestClient client = new TestRestClient(PlainTextSerializer.class, PlainTextParser.class);
+ String r;
+ String url = URL + "/xdocs";
+
+ r = client.doGet(url + "/test.txt").getResponseAsString();
+ assertEquals("OK-1", r);
+ r = client.doGet(url + "/xdocs/test.txt").getResponseAsString();
+ assertEquals("OK-2", r);
+
+ // For security reasons, paths containing ".." should always return 404.
+ try {
+ client.doGet(url + "/xdocs/../test.txt?noTrace=true").connect();
+ fail("404 exception expected");
+ } catch (RestCallException e) {
+ assertEquals(404, e.getResponseCode());
+ }
+
+ try {
+ client.doGet(url + "/xdocs/%2E%2E/test.txt?noTrace=true").connect();
+ fail("404 exception expected");
+ } catch (RestCallException e) {
+ assertEquals(404, e.getResponseCode());
+ }
+
+ client.closeQuietly();
+ }
+}
[23/44] incubator-juneau git commit: Rename CT_* testcases.
Posted by ja...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/RoundTripBeanMapsTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/RoundTripBeanMapsTest.java b/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/RoundTripBeanMapsTest.java
new file mode 100755
index 0000000..6ad9c0f
--- /dev/null
+++ b/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/RoundTripBeanMapsTest.java
@@ -0,0 +1,1012 @@
+/***************************************************************************************************************************
+ * 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.juneau.a.rttests;
+
+import static org.apache.juneau.TestUtils.*;
+import static org.junit.Assert.*;
+
+import java.util.*;
+
+import javax.xml.datatype.*;
+
+import org.apache.juneau.*;
+import org.apache.juneau.annotation.*;
+import org.apache.juneau.json.*;
+import org.apache.juneau.json.annotation.*;
+import org.apache.juneau.parser.*;
+import org.apache.juneau.serializer.*;
+import org.apache.juneau.transform.*;
+import org.apache.juneau.transforms.*;
+import org.junit.*;
+
+/**
+ * Tests designed to serialize and parse objects to make sure we end up
+ * with the same objects for all serializers and parsers.
+ */
+@SuppressWarnings({"unchecked","hiding","serial","unused"})
+public class RoundTripBeanMapsTest extends RoundTripTest {
+
+ public RoundTripBeanMapsTest(String label, Serializer s, Parser p, int flags) throws Exception {
+ super(label, s, p, flags);
+ }
+
+ @Override /* RoundTripTest */
+ public Map<Class<?>,Class<?>> getImplClasses() {
+ Map<Class<?>,Class<?>> m = new HashMap<Class<?>,Class<?>>();
+ m.put(IBean.class, CBean.class);
+ return m;
+ }
+
+ //====================================================================================================
+ // IBean/ABean/Bean
+ //====================================================================================================
+ @Test
+ public void testImplClasses() throws Exception {
+ IBean bean = new CBean();
+
+ bean.setF1("bar");
+ bean = roundTrip(bean, IBean.class);
+ assertEquals("bar", bean.getF1());
+
+ bean.setF1("baz");
+ bean = roundTrip(bean, ABean.class);
+ assertEquals("baz", bean.getF1());
+
+ bean.setF1("bing");
+ bean = roundTrip(bean, CBean.class);
+ assertEquals("bing", bean.getF1());
+ }
+
+ //====================================================================================================
+ // IBean[]/ABean[]/Bean[]
+ //====================================================================================================
+ @Test
+ public void testImplArrayClasses() throws Exception {
+ IBean[] bean = new CBean[]{new CBean()};
+
+ bean[0].setF1("bar");
+ bean = roundTrip(bean, IBean[].class);
+ assertEquals("bar", bean[0].getF1());
+
+ bean[0].setF1("baz");
+ bean = roundTrip(bean, ABean[].class);
+ assertEquals("baz", bean[0].getF1());
+
+ bean[0].setF1("bing");
+ bean = roundTrip(bean, CBean[].class);
+ assertEquals("bing", bean[0].getF1());
+ }
+
+ //====================================================================================================
+ // List<IBean/ABean/Bean>
+ //====================================================================================================
+ @Test
+ public void testImplListClasses() throws Exception {
+ List<IBean> l = new LinkedList<IBean>() {{
+ add(new CBean());
+ }};
+
+ l.get(0).setF1("bar");
+ l = roundTripCollection(l, List.class, IBean.class);
+ assertEquals("bar", l.get(0).getF1());
+ l = roundTripCollection(l, LinkedList.class, IBean.class);
+ assertEquals("bar", l.get(0).getF1());
+
+ l.get(0).setF1("baz");
+ l = roundTripCollection(l, List.class, ABean.class);
+ assertEquals("baz", l.get(0).getF1());
+ l = roundTripCollection(l, LinkedList.class, ABean.class);
+ assertEquals("baz", l.get(0).getF1());
+
+ l.get(0).setF1("bing");
+ l = roundTripCollection(l, List.class, CBean.class);
+ assertEquals("bing", l.get(0).getF1());
+ l = roundTripCollection(l, LinkedList.class, CBean.class);
+ assertEquals("bing", l.get(0).getF1());
+ }
+
+ //====================================================================================================
+ // Map<String,IBean/ABean/Bean>
+ //====================================================================================================
+ @Test
+ public void testImplMap() throws Exception {
+ Map<String,IBean> l = new LinkedHashMap<String,IBean>() {{
+ put("foo", new CBean());
+ }};
+
+ l.get("foo").setF1("bar");
+ l = roundTripMap(l, Map.class, String.class, IBean.class);
+ assertEquals("bar", l.get("foo").getF1());
+ l = roundTripMap(l, LinkedHashMap.class, String.class, IBean.class);
+ assertEquals("bar", l.get("foo").getF1());
+
+ l.get("foo").setF1("baz");
+ l = roundTripMap(l, Map.class, String.class, ABean.class);
+ assertEquals("baz", l.get("foo").getF1());
+ l = roundTripMap(l, LinkedHashMap.class, String.class, ABean.class);
+ assertEquals("baz", l.get("foo").getF1());
+
+ l.get("foo").setF1("bing");
+ l = roundTripMap(l, Map.class, String.class, CBean.class);
+ assertEquals("bing", l.get("foo").getF1());
+ l = roundTripMap(l, LinkedHashMap.class, String.class, CBean.class);
+ assertEquals("bing", l.get("foo").getF1());
+ }
+
+ //====================================================================================================
+ // Map<String,IBean/ABean/Bean>
+ //====================================================================================================
+ @Test
+ public void testImplMap2() throws Exception {
+ A b = new A(1);
+ b = roundTrip(b);
+ if (returnOriginalObject || p == null)
+ return;
+ assertEquals(0, b.f1);
+ assertEquals(0, b.f2);
+ assertEquals(1, b.f3);
+ assertEquals(1, b.f4);
+ assertEquals(0, b.getF5());
+ assertEquals(1, b.getF6());
+ }
+
+ public static interface IBean {
+ public String getF1();
+ public void setF1(String f1);
+ }
+
+ public static abstract class ABean implements IBean {
+ @Override /* IBean */
+ public abstract String getF1();
+ @Override /* IBean */
+ public abstract void setF1(String f1);
+ }
+
+ public static class CBean extends ABean {
+ private String f1 = "foo";
+ @Override /* IBean */
+ public String getF1() {
+ return f1;
+ }
+ @Override /* IBean */
+ public void setF1(String f1) {
+ this.f1 = f1;
+ }
+ }
+
+ public static class A {
+
+ @BeanIgnore
+ public int f1, f2;
+ public int f3, f4;
+
+ private int f5, f6;
+
+ @BeanIgnore
+ public int getF5() {
+ return f5;
+ }
+ public void setF5(int f5) {
+ this.f5 = f5;
+ }
+
+ public int getF6() {
+ return f6;
+ }
+ public void setF6(int f6) {
+ this.f6 = f6;
+ }
+
+ public A() {}
+
+ public A(int v) {
+ f1 = f2 = f3 = f4 = f5 = f6 = v;
+ }
+ }
+
+ //====================================================================================================
+ // Test @Bean(subTypes=xxx)
+ //====================================================================================================
+ @Test
+ public void testSubTypesUsingAnnotation() throws Exception {
+ JsonSerializer js = JsonSerializer.DEFAULT_LAX.clone().addTransforms(XMLGregorianCalendarTransform.class);
+
+ // Skip validation-only tests
+ if (isValidationOnly())
+ return;
+
+ Serializer s = getSerializer().clone().addTransforms(XMLGregorianCalendarTransform.class);
+ Parser p = getParser().clone().addTransforms(XMLGregorianCalendarTransform.class);
+
+ B1 b1 = B1.create();
+ Object r = s.serialize(b1);
+ B b = p.parse(r, B.class);
+ assertTrue(b instanceof B1);
+ assertObjectEquals("{subType:'B1',f0:'f0',f1:'f1'}", b, js);
+
+ B2 b2 = B2.create();
+ r = s.serialize(b2);
+ b = p.parse(r, B.class);
+ assertTrue(b instanceof B2);
+ assertObjectEquals("{subType:'B2',f0:'f0',f2:1}", b, js);
+
+ B3 b3 = B3.create();
+ r = s.serialize(b3);
+ b = p.parse(r, B.class);
+ assertTrue(b instanceof B3);
+ assertObjectEquals("{subType:'B3',f0:'f0',f3:'2001-01-01T12:34:56.789Z'}", b, js);
+}
+
+ @Bean(
+ subTypeProperty="subType",
+ subTypes={
+ @BeanSubType(type=B1.class, id="B1"),
+ @BeanSubType(type=B2.class, id="B2"),
+ @BeanSubType(type=B3.class, id="B3")
+ }
+ )
+ public abstract static class B {
+ public String f0 = "f0";
+ }
+
+ public static class B1 extends B {
+ public String f1;
+ public static B1 create() {
+ B1 b = new B1();
+ b.f0 = "f0";
+ b.f1 = "f1";
+ return b;
+ }
+ }
+
+ public static class B2 extends B {
+ public int f2;
+ public static B2 create() {
+ B2 b = new B2();
+ b.f0 = "f0";
+ b.f2 = 1;
+ return b;
+ }
+ }
+
+ public static class B3 extends B {
+ public XMLGregorianCalendar f3;
+ public static B3 create() throws Exception {
+ B3 b = new B3();
+ b.f0 = "f0";
+ b.f3 = DatatypeFactory.newInstance().newXMLGregorianCalendar("2001-01-01T12:34:56.789Z");
+ return b;
+ }
+ }
+
+ //====================================================================================================
+ // Test @Bean(subTypes=xxx) using BeanTransform
+ //====================================================================================================
+ @Test
+ public void testSubTypesUsingBeanTransform() throws Exception {
+ JsonSerializer js = JsonSerializer.DEFAULT_LAX.clone().addTransforms(XMLGregorianCalendarTransform.class);
+
+ // Skip validation-only tests
+ if (isValidationOnly())
+ return;
+
+ Serializer s = getSerializer().clone().addTransforms(CTransform.class, XMLGregorianCalendarTransform.class);
+ Parser p = getParser().clone().addTransforms(CTransform.class, XMLGregorianCalendarTransform.class);
+
+ C1 c1 = C1.create();
+ Object r = s.serialize(c1);
+ C c = p.parse(r, C.class);
+ assertTrue(c instanceof C1);
+ assertObjectEquals("{f0:'f0',f1:'f1'}", c, js);
+
+ C2 c2 = C2.create();
+ r = s.serialize(c2);
+ c = p.parse(r, C.class);
+ assertTrue(c instanceof C2);
+ assertObjectEquals("{f0:'f0',f2:1}", c, js);
+
+ C3 c3 = C3.create();
+ r = s.serialize(c3);
+ c = p.parse(r, C.class);
+ assertTrue(c instanceof C3);
+ assertObjectEquals("{f0:'f0',f3:'2001-01-01T12:34:56.789Z'}", c, js);
+ }
+
+ public abstract static class C {
+ public String f0;
+ }
+
+ public static class C1 extends C {
+ public String f1;
+ public static C1 create() {
+ C1 c = new C1();
+ c.f0 = "f0";
+ c.f1 = "f1";
+ return c;
+ }
+ }
+
+ public static class C2 extends C {
+ public int f2;
+ public static C2 create() {
+ C2 c = new C2();
+ c.f0 = "f0";
+ c.f2 = 1;
+ return c;
+ }
+ }
+
+ public static class C3 extends C {
+ public XMLGregorianCalendar f3;
+ public static C3 create() throws Exception {
+ C3 c = new C3();
+ c.f0 = "f0";
+ c.f3 = DatatypeFactory.newInstance().newXMLGregorianCalendar("2001-01-01T12:34:56.789Z");
+ return c;
+ }
+ }
+
+ public static class CTransform extends BeanTransform<C> {
+ public CTransform() {
+ setSubTypeProperty("subType");
+ addSubType(C1.class, "C1");
+ addSubType(C2.class, "C2");
+ addSubType(C3.class, "C3");
+ }
+ }
+
+ //====================================================================================================
+ // Test @Bean(subTypeProperty=xxx) with real bean property
+ //====================================================================================================
+ @Test
+ public void testSubTypePropertyWithRealPropertyUsingAnnotation() throws Exception {
+ // Skip validation-only tests
+ if (isValidationOnly())
+ return;
+
+ Serializer s = getSerializer();
+ Parser p = getParser();
+
+ BA1 ba1 = BA1.create();
+ Object r = s.serialize(ba1);
+ BA b = p.parse(r, BA.class);
+ assertTrue(b instanceof BA1);
+ assertEquals("BA1", b.subType);
+ assertObjectEquals("{subType:'BA1',f0a:'f0a',f0b:'f0b',f1:'f1'}", b);
+ }
+
+ @Bean(
+ subTypeProperty="subType",
+ subTypes={
+ @BeanSubType(type=BA1.class, id="BA1"),
+ @BeanSubType(type=BA2.class, id="BA2")
+ }
+ )
+ public abstract static class BA {
+ public String f0a, subType, f0b;
+ }
+
+ public static class BA1 extends BA {
+ public String f1;
+ public static BA1 create() {
+ BA1 b = new BA1();
+ b.f0a = "f0a";
+ b.f0b = "f0b";
+ b.f1 = "f1";
+ b.subType = "xxx";// Should be ignored.
+ return b;
+ }
+ }
+
+ public static class BA2 extends BA {
+ public String f2;
+ }
+
+
+ //====================================================================================================
+ // Test @Bean(subTypes=xxx) with real bean property using BeanTransform
+ //====================================================================================================
+ @Test
+ public void testSubTypePropertyWithRealPropertyUsingBeanTransform() throws Exception {
+ // Skip validation-only tests
+ if (isValidationOnly())
+ return;
+
+ Serializer s = getSerializer().clone().addTransforms(CATransform.class);
+ Parser p = getParser().clone().addTransforms(CATransform.class);
+
+ CA1 c1 = CA1.create();
+ Object r = s.serialize(c1);
+ CA c = p.parse(r, CA.class);
+ assertTrue(c instanceof CA1);
+ assertEquals("CA1", c.subType);
+ assertObjectEquals("{f0a:'f0a',subType:'CA1',f0b:'f0b',f1:'f1'}", c);
+ }
+
+ public abstract static class CA {
+ public String f0a, subType, f0b;
+ }
+
+ public static class CA1 extends CA {
+ public String f1;
+ public static CA1 create() {
+ CA1 c = new CA1();
+ c.f0a = "f0a";
+ c.f0b = "f0b";
+ c.f1 = "f1";
+ c.subType = "xxx";// Should be ignored.
+ return c;
+ }
+ }
+
+ public static class CA2 extends CA {
+ public String f2;
+ }
+
+ public static class CATransform extends BeanTransform<CA> {
+ public CATransform() {
+ setSubTypeProperty("subType");
+ addSubType(CA1.class, "CA1");
+ addSubType(CA2.class, "CA2");
+ }
+ }
+
+ //====================================================================================================
+ // Test @Bean(properties=xxx)
+ //====================================================================================================
+ @Test
+ public void testPropertiesUsingAnnotation() throws Exception {
+ // Skip validation-only tests
+ if (isValidationOnly())
+ return;
+
+ Serializer s = getSerializer();
+ Parser p = getParser();
+
+ D1 d = new D1().init();
+ Object r = s.serialize(d);
+ d = p.parse(r, D1.class);
+ assertNull(d.f1);
+ assertObjectEquals("{f3:'f3',f2:'f2'}", d);
+ }
+
+ @Bean(properties={"f3","f2"})
+ public static class D1 {
+ public String f1, f2, f3;
+ public D1 init() {
+ f1 = "f1";
+ f2 = "f2";
+ f3 = "f3";
+ return this;
+ }
+ }
+
+ //====================================================================================================
+ // Test @Bean(properties=xxx) using BeanTransform
+ //====================================================================================================
+ @Test
+ public void testPropertiesUsingTransform() throws Exception {
+ JsonSerializer js = JsonSerializer.DEFAULT_LAX.clone().addTransforms(D2Transform.class);
+
+ // Skip validation-only tests
+ if (isValidationOnly())
+ return;
+
+ Serializer s = getSerializer().clone().addTransforms(D2Transform.class);
+ Parser p = getParser().clone().addTransforms(D2Transform.class);
+
+ D2 d = new D2().init();
+ Object r = s.serialize(d);
+ d = p.parse(r, D2.class);
+ assertNull(d.f1);
+ assertObjectEquals("{f3:'f3',f2:'f2'}", d, js);
+ }
+
+ public static class D2 {
+ public String f1, f2, f3;
+ public D2 init() {
+ f1 = "f1";
+ f2 = "f2";
+ f3 = "f3";
+ return this;
+ }
+ }
+ public static class D2Transform extends BeanTransform<D2> {
+ public D2Transform() {
+ setProperties("f3","f2");
+ }
+ }
+
+ //====================================================================================================
+ // Test @Bean(excludeProperties=xxx)
+ //====================================================================================================
+ @Test
+ public void testExcludePropertiesUsingAnnotation() throws Exception {
+ // Skip validation-only tests
+ if (isValidationOnly())
+ return;
+
+ Serializer s = getSerializer();
+ Parser p = getParser();
+
+ E1 e = new E1().init();
+ Object r = s.serialize(e);
+ e = p.parse(r, E1.class);
+ assertObjectEquals("{f1:'f1',f3:'f3'}", e);
+ }
+
+ @Bean(excludeProperties={"f2"})
+ public static class E1 {
+ public String f1, f2, f3;
+ public E1 init() {
+ f1 = "f1";
+ f2 = "f2";
+ f3 = "f3";
+ return this;
+ }
+ }
+
+ //====================================================================================================
+ // Test @Bean(excludeProperties=xxx) using BeanTransform
+ //====================================================================================================
+ @Test
+ public void testExcludePropertiesUsingTransform() throws Exception {
+ // Skip validation-only tests
+ if (isValidationOnly())
+ return;
+
+ Serializer s = getSerializer().clone().addTransforms(E2Transform.class);
+ Parser p = getParser().clone().addTransforms(E2Transform.class);
+
+ E2 e = new E2().init();
+ Object r = s.serialize(e);
+ e = p.parse(r, E2.class);
+ assertObjectEquals("{f1:'f1',f3:'f3'}", e);
+ }
+
+ public static class E2 {
+ public String f1, f2, f3;
+ public E2 init() {
+ f1 = "f1";
+ f2 = "f2";
+ f3 = "f3";
+ return this;
+ }
+ }
+ public static class E2Transform extends BeanTransform<E2> {
+ public E2Transform() {
+ setExcludeProperties("f2");
+ }
+ }
+
+ //====================================================================================================
+ // Test @Bean(interfaceClass=xxx)
+ //====================================================================================================
+ @Test
+ public void testInterfaceClassUsingAnnotation() throws Exception {
+ // Skip validation-only tests
+ if (isValidationOnly())
+ return;
+
+ Serializer s = getSerializer();
+ Parser p = getParser();
+
+ FA2 t = new FA2().init();
+ Object r = s.serialize(t);
+ t = p.parse(r, FA2.class);
+ assertObjectEquals("{f1:'f1'}", t);
+ }
+
+ @Bean(interfaceClass=FA1.class)
+ public static class FA1 {
+ public String f1;
+ }
+
+ public static class FA2 extends FA1 {
+ public String f2;
+ public FA2 init() {
+ f1 = "f1";
+ f2 = "f2";
+ return this;
+ }
+ }
+
+ //====================================================================================================
+ // Test @Bean(interfaceClass=xxx) using BeanTransform
+ //====================================================================================================
+ @Test
+ public void testInterfaceClassUsingTransform() throws Exception {
+ Serializer s;
+ Parser p;
+ FB2 t;
+ Object r;
+
+ // Skip validation-only tests
+ if (isValidationOnly())
+ return;
+
+ // --- Transform defined on parent class ---
+ s = getSerializer().clone().addTransforms(FB1Transform.class);
+ p = getParser().clone().addTransforms(FB1Transform.class);
+
+ t = new FB2().init();
+ r = s.serialize(t);
+ t = p.parse(r, FB2.class);
+ assertObjectEquals("{f1:'f1'}", t);
+
+ // --- Transform defined on child class class ---
+ s = getSerializer().clone().addTransforms(FB2Transform.class);
+ p = getParser().clone().addTransforms(FB2Transform.class);
+
+ t = new FB2().init();
+ r = s.serialize(t);
+ t = p.parse(r, FB2.class);
+ assertObjectEquals("{f1:'f1'}", t);
+
+ // --- Transform defined as plain class ---
+ s = getSerializer().clone().addTransforms(FB1.class);
+ p = getParser().clone().addTransforms(FB1.class);
+
+ t = new FB2().init();
+ r = s.serialize(t);
+ t = p.parse(r, FB2.class);
+ assertObjectEquals("{f1:'f1'}", t);
+ }
+
+ public static class FB1 {
+ public String f1;
+ }
+
+ public static class FB2 extends FB1 {
+ public String f2;
+ public FB2 init() {
+ f1 = "f1";
+ f2 = "f2";
+ return this;
+ }
+ }
+ public static class FB1Transform extends BeanTransform<FB1> {
+ public FB1Transform() {
+ setInterfaceClass(FB1.class);
+ }
+ }
+ public static class FB2Transform extends BeanTransform<FB2> {
+ public FB2Transform() {
+ setInterfaceClass(FB1.class);
+ }
+ }
+
+ //====================================================================================================
+ // testMemberClass
+ //====================================================================================================
+ @Test
+ public void testMemberClass() throws Exception {
+ G t = G.create();
+ t = roundTrip(t, G.class);
+ }
+
+ public static class G {
+ public int a1;
+ public G1 g1;
+
+ public static G create() {
+ G g = new G();
+ g.a1 = 1;
+ g.g1.a2 = 2;
+ g.g1.g2.a3 = 3;
+ return g;
+ }
+
+ public G() {
+ g1 = new G1();
+ }
+
+ public class G1 {
+ public int a2;
+ public G2 g2;
+
+ public G1() {
+ g2 = new G2();
+ }
+
+ public class G2 {
+ public int a3;
+ }
+ }
+ }
+
+ //====================================================================================================
+ // testMemberClassWithMapClass
+ //====================================================================================================
+ @Test
+ public void testMemberClassWithMapClass() throws Exception {
+ H t = H.create();
+ t = roundTrip(t, H.class);
+ }
+
+ public static class H extends LinkedHashMap<String,H.H1> {
+
+ static H create() {
+ H h = new H();
+ h.add("foo", 1, 2);
+ return h;
+ }
+
+ H add(String key, int a2, int a3) {
+ H1 h1 = new H1();
+ h1.a2 = a2;
+ h1.h2.a3 = a3;
+ put(key, h1);
+ return this;
+ }
+
+ public class H1 {
+ public int a2;
+ public H2 h2;
+
+ public H1() {
+ h2 = new H2();
+ }
+
+ public class H2 {
+ public int a3;
+ }
+ }
+ }
+
+ //====================================================================================================
+ // testMemberClassWithListClass
+ //====================================================================================================
+ @Test
+ public void testMemberClassWithListClass() throws Exception {
+ I t = I.create();
+ t = roundTrip(t, I.class);
+ }
+
+ public static class I extends LinkedList<I.I1> {
+
+ static I create() {
+ I i = new I();
+ i.add(1, 2);
+ return i;
+ }
+
+ I add(int a2, int a3) {
+ I1 i1 = new I1();
+ i1.a2 = a2;
+ i1.i2.a3 = a3;
+ super.add(i1);
+ return this;
+ }
+
+ public class I1 {
+ public int a2;
+ public I2 i2;
+
+ public I1() {
+ i2 = new I2();
+ }
+
+ public class I2 {
+ public int a3;
+ }
+ }
+ }
+
+ //====================================================================================================
+ // testMemberClassWithStringConstructor
+ //====================================================================================================
+ @Test
+ public void testMemberClassWithStringConstructor() throws Exception {
+ J t = J.create();
+ t = roundTrip(t, J.class);
+ }
+
+ public static class J {
+ public J2 j2;
+
+ static J create() {
+ J j = new J();
+ j.init();
+ return j;
+ }
+
+ private void init() {
+ j2 = new J2("2");
+ }
+
+ public class J2 {
+ int a2;
+
+ public J2(String arg) {
+ this.a2 = Integer.parseInt(arg);
+ }
+
+ @Override /* Object */
+ public String toString() {
+ return String.valueOf(a2);
+ }
+ }
+ }
+
+ //====================================================================================================
+ // testBeanPropertyPrecedence
+ //====================================================================================================
+ @Test
+ public void testBeanPropertyPrecedence() throws Exception {
+ K t = K.create();
+ t = roundTrip(t, K.class);
+ }
+ public static enum KEnum { FOO, BAR, BAZ }
+
+ public static class K {
+ private KEnum a, b, c;
+
+ static K create() {
+ K t = new K();
+ t.a = KEnum.FOO;
+ t.b = KEnum.BAR;
+ t.c = KEnum.BAZ;
+ return t;
+ }
+
+ @BeanIgnore
+ public KEnum getA() {
+ return KEnum.FOO;
+ }
+
+ @BeanProperty(name="a")
+ public String getA2() {
+ return a.toString();
+ }
+
+ // This method should not be interpreted as the setter for this
+ // property because it doesn't match the getter return type above.
+ public void setA(KEnum a) {
+ throw new RuntimeException("Should not be called!");
+ }
+
+ public void setA(String a) {
+ this.a = KEnum.valueOf(a);
+ }
+
+ public KEnum getB() {
+ return b;
+ }
+
+ public void setB(String b) {
+ throw new RuntimeException("Should not be called!");
+ }
+
+ public void setB(Object b) {
+ throw new RuntimeException("Should not be called!");
+ }
+
+ public void setB(KEnum b) {
+ this.b = b;
+ }
+
+ public KEnum getC() {
+ return c;
+ }
+
+ public void setC(KEnum c) {
+ this.c = c;
+ }
+
+ public void setC(String c) {
+ throw new RuntimeException("Should not be called!");
+ }
+
+ public void setC(Object c) {
+ throw new RuntimeException("Should not be called!");
+ }
+ }
+
+ //====================================================================================================
+ // testWrapperAttrAnnotationOnBean
+ //====================================================================================================
+ @Test
+ public void testWrapperAttrAnnotationOnBean() throws Exception {
+ L t = L.create();
+ t = roundTrip(t, L.class);
+
+ Map<String,L> m = new LinkedHashMap<String,L>();
+ m.put("bar", L.create());
+ roundTripMap(m, LinkedHashMap.class, String.class, L.class);
+ }
+
+ @Json(wrapperAttr="foo")
+ public static class L {
+ public int f1;
+
+ static L create() {
+ L l = new L();
+ l.f1 = 1;
+ return l;
+ }
+ }
+
+ //====================================================================================================
+ // testWrapperAttrAnnotationOnNonBean
+ //====================================================================================================
+ @Test
+ public void testWrapperAttrAnnotationOnNonBean() throws Exception {
+ M t = M.create();
+ t = roundTrip(t, M.class);
+
+ Map<String,M> m = new LinkedHashMap<String,M>();
+ m.put("bar", M.create());
+ roundTripMap(m, LinkedHashMap.class, String.class, M.class);
+ }
+
+ @Json(wrapperAttr="foo")
+ public static class M {
+ int f1;
+
+ static M create() {
+ M m = new M();
+ m.f1 = 1;
+ return m;
+ }
+
+ @Override /* Object */
+ public String toString() {
+ return String.valueOf(f1);
+ }
+
+ public static M valueOf(String s) {
+ M m = new M();
+ m.f1 = Integer.parseInt(s);
+ return m;
+ }
+ }
+
+ //====================================================================================================
+ // Test parsing into top-level non-static inner classes with outer context.
+ //====================================================================================================
+ @Test
+ public void testParsingIntoTopLevelNonStaticInnerClasses() throws Exception {
+ N n = new N(1);
+
+ if (returnOriginalObject)
+ return;
+
+ Serializer s = getSerializer();
+ Parser p = getParser();
+
+ Object r = s.serialize(n.n2);
+ n = new N(2);
+ ParserSession session = p.createSession(r, null, null, n);
+
+ N.N2 n2 = p.parse(session, BeanContext.DEFAULT.getClassMeta(N.N2.class));
+
+ // The inner N2.f1 field should be the value of the outer object passed in through the context.
+ assertEquals(2, n2.f1);
+ }
+
+ public static class N {
+ public int f1;
+ public N2 n2;
+
+ public N(int f1) {
+ this.f1 = f1;
+ n2 = new N2();
+ }
+ public class N2 {
+ private int f1 = N.this.f1;
+ public int dummy = 1;
+ }
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/RoundTripClassesTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/RoundTripClassesTest.java b/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/RoundTripClassesTest.java
new file mode 100644
index 0000000..49df439
--- /dev/null
+++ b/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/RoundTripClassesTest.java
@@ -0,0 +1,53 @@
+/***************************************************************************************************************************
+ * 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.juneau.a.rttests;
+
+import static org.apache.juneau.TestUtils.*;
+import static org.junit.Assert.*;
+
+import java.util.*;
+
+import org.apache.juneau.parser.*;
+import org.apache.juneau.serializer.*;
+import org.junit.*;
+
+/**
+ * Tests designed to serialize and parse objects to make sure we end up
+ * with the same objects for all serializers and parsers.
+ */
+public class RoundTripClassesTest extends RoundTripTest {
+
+ public RoundTripClassesTest(String label, Serializer s, Parser p, int flags) throws Exception {
+ super(label, s, p, flags);
+ }
+
+ @SuppressWarnings("serial")
+ @Test
+ public void classObjects() throws Exception {
+ Object o = String.class;
+ o = roundTrip(o);
+ assertTrue(o == String.class);
+
+ o = new Class[]{String.class};
+ o = roundTrip(o);
+ assertObjectEquals("['java.lang.String']", o);
+
+ o = new LinkedList<Class<?>>(){{add(String.class);add(Integer.class);}};
+ o = roundTrip(o);
+ assertObjectEquals("['java.lang.String','java.lang.Integer']", o);
+
+ o = new LinkedHashMap<Class<?>,Class<?>>(){{put(String.class,String.class);}};
+ o = roundTrip(o);
+ assertObjectEquals("{'java.lang.String':'java.lang.String'}", o);
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/RoundTripDTOsTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/RoundTripDTOsTest.java b/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/RoundTripDTOsTest.java
new file mode 100755
index 0000000..2bee742
--- /dev/null
+++ b/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/RoundTripDTOsTest.java
@@ -0,0 +1,50 @@
+/***************************************************************************************************************************
+ * 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.juneau.a.rttests;
+
+import static org.apache.juneau.TestUtils.*;
+
+import org.apache.juneau.dto.jsonschema.*;
+import org.apache.juneau.parser.*;
+import org.apache.juneau.serializer.*;
+import org.junit.*;
+
+
+/**
+ * Tests designed to serialize and parse objects to make sure we end up
+ * with the same objects for all serializers and parsers.
+ */
+@SuppressWarnings("hiding")
+public class RoundTripDTOsTest extends RoundTripTest {
+
+ public RoundTripDTOsTest(String label, Serializer s, Parser p, int flags) throws Exception {
+ super(label, s, p, flags);
+ }
+
+ //====================================================================================================
+ // org.apache.juneau.test.dto.jsonschema
+ //====================================================================================================
+ @Test
+ public void testJsonSchema1() throws Exception {
+ Schema s = JsonSchemaTest.getTest1();
+ Schema s2 = roundTrip(s, Schema.class);
+ assertEqualObjects(s, s2);
+ }
+
+ @Test
+ public void testJsonSchema2() throws Exception {
+ Schema s = JsonSchemaTest.getTest2();
+ Schema s2 = roundTrip(s, Schema.class);
+ assertEqualObjects(s, s2);
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/RoundTripEnumTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/RoundTripEnumTest.java b/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/RoundTripEnumTest.java
new file mode 100755
index 0000000..d34221c
--- /dev/null
+++ b/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/RoundTripEnumTest.java
@@ -0,0 +1,246 @@
+/***************************************************************************************************************************
+ * 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.juneau.a.rttests;
+
+import static org.apache.juneau.TestUtils.*;
+import static org.junit.Assert.*;
+
+import java.util.*;
+
+import org.apache.juneau.json.*;
+import org.apache.juneau.parser.*;
+import org.apache.juneau.serializer.*;
+import org.junit.*;
+
+/**
+ * Tests designed to serialize and parse objects to make sure we end up
+ * with the same objects for all serializers and parsers.
+ */
+@SuppressWarnings({"hiding","serial"})
+public class RoundTripEnumTest extends RoundTripTest {
+
+ public RoundTripEnumTest(String label, Serializer s, Parser p, int flags) throws Exception {
+ super(label, s, p, flags);
+ }
+
+ //====================================================================================================
+ // Enum object
+ //====================================================================================================
+ @Test
+ public void testEnumA() throws Exception {
+ AEnum t = AEnum.FOO;
+ assertObjectEquals("'FOO'", t);
+ t = roundTrip(t, AEnum.class);
+ assertEquals(AEnum.FOO, t);
+ }
+
+ @Test
+ public void testEnumB() throws Exception {
+ WriterSerializer s = new JsonSerializer.Simple().addTransforms(getTransforms());
+ BEnum t = BEnum.FOO;
+ assertEquals("'xfoo'", s.serialize(t));
+ t = roundTrip(t, BEnum.class);
+ assertEquals(BEnum.FOO, t);
+ }
+
+ //====================================================================================================
+ // Enum[] object
+ //====================================================================================================
+ @Test
+ public void testEnumArrayA() throws Exception {
+ AEnum[] t = {AEnum.FOO,AEnum.BAR,null};
+ assertObjectEquals("['FOO','BAR',null]", t);
+ t = roundTrip(t, AEnum[].class);
+ assertEquals(AEnum.FOO, t[0]);
+ assertEquals(AEnum.BAR, t[1]);
+ assertNull(t[2]);
+ }
+
+ @Test
+ public void testEnumArrayB() throws Exception {
+ BEnum[] t = {BEnum.FOO,BEnum.BAR,null};
+ assertObjectEquals("['xfoo','xbar',null]", t);
+ t = roundTrip(t, BEnum[].class);
+ assertEquals(BEnum.FOO, t[0]);
+ assertEquals(BEnum.BAR, t[1]);
+ assertNull(t[2]);
+ }
+
+ //====================================================================================================
+ // Enum[][] object
+ //====================================================================================================
+ @Test
+ public void testEnum2dArrayA() throws Exception {
+ AEnum[][] t = {{AEnum.FOO,AEnum.BAR,null},null};
+ assertObjectEquals("[['FOO','BAR',null],null]", t);
+ t = roundTrip(t, AEnum[][].class);
+ assertEquals(AEnum.FOO, t[0][0]);
+ assertEquals(AEnum.BAR, t[0][1]);
+ assertNull(t[0][2]);
+ assertNull(t[1]);
+ }
+
+ @Test
+ public void testEnum2dArrayB() throws Exception {
+ BEnum[][] t = {{BEnum.FOO,BEnum.BAR,null},null};
+ assertObjectEquals("[['xfoo','xbar',null],null]", t);
+ t = roundTrip(t, BEnum[][].class);
+ assertEquals(BEnum.FOO, t[0][0]);
+ assertEquals(BEnum.BAR, t[0][1]);
+ assertNull(t[0][2]);
+ assertNull(t[1]);
+ }
+
+ //====================================================================================================
+ // Bean with Enum fields
+ //====================================================================================================
+ @Test
+ public void testBeansWithEnumA() throws Exception {
+ A t1 = new A().init(), t2;
+ t2 = roundTrip(t1, A.class);
+ assertEqualObjects(t1, t2);
+ assertEquals(AEnum.FOO, t2.f3[0]);
+ assertNull(t2.f3[1]);
+ assertEquals(AEnum.FOO, t2.f4[0][0]);
+ assertNull(t2.f4[0][1]);
+ assertNull(t2.f4[1]);
+ }
+
+ @Test
+ public void testBeansWithEnumB() throws Exception {
+ B t1 = new B().init(), t2;
+ t2 = roundTrip(t1, B.class);
+ assertEqualObjects(t1, t2);
+ assertEquals(BEnum.FOO, t2.f3[0]);
+ assertNull(t2.f3[1]);
+ assertEquals(BEnum.FOO, t2.f4[0][0]);
+ assertNull(t2.f4[0][1]);
+ assertNull(t2.f4[1]);
+ }
+
+
+ /** Normal Enum */
+ public enum AEnum {
+ FOO,BAR,BAZ
+ }
+
+ /** Enum with custom serialized values */
+ public enum BEnum {
+ FOO("xfoo"), BAR("xbar"), BAZ("xbaz");
+
+ private String val;
+
+ private BEnum(String val) {
+ this.val = val;
+ }
+
+ @Override /* Object */
+ public String toString() {
+ return val;
+ }
+
+ public static BEnum fromString(String val) {
+ if (val.equals("xfoo"))
+ return FOO;
+ if (val.equals("xbar"))
+ return BAR;
+ if (val.equals("xbaz"))
+ return BAZ;
+ return null;
+ }
+ }
+
+ public static class A {
+
+ // Should have 'enum' attribute.
+ public AEnum f1;
+
+ private AEnum f2;
+ public AEnum getF2() {return f2;}
+ public void setF2(AEnum f2) {this.f2 = f2;}
+
+ public AEnum[] f3;
+ public AEnum[][] f4;
+
+ // Should not have 'uniqueSet' attribute.
+ public List<AEnum> f5 = new LinkedList<AEnum>();
+
+ private List<AEnum> f6 = new LinkedList<AEnum>();
+ public List<AEnum> getF6() {return f6;}
+ public void setF6(List<AEnum> f6) {this.f6 = f6;}
+
+ // Should have 'uniqueSet' attribute.
+ public Set<AEnum> f7 = new HashSet<AEnum>();
+
+ private Set<AEnum> f8 = new HashSet<AEnum>();
+ public Set<AEnum> getF8() {return f8;}
+ public void setF8(Set<AEnum> f8) {this.f8 = f8;}
+
+ public Map<AEnum,AEnum> f9 = new LinkedHashMap<AEnum,AEnum>();
+
+ public A init() {
+ f1 = AEnum.FOO;
+ f2 = AEnum.BAR;
+ f3 = new AEnum[]{AEnum.FOO,null};
+ f4 = new AEnum[][]{{AEnum.FOO,null},null};
+ f5 = new ArrayList<AEnum>(){{add(AEnum.FOO);}};
+ f6 = new ArrayList<AEnum>(){{add(AEnum.FOO);}};
+ f7 = new HashSet<AEnum>(){{add(AEnum.FOO);}};
+ f8 = new HashSet<AEnum>(){{add(AEnum.FOO);}};
+
+ return this;
+ }
+ }
+
+ public static class B {
+
+ // Should have 'enum' attribute.
+ public BEnum f1;
+
+ private BEnum f2;
+ public BEnum getF2() {return f2;}
+ public void setF2(BEnum f2) {this.f2 = f2;}
+
+ public BEnum[] f3;
+ public BEnum[][] f4;
+
+ // Should not have 'uniqueSet' attribute.
+ public List<BEnum> f5 = new LinkedList<BEnum>();
+
+ private List<BEnum> f6 = new LinkedList<BEnum>();
+ public List<BEnum> getF6() {return f6;}
+ public void setF6(List<BEnum> f6) {this.f6 = f6;}
+
+ // Should have 'uniqueSet' attribute.
+ public Set<BEnum> f7 = new HashSet<BEnum>();
+
+ private Set<BEnum> f8 = new HashSet<BEnum>();
+ public Set<BEnum> getF8() {return f8;}
+ public void setF8(Set<BEnum> f8) {this.f8 = f8;}
+
+ public Map<BEnum,BEnum> f9 = new LinkedHashMap<BEnum,BEnum>();
+
+ public B init() {
+ f1 = BEnum.FOO;
+ f2 = BEnum.BAR;
+ f3 = new BEnum[]{BEnum.FOO,null};
+ f4 = new BEnum[][]{{BEnum.FOO,null},null};
+ f5 = new ArrayList<BEnum>(){{add(BEnum.FOO);}};
+ f6 = new ArrayList<BEnum>(){{add(BEnum.FOO);}};
+ f7 = new HashSet<BEnum>(){{add(BEnum.FOO);}};
+ f8 = new HashSet<BEnum>(){{add(BEnum.FOO);}};
+
+ return this;
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/RoundTripGenericsTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/RoundTripGenericsTest.java b/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/RoundTripGenericsTest.java
new file mode 100755
index 0000000..51a6eb0
--- /dev/null
+++ b/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/RoundTripGenericsTest.java
@@ -0,0 +1,97 @@
+/***************************************************************************************************************************
+ * 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.juneau.a.rttests;
+
+import static org.apache.juneau.TestUtils.*;
+import static org.junit.Assert.*;
+
+import org.apache.juneau.annotation.*;
+import org.apache.juneau.parser.*;
+import org.apache.juneau.serializer.*;
+import org.junit.*;
+
+/**
+ * Tests designed to serialize and parse objects to make sure we end up
+ * with the same objects for all serializers and parsers.
+ */
+public class RoundTripGenericsTest extends RoundTripTest {
+
+ public RoundTripGenericsTest(String label, Serializer s, Parser p, int flags) throws Exception {
+ super(label, s, p, flags);
+ }
+
+ //====================================================================================================
+ // testBeansWithUnboundTypeVars
+ //====================================================================================================
+ @SuppressWarnings("rawtypes")
+ @Test
+ public void testBeansWithUnboundTypeVars() throws Exception {
+
+ if (returnOriginalObject)
+ return;
+
+ // Unbound type variables should be interpreted as Object.
+ // During parsing, these become ObjectMaps.
+ Pair pair = new Pair<Source,Target>(new Source().init(), new Target().init());
+ pair = roundTrip(pair);
+ assertSortedObjectEquals("{s:{s1:'a1'},t:{t1:'b1'}}", pair);
+ assertEquals("ObjectMap", pair.getS().getClass().getSimpleName());
+ assertEquals("ObjectMap", pair.getT().getClass().getSimpleName());
+
+ // If you specify a concrete class, the type variables become bound and
+ // the property types correctly resolve.
+ pair = roundTrip(pair, RealPair.class);
+ assertSortedObjectEquals("{s:{s1:'a1'},t:{t1:'b1'}}", pair);
+ assertEquals("Source", pair.getS().getClass().getSimpleName());
+ assertEquals("Target", pair.getT().getClass().getSimpleName());
+ }
+
+ // Class with unbound type variables.
+ @Bean(properties={"s","t"})
+ public static class Pair<S,T> {
+ private S s;
+ private T t;
+
+ public Pair() {}
+
+ public Pair(S s, T t) {
+ this.s = s;
+ this.t = t;
+ }
+
+ // Getters/setters
+ public S getS() { return s; }
+ public void setS(S s) { this.s = s; }
+ public T getT() { return t; }
+ public void setT(T t) { this.t = t; }
+ }
+
+ // Sublcass with bound type variables.
+ public static class RealPair extends Pair<Source,Target> {}
+
+ public static class Source {
+ public String s1;
+ public Source init() {
+ this.s1 = "a1";
+ return this;
+ }
+ }
+
+ public static class Target {
+ public String t1;
+ public Target init() {
+ this.t1 = "b1";
+ return this;
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/RoundTripLargeObjectsTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/RoundTripLargeObjectsTest.java b/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/RoundTripLargeObjectsTest.java
new file mode 100755
index 0000000..9e46375
--- /dev/null
+++ b/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/RoundTripLargeObjectsTest.java
@@ -0,0 +1,193 @@
+/***************************************************************************************************************************
+ * 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.juneau.a.rttests;
+
+import static org.apache.juneau.a.rttests.RoundTripTest.Flags.*;
+import static org.apache.juneau.serializer.SerializerContext.*;
+import static org.apache.juneau.urlencoding.UonSerializerContext.*;
+import static org.apache.juneau.xml.XmlSerializerContext.*;
+
+import java.text.*;
+import java.util.*;
+
+import org.apache.juneau.html.*;
+import org.apache.juneau.json.*;
+import org.apache.juneau.msgpack.*;
+import org.apache.juneau.parser.*;
+import org.apache.juneau.serializer.*;
+import org.apache.juneau.urlencoding.*;
+import org.apache.juneau.xml.*;
+import org.junit.*;
+import org.junit.runners.*;
+
+/**
+ * Tests designed to serialize and parse objects to make sure we end up
+ * with the same objects for all serializers and parsers.
+ */
+@Ignore
+@SuppressWarnings({"hiding","serial"})
+public class RoundTripLargeObjectsTest extends RoundTripTest {
+
+ private static final int NUM_RUNS = 10;
+ private static final int SIZE_PARAM = 20000;
+
+ public RoundTripLargeObjectsTest(String label, Serializer s, Parser p, int flags) throws Exception {
+ super(label, s, p, flags);
+ }
+
+ @Parameterized.Parameters
+ public static Collection<Object[]> getPairs() {
+ return Arrays.asList(new Object[][] {
+ // Full round-trip testing
+ { /* 0 */
+ "Json DEFAULT",
+ new JsonSerializer().setProperty(SERIALIZER_trimNullProperties, false),
+ JsonParser.DEFAULT,
+ 0
+ },
+ { /* 1 */
+ "Json DEFAULT_LAX",
+ new JsonSerializer.Simple().setProperty(SERIALIZER_trimNullProperties, false),
+ JsonParser.DEFAULT,
+ 0
+ },
+ { /* 2 */
+ "Json DEFAULT_SQ",
+ new JsonSerializer.Simple().setProperty(SERIALIZER_trimNullProperties, false),
+ JsonParser.DEFAULT,
+ 0
+ },
+ { /* 3 */
+ "Xml DEFAULT w/namespaces,validation",
+ new XmlSerializer.XmlJsonSq().setProperty(SERIALIZER_trimNullProperties, false).setProperty(XML_addNamespaceUrisToRoot, true).setProperty(SERIALIZER_useIndentation, true),
+ XmlParser.DEFAULT,
+ CHECK_XML_WHITESPACE | VALIDATE_XML
+ },
+ { /* 4 */
+ "Xml DEFAULT wo/namespaces,validation",
+ new XmlSerializer.SimpleXmlJsonSq().setProperty(SERIALIZER_trimNullProperties, false),
+ XmlParser.DEFAULT,
+ CHECK_XML_WHITESPACE
+ },
+ { /* 5 */
+ "Html",
+ new HtmlSerializer().setProperty(SERIALIZER_trimNullProperties, false),
+ HtmlParser.DEFAULT,
+ CHECK_XML_WHITESPACE
+ },
+ { /* 6 */
+ "UrlEncoding",
+ new UrlEncodingSerializer().setProperty(SERIALIZER_trimNullProperties, false).setProperty(UON_simpleMode, false),
+ UrlEncodingParser.DEFAULT,
+ 0
+ },
+ { /* 7 */
+ "Uon",
+ new UonSerializer().setProperty(SERIALIZER_trimNullProperties, false).setProperty(UON_simpleMode, false),
+ UonParser.DEFAULT,
+ 0
+ },
+ { /* 8 */
+ "MsgPack",
+ new MsgPackSerializer().setProperty(SERIALIZER_trimNullProperties, false).setProperty(UON_simpleMode, false),
+ MsgPackParser.DEFAULT,
+ 0
+ },
+// { /* 9 */
+// "Rdf.Xml",
+// new RdfSerializer.Xml().setProperty(SERIALIZER_trimNullProperties, false).setProperty(RDF_addLiteralTypes, true),
+// RdfParser.DEFAULT_XML,
+// 0
+// },
+// { /* 10 */
+// "Rdf.XmlAbbrev",
+// new RdfSerializer.XmlAbbrev().setProperty(SERIALIZER_trimNullProperties, false).setProperty(RDF_addLiteralTypes, true),
+// RdfParser.DEFAULT_XML,
+// 0
+// },
+// { /* 11 */
+// "Rdf.Turtle",
+// new RdfSerializer.Turtle().setProperty(SERIALIZER_trimNullProperties, false).setProperty(RDF_addLiteralTypes, true),
+// RdfParser.DEFAULT_TURTLE,
+// 0
+// },
+// { /* 12 */
+// "Rdf.NTriple",
+// new RdfSerializer.NTriple().setProperty(SERIALIZER_trimNullProperties, false).setProperty(RDF_addLiteralTypes, true),
+// RdfParser.DEFAULT_NTRIPLE,
+// 0
+// },
+// { /* 13 */
+// "Rdf.N3",
+// new RdfSerializer.N3().setProperty(SERIALIZER_trimNullProperties, false).setProperty(RDF_addLiteralTypes, true),
+// RdfParser.DEFAULT_N3,
+// 0
+// },
+ });
+ }
+
+ //====================================================================================================
+ // test
+ //====================================================================================================
+ @Test
+ public void testLargeMap() throws Exception {
+ long startTime;
+ int numRuns = NUM_RUNS;
+
+ A a = A.create();
+ Serializer s = getSerializer();
+ Parser p = getParser();
+ System.err.println("\n---Speed test on " + label + "---");
+ Object r = "";
+
+ // Initialization run.
+ r = s.serialize(a);
+ System.err.println(MessageFormat.format("Serialized size: {0,number} ", (r instanceof String ? r.toString().length() : ((byte[])r).length)));
+ p.parse(r, A.class);
+
+ startTime = System.currentTimeMillis();
+ for (int i = 0; i < numRuns; i++)
+ r = s.serialize(a);
+ System.err.println(MessageFormat.format("Average serialize time: {0,number}ms", (System.currentTimeMillis()-startTime)/numRuns));
+ startTime = System.currentTimeMillis();
+ for (int i = 0; i < numRuns; i++)
+ a = p.parse(r, A.class);
+ System.err.println(MessageFormat.format("Average parsed time: {0,number}ms", (System.currentTimeMillis()-startTime)/numRuns));
+ }
+
+ public static class A {
+ public A1Map a1Map;
+ public A1List a1List;
+ public A1[] a1Array;
+
+ static A create() {
+ A a = new A();
+ a.a1Map = new A1Map();
+ a.a1List = new A1List();
+ for (int i = 0; i < SIZE_PARAM; i++) {
+ a.a1Map.put(String.valueOf(i), new A1());
+ a.a1List.add(new A1());
+ }
+ a.a1Array = a.a1List.toArray(new A1[0]);
+ return a;
+ }
+ }
+
+ public static class A1 {
+ public String f1 = "a123456789b123456789c123456789d123456789e123456789f123456789g123456789h123456789i123456789j123456789";
+ }
+
+ public static class A1Map extends LinkedHashMap<String,A1> {}
+
+ public static class A1List extends LinkedList<A1> {}
+}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/RoundTripMapsTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/RoundTripMapsTest.java b/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/RoundTripMapsTest.java
new file mode 100755
index 0000000..dbc7dff
--- /dev/null
+++ b/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/RoundTripMapsTest.java
@@ -0,0 +1,215 @@
+/***************************************************************************************************************************
+ * 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.juneau.a.rttests;
+
+import static org.apache.juneau.serializer.SerializerContext.*;
+import static org.junit.Assert.*;
+
+import java.util.*;
+
+import org.apache.juneau.html.*;
+import org.apache.juneau.json.*;
+import org.apache.juneau.parser.*;
+import org.apache.juneau.serializer.*;
+import org.apache.juneau.transforms.*;
+import org.apache.juneau.urlencoding.*;
+import org.apache.juneau.xml.*;
+import org.junit.*;
+
+
+
+/**
+ * Tests designed to serialize and parse objects to make sure we end up
+ * with the same objects for all serializers and parsers.
+ */
+@SuppressWarnings({"unchecked","deprecation"})
+public class RoundTripMapsTest extends RoundTripTest {
+
+ public RoundTripMapsTest(String label, Serializer s, Parser p, int flags) throws Exception {
+ super(label, s, p, flags);
+ }
+
+ @Override /* RoundTripTest */
+ public Class<?>[] getTransforms() {
+ return new Class<?>[]{
+ ByteArrayBase64Transform.class,
+ DateTransform.ISO8601DTZ.class,
+ CalendarLongTransform.class,
+ };
+ }
+
+ //====================================================================================================
+ // Map<Integer,String> test
+ //====================================================================================================
+ @Test
+ public void testMapIntegerString() throws Exception {
+ Map<Integer,String> t = new TreeMap<Integer,String>();
+ t.put(1, "a");
+ t.put(2, null);
+ t = roundTripMap(t, TreeMap.class, Integer.class, String.class);
+ assertEquals("a", t.get(1));
+ assertNull(null, t.get(2));
+
+ t = new HashMap<Integer,String>();
+ t.put(1, "a");
+ t.put(2, null);
+ t.put(null, "b");
+ t = roundTripMap(t, HashMap.class, Integer.class, String.class);
+ assertEquals("a", t.get(1));
+ assertNull(t.get(2));
+ assertEquals("b", t.get(null));
+ }
+
+ //====================================================================================================
+ // Map<Boolean,String> test
+ //====================================================================================================
+ @Test
+ public void testMapBooleanString() throws Exception {
+ Map<Boolean,String> t = new TreeMap<Boolean,String>();
+ t.put(true, "a");
+ t.put(false, null);
+ t = roundTripMap(t, TreeMap.class, Boolean.class, String.class);
+ assertEquals("a", t.get(true));
+ assertNull(null, t.get(false));
+
+ t = new HashMap<Boolean,String>();
+ t.put(true, "a");
+ t.put(false, null);
+ t.put(null, "b");
+ t = roundTripMap(t, HashMap.class, Boolean.class, String.class);
+ assertEquals("a", t.get(true));
+ assertNull(t.get(false));
+ assertEquals("b", t.get(null));
+ }
+
+ //====================================================================================================
+ // Map<byte[],String> test
+ //====================================================================================================
+ @Test
+ public void testMapByteArrayString() throws Exception {
+
+ // Note, you cannot really test maps with byte[] keys since byte[] does not test for equality.
+ // So just test serialization.
+ String e;
+ Object r;
+
+ Map<byte[],String> t = new LinkedHashMap<byte[],String>();
+ t.put(new byte[]{1,2,3}, "a");
+ t.put(new byte[]{4,5,6}, null);
+ t.put(null, "b");
+
+ s = new JsonSerializer.Simple().addTransforms(getTransforms()).setProperty(SERIALIZER_trimNullProperties, false);
+ e = "{AQID:'a',BAUG:null,null:'b'}";
+ r = s.serialize(t);
+ assertEquals(e, r);
+
+ s = new XmlSerializer.SimpleXmlJsonSq().addTransforms(getTransforms()).setProperty(SERIALIZER_trimNullProperties, false);
+ e = "<object><AQID>a</AQID><BAUG nil='true'/><_x0000_>b</_x0000_></object>";
+ r = s.serialize(t);
+ assertEquals(e, r);
+
+ s = new HtmlSerializer.Sq().addTransforms(getTransforms()).setProperty(SERIALIZER_trimNullProperties, false);
+ e = "<table type='object'><tr><th><string>key</string></th><th><string>value</string></th></tr><tr><td><string>AQID</string></td><td><string>a</string></td></tr><tr><td><string>BAUG</string></td><td><null/></td></tr><tr><td><null/></td><td><string>b</string></td></tr></table>";
+ r = s.serialize(t);
+ assertEquals(e, r);
+
+ s = new UonSerializer.Encoding().addTransforms(getTransforms()).setProperty(SERIALIZER_trimNullProperties, false);
+ e = "$o(AQID=a,BAUG=%00,%00=b)";
+ r = s.serialize(t);
+ assertEquals(e, r);
+
+ s = new UrlEncodingSerializer().addTransforms(getTransforms()).setProperty(SERIALIZER_trimNullProperties, false);
+ e = "AQID=a&BAUG=%00&%00=b";
+ r = s.serialize(t);
+ assertEquals(e, r);
+ }
+
+ //====================================================================================================
+ // Map<Date,String> test
+ //====================================================================================================
+ @Test
+ public void testMapDateString() throws Exception {
+ Date td1 = new Date(1,2,3,4,5,6);
+ Date td2 = new Date(2,3,4,5,6,7);
+
+ Map<Date,String> t = new TreeMap<Date,String>();
+ t.put(td1, "a");
+ t.put(td2, null);
+ t = roundTripMap(t, TreeMap.class, Date.class, String.class);
+ assertEquals("a", t.get(td1));
+ assertNull(null, t.get(td2));
+
+ t = new HashMap<Date,String>();
+ t.put(td1, "a");
+ t.put(td2, null);
+ t.put(null, "b");
+ t = roundTripMap(t, HashMap.class, Date.class, String.class);
+ assertEquals("a", t.get(td1));
+ assertNull(t.get(td2));
+ assertEquals("b", t.get(null));
+ }
+
+ //====================================================================================================
+ // Map<Calendar,String> test
+ //====================================================================================================
+ @Test
+ public void testMapCalendarString() throws Exception {
+ Calendar td1 = new GregorianCalendar();
+ td1.setTime(new Date(1,2,3,4,5,6));
+ Calendar td2 = new GregorianCalendar();
+ td2.setTime(new Date(2,3,4,5,6,7));
+
+ Map<Calendar,String> t = new TreeMap<Calendar,String>();
+ t.put(td1, "a");
+ t.put(td2, null);
+ t = roundTripMap(t, TreeMap.class, GregorianCalendar.class, String.class);
+ assertEquals("a", t.get(td1));
+ assertNull(null, t.get(td2));
+
+ t = new HashMap<Calendar,String>();
+ t.put(td1, "a");
+ t.put(td2, null);
+ t.put(null, "b");
+ t = roundTripMap(t, HashMap.class, GregorianCalendar.class, String.class);
+ assertEquals("a", t.get(td1));
+ assertNull(t.get(td2));
+ assertEquals("b", t.get(null));
+ }
+
+ //====================================================================================================
+ // Map<Enum,String> test
+ //====================================================================================================
+ @Test
+ public void testMapEnumString() throws Exception {
+
+ Map<TestEnum,String> t = new TreeMap<TestEnum,String>();
+ t.put(TestEnum.FOO, "a");
+ t.put(TestEnum.BAR, null);
+ t = roundTripMap(t, TreeMap.class, TestEnum.class, String.class);
+ assertEquals("a", t.get(TestEnum.FOO));
+ assertNull(null, t.get(TestEnum.BAR));
+
+ t = new HashMap<TestEnum,String>();
+ t.put(TestEnum.FOO, "a");
+ t.put(TestEnum.BAR, null);
+ t.put(null, "b");
+ t = roundTripMap(t, HashMap.class, TestEnum.class, String.class);
+ assertEquals("a", t.get(TestEnum.FOO));
+ assertNull(t.get(TestEnum.BAR));
+ assertEquals("b", t.get(null));
+ }
+
+ public enum TestEnum {
+ FOO,BAR,BAZ
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/RoundTripNumericConstructorsTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/RoundTripNumericConstructorsTest.java b/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/RoundTripNumericConstructorsTest.java
new file mode 100644
index 0000000..e7848d9
--- /dev/null
+++ b/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/RoundTripNumericConstructorsTest.java
@@ -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.juneau.a.rttests;
+
+import static org.apache.juneau.TestUtils.*;
+import static org.junit.Assert.*;
+
+import java.text.*;
+import java.util.*;
+
+import org.apache.juneau.dto.jsonschema.*;
+import org.apache.juneau.parser.*;
+import org.apache.juneau.serializer.*;
+import org.junit.*;
+
+
+/**
+ * Tests designed to serialize and parse objects to make sure we end up
+ * with the same objects for all serializers and parsers.
+ */
+@SuppressWarnings("hiding")
+public class RoundTripNumericConstructorsTest extends RoundTripTest {
+
+ public RoundTripNumericConstructorsTest(String label, Serializer s, Parser p, int flags) throws Exception {
+ super(label, s, p, flags);
+ }
+
+ //====================================================================================================
+ // Test parsing numbers to dates.
+ //====================================================================================================
+ @Test
+ public void testParseNumberToDate() throws Exception {
+ if (isValidationOnly())
+ return;
+
+ Serializer s = getSerializer();
+ Parser p = getParser();
+ Date d = new Date(100, 1, 1);
+
+ Object r = s.serialize(d.getTime());
+ Date d2 = p.parse(r, Date.class);
+ assertEquals(d.getTime(), d2.getTime());
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/RoundTripObjectsAsStringsTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/RoundTripObjectsAsStringsTest.java b/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/RoundTripObjectsAsStringsTest.java
new file mode 100755
index 0000000..557f600
--- /dev/null
+++ b/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/RoundTripObjectsAsStringsTest.java
@@ -0,0 +1,272 @@
+/***************************************************************************************************************************
+ * 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.juneau.a.rttests;
+
+import static org.apache.juneau.TestUtils.*;
+import static org.junit.Assert.*;
+
+import org.apache.juneau.*;
+import org.apache.juneau.parser.*;
+import org.apache.juneau.serializer.*;
+import org.junit.*;
+
+/**
+ * Tests to ensure the valueOf(String), fromString(String), parse(String), and parseString(String) methods
+ * are used correctly by parsers.
+ */
+@SuppressWarnings("unused")
+public class RoundTripObjectsAsStringsTest extends RoundTripTest {
+
+ public RoundTripObjectsAsStringsTest(String label, Serializer s, Parser p, int flags) throws Exception {
+ super(label, s, p, flags);
+ }
+
+ //====================================================================================================
+ // testBasic
+ //====================================================================================================
+ @Test
+ public void testBasic() throws Exception {
+ A t = new A().init();
+ t = roundTrip(t);
+ assertObjectEquals("{a1:{f:'1'},a2:{f:'2'},a3:{f:'3'},a4:{f:'4'}}", t);
+ }
+
+ public static class A {
+ public A1 a1;
+ public A2 a2;
+ public A3 a3;
+ public A4 a4;
+
+ public A init() {
+ a1 = new A1();
+ a1.f = "1";
+ a2 = new A2();
+ a2.f = "2";
+ a3 = new A3();
+ a3.f = "3";
+ a4 = new A4();
+ a4.f = "4";
+ return this;
+ }
+ }
+
+ public static class A1 {
+ public String f;
+ public static A1 fromString(String s) {
+ A1 x = new A1();
+ x.f = s.substring(3);
+ return x;
+ }
+ @Override /* Object */
+ public String toString() {
+ return "A1-" + f;
+ }
+ }
+
+ public static class A2 {
+ public String f;
+ public static A2 valueOf(String s) {
+ A2 x = new A2();
+ x.f = s.substring(3);
+ return x;
+ }
+ @Override /* Object */
+ public String toString() {
+ return "A2-" + f;
+ }
+ }
+
+ public static class A3 {
+ public String f;
+ public static A3 parse(String s) {
+ A3 x = new A3();
+ x.f = s.substring(3);
+ return x;
+ }
+ @Override /* Object */
+ public String toString() {
+ return "A3-" + f;
+ }
+ }
+
+ public static class A4 {
+ public String f;
+ public static A4 parseString(String s) {
+ A4 x = new A4();
+ x.f = s.substring(3);
+ return x;
+ }
+ @Override /* Object */
+ public String toString() {
+ return "A4-" + f;
+ }
+ }
+
+ //====================================================================================================
+ // testEnumWithOverriddenStringValue
+ // The B1 enum should serialize as "X1" but the B2 enum should serialize as "X-1".
+ //====================================================================================================
+ @Test
+ public void testEnumWithOverriddenStringValue() throws Exception {
+ B t = new B().init();
+ if (! returnOriginalObject) {
+ Object r = getSerializer().serialize(t);
+ assertTrue(TestUtils.toString(r).contains("X-2"));
+ }
+ t = roundTrip(t);
+ assertObjectEquals("{b1:'X1',b2:'X-2'}", t);
+ }
+
+ public static class B {
+ public B1 b1;
+ public B2 b2;
+
+ public B init() {
+ b1 = B1.X1;
+ b2 = B2.X2;
+ return this;
+ }
+
+ }
+
+ public static enum B1 {
+ X1(1),
+ X2(2),
+ X3(3);
+
+ private int i;
+ B1(int i) {
+ this.i = i;
+ }
+ }
+
+ public static enum B2 {
+ X1(1),
+ X2(2),
+ X3(3);
+
+ private int i;
+ B2(int i) {
+ this.i = i;
+ }
+
+ @Override /* Object */
+ public String toString() {
+ return "X-" + i;
+ }
+
+ public static B2 fromString(String s) {
+ return valueOf("X" + s.substring(2));
+ }
+ }
+
+ //====================================================================================================
+ // testMethodOrdering
+ //====================================================================================================
+ @Test
+ public void testOrdering() throws Exception {
+ C t = new C().init();
+ t = roundTrip(t);
+ assertObjectEquals("{c1:{f:'1'},c2:{f:'2'},c3:{f:'3'},c4:{f:'4'}}", t);
+ }
+
+ public static class C {
+ public C1 c1;
+ public C2 c2;
+ public C3 c3;
+ public C4 c4;
+
+ public C init() {
+ c1 = new C1();
+ c1.f = "1";
+ c2 = new C2();
+ c2.f = "2";
+ c3 = new C3();
+ c3.f = "3";
+ c4 = new C4();
+ c4.f = "4";
+ return this;
+ }
+ }
+
+ public static class C1 {
+ public String f;
+ public static C2 valueOf(String s) {
+ throw new RuntimeException("Shouldn't be called!");
+ }
+ public static C2 parse(String s) {
+ throw new RuntimeException("Shouldn't be called!");
+ }
+ public static C2 parseString(String s) {
+ throw new RuntimeException("Shouldn't be called!");
+ }
+ public static C1 fromString(String s) {
+ C1 x = new C1();
+ x.f = s.substring(3);
+ return x;
+ }
+
+ @Override /* Object */
+ public String toString() {
+ return "C1-" + f;
+ }
+ }
+
+ public static class C2 {
+ public String f;
+ public static C2 parse(String s) {
+ throw new RuntimeException("Shouldn't be called!");
+ }
+ public static C2 parseString(String s) {
+ throw new RuntimeException("Shouldn't be called!");
+ }
+ public static C2 valueOf(String s) {
+ C2 x = new C2();
+ x.f = s.substring(3);
+ return x;
+ }
+ @Override /* Object */
+ public String toString() {
+ return "C2-" + f;
+ }
+ }
+
+ public static class C3 {
+ public String f;
+ public static C2 parseString(String s) {
+ throw new RuntimeException("Shouldn't be called!");
+ }
+ public static C3 parse(String s) {
+ C3 x = new C3();
+ x.f = s.substring(3);
+ return x;
+ }
+ @Override /* Object */
+ public String toString() {
+ return "C3-" + f;
+ }
+ }
+
+ public static class C4 {
+ public String f;
+ public static C4 parseString(String s) {
+ C4 x = new C4();
+ x.f = s.substring(3);
+ return x;
+ }
+ @Override /* Object */
+ public String toString() {
+ return "C4" + f;
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/RoundTripObjectsWithSpecialMethodsTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/RoundTripObjectsWithSpecialMethodsTest.java b/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/RoundTripObjectsWithSpecialMethodsTest.java
new file mode 100755
index 0000000..19f83dd
--- /dev/null
+++ b/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/RoundTripObjectsWithSpecialMethodsTest.java
@@ -0,0 +1,116 @@
+/***************************************************************************************************************************
+ * 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.juneau.a.rttests;
+
+import static org.apache.juneau.TestUtils.*;
+import static org.junit.Assert.*;
+
+import java.util.*;
+
+import org.apache.juneau.annotation.*;
+import org.apache.juneau.json.*;
+import org.apache.juneau.parser.*;
+import org.apache.juneau.serializer.*;
+import org.junit.*;
+
+
+
+/**
+ * Tests designed to serialize and parse objects to make sure we end up
+ * with the same objects for all serializers and parsers.
+ */
+public class RoundTripObjectsWithSpecialMethodsTest extends RoundTripTest {
+
+ public RoundTripObjectsWithSpecialMethodsTest(String label, Serializer s, Parser p, int flags) throws Exception {
+ super(label, s, p, flags);
+ }
+
+ //====================================================================================================
+ // @NameProperty method.
+ //====================================================================================================
+ @Test
+ public void testNameProperty() throws Exception {
+ A t = new A().init();
+ t = roundTrip(t);
+ assertObjectEquals("{a2:{f2:2},m:{k1:{f2:2}}}", t);
+ if (isValidationOnly())
+ return;
+ assertEquals("a2", t.a2.name);
+ assertEquals("k1", t.m.get("k1").name);
+ }
+
+ public static class A {
+ public A2 a2;
+ public Map<String,A2> m;
+
+ A init() {
+ a2 = new A2().init();
+ m = new LinkedHashMap<String,A2>();
+ m.put("k1", new A2().init());
+ return this;
+ }
+
+ }
+ public static class A2 {
+ String name;
+ public int f2;
+
+ @NameProperty
+ protected void setName(String name) {
+ this.name = name;
+ }
+
+ A2 init() {
+ f2 = 2;
+ return this;
+ }
+ }
+
+ //====================================================================================================
+ // @ParentProperty method.
+ //====================================================================================================
+ @Test
+ public void testParentProperty() throws Exception {
+ B t = new B().init();
+ t = roundTrip(t);
+ if (isValidationOnly())
+ return;
+ assertEquals(t.f1, t.b2.parent.f1);
+ }
+
+ public static class B {
+ public int f1;
+ public B2 b2;
+
+ B init() {
+ f1 = 1;
+ b2 = new B2().init();
+ return this;
+ }
+
+ }
+ public static class B2 {
+ B parent;
+ public int f2;
+
+ @ParentProperty
+ protected void setParent(B parent) {
+ this.parent = parent;
+ }
+
+ B2 init() {
+ f2 = 2;
+ return this;
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/RoundTripPrimitiveObjectBeansTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/RoundTripPrimitiveObjectBeansTest.java b/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/RoundTripPrimitiveObjectBeansTest.java
new file mode 100755
index 0000000..20520f0
--- /dev/null
+++ b/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/RoundTripPrimitiveObjectBeansTest.java
@@ -0,0 +1,197 @@
+/***************************************************************************************************************************
+ * 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.juneau.a.rttests;
+
+import static org.junit.Assert.*;
+
+import org.apache.juneau.jena.*;
+import org.apache.juneau.parser.*;
+import org.apache.juneau.serializer.*;
+import org.apache.juneau.testbeans.*;
+import org.junit.*;
+
+/**
+ * Tests designed to serialize and parse objects to make sure we end up
+ * with the same objects for all serializers and parsers.
+ */
+public class RoundTripPrimitiveObjectBeansTest extends RoundTripTest {
+
+ public RoundTripPrimitiveObjectBeansTest(String label, Serializer s, Parser p, int flags) throws Exception {
+ super(label, s, p, flags);
+ }
+
+ //====================================================================================================
+ // testPrimitiveObjectsBean
+ //====================================================================================================
+ @Test
+ public void testPrimitiveObjectsBean() throws Exception {
+ PrimitiveObjectsBean t = new PrimitiveObjectsBean().init();
+ t = roundTrip(t, PrimitiveObjectsBean.class);
+ t = roundTrip(t, PrimitiveObjectsBean.class);
+
+ // primitives
+ assertEquals(Boolean.valueOf(true), t.poBoolean);
+ assertEquals(Byte.valueOf((byte)1), t.poByte);
+ assertEquals(Character.valueOf('a'), t.poChar);
+ assertEquals(Short.valueOf("2"), t.poShort);
+ assertEquals(Integer.valueOf(3), t.poInt);
+ assertEquals(Long.valueOf(4), t.poLong);
+ assertEquals(Float.valueOf(5), t.poFloat);
+ assertEquals(Double.valueOf(6), t.poDouble);
+ assertEquals(Integer.valueOf(7), t.poNumber);
+ assertEquals(8, t.poBigInteger.intValue());
+ assertTrue(t.poBigDecimal.floatValue() == 9f);
+
+ // uninitialized primitives
+ assertNull(t.pouBoolean);
+ assertNull(t.pouByte);
+ assertNull(t.pouChar);
+ assertNull(t.pouShort);
+ assertNull(t.pouInt);
+ assertNull(t.pouLong);
+ assertNull(t.pouFloat);
+ assertNull(t.pouDouble);
+ assertNull(t.pouNumber);
+ assertNull(t.pouBigInteger);
+ assertNull(t.pouBigDecimal);
+
+ // primitive arrays
+ assertEquals(Boolean.valueOf(false), t.poaBoolean[1][0]);
+ assertEquals(Byte.valueOf((byte)2), t.poaByte[1][0]);
+ assertEquals(Character.valueOf('b'), t.poaChar[1][0]);
+ assertEquals(Short.valueOf("2"), t.poaShort[1][0]);
+ assertEquals(Integer.valueOf(2), t.poaInt[1][0]);
+ assertEquals(Long.valueOf(2), t.poaLong[1][0]);
+ assertEquals(Float.valueOf(2), t.poaFloat[1][0]);
+ assertEquals(Double.valueOf(2), t.poaDouble[1][0]);
+ assertEquals(Integer.valueOf(2), t.poaNumber[1][0]);
+ assertEquals(2, t.poaBigInteger[1][0].intValue());
+ assertEquals(2, t.poaBigDecimal[1][0].intValue());
+ assertNull(t.poaBoolean[2]);
+ assertNull(t.poaByte[2]);
+ assertNull(t.poaChar[2]);
+ assertNull(t.poaShort[2]);
+ assertNull(t.poaInt[2]);
+ assertNull(t.poaLong[2]);
+ assertNull(t.poaFloat[2]);
+ assertNull(t.poaDouble[2]);
+ assertNull(t.poaNumber[2]);
+ assertNull(t.poaBigInteger[2]);
+ assertNull(t.poaBigDecimal[2]);
+
+ // uninitialized primitive arrays
+ assertNull(t.poauBoolean);
+ assertNull(t.poauByte);
+ assertNull(t.poauChar);
+ assertNull(t.poauShort);
+ assertNull(t.poauInt);
+ assertNull(t.poauLong);
+ assertNull(t.poauFloat);
+ assertNull(t.poauDouble);
+ assertNull(t.poauNumber);
+ assertNull(t.poauBigInteger);
+ assertNull(t.poauBigDecimal);
+
+ // anonymous list of object primitive arrays
+ assertEquals(Boolean.valueOf(true), t.poalBoolean.get(0)[0]);
+ assertEquals(Byte.valueOf((byte)1), t.poalByte.get(0)[0]);
+ assertEquals(Character.valueOf('a'), t.poalChar.get(0)[0]);
+ assertEquals(Short.valueOf((short)1), t.poalShort.get(0)[0]);
+ assertEquals(Integer.valueOf(1), t.poalInt.get(0)[0]);
+ assertEquals(Long.valueOf(1l), t.poalLong.get(0)[0]);
+ assertEquals(Float.valueOf(1f), t.poalFloat.get(0)[0]);
+ assertEquals(Double.valueOf(1d), t.poalDouble.get(0)[0]);
+ assertEquals(1, t.poalBigInteger.get(0)[0].intValue());
+ assertEquals(1, t.poalBigDecimal.get(0)[0].intValue());
+ assertNull(t.poalBoolean.get(1));
+ assertNull(t.poalByte.get(1));
+ assertNull(t.poalChar.get(1));
+ assertNull(t.poalShort.get(1));
+ assertNull(t.poalInt.get(1));
+ assertNull(t.poalLong.get(1));
+ assertNull(t.poalFloat.get(1));
+ assertNull(t.poalDouble.get(1));
+ assertNull(t.poalNumber.get(1));
+ assertNull(t.poalBigInteger.get(1));
+ assertNull(t.poalBigDecimal.get(1));
+
+ // regular list of object primitive arrays
+ assertEquals(Boolean.valueOf(true), t.polBoolean.get(0)[0]);
+ assertEquals(Byte.valueOf((byte)1), t.polByte.get(0)[0]);
+ assertEquals(Character.valueOf('a'), t.polChar.get(0)[0]);
+ assertEquals(Short.valueOf((short)1), t.polShort.get(0)[0]);
+ assertEquals(Integer.valueOf(1), t.polInt.get(0)[0]);
+ assertEquals(Long.valueOf(1l), t.polLong.get(0)[0]);
+ assertEquals(Float.valueOf(1f), t.polFloat.get(0)[0]);
+ assertEquals(Double.valueOf(1d), t.polDouble.get(0)[0]);
+ assertEquals(1, t.polBigInteger.get(0)[0].intValue());
+ assertEquals(1, t.polBigDecimal.get(0)[0].intValue());
+ assertNull(t.polBoolean.get(1));
+ assertNull(t.polByte.get(1));
+ assertNull(t.polChar.get(1));
+ assertNull(t.polShort.get(1));
+ assertNull(t.polInt.get(1));
+ assertNull(t.polLong.get(1));
+ assertNull(t.polFloat.get(1));
+ assertNull(t.polDouble.get(1));
+ assertNull(t.polNumber.get(1));
+ assertNull(t.polBigInteger.get(1));
+ assertNull(t.polBigDecimal.get(1));
+ }
+
+ //====================================================================================================
+ // testPrimitiveAtomicObjectsBean
+ //====================================================================================================
+ @Test
+ public void testPrimitiveAtomicObjectsBean() throws Exception {
+
+ // Jena does not support parsing into AtomicIntegers and AtomicLongs.
+ if (getSerializer() instanceof RdfSerializer)
+ return;
+
+ PrimitiveAtomicObjectsBean t = new PrimitiveAtomicObjectsBean().init();
+ t = roundTrip(t, PrimitiveAtomicObjectsBean.class);
+ t = roundTrip(t, PrimitiveAtomicObjectsBean.class);
+
+ // primitives
+ assertEquals(1, t.poAtomicInteger.intValue());
+ assertEquals(2, t.poAtomicLong.intValue());
+
+ // uninitialized primitives
+ assertNull(t.pouAtomicInteger);
+ assertNull(t.pouAtomicLong);
+
+ // primitive arrays
+ assertEquals(2, t.poaAtomicInteger[1][0].intValue());
+ assertEquals(2, t.poaAtomicLong[1][0].intValue());
+ assertNull(t.poaAtomicInteger[2]);
+ assertNull(t.poaAtomicLong[2]);
+
+ // uninitialized primitive arrays
+ assertNull(t.poauAtomicInteger);
+ assertNull(t.poauAtomicLong);
+
+ // anonymous list of object primitive arrays
+ assertEquals(1, t.poalAtomicInteger.get(0)[0].intValue());
+ assertEquals(1, t.poalAtomicLong.get(0)[0].intValue());
+ assertNull(t.poalAtomicInteger.get(1));
+ assertNull(t.poalAtomicLong.get(1));
+
+ // regular list of object primitive arrays
+ assertEquals(1, t.polAtomicInteger.get(0)[0].intValue());
+ assertEquals(1, t.polAtomicLong.get(0)[0].intValue());
+ assertNull(t.polAtomicInteger.get(1));
+ assertNull(t.polAtomicLong.get(1));
+ }
+
+}
[09/44] incubator-juneau git commit: Rename CT_* testcases.
Posted by ja...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/urlencoding/Common_UonTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/urlencoding/Common_UonTest.java b/org.apache.juneau/src/test/java/org/apache/juneau/urlencoding/Common_UonTest.java
new file mode 100755
index 0000000..9e2e9e4
--- /dev/null
+++ b/org.apache.juneau/src/test/java/org/apache/juneau/urlencoding/Common_UonTest.java
@@ -0,0 +1,450 @@
+/***************************************************************************************************************************
+ * 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.juneau.urlencoding;
+
+import static org.apache.juneau.TestUtils.*;
+import static org.apache.juneau.serializer.SerializerContext.*;
+import static org.junit.Assert.*;
+
+import java.net.*;
+import java.net.URI;
+import java.util.*;
+
+import org.apache.juneau.*;
+import org.apache.juneau.annotation.*;
+import org.apache.juneau.json.*;
+import org.apache.juneau.serializer.*;
+import org.apache.juneau.testbeans.*;
+import org.junit.*;
+
+@SuppressWarnings({"hiding","serial"})
+public class Common_UonTest {
+ UonParser p = UonParser.DEFAULT;
+ UonParser pe = UonParser.DEFAULT_DECODING;
+
+ //====================================================================================================
+ // Trim nulls from beans
+ //====================================================================================================
+ @Test
+ public void testTrimNullsFromBeans() throws Exception {
+ UonSerializer s = new UonSerializer.Encoding();
+ A t1 = A.create(), t2;
+
+ s.setProperty(SERIALIZER_trimNullProperties, false);
+ String r = s.serialize(t1);
+ assertEquals("$o(s1=%00,s2=s2)", r);
+ t2 = pe.parse(r, A.class);
+ assertEqualObjects(t1, t2);
+
+ s.setProperty(SERIALIZER_trimNullProperties, true);
+ r = s.serialize(t1);
+ assertEquals("$o(s2=s2)", r);
+ t2 = p.parse(r, A.class);
+ assertEqualObjects(t1, t2);
+ }
+
+ public static class A {
+ public String s1, s2;
+
+ public static A create() {
+ A t = new A();
+ t.s2 = "s2";
+ return t;
+ }
+ }
+
+ //====================================================================================================
+ // Trim empty maps
+ //====================================================================================================
+ @Test
+ public void testTrimEmptyMaps() throws Exception {
+ UonSerializer s = UonSerializer.DEFAULT_SIMPLE_ENCODING.clone();
+ B t1 = B.create(), t2;
+ String r;
+
+ s.setProperty(SERIALIZER_trimEmptyMaps, false);
+ r = s.serialize(t1);
+ assertEquals("(f1=(),f2=(f2a=%00,f2b=(s2=s2)))", r);
+ t2 = pe.parse(r, B.class);
+ assertEqualObjects(t1, t2);
+
+ s.setProperty(SERIALIZER_trimEmptyMaps, true);
+ r = s.serialize(t1);
+ assertEquals("(f2=(f2a=%00,f2b=(s2=s2)))", r);
+ t2 = pe.parse(r, B.class);
+ assertNull(t2.f1);
+ }
+
+ public static class B {
+ public TreeMap<String,A> f1, f2;
+
+ public static B create() {
+ B t = new B();
+ t.f1 = new TreeMap<String,A>();
+ t.f2 = new TreeMap<String,A>(){{put("f2a",null);put("f2b",A.create());}};
+ return t;
+ }
+ }
+
+ //====================================================================================================
+ // Trim empty lists
+ //====================================================================================================
+ @Test
+ public void testTrimEmptyLists() throws Exception {
+ UonSerializer s = new UonSerializer.Encoding();
+ C t1 = C.create(), t2;
+ String r;
+
+ s.setProperty(SERIALIZER_trimEmptyLists, false);
+ r = s.serialize(t1);
+ assertEquals("$o(f1=$a(),f2=$a(%00,$o(s2=s2)))", r);
+ t2 = pe.parse(r, C.class);
+ assertEqualObjects(t1, t2);
+
+ s.setProperty(SERIALIZER_trimEmptyLists, true);
+ r = s.serialize(t1);
+ assertEquals("$o(f2=$a(%00,$o(s2=s2)))", r);
+ t2 = pe.parse(r, C.class);
+ assertNull(t2.f1);
+ }
+
+ public static class C {
+ public List<A> f1, f2;
+
+ public static C create() {
+ C t = new C();
+ t.f1 = new LinkedList<A>();
+ t.f2 = new LinkedList<A>(){{add(null);add(A.create());}};
+ return t;
+ }
+ }
+
+ //====================================================================================================
+ // Trim empty arrays
+ //====================================================================================================
+ @Test
+ public void testTrimEmptyArrays() throws Exception {
+ UonSerializer s = new UonSerializer.Encoding();
+ D t1 = D.create(), t2;
+ String r;
+
+ s.setProperty(SERIALIZER_trimEmptyLists, false);
+ r = s.serialize(t1);
+ assertEquals("$o(f1=$a(),f2=$a(%00,$o(s2=s2)))", r);
+ t2 = pe.parse(r, D.class);
+ assertEqualObjects(t1, t2);
+
+ s.setProperty(SERIALIZER_trimEmptyLists, true);
+ r = s.serialize(t1);
+ assertEquals("$o(f2=$a(%00,$o(s2=s2)))", r);
+ t2 = pe.parse(r, D.class);
+ assertNull(t2.f1);
+ }
+
+ public static class D {
+ public A[] f1, f2;
+
+ public static D create() {
+ D t = new D();
+ t.f1 = new A[]{};
+ t.f2 = new A[]{null, A.create()};
+ return t;
+ }
+ }
+
+ //====================================================================================================
+ // @BeanProperty.properties annotation.
+ //====================================================================================================
+ @Test
+ public void testBeanPropertyProperies() throws Exception {
+ UonSerializer s = UonSerializer.DEFAULT;
+ UonSerializer ss = UonSerializer.DEFAULT_SIMPLE;
+ String ue = ss.serialize(new E1());
+ assertEquals("(x1=(f1=1),x2=(f1=1),x3=((f1=1)),x4=((f1=1)),x5=((f1=1)),x6=((f1=1)))", ue);
+ ue = s.serialize(new E1());
+ assertEquals("$o(x1=$o(f1=$n(1)),x2=$o(f1=$n(1)),x3=$a($o(f1=$n(1))),x4=$a($o(f1=$n(1))),x5=$a($o(f1=$n(1))),x6=$a($o(f1=$n(1))))", ue);
+ }
+
+ public static class E1 {
+ @BeanProperty(properties={"f1"}) public E2 x1 = new E2();
+ @BeanProperty(properties={"f1"}) public Map<String,Integer> x2 = new LinkedHashMap<String,Integer>() {{
+ put("f1",1); put("f2",2);
+ }};
+ @BeanProperty(properties={"f1"}) public E2[] x3 = {new E2()};
+ @BeanProperty(properties={"f1"}) public List<E2> x4 = new LinkedList<E2>() {{
+ add(new E2());
+ }};
+ @BeanProperty(properties={"f1"}) public ObjectMap[] x5 = {new ObjectMap().append("f1",1).append("f2",2)};
+ @BeanProperty(properties={"f1"}) public List<ObjectMap> x6 = new LinkedList<ObjectMap>() {{
+ add(new ObjectMap().append("f1",1).append("f2",2));
+ }};
+ }
+
+ public static class E2 {
+ public int f1 = 1;
+ public int f2 = 2;
+ }
+
+ //====================================================================================================
+ // @BeanProperty.properties annotation on list of beans.
+ //====================================================================================================
+ @Test
+ public void testBeanPropertyPropertiesOnListOfBeans() throws Exception {
+ UonSerializer s = UonSerializer.DEFAULT;
+ List<F> l = new LinkedList<F>();
+ F t = new F();
+ t.x1.add(new F());
+ l.add(t);
+ String xml = s.serialize(l);
+ assertEquals("$a($o(x1=$a($o(x2=$n(2))),x2=$n(2)))", xml);
+ }
+
+ public static class F {
+ @BeanProperty(properties={"x2"}) public List<F> x1 = new LinkedList<F>();
+ public int x2 = 2;
+ }
+
+ //====================================================================================================
+ // Test URIAttr - Test that URLs and URIs are serialized and parsed correctly.
+ //====================================================================================================
+ @Test
+ public void testURIAttr() throws Exception {
+ UonSerializer s = UonSerializer.DEFAULT;
+ UonParser p = UonParser.DEFAULT;
+
+ G t = new G();
+ t.uri = new URI("http://uri");
+ t.f1 = new URI("http://f1");
+ t.f2 = new URL("http://f2");
+
+ String r = s.serialize(t);
+ t = p.parse(r, G.class);
+ assertEquals("http://uri", t.uri.toString());
+ assertEquals("http://f1", t.f1.toString());
+ assertEquals("http://f2", t.f2.toString());
+ }
+
+ public static class G {
+ @BeanProperty(beanUri=true) public URI uri;
+ public URI f1;
+ public URL f2;
+ }
+
+ //====================================================================================================
+ // Test URIs with URI_CONTEXT and URI_AUTHORITY
+ //====================================================================================================
+ @Test
+ public void testUris() throws Exception {
+ WriterSerializer s = new UonSerializer();
+ TestURI t = new TestURI();
+ String r;
+ String expected;
+
+ s.setProperty(SERIALIZER_relativeUriBase, null);
+ r = s.serialize(t);
+ expected = ""
+ +"$o("
+ +"f0=f0/x0,"
+ +"f1=f1/x1,"
+ +"f2=/f2/x2,"
+ +"f3=http://www.ibm.com/f3/x3,"
+ +"f4=f4/x4,"
+ +"f5=/f5/x5,"
+ +"f6=http://www.ibm.com/f6/x6,"
+ +"f7=http://www.ibm.com/f7/x7,"
+ +"f8=f8/x8,"
+ +"f9=f9/x9,"
+ +"fa=http://www.ibm.com/fa/xa#MY_LABEL,"
+ +"fb=http://www.ibm.com/fb/xb?label~=MY_LABEL&foo~=bar,"
+ +"fc=http://www.ibm.com/fc/xc?foo~=bar&label~=MY_LABEL,"
+ +"fd=http://www.ibm.com/fd/xd?label2~=MY_LABEL&foo~=bar,"
+ +"fe=http://www.ibm.com/fe/xe?foo~=bar&label2~=MY_LABEL"
+ +")";
+ assertEquals(expected, r);
+
+ s.setProperty(SERIALIZER_relativeUriBase, ""); // Same as null.
+ r = s.serialize(t);
+ assertEquals(expected, r);
+
+ s.setProperty(SERIALIZER_relativeUriBase, "/cr");
+ r = s.serialize(t);
+ expected = ""
+ +"$o("
+ +"f0=/cr/f0/x0,"
+ +"f1=/cr/f1/x1,"
+ +"f2=/f2/x2,"
+ +"f3=http://www.ibm.com/f3/x3,"
+ +"f4=/cr/f4/x4,"
+ +"f5=/f5/x5,"
+ +"f6=http://www.ibm.com/f6/x6,"
+ +"f7=http://www.ibm.com/f7/x7,"
+ +"f8=/cr/f8/x8,"
+ +"f9=/cr/f9/x9,"
+ +"fa=http://www.ibm.com/fa/xa#MY_LABEL,"
+ +"fb=http://www.ibm.com/fb/xb?label~=MY_LABEL&foo~=bar,"
+ +"fc=http://www.ibm.com/fc/xc?foo~=bar&label~=MY_LABEL,"
+ +"fd=http://www.ibm.com/fd/xd?label2~=MY_LABEL&foo~=bar,"
+ +"fe=http://www.ibm.com/fe/xe?foo~=bar&label2~=MY_LABEL"
+ +")";
+ assertEquals(expected, r);
+
+ s.setProperty(SERIALIZER_relativeUriBase, "/cr/"); // Same as above
+ r = s.serialize(t);
+ assertEquals(expected, r);
+
+ s.setProperty(SERIALIZER_relativeUriBase, "/");
+ r = s.serialize(t);
+ expected = ""
+ +"$o("
+ +"f0=/f0/x0,"
+ +"f1=/f1/x1,"
+ +"f2=/f2/x2,"
+ +"f3=http://www.ibm.com/f3/x3,"
+ +"f4=/f4/x4,"
+ +"f5=/f5/x5,"
+ +"f6=http://www.ibm.com/f6/x6,"
+ +"f7=http://www.ibm.com/f7/x7,"
+ +"f8=/f8/x8,"
+ +"f9=/f9/x9,"
+ +"fa=http://www.ibm.com/fa/xa#MY_LABEL,"
+ +"fb=http://www.ibm.com/fb/xb?label~=MY_LABEL&foo~=bar,"
+ +"fc=http://www.ibm.com/fc/xc?foo~=bar&label~=MY_LABEL,"
+ +"fd=http://www.ibm.com/fd/xd?label2~=MY_LABEL&foo~=bar,"
+ +"fe=http://www.ibm.com/fe/xe?foo~=bar&label2~=MY_LABEL"
+ +")";
+ assertEquals(expected, r);
+
+ s.setProperty(SERIALIZER_relativeUriBase, null);
+
+ s.setProperty(SERIALIZER_absolutePathUriBase, "http://foo");
+ r = s.serialize(t);
+ expected = ""
+ +"$o("
+ +"f0=f0/x0,"
+ +"f1=f1/x1,"
+ +"f2=http://foo/f2/x2,"
+ +"f3=http://www.ibm.com/f3/x3,"
+ +"f4=f4/x4,"
+ +"f5=http://foo/f5/x5,"
+ +"f6=http://www.ibm.com/f6/x6,"
+ +"f7=http://www.ibm.com/f7/x7,"
+ +"f8=f8/x8,"
+ +"f9=f9/x9,"
+ +"fa=http://www.ibm.com/fa/xa#MY_LABEL,"
+ +"fb=http://www.ibm.com/fb/xb?label~=MY_LABEL&foo~=bar,"
+ +"fc=http://www.ibm.com/fc/xc?foo~=bar&label~=MY_LABEL,"
+ +"fd=http://www.ibm.com/fd/xd?label2~=MY_LABEL&foo~=bar,"
+ +"fe=http://www.ibm.com/fe/xe?foo~=bar&label2~=MY_LABEL"
+ +")";
+ assertEquals(expected, r);
+
+ s.setProperty(SERIALIZER_absolutePathUriBase, "http://foo/");
+ r = s.serialize(t);
+ assertEquals(expected, r);
+
+ s.setProperty(SERIALIZER_absolutePathUriBase, ""); // Same as null.
+ r = s.serialize(t);
+ expected = ""
+ +"$o("
+ +"f0=f0/x0,"
+ +"f1=f1/x1,"
+ +"f2=/f2/x2,"
+ +"f3=http://www.ibm.com/f3/x3,"
+ +"f4=f4/x4,"
+ +"f5=/f5/x5,"
+ +"f6=http://www.ibm.com/f6/x6,"
+ +"f7=http://www.ibm.com/f7/x7,"
+ +"f8=f8/x8,"
+ +"f9=f9/x9,"
+ +"fa=http://www.ibm.com/fa/xa#MY_LABEL,"
+ +"fb=http://www.ibm.com/fb/xb?label~=MY_LABEL&foo~=bar,"
+ +"fc=http://www.ibm.com/fc/xc?foo~=bar&label~=MY_LABEL,"
+ +"fd=http://www.ibm.com/fd/xd?label2~=MY_LABEL&foo~=bar,"
+ +"fe=http://www.ibm.com/fe/xe?foo~=bar&label2~=MY_LABEL"
+ +")";
+ assertEquals(expected, r);
+ }
+
+ //====================================================================================================
+ // Validate that you cannot update properties on locked serializer.
+ //====================================================================================================
+ @Test
+ public void testLockedSerializer() throws Exception {
+ UonSerializer s = new UonSerializer().lock();
+ try {
+ s.setProperty(JsonSerializerContext.JSON_simpleMode, true);
+ fail("Locked exception not thrown");
+ } catch (LockedException e) {}
+ try {
+ s.setProperty(SerializerContext.SERIALIZER_addClassAttrs, true);
+ fail("Locked exception not thrown");
+ } catch (LockedException e) {}
+ try {
+ s.setProperty(BeanContext.BEAN_beanMapPutReturnsOldValue, true);
+ fail("Locked exception not thrown");
+ } catch (LockedException e) {}
+ }
+
+ //====================================================================================================
+ // Recursion
+ //====================================================================================================
+ @Test
+ public void testRecursion() throws Exception {
+ WriterSerializer s = new UonSerializer();
+
+ R1 r1 = new R1();
+ R2 r2 = new R2();
+ R3 r3 = new R3();
+ r1.r2 = r2;
+ r2.r3 = r3;
+ r3.r1 = r1;
+
+ // No recursion detection
+ try {
+ s.serialize(r1);
+ fail("Exception expected!");
+ } catch (Exception e) {
+ String msg = e.getLocalizedMessage();
+ assertTrue(msg.contains("It's recommended you use the SerializerContext.SERIALIZER_detectRecursions setting to help locate the loop."));
+ }
+
+ // Recursion detection, no ignore
+ s.setProperty(SERIALIZER_detectRecursions, true);
+ try {
+ s.serialize(r1);
+ fail("Exception expected!");
+ } catch (Exception e) {
+ String msg = e.getLocalizedMessage();
+ assertTrue(msg.contains("[0]root:org.apache.juneau.urlencoding.Common_UonTest$R1"));
+ assertTrue(msg.contains("->[1]r2:org.apache.juneau.urlencoding.Common_UonTest$R2"));
+ assertTrue(msg.contains("->[2]r3:org.apache.juneau.urlencoding.Common_UonTest$R3"));
+ assertTrue(msg.contains("->[3]r1:org.apache.juneau.urlencoding.Common_UonTest$R1"));
+ }
+
+ s.setProperty(SERIALIZER_ignoreRecursions, true);
+ assertEquals("$o(name=foo,r2=$o(name=bar,r3=$o(name=baz)))", s.serialize(r1));
+ }
+
+ public static class R1 {
+ public String name = "foo";
+ public R2 r2;
+ }
+ public static class R2 {
+ public String name = "bar";
+ public R3 r3;
+ }
+ public static class R3 {
+ public String name = "baz";
+ public R1 r1;
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/urlencoding/Common_UrlEncodingTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/urlencoding/Common_UrlEncodingTest.java b/org.apache.juneau/src/test/java/org/apache/juneau/urlencoding/Common_UrlEncodingTest.java
new file mode 100755
index 0000000..dbd8518
--- /dev/null
+++ b/org.apache.juneau/src/test/java/org/apache/juneau/urlencoding/Common_UrlEncodingTest.java
@@ -0,0 +1,442 @@
+/***************************************************************************************************************************
+ * 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.juneau.urlencoding;
+
+import static org.apache.juneau.TestUtils.*;
+import static org.apache.juneau.serializer.SerializerContext.*;
+import static org.junit.Assert.*;
+
+import java.net.*;
+import java.net.URI;
+import java.util.*;
+
+import org.apache.juneau.*;
+import org.apache.juneau.annotation.*;
+import org.apache.juneau.json.*;
+import org.apache.juneau.serializer.*;
+import org.apache.juneau.testbeans.*;
+import org.junit.*;
+
+@SuppressWarnings({"hiding","serial"})
+public class Common_UrlEncodingTest {
+ UrlEncodingParser p = UrlEncodingParser.DEFAULT;
+
+ //====================================================================================================
+ // Trim nulls from beans
+ //====================================================================================================
+ @Test
+ public void testTrimNullsFromBeans() throws Exception {
+ UrlEncodingSerializer s = new UrlEncodingSerializer();
+ A t1 = A.create(), t2;
+
+ s.setProperty(SERIALIZER_trimNullProperties, false);
+ String r = s.serialize(t1);
+ assertEquals("s1=%00&s2=s2", r);
+ t2 = p.parse(r, A.class);
+ assertEqualObjects(t1, t2);
+
+ s.setProperty(SERIALIZER_trimNullProperties, true);
+ r = s.serialize(t1);
+ assertEquals("s2=s2", r);
+ t2 = p.parse(r, A.class);
+ assertEqualObjects(t1, t2);
+ }
+
+ public static class A {
+ public String s1, s2;
+
+ public static A create() {
+ A t = new A();
+ t.s2 = "s2";
+ return t;
+ }
+ }
+
+ //====================================================================================================
+ // Trim empty maps
+ //====================================================================================================
+ @Test
+ public void testTrimEmptyMaps() throws Exception {
+ UrlEncodingSerializer s = UrlEncodingSerializer.DEFAULT_SIMPLE.clone();
+ B t1 = B.create(), t2;
+ String r;
+
+ s.setProperty(SERIALIZER_trimEmptyMaps, false);
+ r = s.serialize(t1);
+ assertEquals("f1=()&f2=(f2a=%00,f2b=(s2=s2))", r);
+ t2 = p.parse(r, B.class);
+ assertEqualObjects(t1, t2);
+
+ s.setProperty(SERIALIZER_trimEmptyMaps, true);
+ r = s.serialize(t1);
+ assertEquals("f2=(f2a=%00,f2b=(s2=s2))", r);
+ t2 = p.parse(r, B.class);
+ assertNull(t2.f1);
+ }
+
+ public static class B {
+ public TreeMap<String,A> f1, f2;
+
+ public static B create() {
+ B t = new B();
+ t.f1 = new TreeMap<String,A>();
+ t.f2 = new TreeMap<String,A>(){{put("f2a",null);put("f2b",A.create());}};
+ return t;
+ }
+ }
+
+ //====================================================================================================
+ // Trim empty lists
+ //====================================================================================================
+ @Test
+ public void testTrimEmptyLists() throws Exception {
+ UrlEncodingSerializer s = new UrlEncodingSerializer();
+ C t1 = C.create(), t2;
+ String r;
+
+ s.setProperty(SERIALIZER_trimEmptyLists, false);
+ r = s.serialize(t1);
+ assertEquals("f1=$a()&f2=$a(%00,$o(s2=s2))", r);
+ t2 = p.parse(r, C.class);
+ assertEqualObjects(t1, t2);
+
+ s.setProperty(SERIALIZER_trimEmptyLists, true);
+ r = s.serialize(t1);
+ assertEquals("f2=$a(%00,$o(s2=s2))", r);
+ t2 = p.parse(r, C.class);
+ assertNull(t2.f1);
+ }
+
+ public static class C {
+ public List<A> f1, f2;
+
+ public static C create() {
+ C t = new C();
+ t.f1 = new LinkedList<A>();
+ t.f2 = new LinkedList<A>(){{add(null);add(A.create());}};
+ return t;
+ }
+ }
+
+ //====================================================================================================
+ // Trim empty arrays
+ //====================================================================================================
+ @Test
+ public void testTrimEmptyArrays() throws Exception {
+ UrlEncodingSerializer s = new UrlEncodingSerializer();
+ D t1 = D.create(), t2;
+ String r;
+
+ s.setProperty(SERIALIZER_trimEmptyLists, false);
+ r = s.serialize(t1);
+ assertEquals("f1=$a()&f2=$a(%00,$o(s2=s2))", r);
+ t2 = p.parse(r, D.class);
+ assertEqualObjects(t1, t2);
+
+ s.setProperty(SERIALIZER_trimEmptyLists, true);
+ r = s.serialize(t1);
+ assertEquals("f2=$a(%00,$o(s2=s2))", r);
+ t2 = p.parse(r, D.class);
+ assertNull(t2.f1);
+ }
+
+ public static class D {
+ public A[] f1, f2;
+
+ public static D create() {
+ D t = new D();
+ t.f1 = new A[]{};
+ t.f2 = new A[]{null, A.create()};
+ return t;
+ }
+ }
+
+ //====================================================================================================
+ // @BeanProperty.properties annotation.
+ //====================================================================================================
+ @Test
+ public void testBeanPropertyProperies() throws Exception {
+ UrlEncodingSerializer s = UrlEncodingSerializer.DEFAULT;
+ UrlEncodingSerializer ss = UrlEncodingSerializer.DEFAULT_SIMPLE;
+ String ue = ss.serialize(new E1());
+ assertEquals("x1=(f1=1)&x2=(f1=1)&x3=((f1=1))&x4=((f1=1))&x5=((f1=1))&x6=((f1=1))", ue);
+ ue = s.serialize(new E1());
+ assertEquals("x1=$o(f1=$n(1))&x2=$o(f1=$n(1))&x3=$a($o(f1=$n(1)))&x4=$a($o(f1=$n(1)))&x5=$a($o(f1=$n(1)))&x6=$a($o(f1=$n(1)))", ue);
+ }
+
+ public static class E1 {
+ @BeanProperty(properties={"f1"}) public E2 x1 = new E2();
+ @BeanProperty(properties={"f1"}) public Map<String,Integer> x2 = new LinkedHashMap<String,Integer>() {{
+ put("f1",1); put("f2",2);
+ }};
+ @BeanProperty(properties={"f1"}) public E2[] x3 = {new E2()};
+ @BeanProperty(properties={"f1"}) public List<E2> x4 = new LinkedList<E2>() {{
+ add(new E2());
+ }};
+ @BeanProperty(properties={"f1"}) public ObjectMap[] x5 = {new ObjectMap().append("f1",1).append("f2",2)};
+ @BeanProperty(properties={"f1"}) public List<ObjectMap> x6 = new LinkedList<ObjectMap>() {{
+ add(new ObjectMap().append("f1",1).append("f2",2));
+ }};
+ }
+
+ public static class E2 {
+ public int f1 = 1;
+ public int f2 = 2;
+ }
+
+ //====================================================================================================
+ // @BeanProperty.properties annotation on list of beans.
+ //====================================================================================================
+ @Test
+ public void testBeanPropertyPropertiesOnListOfBeans() throws Exception {
+ UrlEncodingSerializer s = UrlEncodingSerializer.DEFAULT;
+ List<F> l = new LinkedList<F>();
+ F t = new F();
+ t.x1.add(new F());
+ l.add(t);
+ ObjectMap m = new ObjectMap().append("t", l);
+ String xml = s.serialize(m);
+ assertEquals("t=$a($o(x1=$a($o(x2=$n(2))),x2=$n(2)))", xml);
+ xml = s.serialize(l);
+ assertEquals("$n(0)=$o(x1=$a($o(x2=$n(2))),x2=$n(2))", xml);
+ }
+
+ public static class F {
+ @BeanProperty(properties={"x2"}) public List<F> x1 = new LinkedList<F>();
+ public int x2 = 2;
+ }
+
+ //====================================================================================================
+ // Test URIAttr - Test that URLs and URIs are serialized and parsed correctly.
+ //====================================================================================================
+ @Test
+ public void testURIAttr() throws Exception {
+ UrlEncodingSerializer s = UrlEncodingSerializer.DEFAULT;
+ UrlEncodingParser p = UrlEncodingParser.DEFAULT;
+
+ G t = new G();
+ t.uri = new URI("http://uri");
+ t.f1 = new URI("http://f1");
+ t.f2 = new URL("http://f2");
+
+ String r = s.serialize(t);
+ t = p.parse(r, G.class);
+ assertEquals("http://uri", t.uri.toString());
+ assertEquals("http://f1", t.f1.toString());
+ assertEquals("http://f2", t.f2.toString());
+ }
+
+ public static class G {
+ @BeanProperty(beanUri=true) public URI uri;
+ public URI f1;
+ public URL f2;
+ }
+
+ //====================================================================================================
+ // Test URIs with URI_CONTEXT and URI_AUTHORITY
+ //====================================================================================================
+ @Test
+ public void testUris() throws Exception {
+ WriterSerializer s = new UrlEncodingSerializer();
+ TestURI t = new TestURI();
+ String r;
+ String expected = "";
+
+ s.setProperty(SERIALIZER_relativeUriBase, null);
+ r = s.serialize(t);
+ expected = ""
+ +"f0=f0/x0"
+ +"&f1=f1/x1"
+ +"&f2=/f2/x2"
+ +"&f3=http://www.ibm.com/f3/x3"
+ +"&f4=f4/x4"
+ +"&f5=/f5/x5"
+ +"&f6=http://www.ibm.com/f6/x6"
+ +"&f7=http://www.ibm.com/f7/x7"
+ +"&f8=f8/x8"
+ +"&f9=f9/x9"
+ +"&fa=http://www.ibm.com/fa/xa%23MY_LABEL"
+ +"&fb=http://www.ibm.com/fb/xb?label=MY_LABEL%26foo=bar"
+ +"&fc=http://www.ibm.com/fc/xc?foo=bar%26label=MY_LABEL"
+ +"&fd=http://www.ibm.com/fd/xd?label2=MY_LABEL%26foo=bar"
+ +"&fe=http://www.ibm.com/fe/xe?foo=bar%26label2=MY_LABEL";
+ assertEquals(expected, r);
+
+ s.setProperty(SERIALIZER_relativeUriBase, ""); // Same as null.
+ r = s.serialize(t);
+ assertEquals(expected, r);
+
+ s.setProperty(SERIALIZER_relativeUriBase, "/cr");
+ r = s.serialize(t);
+ expected = ""
+ +"f0=/cr/f0/x0"
+ +"&f1=/cr/f1/x1"
+ +"&f2=/f2/x2"
+ +"&f3=http://www.ibm.com/f3/x3"
+ +"&f4=/cr/f4/x4"
+ +"&f5=/f5/x5"
+ +"&f6=http://www.ibm.com/f6/x6"
+ +"&f7=http://www.ibm.com/f7/x7"
+ +"&f8=/cr/f8/x8"
+ +"&f9=/cr/f9/x9"
+ +"&fa=http://www.ibm.com/fa/xa%23MY_LABEL"
+ +"&fb=http://www.ibm.com/fb/xb?label=MY_LABEL%26foo=bar"
+ +"&fc=http://www.ibm.com/fc/xc?foo=bar%26label=MY_LABEL"
+ +"&fd=http://www.ibm.com/fd/xd?label2=MY_LABEL%26foo=bar"
+ +"&fe=http://www.ibm.com/fe/xe?foo=bar%26label2=MY_LABEL";
+ assertEquals(expected, r);
+
+ s.setProperty(SERIALIZER_relativeUriBase, "/cr/"); // Same as above
+ r = s.serialize(t);
+ assertEquals(expected, r);
+
+ s.setProperty(SERIALIZER_relativeUriBase, "/");
+ r = s.serialize(t);
+ expected = ""
+ +"f0=/f0/x0"
+ +"&f1=/f1/x1"
+ +"&f2=/f2/x2"
+ +"&f3=http://www.ibm.com/f3/x3"
+ +"&f4=/f4/x4"
+ +"&f5=/f5/x5"
+ +"&f6=http://www.ibm.com/f6/x6"
+ +"&f7=http://www.ibm.com/f7/x7"
+ +"&f8=/f8/x8"
+ +"&f9=/f9/x9"
+ +"&fa=http://www.ibm.com/fa/xa%23MY_LABEL"
+ +"&fb=http://www.ibm.com/fb/xb?label=MY_LABEL%26foo=bar"
+ +"&fc=http://www.ibm.com/fc/xc?foo=bar%26label=MY_LABEL"
+ +"&fd=http://www.ibm.com/fd/xd?label2=MY_LABEL%26foo=bar"
+ +"&fe=http://www.ibm.com/fe/xe?foo=bar%26label2=MY_LABEL";
+ assertEquals(expected, r);
+
+ s.setProperty(SERIALIZER_relativeUriBase, null);
+
+ s.setProperty(SERIALIZER_absolutePathUriBase, "http://foo");
+ r = s.serialize(t);
+ expected = ""
+ +"f0=f0/x0"
+ +"&f1=f1/x1"
+ +"&f2=http://foo/f2/x2"
+ +"&f3=http://www.ibm.com/f3/x3"
+ +"&f4=f4/x4"
+ +"&f5=http://foo/f5/x5"
+ +"&f6=http://www.ibm.com/f6/x6"
+ +"&f7=http://www.ibm.com/f7/x7"
+ +"&f8=f8/x8"
+ +"&f9=f9/x9"
+ +"&fa=http://www.ibm.com/fa/xa%23MY_LABEL"
+ +"&fb=http://www.ibm.com/fb/xb?label=MY_LABEL%26foo=bar"
+ +"&fc=http://www.ibm.com/fc/xc?foo=bar%26label=MY_LABEL"
+ +"&fd=http://www.ibm.com/fd/xd?label2=MY_LABEL%26foo=bar"
+ +"&fe=http://www.ibm.com/fe/xe?foo=bar%26label2=MY_LABEL";
+ assertEquals(expected, r);
+
+ s.setProperty(SERIALIZER_absolutePathUriBase, "http://foo/");
+ r = s.serialize(t);
+ assertEquals(expected, r);
+
+ s.setProperty(SERIALIZER_absolutePathUriBase, ""); // Same as null.
+ r = s.serialize(t);
+ expected = ""
+ +"f0=f0/x0"
+ +"&f1=f1/x1"
+ +"&f2=/f2/x2"
+ +"&f3=http://www.ibm.com/f3/x3"
+ +"&f4=f4/x4"
+ +"&f5=/f5/x5"
+ +"&f6=http://www.ibm.com/f6/x6"
+ +"&f7=http://www.ibm.com/f7/x7"
+ +"&f8=f8/x8"
+ +"&f9=f9/x9"
+ +"&fa=http://www.ibm.com/fa/xa%23MY_LABEL"
+ +"&fb=http://www.ibm.com/fb/xb?label=MY_LABEL%26foo=bar"
+ +"&fc=http://www.ibm.com/fc/xc?foo=bar%26label=MY_LABEL"
+ +"&fd=http://www.ibm.com/fd/xd?label2=MY_LABEL%26foo=bar"
+ +"&fe=http://www.ibm.com/fe/xe?foo=bar%26label2=MY_LABEL";
+ assertEquals(expected, r);
+ }
+
+ //====================================================================================================
+ // Validate that you cannot update properties on locked serializer.
+ //====================================================================================================
+ @Test
+ public void testLockedSerializer() throws Exception {
+ UrlEncodingSerializer s = new UrlEncodingSerializer().lock();
+ try {
+ s.setProperty(JsonSerializerContext.JSON_simpleMode, true);
+ fail("Locked exception not thrown");
+ } catch (LockedException e) {}
+ try {
+ s.setProperty(SerializerContext.SERIALIZER_addClassAttrs, true);
+ fail("Locked exception not thrown");
+ } catch (LockedException e) {}
+ try {
+ s.setProperty(BeanContext.BEAN_beanMapPutReturnsOldValue, true);
+ fail("Locked exception not thrown");
+ } catch (LockedException e) {}
+ }
+
+ //====================================================================================================
+ // Recursion
+ //====================================================================================================
+ @Test
+ public void testRecursion() throws Exception {
+ WriterSerializer s = new UrlEncodingSerializer();
+
+ R1 r1 = new R1();
+ R2 r2 = new R2();
+ R3 r3 = new R3();
+ r1.r2 = r2;
+ r2.r3 = r3;
+ r3.r1 = r1;
+
+ // No recursion detection
+ try {
+ s.serialize(r1);
+ fail("Exception expected!");
+ } catch (Exception e) {
+ String msg = e.getLocalizedMessage();
+ assertTrue(msg.contains("It's recommended you use the SerializerContext.SERIALIZER_detectRecursions setting to help locate the loop."));
+ }
+
+ // Recursion detection, no ignore
+ s.setProperty(SERIALIZER_detectRecursions, true);
+ try {
+ s.serialize(r1);
+ fail("Exception expected!");
+ } catch (Exception e) {
+ String msg = e.getLocalizedMessage();
+ assertTrue(msg.contains("[0]root:org.apache.juneau.urlencoding.Common_UrlEncodingTest$R1"));
+ assertTrue(msg.contains("->[1]r2:org.apache.juneau.urlencoding.Common_UrlEncodingTest$R2"));
+ assertTrue(msg.contains("->[2]r3:org.apache.juneau.urlencoding.Common_UrlEncodingTest$R3"));
+ assertTrue(msg.contains("->[3]r1:org.apache.juneau.urlencoding.Common_UrlEncodingTest$R1"));
+ }
+
+ s.setProperty(SERIALIZER_ignoreRecursions, true);
+ assertEquals("name=foo&r2=$o(name=bar,r3=$o(name=baz))", s.serialize(r1));
+ }
+
+ public static class R1 {
+ public String name = "foo";
+ public R2 r2;
+ }
+ public static class R2 {
+ public String name = "bar";
+ public R3 r3;
+ }
+ public static class R3 {
+ public String name = "baz";
+ public R1 r1;
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/urlencoding/UonParserReaderTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/urlencoding/UonParserReaderTest.java b/org.apache.juneau/src/test/java/org/apache/juneau/urlencoding/UonParserReaderTest.java
new file mode 100755
index 0000000..3a38a36
--- /dev/null
+++ b/org.apache.juneau/src/test/java/org/apache/juneau/urlencoding/UonParserReaderTest.java
@@ -0,0 +1,217 @@
+/***************************************************************************************************************************
+ * 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.juneau.urlencoding;
+
+import static org.junit.Assert.*;
+
+import java.io.*;
+
+import org.apache.juneau.*;
+import org.junit.*;
+
+public class UonParserReaderTest {
+
+ //====================================================================================================
+ // Basic tests
+ //====================================================================================================
+ @Test
+ public void testBasic() throws Exception {
+
+ UonReader r;
+ String s, in;
+ r = r("f", true);
+ assertEquals('f', r.read());
+ assertEquals(-1, r.read());
+
+ r = r("%66", true);
+ assertEquals('f', r.read());
+ assertEquals(-1, r.read());
+
+ r = r("%7D", true);
+ assertEquals('}', r.read());
+ assertEquals(-1, r.read());
+
+ r = r("%7D%7D", true);
+ assertEquals('}', r.read());
+ assertEquals('}', r.read());
+ assertEquals(-1, r.read());
+
+ r = r("%00%00", true);
+ r.mark();
+ assertEquals(0, r.read());
+ assertEquals(0, r.read());
+ assertEquals("\u0000\u0000", r.getMarked());
+ assertEquals(-1, r.read());
+
+ in = escape("\u0080");
+ r = r(in, true);
+ assertEquals('\u0080', r.read());
+ assertEquals(-1, r.read());
+
+ in = escape("\u0800");
+ r = r(in, true);
+ assertEquals('\u0800', r.read());
+ assertEquals(-1, r.read());
+
+ in = escape("\uffff");
+ r = r(in, true);
+ assertEquals('\uffff', r.read());
+ assertEquals(-1, r.read());
+
+ // 2-byte codepoint
+ s = "�";
+ r = r(escape(s), true);
+ assertEquals(s.codePointAt(0), r.read());
+ assertEquals(-1, r.read());
+
+ // 3-byte codepoint
+ s = "\u20ac";
+ r = r(escape(s), true);
+ assertEquals(s.codePointAt(0), r.readCodePoint());
+ assertEquals(-1, r.read());
+
+ // 4-byte codepoint
+ s = "\U00024b62";
+ r = r(escape(s), true);
+ assertEquals(s.codePointAt(0), r.readCodePoint());
+ assertEquals(-1, r.read());
+
+ s = "\U00024b62\U00024b62";
+ r = r(escape(s), true);
+ assertEquals(s.codePointAt(0), r.readCodePoint());
+ assertEquals(s.codePointAt(2), r.readCodePoint());
+ assertEquals(-1, r.read());
+
+ // Multiple codepoints
+ s = "�\u20ac\U00024b62�\u20ac\U00024b62";
+ in = escape(s);
+ r = r(in, true);
+ assertEquals(s.codePointAt(0), r.readCodePoint());
+ assertEquals(s.codePointAt(1), r.readCodePoint());
+ assertEquals(s.codePointAt(2), r.readCodePoint());
+ assertEquals(s.codePointAt(4), r.readCodePoint());
+ assertEquals(s.codePointAt(5), r.readCodePoint());
+ assertEquals(s.codePointAt(6), r.readCodePoint());
+ assertEquals(-1, r.read());
+
+ // Multiple codepoints read in small chunks.
+ s = "�\u20ac\U00024b62�\u20ac\U00024b62";
+ String s2;
+ int i;
+ in = escape(s);
+ r = r(in, true);
+ char[] buff = new char[2];
+ i = r.read(buff, 0, buff.length);
+ s2 = new String(buff, 0, i);
+ assertEquals("�", s2);
+ i = r.read(buff, 0, buff.length);
+ s2 = new String(buff, 0, i);
+ assertEquals("\u20ac", s2);
+ i = r.read(buff, 0, buff.length);
+ s2 = new String(buff, 0, i);
+ assertEquals("\U00024b62", s2);
+ i = r.read(buff, 0, buff.length);
+ s2 = new String(buff, 0, i);
+ assertEquals("�", s2);
+ i = r.read(buff, 0, buff.length);
+ s2 = new String(buff, 0, i);
+ assertEquals("\u20ac", s2);
+ i = r.read(buff, 0, buff.length);
+ s2 = new String(buff, 0, i);
+ assertEquals("\U00024b62", s2);
+ i = r.read(buff, 0, buff.length);
+ assertEquals(-1, i);
+
+ // Multiple codepoints read in slightly larger chunks.
+ s = "�\u20ac\U00024b62�\u20ac\U00024b62";
+ in = escape(s);
+ r = r(in, true);
+ buff = new char[3];
+ i = r.read(buff, 0, buff.length);
+ s2 = new String(buff, 0, i);
+ assertEquals("�\u20ac", s2);
+ i = r.read(buff, 0, buff.length);
+ s2 = new String(buff, 0, i);
+ assertEquals("\U00024b62", s2);
+ i = r.read(buff, 0, buff.length);
+ s2 = new String(buff, 0, i);
+ assertEquals("�\u20ac", s2);
+ i = r.read(buff, 0, buff.length);
+ s2 = new String(buff, 0, i);
+ assertEquals("\U00024b62", s2);
+ i = r.read(buff, 0, buff.length);
+ assertEquals(-1, i);
+
+ s = "�\u20ac\U00024b62�\u20ac\U00024b62";
+ in = escape(s);
+ r = r(in, true);
+ buff = new char[4];
+ i = r.read(buff, 0, buff.length);
+ s2 = new String(buff, 0, i);
+ assertEquals("�\u20ac\U00024b62", s2);
+ i = r.read(buff, 0, buff.length);
+ s2 = new String(buff, 0, i);
+ assertEquals("�\u20ac\U00024b62", s2);
+ i = r.read(buff, 0, buff.length);
+ assertEquals(-1, i);
+
+ // Reader that only returns 1 character at a time;
+ s = "x�\u20ac\U00024b62x�\u20ac\U00024b62";
+ in = "x" + escape("�\u20ac\U00024b62") + "x" + escape("�\u20ac\U00024b62");
+ r = new UonReader(new SlowStringReader(in), true);
+ assertEquals(s.codePointAt(0), r.readCodePoint());
+ assertEquals(s.codePointAt(1), r.readCodePoint());
+ assertEquals(s.codePointAt(2), r.readCodePoint());
+ assertEquals(s.codePointAt(3), r.readCodePoint());
+ assertEquals(s.codePointAt(5), r.readCodePoint());
+ assertEquals(s.codePointAt(6), r.readCodePoint());
+ assertEquals(s.codePointAt(7), r.readCodePoint());
+ assertEquals(s.codePointAt(8), r.readCodePoint());
+ assertEquals(-1, r.readCodePoint());
+ }
+
+ private String escape(String s) throws UnsupportedEncodingException {
+ StringBuilder sb = new StringBuilder();
+ byte[] b = s.getBytes("UTF-8");
+ for (int i = 0; i < b.length; i++)
+ sb.append('%').append(TestUtils.toHex(b[i]));
+ return sb.toString();
+ }
+
+ private UonReader r(String in, boolean decodeChars) {
+ return new UonReader(in, decodeChars);
+ }
+
+ private static class SlowStringReader extends Reader {
+
+ String s;
+ int i = 0;
+
+ SlowStringReader(String s) {
+ this.s = s;
+ }
+
+ @Override /* Reader */
+ public int read(char[] cbuf, int off, int len) throws IOException {
+ if (i >= s.length())
+ return -1;
+ cbuf[off] = s.charAt(i++);
+ return 1;
+ }
+
+ @Override /* Reader */
+ public void close() throws IOException {
+ }
+
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/urlencoding/UonParserTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/urlencoding/UonParserTest.java b/org.apache.juneau/src/test/java/org/apache/juneau/urlencoding/UonParserTest.java
new file mode 100755
index 0000000..ae67e27
--- /dev/null
+++ b/org.apache.juneau/src/test/java/org/apache/juneau/urlencoding/UonParserTest.java
@@ -0,0 +1,542 @@
+/***************************************************************************************************************************
+ * 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.juneau.urlencoding;
+
+import static org.junit.Assert.*;
+
+import java.util.*;
+
+import org.apache.juneau.parser.*;
+import org.junit.*;
+
+@SuppressWarnings({"rawtypes","unchecked","hiding"})
+public class UonParserTest {
+
+ static UonParser p = UonParser.DEFAULT;
+ static UonParser pe = UonParser.DEFAULT_DECODING;
+
+ //====================================================================================================
+ // Basic test
+ //====================================================================================================
+ @Test
+ public void testBasic() throws Exception {
+
+ String t;
+ Map m;
+
+ // Simple string
+ // Top level
+ t = "a";
+ assertEquals("a", p.parse(t, String.class));
+ assertEquals("a", p.parse(t, Object.class));
+ assertEquals("a", pe.parse(t, String.class));
+ t = "(a)";
+ assertEquals("a", p.parse(t, String.class));
+ assertEquals("a", p.parse(t, Object.class));
+ t = "$s(a)";
+ assertEquals("a", p.parse(t, String.class));
+
+ // 2nd level
+ t = "$o(a=a)";
+ assertEquals("a", p.parse(t, Map.class).get("a"));
+ assertEquals("a", pe.parse(t, Map.class).get("a"));
+
+ t = "(a=a)";
+ assertEquals("a", p.parse(t, Map.class).get("a"));
+ assertEquals("a", pe.parse(t, Map.class).get("a"));
+
+ // Simple map
+ // Top level
+ t = "$o(a=b,c=$n(123),d=$b(false),e=$b(true),f=%00)";
+ m = p.parse(t, Map.class);
+ assertEquals("b", m.get("a"));
+ assertTrue(m.get("c") instanceof Number);
+ assertEquals(123, m.get("c"));
+ assertTrue(m.get("d") instanceof Boolean);
+ assertEquals(Boolean.FALSE, m.get("d"));
+ assertTrue(m.get("e") instanceof Boolean);
+ assertEquals(Boolean.TRUE, m.get("e"));
+ m = pe.parse(t, Map.class);
+ assertNull(m.get("f"));
+
+ t = "(a=true)";
+ m = p.parseMap(t, HashMap.class, String.class, Boolean.class);
+ assertTrue(m.get("a") instanceof Boolean);
+ assertEquals("true", m.get("a").toString());
+
+ // null
+ // Top level
+ t = "%00";
+ assertEquals("%00", p.parse(t, Object.class));
+ assertNull(pe.parse(t, Object.class));
+
+ // 2nd level
+ t = "$o(%00=%00)";
+ m = p.parse(t, Map.class);
+ assertEquals("%00", m.get("%00"));
+ m = pe.parse(t, Map.class);
+ assertTrue(m.containsKey(null));
+ assertNull(m.get(null));
+
+ t = "(%00=%00)";
+ m = p.parse(t, Map.class);
+ assertEquals("%00", m.get("%00"));
+ m = pe.parse(t, Map.class);
+ assertTrue(m.containsKey(null));
+ assertNull(m.get(null));
+
+ t = "(\u0000=\u0000)";
+ m = p.parse(t, Map.class);
+ assertTrue(m.containsKey(null));
+ assertNull(m.get(null));
+ m = pe.parse(t, Map.class);
+ assertTrue(m.containsKey(null));
+ assertNull(m.get(null));
+
+ // 3rd level
+ t = "$o(%00=$o(%00=%00))";
+ m = p.parse(t, Map.class);
+ assertEquals("%00", ((Map)m.get("%00")).get("%00"));
+ m = pe.parse(t, Map.class);
+ assertTrue(((Map)m.get(null)).containsKey(null));
+ assertNull(((Map)m.get(null)).get(null));
+
+ // Empty array
+ // Top level
+ t = "$a()";
+ List l = (List)p.parse(t, Object.class);
+ assertTrue(l.isEmpty());
+ t = "()";
+ l = p.parse(t, List.class);
+ assertTrue(l.isEmpty());
+
+ // 2nd level in map
+ t = "$o(x=$a())";
+ m = p.parseMap(t, HashMap.class, String.class, List.class);
+ assertTrue(m.containsKey("x"));
+ assertTrue(((List)m.get("x")).isEmpty());
+ m = (Map)p.parse(t, Object.class);
+ assertTrue(m.containsKey("x"));
+ assertTrue(((List)m.get("x")).isEmpty());
+ t = "(x=())";
+ m = p.parseMap(t, HashMap.class, String.class, List.class);
+ assertTrue(m.containsKey("x"));
+ assertTrue(((List)m.get("x")).isEmpty());
+
+ // Empty 2 dimensional array
+ t = "$a($a())";
+ l = (List)p.parse(t, Object.class);
+ assertTrue(l.size() == 1);
+ l = (List)l.get(0);
+ assertTrue(l.isEmpty());
+ t = "(())";
+ l = p.parseCollection(t, LinkedList.class, List.class);
+ assertTrue(l.size() == 1);
+ l = (List)l.get(0);
+ assertTrue(l.isEmpty());
+
+ // Array containing empty string
+ // Top level
+ t = "$a(())";
+ l = (List)p.parse(t, Object.class);
+ assertTrue(l.size() == 1);
+ assertEquals("", l.get(0));
+ t = "(())";
+ l = p.parseCollection(t, List.class, String.class);
+ assertTrue(l.size() == 1);
+ assertEquals("", l.get(0));
+
+ // 2nd level
+ t = "$o(()=$a(()))";
+ m = (Map)p.parse(t, Object.class);
+ assertEquals("", ((List)m.get("")).get(0));
+ t = "(=(()))";
+ m = p.parseMap(t, HashMap.class, String.class, List.class);
+ assertEquals("", ((List)m.get("")).get(0));
+
+ // Array containing 3 empty strings
+ t = "$a(,,)";
+ l = (List)p.parse(t, Object.class);
+ assertTrue(l.size() == 3);
+ assertEquals("", l.get(0));
+ assertEquals("", l.get(1));
+ assertEquals("", l.get(2));
+ t = "(,,)";
+ l = p.parseCollection(t, List.class, Object.class);
+ assertTrue(l.size() == 3);
+ assertEquals("", l.get(0));
+ assertEquals("", l.get(1));
+ assertEquals("", l.get(2));
+
+ // String containing \u0000
+ // Top level
+ t = "$s(\u0000)";
+ assertEquals("\u0000", p.parse(t, Object.class));
+ t = "(\u0000)";
+ assertEquals("\u0000", p.parse(t, String.class));
+ assertEquals("\u0000", p.parse(t, Object.class));
+
+ // 2nd level
+ t = "$o((\u0000)=(\u0000))";
+ m = (Map)p.parse(t, Object.class);
+ assertTrue(m.size() == 1);
+ assertEquals("\u0000", m.get("\u0000"));
+ t = "((\u0000)=(\u0000))";
+ m = p.parseMap(t, HashMap.class, String.class, String.class);
+ assertTrue(m.size() == 1);
+ assertEquals("\u0000", m.get("\u0000"));
+ m = p.parseMap(t, HashMap.class, String.class, Object.class);
+ assertTrue(m.size() == 1);
+ assertEquals("\u0000", m.get("\u0000"));
+
+ // Boolean
+ // Top level
+ t = "$b(false)";
+ Boolean b = (Boolean)p.parse(t, Object.class);
+ assertEquals(Boolean.FALSE, b);
+ b = p.parse(t, Boolean.class);
+ assertEquals(Boolean.FALSE, b);
+ t = "false";
+ b = p.parse(t, Boolean.class);
+ assertEquals(Boolean.FALSE, b);
+
+ // 2nd level
+ t = "$o(x=$b(false))";
+ m = (Map)p.parse(t, Object.class);
+ assertEquals(Boolean.FALSE, m.get("x"));
+ t = "(x=$b(false))";
+ m = p.parseMap(t, HashMap.class, String.class, Object.class);
+ assertEquals(Boolean.FALSE, m.get("x"));
+ t = "(x=false)";
+ m = p.parseMap(t, HashMap.class, String.class, Boolean.class);
+ assertEquals(Boolean.FALSE, m.get("x"));
+
+ // Number
+ // Top level
+ t = "$n(123)";
+ Integer i = (Integer)p.parse(t, Object.class);
+ assertEquals(123, i.intValue());
+ i = p.parse(t, Integer.class);
+ assertEquals(123, i.intValue());
+ Double d = p.parse(t, Double.class);
+ assertEquals(123, d.intValue());
+ Float f = p.parse(t, Float.class);
+ assertEquals(123, f.intValue());
+ t = "123";
+ i = p.parse(t, Integer.class);
+ assertEquals(123, i.intValue());
+
+ // 2nd level
+ t = "$o(x=$n(123))";
+ m = (Map)p.parse(t, Object.class);
+ assertEquals(123, ((Integer)m.get("x")).intValue());
+ t = "(x=123)";
+ m = p.parseMap(t, HashMap.class, String.class, Number.class);
+ assertEquals(123, ((Integer)m.get("x")).intValue());
+ m = p.parseMap(t, HashMap.class, String.class, Double.class);
+ assertEquals(123, ((Double)m.get("x")).intValue());
+
+ // Unencoded chars
+ // Top level
+ t = "x;/?:@-_.!*'";
+ assertEquals("x;/?:@-_.!*'", p.parse(t, Object.class));
+ assertEquals("x;/?:@-_.!*'", pe.parse(t, Object.class));
+
+ // 2nd level
+ t = "$o(x;/?:@-_.!*'=x;/?:@-_.!*')";
+ m = (Map)p.parse(t, Object.class);
+ assertEquals("x;/?:@-_.!*'", m.get("x;/?:@-_.!*'"));
+ m = p.parseMap(t, HashMap.class, String.class, Object.class);
+ assertEquals("x;/?:@-_.!*'", m.get("x;/?:@-_.!*'"));
+ m = p.parseMap(t, HashMap.class, String.class, String.class);
+ assertEquals("x;/?:@-_.!*'", m.get("x;/?:@-_.!*'"));
+
+ // Encoded chars
+ // Top level
+ t = "x{}|\\^[]`<>#%\"&+";
+ assertEquals("x{}|\\^[]`<>#%\"&+", p.parse(t, Object.class));
+ assertEquals("x{}|\\^[]`<>#%\"&+", p.parse(t, String.class));
+ try {
+ assertEquals("x{}|\\^[]`<>#%\"&+", pe.parse(t, Object.class));
+ fail("Expected parse exception from invalid hex sequence.");
+ } catch (ParseException e) {
+ // Good.
+ }
+ t = "x%7B%7D%7C%5C%5E%5B%5D%60%3C%3E%23%25%22%26%2B";
+ assertEquals("x{}|\\^[]`<>#%\"&+", pe.parse(t, Object.class));
+ assertEquals("x{}|\\^[]`<>#%\"&+", pe.parse(t, String.class));
+
+ // 2nd level
+ t = "$o(x{}|\\^[]`<>#%\"&+=x{}|\\^[]`<>#%\"&+)";
+ m = (Map)p.parse(t, Object.class);
+ assertEquals("x{}|\\^[]`<>#%\"&+", m.get("x{}|\\^[]`<>#%\"&+"));
+ try {
+ m = (Map)pe.parse(t, Object.class);
+ fail("Expected parse exception from invalid hex sequence.");
+ } catch (ParseException e) {
+ // Good.
+ }
+ t = "$o(x%7B%7D%7C%5C%5E%5B%5D%60%3C%3E%23%25%22%26%2B=x%7B%7D%7C%5C%5E%5B%5D%60%3C%3E%23%25%22%26%2B)";
+ m = (Map)pe.parse(t, Object.class);
+ assertEquals("x{}|\\^[]`<>#%\"&+", m.get("x{}|\\^[]`<>#%\"&+"));
+
+ // Special chars
+ // Top level
+ t = "x~$~,~(~)";
+ assertEquals("x$,()", p.parse(t, Object.class));
+ t = "(x~$~,~(~))";
+ assertEquals("x$,()", p.parse(t, Object.class));
+ t = "$s(x~$~,~(~))";
+ assertEquals("x$,()", p.parse(t, Object.class));
+
+ // 2nd level
+ // Note behavior on serializeParams() is different since 2nd-level is top level.
+ t = "$o(x~$~,~(~)=x~$~,~(~))";
+ m = (Map)p.parse(t, Object.class);
+ assertEquals("x$,()", m.get("x$,()"));
+ t = "$o((x~$~,~(~))=(x~$~,~(~)))";
+ m = (Map)p.parse(t, Object.class);
+ assertEquals("x$,()", m.get("x$,()"));
+ t = "$o($s(x~$~,~(~))=$s(x~$~,~(~)))";
+ m = (Map)p.parse(t, Object.class);
+ assertEquals("x$,()", m.get("x$,()"));
+
+ // Equals sign
+ // Gets encoded at top level, and encoded+escaped at 2nd level.
+ // Top level
+ t = "x=";
+ assertEquals("x=", p.parse(t, Object.class));
+ t = "x%3D";
+ assertEquals("x=", pe.parse(t, Object.class));
+
+ // 2nd level
+ t = "$o(x~==x~=)";
+ m = (Map)p.parse(t, Object.class);
+ assertEquals("x=", m.get("x="));
+ t = "$o((x~=)=(x~=))";
+ m = (Map)p.parse(t, Object.class);
+ assertEquals("x=", m.get("x="));
+ t = "$o($s(x~=)=$s(x~=))";
+ m = (Map)p.parse(t, Object.class);
+ assertEquals("x=", m.get("x="));
+ t = "(x~==x~=)";
+ m = p.parseMap(t, HashMap.class, String.class, Object.class);
+ assertEquals("x=", m.get("x="));
+ t = "((x~=)=(x~=))";
+ m = p.parseMap(t, HashMap.class, String.class, Object.class);
+ assertEquals("x=", m.get("x="));
+ t = "($s(x~=)=$s(x~=))";
+ m = p.parseMap(t, HashMap.class, String.class, Object.class);
+ assertEquals("x=", m.get("x="));
+ t = "$o(x~%3D=x~%3D)";
+ m = (Map)pe.parse(t, Object.class);
+ assertEquals("x=", m.get("x="));
+ t = "$o((x~%3D)=(x~%3D))";
+ m = (Map)pe.parse(t, Object.class);
+ assertEquals("x=", m.get("x="));
+ t = "$o($s(x~%3D)=$s(x~%3D))";
+ m = (Map)pe.parse(t, Object.class);
+ assertEquals("x=", m.get("x="));
+ t = "(x~%3D=x~%3D)";
+ m = pe.parseMap(t, HashMap.class, String.class, Object.class);
+ assertEquals("x=", m.get("x="));
+ t = "((x~%3D)=(x~%3D))";
+ m = pe.parseMap(t, HashMap.class, String.class, Object.class);
+ assertEquals("x=", m.get("x="));
+ t = "($s(x~%3D)=$s(x~%3D))";
+ m = pe.parseMap(t, HashMap.class, String.class, Object.class);
+ assertEquals("x=", m.get("x="));
+
+ // String starting with parenthesis
+ // Top level
+ t = "~(~)";
+ assertEquals("()", p.parse(t, Object.class));
+ assertEquals("()", p.parse(t, String.class));
+
+ t = "(~(~))";
+ assertEquals("()", p.parse(t, Object.class));
+ assertEquals("()", p.parse(t, String.class));
+ t = "$s(~(~))";
+ assertEquals("()", p.parse(t, Object.class));
+ assertEquals("()", p.parse(t, String.class));
+
+ // 2nd level
+ t = "$o((~(~))=(~(~)))";
+ m = (Map)p.parse(t, Object.class);
+ assertEquals("()", m.get("()"));
+ t = "((~(~))=(~(~)))";
+ m = p.parseMap(t, HashMap.class, String.class, Object.class);
+ assertEquals("()", m.get("()"));
+ t = "($s(~(~))=$s(~(~)))";
+ m = p.parseMap(t, HashMap.class, String.class, Object.class);
+ assertEquals("()", m.get("()"));
+
+ // String starting with $
+ // Top level
+ t = "($a)";
+ assertEquals("$a", p.parse(t, Object.class));
+ t = "($a)";
+ assertEquals("$a", p.parse(t, Object.class));
+
+ // 2nd level
+ t = "$o(($a)=($a))";
+ m = (Map)p.parse(t, Object.class);
+ assertEquals("$a", m.get("$a"));
+ t = "(($a)=($a))";
+ m = p.parseMap(t, HashMap.class, String.class, Object.class);
+ assertEquals("$a", m.get("$a"));
+
+ // Blank string
+ // Top level
+ t = "";
+ assertEquals("", p.parse(t, Object.class));
+ assertEquals("", pe.parse(t, Object.class));
+
+ // 2nd level
+ t = "$o(=)";
+ m = (Map)p.parse(t, Object.class);
+ assertEquals("", m.get(""));
+ t = "(=)";
+ m = p.parseMap(t, HashMap.class, String.class, Object.class);
+ assertEquals("", m.get(""));
+
+ // 3rd level
+ t = "$o(=$o(=))";
+ m = (Map)p.parse(t, Object.class);
+ assertEquals("", ((Map)m.get("")).get(""));
+ t = "(=(=))";
+ m = p.parseMap(t, HashMap.class, String.class, HashMap.class);
+ assertEquals("", ((Map)m.get("")).get(""));
+
+ // Newline character
+ // Top level
+ t = "(%0A)";
+ assertEquals("\n", pe.parse(t, Object.class));
+ assertEquals("%0A", p.parse(t, Object.class));
+
+ // 2nd level
+ t = "$o((%0A)=(%0A))";
+ m = (Map)pe.parse(t, Object.class);
+ assertEquals("\n", m.get("\n"));
+ m = (Map)p.parse(t, Object.class);
+ assertEquals("%0A", m.get("%0A"));
+
+ // 3rd level
+ t = "$o((%0A)=$o((%0A)=(%0A)))";
+ m = (Map)pe.parse(t, Object.class);
+ assertEquals("\n", ((Map)m.get("\n")).get("\n"));
+ }
+
+ //====================================================================================================
+ // Unicode character test
+ //====================================================================================================
+ @Test
+ public void testUnicodeChars() throws Exception {
+ String t;
+ Map m;
+
+ // 2-byte UTF-8 character
+ // Top level
+ t = "�";
+ assertEquals("�", p.parse(t, Object.class));
+ assertEquals("�", p.parse(t, String.class));
+ t = "%C2%A2";
+ assertEquals("�", pe.parse(t, Object.class));
+ assertEquals("�", pe.parse(t, String.class));
+
+ // 2nd level
+ t = "$o(�=�)";
+ m = (Map)p.parse(t, Object.class);
+ assertEquals("�", m.get("�"));
+ t = "$o(%C2%A2=%C2%A2)";
+ m = (Map)pe.parse(t, Object.class);
+ assertEquals("�", m.get("�"));
+
+ // 3rd level
+ t = "$o(�=$o(�=�))";
+ m = (Map)p.parse(t, Object.class);
+ assertEquals("�", ((Map)m.get("�")).get("�"));
+ t = "$o(%C2%A2=$o(%C2%A2=%C2%A2))";
+ m = (Map)pe.parse(t, Object.class);
+ assertEquals("�", ((Map)m.get("�")).get("�"));
+
+ // 3-byte UTF-8 character
+ // Top level
+ t = "\u20ac";
+ assertEquals("\u20ac", p.parse(t, Object.class));
+ assertEquals("\u20ac", p.parse(t, String.class));
+ t = "%E2%82%AC";
+ assertEquals("\u20ac", pe.parse(t, Object.class));
+ assertEquals("\u20ac", pe.parse(t, String.class));
+
+ // 2nd level
+ t = "$o(\u20ac=\u20ac)";
+ m = (Map)p.parse(t, Object.class);
+ assertEquals("\u20ac", m.get("\u20ac"));
+ t = "$o(%E2%82%AC=%E2%82%AC)";
+ m = (Map)pe.parse(t, Object.class);
+ assertEquals("\u20ac", m.get("\u20ac"));
+
+ // 3rd level
+ t = "$o(\u20ac=$o(\u20ac=\u20ac))";
+ m = (Map)p.parse(t, Object.class);
+ assertEquals("\u20ac", ((Map)m.get("\u20ac")).get("\u20ac"));
+ t = "$o(%E2%82%AC=$o(%E2%82%AC=%E2%82%AC))";
+ m = (Map)pe.parse(t, Object.class);
+ assertEquals("\u20ac", ((Map)m.get("\u20ac")).get("\u20ac"));
+
+ // 4-byte UTF-8 character
+ // Top level
+ t = "\U00024b62";
+ assertEquals("\U00024b62", p.parse(t, Object.class));
+ assertEquals("\U00024b62", p.parse(t, String.class));
+ t = "%F0%A4%AD%A2";
+ assertEquals("\U00024b62", pe.parse(t, Object.class));
+ assertEquals("\U00024b62", pe.parse(t, String.class));
+
+ // 2nd level
+ t = "$o(\U00024b62=\U00024b62)";
+ m = (Map)p.parse(t, Object.class);
+ assertEquals("\U00024b62", m.get("\U00024b62"));
+ t = "$o(%F0%A4%AD%A2=%F0%A4%AD%A2)";
+ m = (Map)pe.parse(t, Object.class);
+ assertEquals("\U00024b62", m.get("\U00024b62"));
+
+ // 3rd level
+ t = "$o(\U00024b62=$o(\U00024b62=\U00024b62))";
+ m = (Map)p.parse(t, Object.class);
+ assertEquals("\U00024b62", ((Map)m.get("\U00024b62")).get("\U00024b62"));
+ t = "$o(%F0%A4%AD%A2=$o(%F0%A4%AD%A2=%F0%A4%AD%A2))";
+ m = (Map)pe.parse(t, Object.class);
+ assertEquals("\U00024b62", ((Map)m.get("\U00024b62")).get("\U00024b62"));
+ }
+
+ //====================================================================================================
+ // Test simple bean
+ //====================================================================================================
+ @Test
+ public void testSimpleBean() throws Exception {
+ UonParser p = UonParser.DEFAULT;
+ A t;
+
+ String s = "(f1=foo,f2=123)";
+ t = p.parse(s, A.class);
+ assertEquals("foo", t.f1);
+ assertEquals(123, t.f2);
+ }
+
+ public static class A {
+ public String f1;
+ public int f2;
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/urlencoding/UonSerializerTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/urlencoding/UonSerializerTest.java b/org.apache.juneau/src/test/java/org/apache/juneau/urlencoding/UonSerializerTest.java
new file mode 100755
index 0000000..818b5dd
--- /dev/null
+++ b/org.apache.juneau/src/test/java/org/apache/juneau/urlencoding/UonSerializerTest.java
@@ -0,0 +1,460 @@
+/***************************************************************************************************************************
+ * 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.juneau.urlencoding;
+
+import static org.junit.Assert.*;
+
+import org.apache.juneau.*;
+import org.junit.*;
+
+public class UonSerializerTest {
+
+ static UonSerializer s = UonSerializer.DEFAULT_ENCODING;
+ static UonSerializer ss = UonSerializer.DEFAULT_SIMPLE_ENCODING;
+ static UonSerializer su = UonSerializer.DEFAULT;
+ static UonSerializer ssu = UonSerializer.DEFAULT_SIMPLE;
+ static UonSerializer sr = UonSerializer.DEFAULT_READABLE;
+
+
+ //====================================================================================================
+ // Basic test
+ //====================================================================================================
+ @Test
+ public void testBasic() throws Exception {
+
+ Object t;
+
+ // Simple string
+ // Top level
+ t = "a";
+ assertEquals("a", s.serialize(t));
+ assertEquals("a", ss.serialize(t));
+ assertEquals("a", su.serialize(t));
+ assertEquals("a", ssu.serialize(t));
+ assertEquals("a", sr.serialize(t));
+
+ // 2nd level
+ t = new ObjectMap("{a:'a'}");
+ assertEquals("$o(a=a)", s.serialize(t));
+ assertEquals("(a=a)", ss.serialize(t));
+ assertEquals("$o(a=a)", su.serialize(t));
+ assertEquals("(a=a)", ssu.serialize(t));
+ assertEquals("$o(\n\ta=a\n)", sr.serialize(t));
+
+ // Simple map
+ // Top level
+ t = new ObjectMap("{a:'b',c:123,d:false,e:true,f:null}");
+ assertEquals("$o(a=b,c=$n(123),d=$b(false),e=$b(true),f=%00)", s.serialize(t));
+ assertEquals("(a=b,c=123,d=false,e=true,f=%00)", ss.serialize(t));
+ assertEquals("$o(a=b,c=$n(123),d=$b(false),e=$b(true),f=\u0000)", su.serialize(t));
+ assertEquals("(a=b,c=123,d=false,e=true,f=\u0000)", ssu.serialize(t));
+ assertEquals("$o(\n\ta=b,\n\tc=$n(123),\n\td=$b(false),\n\te=$b(true),\n\tf=\u0000\n)", sr.serialize(t));
+
+ // 2nd level
+ t = new ObjectMap("{a:{a:'b',c:123,d:false,e:true,f:null}}");
+ assertEquals("$o(a=$o(a=b,c=$n(123),d=$b(false),e=$b(true),f=%00))", s.serialize(t));
+ assertEquals("(a=(a=b,c=123,d=false,e=true,f=%00))", ss.serialize(t));
+ assertEquals("$o(a=$o(a=b,c=$n(123),d=$b(false),e=$b(true),f=\u0000))", su.serialize(t));
+ assertEquals("(a=(a=b,c=123,d=false,e=true,f=\u0000))", ssu.serialize(t));
+ assertEquals("$o(\n\ta=$o(\n\t\ta=b,\n\t\tc=$n(123),\n\t\td=$b(false),\n\t\te=$b(true),\n\t\tf=\u0000\n\t)\n)", sr.serialize(t));
+
+ // Simple map with primitives as literals
+ t = new ObjectMap("{a:'b',c:'123',d:'false',e:'true',f:'null'}");
+ assertEquals("$o(a=b,c=123,d=false,e=true,f=null)", s.serialize(t));
+ assertEquals("(a=b,c=123,d=false,e=true,f=null)", ss.serialize(t));
+ assertEquals("$o(a=b,c=123,d=false,e=true,f=null)", su.serialize(t));
+ assertEquals("(a=b,c=123,d=false,e=true,f=null)", ssu.serialize(t));
+ assertEquals("$o(\n\ta=b,\n\tc=123,\n\td=false,\n\te=true,\n\tf=null\n)", sr.serialize(t));
+
+ // null
+ // Note that serializeParams is always encoded.
+ // Top level
+ t = null;
+ assertEquals("%00", s.serialize(t));
+ assertEquals("%00", ss.serialize(t));
+ assertEquals("\u0000", su.serialize(t));
+ assertEquals("\u0000", ssu.serialize(t));
+ assertEquals("\u0000", sr.serialize(t));
+
+ // 2nd level
+ t = new ObjectMap("{null:null}");
+ assertEquals("$o(%00=%00)", s.serialize(t));
+ assertEquals("(%00=%00)", ss.serialize(t));
+ assertEquals("$o(\u0000=\u0000)", su.serialize(t));
+ assertEquals("(\u0000=\u0000)", ssu.serialize(t));
+ assertEquals("$o(\n\t\u0000=\u0000\n)", sr.serialize(t));
+
+ // 3rd level
+ t = new ObjectMap("{null:{null:null}}");
+ assertEquals("$o(%00=$o(%00=%00))", s.serialize(t));
+ assertEquals("(%00=(%00=%00))", ss.serialize(t));
+ assertEquals("$o(\u0000=$o(\u0000=\u0000))", su.serialize(t));
+ assertEquals("(\u0000=(\u0000=\u0000))", ssu.serialize(t));
+ assertEquals("$o(\n\t\u0000=$o(\n\t\t\u0000=\u0000\n\t)\n)", sr.serialize(t));
+
+ // Empty array
+ // Top level
+ t = new String[0];
+ assertEquals("$a()", s.serialize(t));
+ assertEquals("()", ss.serialize(t));
+ assertEquals("$a()", su.serialize(t));
+ assertEquals("()", ssu.serialize(t));
+ assertEquals("$a()", sr.serialize(t));
+
+ // 2nd level in map
+ t = new ObjectMap("{x:[]}");
+ assertEquals("$o(x=$a())", s.serialize(t));
+ assertEquals("(x=())", ss.serialize(t));
+ assertEquals("$o(x=$a())", su.serialize(t));
+ assertEquals("(x=())", ssu.serialize(t));
+ assertEquals("$o(\n\tx=$a()\n)", sr.serialize(t));
+
+ // Empty 2 dimensional array
+ t = new String[1][0];
+ assertEquals("$a($a())", s.serialize(t));
+ assertEquals("(())", ss.serialize(t));
+ assertEquals("$a($a())", su.serialize(t));
+ assertEquals("(())", ssu.serialize(t));
+ assertEquals("$a(\n\t$a()\n)", sr.serialize(t));
+
+ // Array containing empty string
+ // Top level
+ t = new String[]{""};
+ assertEquals("$a(())", s.serialize(t));
+ assertEquals("(())", ss.serialize(t));
+ assertEquals("$a(())", su.serialize(t));
+ assertEquals("(())", ssu.serialize(t));
+ assertEquals("$a(\n\t()\n)", sr.serialize(t));
+
+ // 2nd level
+ t = new ObjectMap("{x:['']}");
+ assertEquals("$o(x=$a(()))", s.serialize(t));
+ assertEquals("(x=(()))", ss.serialize(t));
+ assertEquals("$o(x=$a(()))", su.serialize(t));
+ assertEquals("(x=(()))", ssu.serialize(t));
+ assertEquals("$o(\n\tx=$a(\n\t\t()\n\t)\n)", sr.serialize(t));
+
+ // Array containing 3 empty strings
+ t = new String[]{"","",""};
+ assertEquals("$a(,,)", s.serialize(t));
+ assertEquals("(,,)", ss.serialize(t));
+ assertEquals("$a(,,)", su.serialize(t));
+ assertEquals("(,,)", ssu.serialize(t));
+ assertEquals("$a(\n\t(),\n\t(),\n\t()\n)", sr.serialize(t));
+
+ // String containing \u0000
+ // Top level
+ t = "\u0000";
+ assertEquals("(%00)", s.serialize(t));
+ assertEquals("(%00)", ss.serialize(t));
+ assertEquals("(\u0000)", su.serialize(t));
+ assertEquals("(\u0000)", ssu.serialize(t));
+ assertEquals("(\u0000)", sr.serialize(t));
+
+ // 2nd level
+ t = new ObjectMap("{'\u0000':'\u0000'}");
+ assertEquals("$o((%00)=(%00))", s.serialize(t));
+ assertEquals("((%00)=(%00))", ss.serialize(t));
+ assertEquals("$o((\u0000)=(\u0000))", su.serialize(t));
+ assertEquals("((\u0000)=(\u0000))", ssu.serialize(t));
+ assertEquals("$o(\n\t(\u0000)=(\u0000)\n)", sr.serialize(t));
+
+ // Boolean
+ // Top level
+ t = false;
+ assertEquals("$b(false)", s.serialize(t));
+ assertEquals("false", ss.serialize(t));
+ assertEquals("$b(false)", su.serialize(t));
+ assertEquals("false", ssu.serialize(t));
+ assertEquals("$b(false)", sr.serialize(t));
+
+ // 2nd level
+ t = new ObjectMap("{x:false}");
+ assertEquals("$o(x=$b(false))", s.serialize(t));
+ assertEquals("(x=false)", ss.serialize(t));
+ assertEquals("$o(x=$b(false))", su.serialize(t));
+ assertEquals("(x=false)", ssu.serialize(t));
+ assertEquals("$o(\n\tx=$b(false)\n)", sr.serialize(t));
+
+ // Number
+ // Top level
+ t = 123;
+ assertEquals("$n(123)", s.serialize(t));
+ assertEquals("123", ss.serialize(t));
+ assertEquals("$n(123)", su.serialize(t));
+ assertEquals("123", ssu.serialize(t));
+ assertEquals("$n(123)", sr.serialize(t));
+
+ // 2nd level
+ t = new ObjectMap("{x:123}");
+ assertEquals("$o(x=$n(123))", s.serialize(t));
+ assertEquals("(x=123)", ss.serialize(t));
+ assertEquals("$o(x=$n(123))", su.serialize(t));
+ assertEquals("(x=123)", ssu.serialize(t));
+ assertEquals("$o(\n\tx=$n(123)\n)", sr.serialize(t));
+
+ // Unencoded chars
+ // Top level
+ t = "x;/?:@-_.!*'";
+ assertEquals("x;/?:@-_.!*'", s.serialize(t));
+ assertEquals("x;/?:@-_.!*'", ss.serialize(t));
+ assertEquals("x;/?:@-_.!*'", su.serialize(t));
+ assertEquals("x;/?:@-_.!*'", ssu.serialize(t));
+ assertEquals("x;/?:@-_.!*'", sr.serialize(t));
+
+ // 2nd level
+ t = new ObjectMap("{x:'x;/?:@-_.!*\\''}");
+ assertEquals("$o(x=x;/?:@-_.!*')", s.serialize(t));
+ assertEquals("(x=x;/?:@-_.!*')", ss.serialize(t));
+ assertEquals("$o(x=x;/?:@-_.!*')", su.serialize(t));
+ assertEquals("(x=x;/?:@-_.!*')", ssu.serialize(t));
+ assertEquals("$o(\n\tx=x;/?:@-_.!*'\n)", sr.serialize(t));
+
+ // Encoded chars
+ // Top level
+ t = "x{}|\\^[]`<>#%\"&+";
+ assertEquals("x%7B%7D%7C%5C%5E%5B%5D%60%3C%3E%23%25%22%26%2B", s.serialize(t));
+ assertEquals("x%7B%7D%7C%5C%5E%5B%5D%60%3C%3E%23%25%22%26%2B", ss.serialize(t));
+ assertEquals("x{}|\\^[]`<>#%\"&+", su.serialize(t));
+ assertEquals("x{}|\\^[]`<>#%\"&+", ssu.serialize(t));
+ assertEquals("x{}|\\^[]`<>#%\"&+", sr.serialize(t));
+
+ // 2nd level
+ t = new ObjectMap("{'x{}|\\\\^[]`<>#%\"&+':'x{}|\\\\^[]`<>#%\"&+'}");
+ assertEquals("$o(x%7B%7D%7C%5C%5E%5B%5D%60%3C%3E%23%25%22%26%2B=x%7B%7D%7C%5C%5E%5B%5D%60%3C%3E%23%25%22%26%2B)", s.serialize(t));
+ assertEquals("(x%7B%7D%7C%5C%5E%5B%5D%60%3C%3E%23%25%22%26%2B=x%7B%7D%7C%5C%5E%5B%5D%60%3C%3E%23%25%22%26%2B)", ss.serialize(t));
+ assertEquals("$o(x{}|\\^[]`<>#%\"&+=x{}|\\^[]`<>#%\"&+)", su.serialize(t));
+ assertEquals("(x{}|\\^[]`<>#%\"&+=x{}|\\^[]`<>#%\"&+)", ssu.serialize(t));
+ assertEquals("$o(\n\tx{}|\\^[]`<>#%\"&+=x{}|\\^[]`<>#%\"&+\n)", sr.serialize(t));
+
+ // Escaped chars
+ // Top level
+ t = "x$,()~";
+ assertEquals("x$,()~", s.serialize(t));
+ assertEquals("x$,()~", ss.serialize(t));
+ assertEquals("x$,()~", su.serialize(t));
+ assertEquals("x$,()~", ssu.serialize(t));
+ assertEquals("x$,()~", sr.serialize(t));
+
+ // 2nd level
+ // Note behavior on serializeParams() is different since 2nd-level is top level.
+ t = new ObjectMap("{'x$,()~':'x$,()~'}");
+ assertEquals("$o(x$~,~(~)~~=x$~,~(~)~~)", s.serialize(t));
+ assertEquals("(x$~,~(~)~~=x$~,~(~)~~)", ss.serialize(t));
+ assertEquals("$o(x$~,~(~)~~=x$~,~(~)~~)", su.serialize(t));
+ assertEquals("(x$~,~(~)~~=x$~,~(~)~~)", ssu.serialize(t));
+ assertEquals("$o(\n\tx$~,~(~)~~=x$~,~(~)~~\n)", sr.serialize(t));
+
+ // 3rd level
+ // Note behavior on serializeParams().
+ t = new ObjectMap("{'x$,()~':{'x$,()~':'x$,()~'}}");
+ assertEquals("$o(x$~,~(~)~~=$o(x$~,~(~)~~=x$~,~(~)~~))", s.serialize(t));
+ assertEquals("(x$~,~(~)~~=(x$~,~(~)~~=x$~,~(~)~~))", ss.serialize(t));
+ assertEquals("$o(x$~,~(~)~~=$o(x$~,~(~)~~=x$~,~(~)~~))", su.serialize(t));
+ assertEquals("(x$~,~(~)~~=(x$~,~(~)~~=x$~,~(~)~~))", ssu.serialize(t));
+ assertEquals("$o(\n\tx$~,~(~)~~=$o(\n\t\tx$~,~(~)~~=x$~,~(~)~~\n\t)\n)", sr.serialize(t));
+
+ // Equals sign
+ // Gets encoded at top level, and encoded+escaped at 2nd level.
+ // Top level
+ t = "x=";
+ assertEquals("x=", s.serialize(t));
+ assertEquals("x=", ss.serialize(t));
+ assertEquals("x=", su.serialize(t));
+ assertEquals("x=", ssu.serialize(t));
+ assertEquals("x=", sr.serialize(t));
+
+ // 2nd level
+ t = new ObjectMap("{'x=':'x='}");
+ assertEquals("$o(x~==x~=)", s.serialize(t));
+ assertEquals("(x~==x~=)", ss.serialize(t));
+ assertEquals("$o(x~==x~=)", su.serialize(t));
+ assertEquals("(x~==x~=)", ssu.serialize(t));
+ assertEquals("$o(\n\tx~==x~=\n)", sr.serialize(t));
+
+ // 3rd level
+ t = new ObjectMap("{'x=':{'x=':'x='}}");
+ assertEquals("$o(x~==$o(x~==x~=))", s.serialize(t));
+ assertEquals("(x~==(x~==x~=))", ss.serialize(t));
+ assertEquals("$o(x~==$o(x~==x~=))", su.serialize(t));
+ assertEquals("(x~==(x~==x~=))", ssu.serialize(t));
+ assertEquals("$o(\n\tx~==$o(\n\t\tx~==x~=\n\t)\n)", sr.serialize(t));
+
+ // String starting with parenthesis
+ // Top level
+ t = "()";
+ assertEquals("(~(~))", s.serialize(t));
+ assertEquals("(~(~))", ss.serialize(t));
+ assertEquals("(~(~))", su.serialize(t));
+ assertEquals("(~(~))", ssu.serialize(t));
+ assertEquals("(~(~))", sr.serialize(t));
+
+ // 2nd level
+ t = new ObjectMap("{'()':'()'}");
+ assertEquals("$o((~(~))=(~(~)))", s.serialize(t));
+ assertEquals("((~(~))=(~(~)))", ss.serialize(t));
+ assertEquals("$o((~(~))=(~(~)))", su.serialize(t));
+ assertEquals("((~(~))=(~(~)))", ssu.serialize(t));
+ assertEquals("$o(\n\t(~(~))=(~(~))\n)", sr.serialize(t));
+
+ // String starting with $
+ // Top level
+ t = "$a";
+ assertEquals("($a)", s.serialize(t));
+ assertEquals("($a)", ss.serialize(t));
+ assertEquals("($a)", su.serialize(t));
+ assertEquals("($a)", ssu.serialize(t));
+ assertEquals("($a)", sr.serialize(t));
+
+ // 2nd level
+ t = new ObjectMap("{$a:'$a'}");
+ assertEquals("$o(($a)=($a))", s.serialize(t));
+ assertEquals("(($a)=($a))", ss.serialize(t));
+ assertEquals("$o(($a)=($a))", su.serialize(t));
+ assertEquals("(($a)=($a))", ssu.serialize(t));
+ assertEquals("$o(\n\t($a)=($a)\n)", sr.serialize(t));
+
+ // Blank string
+ // Top level
+ t = "";
+ assertEquals("", s.serialize(t));
+ assertEquals("", ss.serialize(t));
+ assertEquals("", su.serialize(t));
+ assertEquals("", ssu.serialize(t));
+ assertEquals("", sr.serialize(t));
+
+ // 2nd level
+ t = new ObjectMap("{'':''}");
+ assertEquals("$o(=)", s.serialize(t));
+ assertEquals("(=)", ss.serialize(t));
+ assertEquals("$o(=)", su.serialize(t));
+ assertEquals("(=)", ssu.serialize(t));
+ assertEquals("$o(\n\t()=()\n)", sr.serialize(t));
+
+ // 3rd level
+ t = new ObjectMap("{'':{'':''}}");
+ assertEquals("$o(=$o(=))", s.serialize(t));
+ assertEquals("(=(=))", ss.serialize(t));
+ assertEquals("$o(=$o(=))", su.serialize(t));
+ assertEquals("(=(=))", ssu.serialize(t));
+ assertEquals("$o(\n\t()=$o(\n\t\t()=()\n\t)\n)", sr.serialize(t));
+
+ // Newline character
+ // Top level
+ t = "\n";
+ assertEquals("%0A", s.serialize(t));
+ assertEquals("%0A", ss.serialize(t));
+ assertEquals("\n", su.serialize(t));
+ assertEquals("\n", ssu.serialize(t));
+ assertEquals("(\n)", sr.serialize(t));
+
+ // 2nd level
+ t = new ObjectMap("{'\n':'\n'}");
+ assertEquals("$o(%0A=%0A)", s.serialize(t));
+ assertEquals("(%0A=%0A)", ss.serialize(t));
+ assertEquals("$o(\n=\n)", su.serialize(t));
+ assertEquals("(\n=\n)", ssu.serialize(t));
+ assertEquals("$o(\n\t(\n)=(\n)\n)", sr.serialize(t));
+
+ // 3rd level
+ t = new ObjectMap("{'\n':{'\n':'\n'}}");
+ assertEquals("$o(%0A=$o(%0A=%0A))", s.serialize(t));
+ assertEquals("(%0A=(%0A=%0A))", ss.serialize(t));
+ assertEquals("$o(\n=$o(\n=\n))", su.serialize(t));
+ assertEquals("(\n=(\n=\n))", ssu.serialize(t));
+ assertEquals("$o(\n\t(\n)=$o(\n\t\t(\n)=(\n)\n\t)\n)", sr.serialize(t));
+ }
+
+ //====================================================================================================
+ // Unicode characters test
+ //====================================================================================================
+ @Test
+ public void testUnicodeChars() throws Exception {
+ Object t;
+
+ // 2-byte UTF-8 character
+ // Top level
+ t = "�";
+ assertEquals("%C2%A2", s.serialize(t));
+ assertEquals("%C2%A2", ss.serialize(t));
+ assertEquals("�", su.serialize(t));
+ assertEquals("�", ssu.serialize(t));
+ assertEquals("�", sr.serialize(t));
+
+ // 2nd level
+ t = new ObjectMap("{'�':'�'}");
+ assertEquals("$o(%C2%A2=%C2%A2)", s.serialize(t));
+ assertEquals("(%C2%A2=%C2%A2)", ss.serialize(t));
+ assertEquals("$o(�=�)", su.serialize(t));
+ assertEquals("(�=�)", ssu.serialize(t));
+ assertEquals("$o(\n\t�=�\n)", sr.serialize(t));
+
+ // 3rd level
+ t = new ObjectMap("{'�':{'�':'�'}}");
+ assertEquals("$o(%C2%A2=$o(%C2%A2=%C2%A2))", s.serialize(t));
+ assertEquals("(%C2%A2=(%C2%A2=%C2%A2))", ss.serialize(t));
+ assertEquals("$o(�=$o(�=�))", su.serialize(t));
+ assertEquals("(�=(�=�))", ssu.serialize(t));
+ assertEquals("$o(\n\t�=$o(\n\t\t�=�\n\t)\n)", sr.serialize(t));
+
+ // 3-byte UTF-8 character
+ // Top level
+ t = "\u20ac";
+ assertEquals("%E2%82%AC", s.serialize(t));
+ assertEquals("%E2%82%AC", ss.serialize(t));
+ assertEquals("\u20ac", su.serialize(t));
+ assertEquals("\u20ac", ssu.serialize(t));
+ assertEquals("\u20ac", sr.serialize(t));
+
+ // 2nd level
+ t = new ObjectMap("{'\u20ac':'\u20ac'}");
+ assertEquals("$o(%E2%82%AC=%E2%82%AC)", s.serialize(t));
+ assertEquals("(%E2%82%AC=%E2%82%AC)", ss.serialize(t));
+ assertEquals("$o(\u20ac=\u20ac)", su.serialize(t));
+ assertEquals("(\u20ac=\u20ac)", ssu.serialize(t));
+ assertEquals("$o(\n\t\u20ac=\u20ac\n)", sr.serialize(t));
+
+ // 3rd level
+ t = new ObjectMap("{'\u20ac':{'\u20ac':'\u20ac'}}");
+ assertEquals("$o(%E2%82%AC=$o(%E2%82%AC=%E2%82%AC))", s.serialize(t));
+ assertEquals("(%E2%82%AC=(%E2%82%AC=%E2%82%AC))", ss.serialize(t));
+ assertEquals("$o(\u20ac=$o(\u20ac=\u20ac))", su.serialize(t));
+ assertEquals("(\u20ac=(\u20ac=\u20ac))", ssu.serialize(t));
+ assertEquals("$o(\n\t\u20ac=$o(\n\t\t\u20ac=\u20ac\n\t)\n)", sr.serialize(t));
+
+ // 4-byte UTF-8 character
+ // Top level
+ t = "\U00024b62";
+ assertEquals("%F0%A4%AD%A2", s.serialize(t));
+ assertEquals("%F0%A4%AD%A2", ss.serialize(t));
+ assertEquals("\U00024b62", su.serialize(t));
+ assertEquals("\U00024b62", ssu.serialize(t));
+ assertEquals("\U00024b62", sr.serialize(t));
+
+ // 2nd level
+ t = new ObjectMap("{'\U00024b62':'\U00024b62'}");
+ assertEquals("$o(%F0%A4%AD%A2=%F0%A4%AD%A2)", s.serialize(t));
+ assertEquals("(%F0%A4%AD%A2=%F0%A4%AD%A2)", ss.serialize(t));
+ assertEquals("$o(\U00024b62=\U00024b62)", su.serialize(t));
+ assertEquals("(\U00024b62=\U00024b62)", ssu.serialize(t));
+ assertEquals("$o(\n\t\U00024b62=\U00024b62\n)", sr.serialize(t));
+
+ // 3rd level
+ t = new ObjectMap("{'\U00024b62':{'\U00024b62':'\U00024b62'}}");
+ assertEquals("$o(%F0%A4%AD%A2=$o(%F0%A4%AD%A2=%F0%A4%AD%A2))", s.serialize(t));
+ assertEquals("(%F0%A4%AD%A2=(%F0%A4%AD%A2=%F0%A4%AD%A2))", ss.serialize(t));
+ assertEquals("$o(\U00024b62=$o(\U00024b62=\U00024b62))", su.serialize(t));
+ assertEquals("(\U00024b62=(\U00024b62=\U00024b62))", ssu.serialize(t));
+ assertEquals("$o(\n\t\U00024b62=$o(\n\t\t\U00024b62=\U00024b62\n\t)\n)", sr.serialize(t));
+ }
+}
\ No newline at end of file
[37/44] incubator-juneau git commit: Rename CT_* testcases.
Posted by ja...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestErrorConditionsTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestErrorConditionsTest.java b/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestErrorConditionsTest.java
new file mode 100755
index 0000000..5b7c1fa
--- /dev/null
+++ b/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestErrorConditionsTest.java
@@ -0,0 +1,220 @@
+/***************************************************************************************************************************
+ * 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.juneau.server;
+
+import static javax.servlet.http.HttpServletResponse.*;
+import static org.apache.juneau.server.TestUtils.*;
+import static org.junit.Assert.*;
+
+import org.apache.juneau.*;
+import org.apache.juneau.client.*;
+import org.apache.juneau.json.*;
+import org.junit.*;
+
+
+public class TestErrorConditionsTest {
+
+ private static String URL = "/testErrorConditions";
+ private static boolean debug = false;
+ private static RestClient client;
+
+ @BeforeClass
+ public static void beforeClass() {
+ client = new TestRestClient(JsonSerializer.DEFAULT, JsonParser.DEFAULT);
+ }
+
+ @AfterClass
+ public static void afterClass() {
+ client.closeQuietly();
+ }
+ //====================================================================================================
+ // Test non-existent properties
+ //====================================================================================================
+ @Test
+ public void testNonExistentBeanProperties() throws Exception {
+ String url = URL + "/testNonExistentBeanProperties";
+
+ try {
+ client.doPut(url + "?noTrace=true", new ObjectMap("{f2:'foo'}")).getResponseAsString();
+ fail("Exception expected");
+ } catch (RestCallException e) {
+ checkErrorResponse(debug, e, SC_BAD_REQUEST,
+ "Could not convert request body content to class type 'org.apache.juneau.server.TestErrorConditions$Test1' using parser 'org.apache.juneau.json.JsonParser'",
+ "Unknown property 'f2' encountered while trying to parse into class 'org.apache.juneau.server.TestErrorConditions$Test1'");
+ }
+
+ try {
+ client.doPut(url + "?noTrace=true", new ObjectMap("{f1:'foo', f2:'foo'}")).getResponseAsString();
+ fail("Exception expected");
+ } catch (RestCallException e) {
+ checkErrorResponse(debug, e, SC_BAD_REQUEST,
+ "Could not convert request body content to class type 'org.apache.juneau.server.TestErrorConditions$Test1' using parser 'org.apache.juneau.json.JsonParser'",
+ "Unknown property 'f2' encountered while trying to parse into class 'org.apache.juneau.server.TestErrorConditions$Test1'");
+ }
+ }
+
+ //====================================================================================================
+ // Test trying to set properties to wrong data type
+ //====================================================================================================
+ @Test
+ public void testWrongDataType() throws Exception {
+ String url = URL + "/testWrongDataType";
+ try {
+ client.doPut(url + "?noTrace=true", new ObjectMap("{f1:'foo'}")).getResponseAsString();
+ fail("Exception expected");
+ } catch (RestCallException e) {
+ checkErrorResponse(debug, e, SC_BAD_REQUEST,
+ "Could not convert request body content to class type 'org.apache.juneau.server.TestErrorConditions$Test2' using parser 'org.apache.juneau.json.JsonParser'.",
+ "Could not convert string 'foo' to class 'int'");
+ }
+ }
+
+ //====================================================================================================
+ // Test trying to parse into class with non-public no-arg constructor.
+ //====================================================================================================
+ @Test
+ public void testParseIntoNonConstructableBean() throws Exception {
+ String url = URL + "/testParseIntoNonConstructableBean";
+ try {
+ client.doPut(url + "?noTrace=true", new ObjectMap("{f1:1}")).getResponseAsString();
+ fail("Exception expected");
+ } catch (RestCallException e) {
+ checkErrorResponse(debug, e, SC_BAD_REQUEST,
+ "Class 'org.apache.juneau.server.TestErrorConditions$Test3a' could not be instantiated.");
+ }
+ }
+
+ //====================================================================================================
+ // Test trying to parse into non-static inner class
+ //====================================================================================================
+ @Test
+ public void testParseIntoNonStaticInnerClass() throws Exception {
+ String url = URL + "/testParseIntoNonStaticInnerClass";
+ try {
+ client.doPut(url + "?noTrace=true", new ObjectMap("{f1:1}")).getResponseAsString();
+ fail("Exception expected");
+ } catch (RestCallException e) {
+ checkErrorResponse(debug, e, SC_BAD_REQUEST,
+ "Class 'org.apache.juneau.server.TestErrorConditions$Test3b' could not be instantiated. Reason: 'No properties detected on bean class'");
+ }
+ }
+
+ //====================================================================================================
+ // Test trying to parse into non-public inner class
+ //====================================================================================================
+ @Test
+ public void testParseIntoNonPublicInnerClass() throws Exception {
+ String url = URL + "/testParseIntoNonPublicInnerClass";
+ try {
+ client.doPut(url + "?noTrace=true", new ObjectMap("{f1:1}")).getResponseAsString();
+ fail("Exception expected");
+ } catch (RestCallException e) {
+ checkErrorResponse(debug, e, SC_BAD_REQUEST,
+ "Class 'org.apache.juneau.server.TestErrorConditions$Test3b1' could not be instantiated",
+ "Class is not public");
+ }
+ }
+
+ //====================================================================================================
+ // Test exception thrown during bean construction.
+ //====================================================================================================
+ @Test
+ public void testThrownConstructorException() throws Exception {
+ String url = URL + "/testThrownConstructorException";
+ try {
+ client.doPut(url + "?noTrace=true", "'foo'").getResponseAsString();
+ fail("Exception expected");
+ } catch (RestCallException e) {
+ checkErrorResponse(debug, e, SC_BAD_REQUEST,
+ "Could not convert request body content to class type 'org.apache.juneau.server.TestErrorConditions$Test3c' using parser 'org.apache.juneau.json.JsonParser'.",
+ "Caused by (RuntimeException): Test error");
+ }
+ }
+
+ //====================================================================================================
+ // Test trying to set parameters to invalid types.
+ //====================================================================================================
+ @Test
+ public void testSetParameterToInvalidTypes() throws Exception {
+ String url = URL + "/testSetParameterToInvalidTypes";
+ try {
+ client.doPut(url + "/1?noTrace=true&p1=foo", "").getResponseAsString();
+ fail("Exception expected");
+ } catch (RestCallException e) {
+ checkErrorResponse(debug, e, SC_BAD_REQUEST,
+ "Could not convert PARAM 'p1' to type 'int' on method 'org.apache.juneau.server.TestErrorConditions.testSetParameterToInvalidTypes'");
+ }
+
+ try {
+ client.doPut(url + "/foo?noTrace=true&p1=1", "").getResponseAsString();
+ fail("Exception expected");
+ } catch (RestCallException e) {
+ checkErrorResponse(debug, e, SC_BAD_REQUEST,
+ "Could not convert ATTR 'a1' to type 'int' on method 'org.apache.juneau.server.TestErrorConditions.testSetParameterToInvalidTypes'");
+ }
+
+ try {
+ client.doPut(url + "/1?noTrace=true&p1=1", "").setHeader("h1", "foo").getResponseAsString();
+ fail("Exception expected");
+ } catch (RestCallException e) {
+ checkErrorResponse(debug, e, SC_BAD_REQUEST,
+ "Could not convert HEADER 'h1' to type 'int' on method 'org.apache.juneau.server.TestErrorConditions.testSetParameterToInvalidTypes'");
+ }
+ }
+
+ //====================================================================================================
+ // Test SC_NOT_FOUND & SC_METHOD_NOT_ALLOWED
+ //====================================================================================================
+ @Test
+ public void test404and405() throws Exception {
+ String url = URL + "/test404and405";
+ try {
+ client.doGet(URL + "/testNonExistent?noTrace=true").getResponseAsString();
+ fail("Exception expected");
+ } catch (RestCallException e) {
+ checkErrorResponse(debug, e, SC_NOT_FOUND,
+ "Method 'GET' not found on resource with matching pattern on path '/testNonExistent'");
+ }
+
+ try {
+ client.doPut(url + "?noTrace=true", "").getResponseAsString();
+ fail("Exception expected");
+ } catch (RestCallException e) {
+ checkErrorResponse(debug, e, SC_NOT_FOUND,
+ "Method 'PUT' not found on resource with matching pattern on path '/test404and405'");
+ }
+
+ try {
+ client.doPost(url + "?noTrace=true", "").getResponseAsString();
+ fail("Exception expected");
+ } catch (RestCallException e) {
+ checkErrorResponse(debug, e, SC_METHOD_NOT_ALLOWED,
+ "Method 'POST' not found on resource.");
+ }
+ }
+
+ //====================================================================================================
+ // Test SC_PRECONDITION_FAILED
+ //====================================================================================================
+ @Test
+ public void test412() throws Exception {
+ String url = URL + "/test412";
+ try {
+ client.doGet(url + "?noTrace=true").getResponseAsString();
+ fail("Exception expected");
+ } catch (RestCallException e) {
+ checkErrorResponse(debug, e, SC_PRECONDITION_FAILED,
+ "Method 'GET' not found on resource on path '/test412' with matching matcher.");
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestGroupsTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestGroupsTest.java b/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestGroupsTest.java
new file mode 100755
index 0000000..4b57cc7
--- /dev/null
+++ b/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestGroupsTest.java
@@ -0,0 +1,122 @@
+/***************************************************************************************************************************
+ * 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.juneau.server;
+
+import static javax.servlet.http.HttpServletResponse.*;
+import static org.apache.juneau.server.TestUtils.*;
+import static org.junit.Assert.*;
+
+import java.io.*;
+
+import org.apache.juneau.client.*;
+import org.apache.juneau.json.*;
+import org.junit.*;
+
+
+public class TestGroupsTest {
+
+ private static String URL = "/testGroups";
+ private static boolean debug = false;
+
+ //====================================================================================================
+ // Serializer defined on class.
+ //====================================================================================================
+ @Test
+ public void testSerializerDefinedOnClass() throws Exception {
+ RestClient client = new TestRestClient(JsonSerializer.DEFAULT, JsonParser.DEFAULT);
+ String url = URL + "/testSerializerDefinedOnClass";
+ String r;
+
+ try {
+ client.setContentType("text/p1");
+ r = client.doGet(url+"?noTrace=true").getResponseAsString();
+ fail("Exception expected");
+ } catch (RestCallException e) {
+ checkErrorResponse(debug, e, SC_NOT_ACCEPTABLE,
+ "Unsupported media-type in request header 'Accept': 'application/json'",
+ "Supported media-types: [text/s1, text/s2]"
+ );
+ }
+
+ client.setAccept("text/s1").setContentType("");
+ r = client.doGet(url).getResponseAsString();
+ assertEquals("text/s,GET", r);
+
+ client.setAccept("text/s2").setContentType("");
+ r = client.doGet(url).getResponseAsString();
+ assertEquals("text/s,GET", r);
+
+ try {
+ client.setAccept("text/s3").setContentType("");
+ r = client.doGet(url+"?noTrace=true").getResponseAsString();
+ assertEquals("text/s,GET", r);
+ } catch (RestCallException e) {
+ checkErrorResponse(debug, e, SC_NOT_ACCEPTABLE,
+ "Unsupported media-type in request header 'Accept': 'text/s3'",
+ "Supported media-types: [text/s1, text/s2]"
+ );
+ }
+
+ try {
+ client.setAccept("text/json").setContentType("text/p1");
+ r = client.doPut(url+"?noTrace=true", new StringReader("foo")).getResponseAsString();
+ fail("Exception expected");
+ } catch (RestCallException e) {
+ checkErrorResponse(debug, e, SC_NOT_ACCEPTABLE,
+ "Unsupported media-type in request header 'Accept': 'text/json'",
+ "Supported media-types: [text/s1, text/s2]"
+ );
+ }
+
+ try {
+ client.setAccept("text/s1").setContentType("text/json");
+ r = client.doPut(url+"?noTrace=true", new StringReader("foo")).getResponseAsString();
+ fail("Exception expected");
+ } catch (RestCallException e) {
+ checkErrorResponse(debug, e, SC_UNSUPPORTED_MEDIA_TYPE,
+ "Unsupported media-type in request header 'Content-Type': 'text/json'",
+ "Supported media-types: [text/p1, text/p2]"
+ );
+ }
+
+ client.setContentType("text/p1").setAccept("text/s1");
+ r = client.doPut(url, new StringReader("foo")).getResponseAsString();
+ assertEquals("text/s,foo", r);
+
+ client.setContentType("text/p2").setAccept("text/s2");
+ r = client.doPut(url, new StringReader("foo")).getResponseAsString();
+ assertEquals("text/s,foo", r);
+
+ try {
+ client.setContentType("text/p1").setAccept("text/s3");
+ r = client.doPut(url+"?noTrace=true", new StringReader("foo")).getResponseAsString();
+ } catch (RestCallException e) {
+ checkErrorResponse(debug, e, SC_NOT_ACCEPTABLE,
+ "Unsupported media-type in request header 'Accept': 'text/s3'",
+ "Supported media-types: [text/s1, text/s2]"
+ );
+ }
+
+ try {
+ client.setContentType("text/p3").setAccept("text/s1");
+ r = client.doPut(url+"?noTrace=true", new StringReader("foo")).getResponseAsString();
+ } catch (RestCallException e) {
+ checkErrorResponse(debug, e, SC_UNSUPPORTED_MEDIA_TYPE,
+ "Unsupported media-type in request header 'Content-Type': 'text/p3'",
+ "Supported media-types: [text/p1, text/p2]"
+ );
+ }
+
+ client.closeQuietly();
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestGzipTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestGzipTest.java b/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestGzipTest.java
new file mode 100755
index 0000000..37b84d3
--- /dev/null
+++ b/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestGzipTest.java
@@ -0,0 +1,344 @@
+/***************************************************************************************************************************
+ * 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.juneau.server;
+
+import static javax.servlet.http.HttpServletResponse.*;
+import static org.apache.juneau.server.TestUtils.*;
+import static org.junit.Assert.*;
+
+import java.io.*;
+import java.util.zip.*;
+
+import org.apache.http.impl.client.*;
+import org.apache.juneau.client.*;
+import org.apache.juneau.internal.*;
+import org.junit.*;
+
+/**
+ * Test Accept-Encoding and Content-Encoding handling.
+ *
+ * Note: WAS does automatic gzip decompression on http request messages, so we have to invent
+ * our own 'mycoding' compression.
+ */
+public class TestGzipTest {
+
+ private static boolean debug = false;
+
+ private static String testGzipOff = "/testGzipOff";
+ private static String testGzipOn = "/testGzipOn";
+
+ // Converts string into a GZipped input stream.
+ private static InputStream compress(String contents) throws Exception {
+ ByteArrayOutputStream baos = new ByteArrayOutputStream(contents.length()>>1);
+ GZIPOutputStream gos = new GZIPOutputStream(baos);
+ gos.write(contents.getBytes());
+ gos.finish();
+ gos.close();
+ return new ByteArrayInputStream(baos.toByteArray());
+ }
+
+ private static String decompress(InputStream is) throws Exception {
+ return IOUtils.read(new GZIPInputStream(is));
+ }
+
+ //====================================================================================================
+ // Test with no compression enabled.
+ //====================================================================================================
+ @Test
+ public void testGzipOff() throws Exception {
+ RestClient c = new TestRestClient().setAccept("text/plain").setContentType("text/plain");
+ RestCall r;
+ String url = testGzipOff;
+
+ // *** GET ***
+
+ r = c.doGet(url);
+ assertEquals("foo", r.getResponseAsString());
+
+ r = c.doGet(url).setHeader("Accept-Encoding", "");
+ assertEquals("foo", r.getResponseAsString());
+
+ r = c.doGet(url).setHeader("Accept-Encoding", "*");
+ assertEquals("foo", r.getResponseAsString());
+
+ r = c.doGet(url).setHeader("Accept-Encoding", "identity");
+ assertEquals("foo", r.getResponseAsString());
+
+ // Should match identity.
+ r = c.doGet(url).setHeader("Accept-Encoding", "mycoding");
+ assertEquals("foo", r.getResponseAsString());
+
+ // Shouldn't match.
+ try {
+ r = c.doGet(url+"?noTrace=true").setHeader("Accept-Encoding", "mycoding,identity;q=0").connect();
+ fail("Exception expected");
+ } catch (RestCallException e) {
+ checkErrorResponse(debug, e, SC_NOT_ACCEPTABLE,
+ "Unsupported encoding in request header 'Accept-Encoding': 'mycoding,identity;q=0'",
+ "Supported codings: [identity]"
+ );
+ }
+
+ // Shouldn't match.
+ try {
+ c.doGet(url+"?noTrace=true").setHeader("Accept-Encoding", "mycoding,*;q=0").connect();
+ fail("Exception expected");
+ } catch (RestCallException e) {
+ checkErrorResponse(debug, e, SC_NOT_ACCEPTABLE,
+ "Unsupported encoding in request header 'Accept-Encoding': 'mycoding,*;q=0'",
+ "Supported codings: [identity]"
+ );
+ }
+
+ // Should match identity
+ r = c.doGet(url).setHeader("Accept-Encoding", "identity;q=0.8,mycoding;q=0.6");
+ assertEquals("foo", r.getResponseAsString());
+
+ // Should match identity
+ r = c.doGet(url).setHeader("Accept-Encoding", "mycoding;q=0.8,identity;q=0.6");
+ assertEquals("foo", r.getResponseAsString());
+
+ // Should match identity
+ r = c.doGet(url).setHeader("Accept-Encoding", "mycoding;q=0.8,*;q=0.6");
+ assertEquals("foo", r.getResponseAsString());
+
+ // Should match identity
+ r = c.doGet(url).setHeader("Accept-Encoding", "*;q=0.8,myencoding;q=0.6");
+ assertEquals("foo", r.getResponseAsString());
+
+ // Shouldn't match
+ try {
+ c.doGet(url+"?noTrace=true").setHeader("Accept-Encoding", "identity;q=0").connect();
+ fail("Exception expected");
+ } catch (RestCallException e) {
+ checkErrorResponse(debug, e, SC_NOT_ACCEPTABLE,
+ "Unsupported encoding in request header 'Accept-Encoding': 'identity;q=0'",
+ "Supported codings: [identity]"
+ );
+ }
+
+ // Shouldn't match
+ try {
+ c.doGet(url+"?noTrace=true").setHeader("Accept-Encoding", "identity;q=0.0").connect();
+ fail("Exception expected");
+ } catch (RestCallException e) {
+ checkErrorResponse(debug, e, SC_NOT_ACCEPTABLE,
+ "Unsupported encoding in request header 'Accept-Encoding': 'identity;q=0.0'",
+ "Supported codings: [identity]"
+ );
+ }
+
+ // Shouldn't match
+ try {
+ c.doGet(url+"?noTrace=true").setHeader("Accept-Encoding", "*;q=0").connect();
+ fail("Exception expected");
+ } catch (RestCallException e) {
+ checkErrorResponse(debug, e, SC_NOT_ACCEPTABLE,
+ "Unsupported encoding in request header 'Accept-Encoding': '*;q=0'",
+ "Supported codings: [identity]"
+ );
+ }
+
+ // Shouldn't match
+ try {
+ c.doGet(url+"?noTrace=true").setHeader("Accept-Encoding", "*;q=0.0").connect();
+ fail("Exception expected");
+ } catch (RestCallException e) {
+ checkErrorResponse(debug, e, SC_NOT_ACCEPTABLE,
+ "Unsupported encoding in request header 'Accept-Encoding': '*;q=0.0'",
+ "Supported codings: [identity]"
+ );
+ }
+
+
+ // *** PUT ***
+
+ r = c.doPut(url, new StringReader("foo"));
+ assertEquals("foo", r.getResponseAsString());
+
+ r = c.doPut(url, new StringReader("foo")).setHeader("Content-Encoding", "");
+ assertEquals("foo", r.getResponseAsString());
+
+ r = c.doPut(url, new StringReader("foo")).setHeader("Content-Encoding", "identity");
+ assertEquals("foo", r.getResponseAsString());
+
+ try {
+ c.doPut(url+"?noTrace=true", compress("foo")).setHeader("Content-Encoding", "mycoding").connect();
+ fail("Exception expected");
+ } catch (RestCallException e) {
+ checkErrorResponse(debug, e, SC_UNSUPPORTED_MEDIA_TYPE,
+ "Unsupported encoding in request header 'Content-Encoding': 'mycoding'",
+ "Supported codings: [identity]"
+ );
+ }
+
+ c.closeQuietly();
+ }
+
+ //====================================================================================================
+ // Test with compression enabled.
+ //====================================================================================================
+ @Test
+ public void testGzipOn() throws Exception {
+
+ // Create a client that disables content compression support so that we can get the gzipped content directly.
+ CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(TestRestClient.getSSLSocketFactory()).disableContentCompression().build();
+
+ RestClient c = new TestRestClient(httpClient).setAccept("text/plain").setContentType("text/plain");
+ RestCall r;
+ String url = testGzipOn;
+
+ // *** GET ***
+
+ r = c.doGet(url);
+ assertEquals("foo", r.getResponseAsString());
+
+ r = c.doGet(url).setHeader("Accept-Encoding", "");
+ assertEquals("foo", r.getResponseAsString());
+
+ r = c.doGet(url).setHeader("Accept-Encoding", "*");
+ assertEquals("foo", decompress(r.getInputStream()));
+
+ r = c.doGet(url).setHeader("Accept-Encoding", "identity");
+ assertEquals("foo", r.getResponseAsString());
+
+ // Should match identity.
+ r = c.doGet(url).setHeader("Accept-Encoding", "mycoding");
+ assertEquals("foo", decompress(r.getInputStream()));
+
+ r = c.doGet(url).setHeader("Accept-Encoding", "mycoding,identity;q=0").connect();
+ assertEquals("foo", decompress(r.getInputStream()));
+
+ r = c.doGet(url).setHeader("Accept-Encoding", "mycoding,*;q=0").connect();
+ assertEquals("foo", decompress(r.getInputStream()));
+
+ // Should match identity
+ r = c.doGet(url).setHeader("Accept-Encoding", "identity;q=0.8,mycoding;q=0.6");
+ assertEquals("foo", r.getResponseAsString());
+
+ // Should match mycoding
+ r = c.doGet(url).setHeader("Accept-Encoding", "mycoding;q=0.8,identity;q=0.6");
+ assertEquals("foo", decompress(r.getInputStream()));
+
+ // Should match mycoding
+ r = c.doGet(url).setHeader("Accept-Encoding", "mycoding;q=0.8,*;q=0.6");
+ assertEquals("foo", decompress(r.getInputStream()));
+
+ // Should match identity
+ r = c.doGet(url).setHeader("Accept-Encoding", "*;q=0.8,myencoding;q=0.6");
+ assertEquals("foo", decompress(r.getInputStream()));
+
+ // Shouldn't match
+ try {
+ c.doGet(url+"?noTrace=true").setHeader("Accept-Encoding", "identity;q=0").connect();
+ fail("Exception expected");
+ } catch (RestCallException e) {
+ checkErrorResponse(debug, e, SC_NOT_ACCEPTABLE,
+ "Unsupported encoding in request header 'Accept-Encoding': 'identity;q=0'",
+ "Supported codings: [mycoding, identity]"
+ );
+ }
+
+ // Shouldn't match
+ try {
+ c.doGet(url+"?noTrace=true").setHeader("Accept-Encoding", "identity;q=0.0").connect();
+ fail("Exception expected");
+ } catch (RestCallException e) {
+ checkErrorResponse(debug, e, SC_NOT_ACCEPTABLE,
+ "Unsupported encoding in request header 'Accept-Encoding': 'identity;q=0.0'",
+ "Supported codings: [mycoding, identity]"
+ );
+ }
+
+ // Shouldn't match
+ try {
+ c.doGet(url+"?noTrace=true").setHeader("Accept-Encoding", "*;q=0").connect();
+ fail("Exception expected");
+ } catch (RestCallException e) {
+ checkErrorResponse(debug, e, SC_NOT_ACCEPTABLE,
+ "Unsupported encoding in request header 'Accept-Encoding': '*;q=0'",
+ "Supported codings: [mycoding, identity]"
+ );
+ }
+
+ // Shouldn't match
+ try {
+ c.doGet(url+"?noTrace=true").setHeader("Accept-Encoding", "*;q=0.0").connect();
+ fail("Exception expected");
+ } catch (RestCallException e) {
+ checkErrorResponse(debug, e, SC_NOT_ACCEPTABLE,
+ "Unsupported encoding in request header 'Accept-Encoding': '*;q=0.0'",
+ "Supported codings: [mycoding, identity]"
+ );
+ }
+
+
+ // *** PUT ***
+
+ r = c.doPut(url, new StringReader("foo"));
+ assertEquals("foo", r.getResponseAsString());
+
+ r = c.doPut(url, new StringReader("foo")).setHeader("Content-Encoding", "");
+ assertEquals("foo", r.getResponseAsString());
+
+ r = c.doPut(url, new StringReader("foo")).setHeader("Content-Encoding", "identity");
+ assertEquals("foo", r.getResponseAsString());
+
+ r = c.doPut(url, compress("foo")).setHeader("Content-Encoding", "mycoding");
+ assertEquals("foo", r.getResponseAsString());
+
+ c.closeQuietly();
+ }
+
+ //====================================================================================================
+ // Test with compression enabled but with servlet using output stream directly.
+ //====================================================================================================
+ @Test
+ public void testGzipOnDirect() throws Exception {
+ // Create a client that disables content compression support so that we can get the gzipped content directly.
+ CloseableHttpClient httpClient = HttpClientBuilder.create().setSSLSocketFactory(TestRestClient.getSSLSocketFactory()).build();
+ RestClient c = new TestRestClient(httpClient).setAccept("text/plain").setContentType("text/plain");
+ RestCall r = null;
+ String s = null;
+
+ // res.getOutputStream() called....should bypass encoding.
+ r = c.doGet(testGzipOn + "/direct").setHeader("Accept-Encoding", "mycoding");
+ s = r.getResponseAsString();
+ assertEquals("test", s);
+ assertTrue(r.getResponse().getHeaders("Content-Type")[0].getValue().contains("text/direct")); // Should get header set manually.
+ assertEquals(0, r.getResponse().getHeaders("Content-Encoding").length); // Should not be set.
+
+ // res.getWriter() called....should bypass encoding.
+ r = c.doGet(testGzipOn + "/direct2").setHeader("Accept-Encoding", "mycoding");
+ s = r.getResponseAsString();
+ assertEquals("test", s);
+ assertEquals(0, r.getResponse().getHeaders("Content-Encoding").length); // Should not be set.
+
+ // res.getNegotiateWriter() called....should NOT bypass encoding.
+ r = c.doGet(testGzipOn + "/direct3").setHeader("Accept-Encoding", "mycoding");
+ try {
+ assertEquals("mycoding", r.getResponse().getHeaders("content-encoding")[0].getValue());
+ } catch (RestCallException e) {
+ // OK - HttpClient doesn't know what mycoding is.
+ // Newer versions of HttpClient ignore this condition.
+ }
+
+ // res.getNegotiateWriter() called but @RestMethod(encoders={})...should bypass encoding.
+ r = c.doGet(testGzipOn + "/direct4").setHeader("Accept-Encoding", "mycoding");
+ s = r.getResponseAsString();
+ assertEquals("test", s);
+ assertEquals(0, r.getResponse().getHeaders("Content-Encoding").length); // Should not be set.
+
+ c.closeQuietly();
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestInheritanceTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestInheritanceTest.java b/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestInheritanceTest.java
new file mode 100755
index 0000000..1249565
--- /dev/null
+++ b/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestInheritanceTest.java
@@ -0,0 +1,128 @@
+/***************************************************************************************************************************
+ * 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.juneau.server;
+
+import static org.junit.Assert.*;
+
+import org.apache.juneau.client.*;
+import org.apache.juneau.json.*;
+import org.junit.*;
+
+public class TestInheritanceTest {
+
+ private static RestClient client;
+
+ @BeforeClass
+ public static void beforeClass() {
+ client = new TestRestClient();
+ }
+
+ @AfterClass
+ public static void afterClass() {
+ client.closeQuietly();
+ }
+
+ //====================================================================================================
+ // Test serializer inheritance.
+ //====================================================================================================
+ @Test
+ public void testSerializers() throws Exception {
+ String r;
+ String url = "/testInheritanceSerializers";
+ r = client.doGet(url + "/test1").getResponseAsString();
+ assertEquals("['text/s3','text/s4','text/s1','text/s2']", r);
+
+ r = client.doGet(url + "/test2").getResponseAsString();
+ assertEquals("['text/s5']", r);
+
+ r = client.doGet(url + "/test3").getResponseAsString();
+ assertEquals("['text/s5','text/s3','text/s4','text/s1','text/s2']", r);
+ }
+
+ //====================================================================================================
+ // Test parser inheritance.
+ //====================================================================================================
+ @Test
+ public void testParsers() throws Exception {
+ String r;
+ String url = "/testInheritanceParsers";
+ r = client.doGet(url + "/test1").getResponseAsString();
+ assertEquals("['text/p3','text/p4','text/p1','text/p2']", r);
+
+ r = client.doGet(url + "/test2").getResponseAsString();
+ assertEquals("['text/p5']", r);
+
+ r = client.doGet(url + "/test3").getResponseAsString();
+ assertEquals("['text/p5','text/p3','text/p4','text/p1','text/p2']", r);
+ }
+
+ //====================================================================================================
+ // Test encoder inheritance.
+ //====================================================================================================
+ @Test
+ public void testEncoders() throws Exception {
+ String url = "/testInheritanceEncoders";
+ String r = client.doGet(url + "/test").getResponseAsString();
+ assertEquals("['e3','e4','e1','e2','identity']", r);
+ }
+
+ //====================================================================================================
+ // Test filter inheritance.
+ //====================================================================================================
+ @Test
+ @SuppressWarnings("hiding")
+ public void testTransforms() throws Exception {
+ RestClient client = new TestRestClient(JsonSerializer.class, JsonParser.class).setAccept("text/json+simple");
+ String r;
+ String url = "/testInheritanceTransforms";
+
+ r = client.doGet(url + "/test1").getResponseAsString();
+ assertEquals("['F1','F2','Foo3']", r);
+
+ r = client.doGet(url + "/test2").getResponseAsString();
+ assertEquals("['F1','F2','F3']", r);
+
+ r = client.doGet(url + "/test3").getResponseAsString();
+ assertEquals("['F1','F2','F3']", r);
+
+ r = client.doGet(url + "/test4").getResponseAsString();
+ assertEquals("['Foo1','Foo2','F3']", r);
+
+ r = client.doGet(url + "/test5").getResponseAsString();
+ assertEquals("['F1','F2','F3']", r);
+
+ client.closeQuietly();
+ }
+
+ //====================================================================================================
+ // Test properties inheritance.
+ //====================================================================================================
+ @Test
+ @SuppressWarnings("hiding")
+ public void testProperties() throws Exception {
+ RestClient client = new TestRestClient(JsonSerializer.class, JsonParser.class).setAccept("text/json+simple");
+ String r;
+ String url = "/testInheritanceProperties";
+
+ r = client.doGet(url + "/test1").getResponseAsString();
+ assertEquals("{p1:'v1',p2:'v2a',p3:'v3',p4:'v4'}", r);
+
+ r = client.doGet(url + "/test2?override").getResponseAsString();
+ assertEquals("{p1:'x',p2:'x',p3:'x',p4:'x',p5:'x'}", r);
+
+ r = client.doGet(url + "/test2").getResponseAsString();
+ assertEquals("{p1:'v1',p2:'v2a',p3:'v3',p4:'v4a',p5:'v5'}", r);
+
+ client.closeQuietly();
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestLargePojosTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestLargePojosTest.java b/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestLargePojosTest.java
new file mode 100755
index 0000000..fc5863f
--- /dev/null
+++ b/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestLargePojosTest.java
@@ -0,0 +1,83 @@
+/***************************************************************************************************************************
+ * 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.juneau.server;
+
+import org.apache.juneau.client.*;
+import org.apache.juneau.html.*;
+import org.apache.juneau.json.*;
+import org.apache.juneau.urlencoding.*;
+import org.apache.juneau.xml.*;
+import org.junit.*;
+
+@Ignore
+public class TestLargePojosTest {
+
+ private static String URL = "/testLargePojos";
+ boolean debug = false;
+
+ //====================================================================================================
+ // Test how long it takes to serialize/parse various content types.
+ //====================================================================================================
+ @Test
+ public void test() throws Exception {
+ LargePojo p;
+ long t;
+ RestClient c;
+
+ System.err.println("\n---Testing JSON---");
+ c = new TestRestClient(JsonSerializer.class, JsonParser.class);
+ for (int i = 1; i <= 3; i++) {
+ t = System.currentTimeMillis();
+ p = c.doGet(URL).getResponse(LargePojo.class);
+ System.err.println("Download: ["+(System.currentTimeMillis() - t)+"] ms");
+ t = System.currentTimeMillis();
+ c.doPut(URL, p).run();
+ System.err.println("Upload: ["+(System.currentTimeMillis() - t)+"] ms");
+ }
+
+ System.err.println("\n---Testing XML---");
+ c = new TestRestClient(XmlSerializer.class, XmlParser.class);
+ for (int i = 1; i <= 3; i++) {
+ t = System.currentTimeMillis();
+ p = c.doGet(URL).getResponse(LargePojo.class);
+ System.err.println("Download: ["+(System.currentTimeMillis() - t)+"] ms");
+ t = System.currentTimeMillis();
+ c.doPut(URL, p).run();
+ System.err.println("Upload: ["+(System.currentTimeMillis() - t)+"] ms");
+ }
+
+ System.err.println("\n---Testing HTML---");
+ c = new TestRestClient(HtmlSerializer.class, HtmlParser.class).setAccept("text/html+stripped");
+ for (int i = 1; i <= 3; i++) {
+ t = System.currentTimeMillis();
+ p = c.doGet(URL).getResponse(LargePojo.class);
+ System.err.println("Download: ["+(System.currentTimeMillis() - t)+"] ms");
+ t = System.currentTimeMillis();
+ c.doPut(URL, p).run();
+ System.err.println("Upload: ["+(System.currentTimeMillis() - t)+"] ms");
+ }
+
+ System.err.println("\n---Testing UrlEncoding---");
+ c = new TestRestClient(UonSerializer.class, UonParser.class);
+ for (int i = 1; i <= 3; i++) {
+ t = System.currentTimeMillis();
+ p = c.doGet(URL).getResponse(LargePojo.class);
+ System.err.println("Download: ["+(System.currentTimeMillis() - t)+"] ms");
+ t = System.currentTimeMillis();
+ c.doPut(URL, p).run();
+ System.err.println("Upload: ["+(System.currentTimeMillis() - t)+"] ms");
+ }
+
+ c.closeQuietly();
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestMessagesTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestMessagesTest.java b/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestMessagesTest.java
new file mode 100755
index 0000000..0ba1bcb
--- /dev/null
+++ b/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestMessagesTest.java
@@ -0,0 +1,47 @@
+/***************************************************************************************************************************
+ * 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.juneau.server;
+
+import static org.apache.juneau.server.TestUtils.*;
+
+import java.util.*;
+
+import org.apache.juneau.client.*;
+import org.apache.juneau.json.*;
+import org.junit.*;
+
+/**
+ * Validates that resource bundles can be defined on both parent and child classes.
+ */
+public class TestMessagesTest {
+
+ //====================================================================================================
+ // Return contents of resource bundle.
+ //====================================================================================================
+ @SuppressWarnings("rawtypes")
+ @Test
+ public void test() throws Exception {
+ RestClient client = new TestRestClient(JsonSerializer.class,JsonParser.class);
+
+ // Parent resource should just pick up values from its bundle.
+ TreeMap r = client.doGet("/testMessages/test").getResponse(TreeMap.class);
+ assertObjectEquals("{key1:'value1a',key2:'value2a'}", r);
+
+ // Child resource should pick up values from both parent and child,
+ // ordered child before parent.
+ r = client.doGet("/testMessages2/test").getResponse(TreeMap.class);
+ assertObjectEquals("{key1:'value1a',key2:'value2b',key3:'value3b'}", r);
+
+ client.closeQuietly();
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestNlsPropertyTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestNlsPropertyTest.java b/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestNlsPropertyTest.java
new file mode 100755
index 0000000..4a3c225
--- /dev/null
+++ b/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestNlsPropertyTest.java
@@ -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.juneau.server;
+
+import static org.junit.Assert.*;
+
+import org.apache.juneau.client.*;
+import org.apache.juneau.plaintext.*;
+import org.junit.*;
+
+public class TestNlsPropertyTest {
+
+ private static String URL = "/testNlsProperty";
+
+ //====================================================================================================
+ // Test getting an NLS property defined on a class.
+ //====================================================================================================
+ @Test
+ public void testInheritedFromClass() throws Exception {
+ RestClient client = new TestRestClient(PlainTextSerializer.class, PlainTextParser.class);
+ String r = client.doGet(URL + "/testInheritedFromClass").getResponseAsString();
+ assertEquals("value1", r);
+
+ client.closeQuietly();
+ }
+
+ //====================================================================================================
+ // Test getting an NLS property defined on a method.
+ //====================================================================================================
+ @Test
+ public void testInheritedFromMethod() throws Exception {
+ RestClient client = new TestRestClient(PlainTextSerializer.class, PlainTextParser.class);
+ String r = client.doGet(URL + "/testInheritedFromMethod").getResponseAsString();
+ assertEquals("value2", r);
+
+ client.closeQuietly();
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestNlsTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestNlsTest.java b/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestNlsTest.java
new file mode 100755
index 0000000..82d55c1
--- /dev/null
+++ b/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestNlsTest.java
@@ -0,0 +1,170 @@
+/***************************************************************************************************************************
+ * 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.juneau.server;
+
+import static org.junit.Assert.*;
+
+import org.apache.juneau.*;
+import org.apache.juneau.client.*;
+import org.apache.juneau.json.*;
+import org.junit.*;
+
+public class TestNlsTest {
+
+ private static String URL = "/testNls";
+
+ // ====================================================================================================
+ // test1 - Pull labels from annotations only.
+ // ====================================================================================================
+ @Test
+ public void test1() throws Exception {
+ RestClient client = new TestRestClient(JsonSerializer.DEFAULT, JsonParser.DEFAULT);
+ ObjectMap r = null;
+ String expected = null;
+
+ // Labels all pulled from annotations.
+ r = client.doOptions(URL + "/test1").getResponse(ObjectMap.class);
+ assertEquals("Test1.a", r.getString("label"));
+ assertEquals("Test1.b", r.getString("description"));
+ r = r.getObjectList("methods").getObjectMap(0);
+ assertEquals("test1", r.getString("javaMethod"));
+ assertEquals("POST", r.getString("httpMethod"));
+ expected = "[{category:'attr',name:'a',description:'Test1.d'},{category:'attr',name:'a2',description:'Test1.h'},{category:'attr',name:'e'},{category:'content',name:'',description:'Test1.f'},{category:'foo',name:'bar',description:'Test1.k'},{category:'header',name:'D',description:'Test1.g'},{category:'header',name:'D2',description:'Test1.j'},{category:'header',name:'g'},{category:'param',name:'b',description:'Test1.e'},{category:'param',name:'b2',description:'Test1.i'},{category:'param',name:'f'}]";
+ assertEquals(expected, r.getObjectList("input").toString());
+ expected = "[{status:200,description:'OK',output:[]},{status:201,description:'Test1.l',output:[{category:'foo',name:'bar',description:'Test1.m'}]}]";
+ assertEquals(expected, r.getObjectList("responses").toString());
+
+ client.closeQuietly();
+ }
+
+ // ====================================================================================================
+ // test2 - Pull labels from resource bundles only - simple keys.
+ // ====================================================================================================
+ @Test
+ public void test2() throws Exception {
+ RestClient client = new TestRestClient(JsonSerializer.DEFAULT, JsonParser.DEFAULT);
+ ObjectMap r = null;
+ String expected = null;
+
+ // Labels all pulled from annotations.
+ r = client.doOptions(URL + "/test2").getResponse(ObjectMap.class);
+ assertEquals("Test2.a", r.getString("label"));
+ assertEquals("Test2.b", r.getString("description"));
+ r = r.getObjectList("methods").getObjectMap(0);
+ assertEquals("test2", r.getString("javaMethod"));
+ assertEquals("POST", r.getString("httpMethod"));
+ expected = "[{category:'attr',name:'a',description:'Test2.d'},{category:'attr',name:'a2',description:'Test2.h'},{category:'attr',name:'e'},{category:'content',name:'',description:'Test2.f'},{category:'foo',name:'bar',description:'Test2.k'},{category:'header',name:'D',description:'Test2.g'},{category:'header',name:'D2',description:'Test2.j'},{category:'header',name:'g'},{category:'param',name:'b',description:'Test2.e'},{category:'param',name:'b2',description:'Test2.i'},{category:'param',name:'f'}]";
+ assertEquals(expected, r.getObjectList("input").toString());
+ expected = "[{status:200,description:'OK2',output:[]},{status:201,description:'Test2.l',output:[{category:'foo',name:'bar',description:'Test2.m'}]}]";
+ assertEquals(expected, r.getObjectList("responses").toString());
+
+ client.closeQuietly();
+ }
+
+ // ====================================================================================================
+ // test3 - Pull labels from resource bundles only - keys with class names.
+ // ====================================================================================================
+ @Test
+ public void test3() throws Exception {
+ RestClient client = new TestRestClient(JsonSerializer.DEFAULT, JsonParser.DEFAULT);
+ ObjectMap r = null;
+ String expected = null;
+
+ // Labels all pulled from annotations.
+ r = client.doOptions(URL + "/test3").getResponse(ObjectMap.class);
+ assertEquals("Test3.a", r.getString("label"));
+ assertEquals("Test3.b", r.getString("description"));
+ r = r.getObjectList("methods").getObjectMap(1);
+ assertEquals("test3", r.getString("javaMethod"));
+ assertEquals("POST", r.getString("httpMethod"));
+ expected = "[{category:'attr',name:'a',description:'Test3.d'},{category:'attr',name:'a2',description:'Test3.h'},{category:'attr',name:'e'},{category:'content',name:'',description:'Test3.f'},{category:'foo',name:'bar',description:'Test3.k'},{category:'header',name:'D',description:'Test3.g'},{category:'header',name:'D2',description:'Test3.j'},{category:'header',name:'g'},{category:'param',name:'b',description:'Test3.e'},{category:'param',name:'b2',description:'Test3.i'},{category:'param',name:'f'}]";
+ assertEquals(expected, r.getObjectList("input").toString());
+ expected = "[{status:200,description:'OK3',output:[]},{status:201,description:'Test3.l',output:[{category:'foo',name:'bar',description:'Test3.m'}]}]";
+ assertEquals(expected, r.getObjectList("responses").toString());
+
+ client.closeQuietly();
+ }
+
+ // ====================================================================================================
+ // test4 - Pull labels from resource bundles only. Values have localized variables to resolve.
+ // ====================================================================================================
+ @Test
+ public void test4() throws Exception {
+ RestClient client = new TestRestClient(JsonSerializer.DEFAULT, JsonParser.DEFAULT);
+ ObjectMap r = null;
+ String expected = null;
+
+ // Labels all pulled from annotations.
+ r = client.doOptions(URL + "/test4").getResponse(ObjectMap.class);
+ assertEquals("baz", r.getString("label"));
+ assertEquals("baz", r.getString("description"));
+ r = r.getObjectList("methods").getObjectMap(0);
+ assertEquals("test4", r.getString("javaMethod"));
+ assertEquals("POST", r.getString("httpMethod"));
+ expected = "[{category:'attr',name:'a',description:'baz'},{category:'attr',name:'a2',description:'baz'},{category:'attr',name:'e'},{category:'content',name:'',description:'baz'},{category:'foo',name:'bar',description:'baz'},{category:'header',name:'D',description:'baz'},{category:'header',name:'D2',description:'baz'},{category:'header',name:'g'},{category:'param',name:'b',description:'baz'},{category:'param',name:'b2',description:'baz'},{category:'param',name:'f'}]";
+ assertEquals(expected, r.getObjectList("input").toString());
+ expected = "[{status:200,description:'foobazfoobazfoo',output:[]},{status:201,description:'baz',output:[{category:'foo',name:'bar',description:'baz'}]}]";
+ assertEquals(expected, r.getObjectList("responses").toString());
+
+ client.closeQuietly();
+ }
+
+ // ====================================================================================================
+ // test5 - Pull labels from resource bundles only. Values have request variables to resolve.
+ // ====================================================================================================
+ @Test
+ public void test5() throws Exception {
+ RestClient client = new TestRestClient(JsonSerializer.DEFAULT, JsonParser.DEFAULT);
+ ObjectMap r = null;
+ String expected = null;
+
+ // Labels all pulled from annotations.
+ r = client.doOptions(URL + "/test5").getResponse(ObjectMap.class);
+ assertEquals("baz2", r.getString("label"));
+ assertEquals("baz2", r.getString("description"));
+ r = r.getObjectList("methods").getObjectMap(0);
+ assertEquals("test5", r.getString("javaMethod"));
+ assertEquals("POST", r.getString("httpMethod"));
+ expected = "[{category:'attr',name:'a',description:'baz2'},{category:'attr',name:'a2',description:'baz2'},{category:'attr',name:'e'},{category:'content',name:'',description:'baz2'},{category:'foo',name:'bar',description:'baz2'},{category:'header',name:'D',description:'baz2'},{category:'header',name:'D2',description:'baz2'},{category:'header',name:'g'},{category:'param',name:'b',description:'baz2'},{category:'param',name:'b2',description:'baz2'},{category:'param',name:'f'}]";
+ assertEquals(expected, r.getObjectList("input").toString());
+ expected = "[{status:200,description:'foobaz2foobaz2foo',output:[]},{status:201,description:'baz2',output:[{category:'foo',name:'bar',description:'baz2'}]}]";
+ assertEquals(expected, r.getObjectList("responses").toString());
+
+ client.closeQuietly();
+ }
+
+ // ====================================================================================================
+ // test6 - Pull labels from annotations only, but annotations contain variables.
+ // ====================================================================================================
+ @Test
+ public void test6() throws Exception {
+ RestClient client = new TestRestClient(JsonSerializer.DEFAULT, JsonParser.DEFAULT);
+ ObjectMap r = null;
+ String expected = null;
+
+ // Labels all pulled from annotations.
+ r = client.doOptions(URL + "/test6").getResponse(ObjectMap.class);
+ assertEquals("baz", r.getString("label"));
+ assertEquals("baz", r.getString("description"));
+ r = r.getObjectList("methods").getObjectMap(0);
+ assertEquals("test6", r.getString("javaMethod"));
+ assertEquals("POST", r.getString("httpMethod"));
+ expected = "[{category:'attr',name:'a',description:'baz'},{category:'attr',name:'a2',description:'baz'},{category:'attr',name:'e'},{category:'content',name:'',description:'baz'},{category:'foo',name:'bar',description:'baz'},{category:'header',name:'D',description:'baz'},{category:'header',name:'D2',description:'baz'},{category:'header',name:'g'},{category:'param',name:'b',description:'baz'},{category:'param',name:'b2',description:'baz'},{category:'param',name:'f'}]";
+ assertEquals(expected, r.getObjectList("input").toString());
+ expected = "[{status:200,description:'OK',output:[]},{status:201,description:'baz',output:[{category:'foo',name:'bar',description:'baz'}]}]";
+ assertEquals(expected, r.getObjectList("responses").toString());
+
+ client.closeQuietly();
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestNoParserInputTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestNoParserInputTest.java b/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestNoParserInputTest.java
new file mode 100755
index 0000000..6a42c93
--- /dev/null
+++ b/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestNoParserInputTest.java
@@ -0,0 +1,70 @@
+/***************************************************************************************************************************
+ * 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.juneau.server;
+
+import static javax.servlet.http.HttpServletResponse.*;
+import static org.apache.juneau.server.TestUtils.*;
+import static org.junit.Assert.*;
+
+import org.apache.juneau.client.*;
+import org.apache.juneau.plaintext.*;
+import org.junit.*;
+
+public class TestNoParserInputTest {
+
+ private static String URL = "/testNoParserInput";
+ private static boolean debug = false;
+
+ //====================================================================================================
+ // @Content annotated InputStream.
+ //====================================================================================================
+ @Test
+ public void testInputStream() throws Exception {
+ RestClient client = new TestRestClient(PlainTextSerializer.class, PlainTextParser.class);
+ String r = client.doPut(URL + "/testInputStream", "foo").getResponseAsString();
+ assertEquals("foo", r);
+
+ client.closeQuietly();
+ }
+
+ //====================================================================================================
+ // @Content annotated Reader.
+ //====================================================================================================
+ @Test
+ public void testReader() throws Exception {
+ RestClient client = new TestRestClient(PlainTextSerializer.class, PlainTextParser.class);
+ String r = client.doPut(URL + "/testReader", "foo").getResponseAsString();
+ assertEquals("foo", r);
+
+ client.closeQuietly();
+ }
+
+ //====================================================================================================
+ // @Content annotated PushbackReader.
+ // This should always fail since the servlet reader is not a pushback reader.
+ //====================================================================================================
+ @Test
+ public void testPushbackReader() throws Exception {
+ RestClient client = new TestRestClient(PlainTextSerializer.class, PlainTextParser.class);
+ try {
+ client.doPut(URL + "/testPushbackReader?noTrace=true", "foo").getResponseAsString();
+ fail("Exception expected");
+ } catch (RestCallException e) {
+ checkErrorResponse(debug, e, SC_BAD_REQUEST,
+ "Invalid argument type passed to the following method:",
+ "'public java.lang.String org.apache.juneau.server.TestNoParserInput.testPushbackReader(java.io.PushbackReader) throws java.lang.Exception'");
+ }
+
+ client.closeQuietly();
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestOnPostCallTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestOnPostCallTest.java b/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestOnPostCallTest.java
new file mode 100755
index 0000000..9ad422c
--- /dev/null
+++ b/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestOnPostCallTest.java
@@ -0,0 +1,121 @@
+/***************************************************************************************************************************
+ * 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.juneau.server;
+
+import static org.junit.Assert.*;
+
+import java.io.*;
+
+import org.apache.juneau.client.*;
+import org.junit.*;
+
+public class TestOnPostCallTest {
+
+ private static String URL = "/testOnPostCall";
+
+ //====================================================================================================
+ // Properties overridden via properties annotation.
+ //====================================================================================================
+ @Test
+ public void testPropertiesOverridenByAnnotation() throws Exception {
+ RestClient client = new TestRestClient().setAccept("text/s1");
+ String url = URL + "/testPropertiesOverridenByAnnotation";
+ String r;
+ RestCall rc;
+
+ r = client.doPut(url, new StringReader("")).getResponseAsString();
+ assertEquals("p1=sp1,p2=xp2,p3=mp3,p4=xp4,p5=xp5,contentType=text/s1", r);
+
+ r = client.doPut(url, new StringReader("")).setHeader("Override-Accept", "text/s2").getResponseAsString();
+ assertEquals("p1=sp1,p2=xp2,p3=mp3,p4=xp4,p5=xp5,contentType=text/s2", r);
+
+ rc = client.doPut(url, new StringReader("")).setHeader("Override-Content-Type", "text/s3").connect();
+ r = rc.getResponseAsString();
+ assertEquals("p1=sp1,p2=xp2,p3=mp3,p4=xp4,p5=xp5,contentType=text/s1", r);
+ assertTrue(rc.getResponse().getFirstHeader("Content-Type").getValue().startsWith("text/s3"));
+
+ client.closeQuietly();
+ }
+
+ //====================================================================================================
+ // Properties overridden via properties annotation. Default Accept header.
+ //====================================================================================================
+ @Test
+ public void testPropertiesOverridenByAnnotationDefaultAccept() throws Exception {
+ RestClient client = new TestRestClient().setAccept("");
+ String url = URL + "/testPropertiesOverridenByAnnotation";
+ String r;
+ RestCall rc;
+
+ r = client.doPut(url, new StringReader("")).getResponseAsString();
+ assertEquals("p1=sp1,p2=xp2,p3=mp3,p4=xp4,p5=xp5,contentType=text/s2", r);
+
+ r = client.doPut(url, new StringReader("")).setHeader("Override-Accept", "text/s3").getResponseAsString();
+ assertEquals("p1=sp1,p2=xp2,p3=mp3,p4=xp4,p5=xp5,contentType=text/s3", r);
+
+ rc = client.doPut(url, new StringReader("")).setHeader("Override-Content-Type", "text/s3").connect();
+ r = rc.getResponseAsString();
+ assertEquals("p1=sp1,p2=xp2,p3=mp3,p4=xp4,p5=xp5,contentType=text/s2", r);
+ assertTrue(rc.getResponse().getFirstHeader("Content-Type").getValue().startsWith("text/s3"));
+
+ client.closeQuietly();
+ }
+
+ //====================================================================================================
+ // Properties overridden programmatically.
+ //====================================================================================================
+ @Test
+ public void testPropertiesOverriddenProgramatically() throws Exception {
+ RestClient client = new TestRestClient().setAccept("text/s1");
+ String url = URL + "/testPropertiesOverriddenProgramatically";
+ String r;
+ RestCall rc;
+
+ r = client.doPut(url, new StringReader("")).getResponseAsString();
+ assertEquals("p1=sp1,p2=xp2,p3=pp3,p4=xp4,p5=xp5,contentType=text/s1", r);
+
+ r = client.doPut(url, new StringReader("")).setHeader("Override-Accept", "text/s2").getResponseAsString();
+ assertEquals("p1=sp1,p2=xp2,p3=pp3,p4=xp4,p5=xp5,contentType=text/s2", r);
+
+ rc = client.doPut(url, new StringReader("")).setHeader("Override-Content-Type", "text/s3").connect();
+ r = rc.getResponseAsString();
+ assertEquals("p1=sp1,p2=xp2,p3=pp3,p4=xp4,p5=xp5,contentType=text/s1", r);
+ assertTrue(rc.getResponse().getFirstHeader("Content-Type").getValue().startsWith("text/s3"));
+
+ client.closeQuietly();
+ }
+
+ //====================================================================================================
+ // Properties overridden programmatically. Default Accept header.
+ //====================================================================================================
+ @Test
+ public void testPropertiesOverriddenProgramaticallyDefaultAccept() throws Exception {
+ RestClient client = new TestRestClient().setAccept("");
+ String url = URL + "/testPropertiesOverriddenProgramatically";
+ String r;
+ RestCall rc;
+
+ r = client.doPut(url, new StringReader("")).getResponseAsString();
+ assertEquals("p1=sp1,p2=xp2,p3=pp3,p4=xp4,p5=xp5,contentType=text/s2", r);
+
+ r = client.doPut(url, new StringReader("")).setHeader("Override-Accept", "text/s3").getResponseAsString();
+ assertEquals("p1=sp1,p2=xp2,p3=pp3,p4=xp4,p5=xp5,contentType=text/s3", r);
+
+ rc = client.doPut(url, new StringReader("")).setHeader("Override-Content-Type", "text/s3").connect();
+ r = rc.getResponseAsString();
+ assertEquals("p1=sp1,p2=xp2,p3=pp3,p4=xp4,p5=xp5,contentType=text/s2", r);
+ assertTrue(rc.getResponse().getFirstHeader("Content-Type").getValue().startsWith("text/s3"));
+
+ client.closeQuietly();
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestOnPreCallTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestOnPreCallTest.java b/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestOnPreCallTest.java
new file mode 100755
index 0000000..bda13b0
--- /dev/null
+++ b/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestOnPreCallTest.java
@@ -0,0 +1,61 @@
+/***************************************************************************************************************************
+ * 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.juneau.server;
+
+import static org.junit.Assert.*;
+
+import java.io.*;
+
+import org.apache.juneau.client.*;
+import org.junit.*;
+
+public class TestOnPreCallTest {
+
+ private static String URL = "/testOnPreCall";
+
+ //====================================================================================================
+ // Properties overridden via properties annotation.
+ //====================================================================================================
+ @Test
+ public void testPropertiesOverriddenByAnnotation() throws Exception {
+ RestClient client = new TestRestClient().setContentType("text/a1").setAccept("text/plain");
+ String url = URL + "/testPropertiesOverriddenByAnnotation";
+ String r;
+
+ r = client.doPut(url, new StringReader("")).getResponseAsString();
+ assertEquals("p1=sp1,p2=xp2,p3=mp3,p4=xp4,p5=xp5,contentType=text/a1", r);
+
+ r = client.doPut(url, new StringReader("")).setHeader("Override-Content-Type", "text/a2").getResponseAsString();
+ assertEquals("p1=sp1,p2=xp2,p3=mp3,p4=xp4,p5=xp5,contentType=text/a2", r);
+
+ client.closeQuietly();
+ }
+
+ //====================================================================================================
+ // Properties overridden programmatically.
+ //====================================================================================================
+ @Test
+ public void testPropertiesOverriddenProgrammatically() throws Exception {
+ RestClient client = new TestRestClient().setContentType("text/a1").setAccept("text/plain");
+ String url = URL + "/testPropertiesOverriddenProgrammatically";
+ String r;
+
+ r = client.doPut(url, new StringReader("")).getResponseAsString();
+ assertEquals("p1=sp1,p2=xp2,p3=pp3,p4=pp4,p5=xp5,contentType=text/a1", r);
+
+ r = client.doPut(url, new StringReader("")).setHeader("Override-Content-Type", "text/a2").getResponseAsString();
+ assertEquals("p1=sp1,p2=xp2,p3=pp3,p4=pp4,p5=xp5,contentType=text/a2", r);
+
+ client.closeQuietly();
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestOptionsWithoutNlsTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestOptionsWithoutNlsTest.java b/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestOptionsWithoutNlsTest.java
new file mode 100755
index 0000000..b4f7431
--- /dev/null
+++ b/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestOptionsWithoutNlsTest.java
@@ -0,0 +1,51 @@
+/***************************************************************************************************************************
+ * 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.juneau.server;
+
+import static org.junit.Assert.*;
+
+import org.apache.juneau.client.*;
+import org.apache.juneau.json.*;
+import org.apache.juneau.server.labels.*;
+import org.junit.*;
+
+public class TestOptionsWithoutNlsTest {
+
+ private static String URL = "/testOptionsWithoutNls";
+
+ //====================================================================================================
+ // Should get to the options page without errors
+ //====================================================================================================
+ @Test
+ public void testOptions() throws Exception {
+ RestClient client = new TestRestClient(JsonSerializer.DEFAULT, JsonParser.DEFAULT);
+ RestCall r = client.doOptions(URL + "/testOptions");
+ ResourceOptions o = r.getResponse(ResourceOptions.class);
+ assertEquals("", o.getDescription());
+
+ client.closeQuietly();
+ }
+
+ //====================================================================================================
+ // Missing resource bundle should cause {!!x} string.
+ //====================================================================================================
+ @Test
+ public void testMissingResourceBundle() throws Exception {
+ RestClient client = new TestRestClient(JsonSerializer.DEFAULT, JsonParser.DEFAULT);
+ RestCall r = client.doGet(URL + "/testMissingResourceBundle");
+ String o = r.getResponse(String.class);
+ assertEquals("{!!bad}", o);
+
+ client.closeQuietly();
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestOverlappingMethodsTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestOverlappingMethodsTest.java b/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestOverlappingMethodsTest.java
new file mode 100755
index 0000000..54e4c76
--- /dev/null
+++ b/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestOverlappingMethodsTest.java
@@ -0,0 +1,170 @@
+/***************************************************************************************************************************
+ * 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.juneau.server;
+
+import static javax.servlet.http.HttpServletResponse.*;
+import static org.apache.juneau.server.TestUtils.*;
+import static org.junit.Assert.*;
+
+import org.apache.juneau.client.*;
+import org.junit.*;
+
+public class TestOverlappingMethodsTest {
+
+ private static String URL = "/testOverlappingMethods";
+ private static boolean debug = false;
+
+ //====================================================================================================
+ // Overlapping guards
+ //====================================================================================================
+ @Test
+ public void testOverlappingGuards1() throws Exception {
+ RestClient client = new TestRestClient().setHeader("Accept", "text/plain");
+ String r;
+ String url = URL + "/testOverlappingGuards1";
+
+ r = client.doGet(url + "?t1=1").getResponseAsString();
+ assertEquals("test1_doGet", r);
+
+ try {
+ client.doGet(url + "?noTrace=true").connect();
+ fail("Exception expected");
+ } catch (RestCallException e) {
+ checkErrorResponse(debug, e, SC_FORBIDDEN, "Access denied by guard");
+ }
+
+ client.closeQuietly();
+ }
+
+ //====================================================================================================
+ // Overlapping guards
+ //====================================================================================================
+ @Test
+ public void testOverlappingGuards2() throws Exception {
+ RestClient client = new TestRestClient().setHeader("Accept", "text/plain");
+ String r;
+ String url = URL + "/testOverlappingGuards2";
+ try {
+ client.doGet(url + "?noTrace=true").connect();
+ fail("Exception expected");
+ } catch (RestCallException e) {
+ checkErrorResponse(debug, e, SC_FORBIDDEN, "Access denied by guard");
+ }
+
+ try {
+ client.doGet(url + "?t1=1&noTrace=true").connect();
+ fail("Exception expected");
+ } catch (RestCallException e) {
+ checkErrorResponse(debug, e, SC_FORBIDDEN, "Access denied by guard");
+ }
+
+ try {
+ client.doGet(url + "?t2=2&noTrace=true").connect();
+ fail("Exception expected");
+ } catch (RestCallException e) {
+ checkErrorResponse(debug, e, SC_FORBIDDEN, "Access denied by guard");
+ }
+
+ r = client.doGet(url + "?t1=1&t2=2").getResponseAsString();
+ assertEquals("test2_doGet", r);
+
+ client.closeQuietly();
+ }
+
+ //====================================================================================================
+ // Overlapping matchers
+ //====================================================================================================
+ @Test
+ public void testOverlappingMatchers1() throws Exception {
+ RestClient client = new TestRestClient().setHeader("Accept", "text/plain");
+ String r;
+ String url = URL + "/testOverlappingMatchers1";
+
+ r = client.doGet(url + "?t1=1").getResponseAsString();
+ assertEquals("test3a", r);
+
+ r = client.doGet(url + "?t2=2").getResponseAsString();
+ assertEquals("test3b", r);
+
+ r = client.doGet(url).getResponseAsString();
+ assertEquals("test3c", r);
+
+ client.closeQuietly();
+ }
+
+ //====================================================================================================
+ // Overlapping matchers
+ //====================================================================================================
+ @Test
+ public void testOverlappingMatchers2() throws Exception {
+ RestClient client = new TestRestClient().setHeader("Accept", "text/plain");
+ String r;
+ String url = URL + "/testOverlappingMatchers2";
+
+ r = client.doGet(url + "?t1=1").getResponseAsString();
+ assertEquals("test4b", r);
+
+ r = client.doGet(url + "?t2=2").getResponseAsString();
+ assertEquals("test4b", r);
+
+ r = client.doGet(url + "?t1=1&t2=2").getResponseAsString();
+ assertEquals("test4b", r);
+
+ r = client.doGet(url + "?tx=x").getResponseAsString();
+ assertEquals("test4a", r);
+
+ client.closeQuietly();
+ }
+
+ //====================================================================================================
+ // Overlapping URL patterns
+ //====================================================================================================
+ @Test
+ public void testOverlappingUrlPatterns() throws Exception {
+ RestClient client = new TestRestClient().setHeader("Accept", "text/plain");
+ String r;
+ String url = URL + "/testOverlappingUrlPatterns";
+
+ // [/test5] = [test5a]
+ // [/test5/*] = [test5b] -- Cannot get called.
+ // [/test5/foo] = [test5c]
+ // [/test5/foo/*] = [test5d]
+ // [/test5/{id}] = [test5e]
+ // [/test5/{id}/*] = [test5f]
+ // [/test5/{id}/foo] = [test5g]
+ // [/test5/{id}/foo/*] = [test5h]
+
+ r = client.doGet(url).getResponseAsString();
+ assertEquals("test5a", r);
+
+ r = client.doGet(url + "/foo").getResponseAsString();
+ assertEquals("test5c", r);
+
+ r = client.doGet(url + "/foo/x").getResponseAsString();
+ assertEquals("test5d", r);
+
+ r = client.doGet(url + "/x").getResponseAsString();
+ assertEquals("test5e", r);
+
+ r = client.doGet(url + "/x/x").getResponseAsString();
+ assertEquals("test5f", r);
+
+ r = client.doGet(url + "/x/foo").getResponseAsString();
+ assertEquals("test5g", r);
+
+ r = client.doGet(url + "/x/foo/x").getResponseAsString();
+ assertEquals("test5h", r);
+
+ client.closeQuietly();
+ }
+}
[38/44] incubator-juneau git commit: Rename CT_* testcases.
Posted by ja...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestAcceptCharsetTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestAcceptCharsetTest.java b/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestAcceptCharsetTest.java
new file mode 100755
index 0000000..93a02b5
--- /dev/null
+++ b/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestAcceptCharsetTest.java
@@ -0,0 +1,123 @@
+/***************************************************************************************************************************
+ * 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.juneau.server;
+
+import static javax.servlet.http.HttpServletResponse.*;
+import static org.apache.juneau.server.TestUtils.*;
+import static org.junit.Assert.*;
+
+import java.io.*;
+
+import org.apache.juneau.client.*;
+import org.apache.juneau.internal.*;
+import org.junit.*;
+
+public class TestAcceptCharsetTest {
+
+ boolean debug = false;
+
+ //====================================================================================================
+ // Test that Q-values are being resolved correctly.
+ //====================================================================================================
+ @Test
+ public void testQValues() throws Exception {
+ RestClient client = new TestRestClient().setHeader("Accept", "text/plain");
+
+ check1(client, "utf-8", "utf-8");
+ check1(client, "iso-8859-1", "iso-8859-1");
+ check1(client, "bad,utf-8", "utf-8");
+ check1(client, "utf-8,bad", "utf-8");
+ check1(client, "bad;q=0.9,utf-8;q=0.1", "utf-8");
+ check1(client, "bad;q=0.1,utf-8;q=0.9", "utf-8");
+ check1(client, "utf-8,iso-8859-1", "utf-8");
+ check1(client, "iso-8859-1,utf-8", "utf-8");
+ check1(client, "utf-8;q=0.9,iso-8859-1;q=0.1", "utf-8");
+ check1(client, "utf-8;q=0.1,iso-8859-1;q=0.9", "iso-8859-1");
+ check1(client, "*", "utf-8");
+ check1(client, "bad,iso-8859-1;q=0.5,*;q=0.1", "iso-8859-1");
+ check1(client, "bad,iso-8859-1;q=0.1,*;q=0.5", "utf-8");
+
+ client.closeQuietly();
+ }
+
+ private void check1(RestClient client, String requestCharset, String responseCharset) throws Exception {
+ RestCall r;
+ InputStream is;
+ String url = "/testAcceptCharset/testQValues";
+ r = client.doGet(url).setHeader("Accept-Charset", requestCharset).connect();
+ assertTrue(r.getResponse().getFirstHeader("Content-Type").getValue().toLowerCase().contains(responseCharset));
+ is = r.getInputStream();
+ assertEquals("foo", IOUtils.read(new InputStreamReader(is, responseCharset)));
+ }
+
+ //====================================================================================================
+ // Validate various Accept-Charset variations.
+ //====================================================================================================
+ @Test
+ public void testCharsetOnResponse() throws Exception {
+ RestClient client = new TestRestClient().setAccept("text/plain").setContentType("text/plain");
+ String url = "/testAcceptCharset/testCharsetOnResponse";
+ String r;
+
+ r = client.doPut(url, new StringReader("")).getResponseAsString();
+ assertEquals("utf-8/utf-8", r.toLowerCase());
+
+ r = client.doPut(url, new StringReader("")).setHeader("Accept-Charset", "Shift_JIS").getResponseAsString();
+ assertEquals("utf-8/shift_jis", r.toLowerCase());
+
+ try {
+ r = client.doPut(url+"?noTrace=true", new StringReader("")).setHeader("Accept-Charset", "BAD").getResponseAsString();
+ fail("Exception expected");
+ } catch (RestCallException e) {
+ checkErrorResponse(debug, e, SC_NOT_ACCEPTABLE, "No supported charsets in header 'Accept-Charset': 'BAD'");
+ }
+
+ r = client.doPut(url, new StringReader("")).setHeader("Accept-Charset", "UTF-8").getResponseAsString();
+ assertEquals("utf-8/utf-8", r.toLowerCase());
+
+ r = client.doPut(url, new StringReader("")).setHeader("Accept-Charset", "bad,iso-8859-1").getResponseAsString();
+ assertEquals("utf-8/iso-8859-1", r.toLowerCase());
+
+ r = client.doPut(url, new StringReader("")).setHeader("Accept-Charset", "bad;q=0.9,iso-8859-1;q=0.1").getResponseAsString();
+ assertEquals("utf-8/iso-8859-1", r.toLowerCase());
+
+ r = client.doPut(url, new StringReader("")).setHeader("Accept-Charset", "bad;q=0.1,iso-8859-1;q=0.9").getResponseAsString();
+ assertEquals("utf-8/iso-8859-1", r.toLowerCase());
+
+ client.setHeader("Accept-Charset", "utf-8");
+
+ r = client.doPut(url, new StringReader("")).setHeader("Content-Type", "text/plain").getResponseAsString();
+ assertEquals("utf-8/utf-8", r.toLowerCase());
+
+ r = client.doPut(url, new StringReader("")).setHeader("Content-Type", "text/plain;charset=utf-8").getResponseAsString();
+ assertEquals("utf-8/utf-8", r.toLowerCase());
+
+ r = client.doPut(url, new StringReader("")).setHeader("Content-Type", "text/plain;charset=UTF-8").getResponseAsString();
+ assertEquals("utf-8/utf-8", r.toLowerCase());
+
+ r = client.doPut(url, new StringReader("")).setHeader("Content-Type", "text/plain;charset=iso-8859-1").getResponseAsString();
+ assertEquals("iso-8859-1/utf-8", r.toLowerCase());
+
+ r = client.doPut(url, new StringReader("")).setHeader("Content-Type", "text/plain;charset=Shift_JIS").getResponseAsString();
+ assertEquals("shift_jis/utf-8", r.toLowerCase());
+
+ try {
+ r = client.doPut(url + "?noTrace=true&Content-Type=text/plain;charset=BAD", new StringReader("")).getResponseAsString();
+ fail("Exception expected");
+ } catch (RestCallException e) {
+ checkErrorResponse(debug, e, SC_UNSUPPORTED_MEDIA_TYPE, "Unsupported charset in header 'Content-Type': 'text/plain;charset=BAD'");
+ }
+
+ client.closeQuietly();
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestBeanContextPropertiesTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestBeanContextPropertiesTest.java b/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestBeanContextPropertiesTest.java
new file mode 100755
index 0000000..50ec9c6
--- /dev/null
+++ b/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestBeanContextPropertiesTest.java
@@ -0,0 +1,37 @@
+/***************************************************************************************************************************
+ * 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.juneau.server;
+
+import static org.junit.Assert.*;
+
+import org.apache.juneau.client.*;
+import org.apache.juneau.json.*;
+import org.junit.*;
+
+public class TestBeanContextPropertiesTest {
+
+ boolean debug = false;
+
+ //====================================================================================================
+ // Validate that filters defined on class filter to underlying bean context.
+ //====================================================================================================
+ @Test
+ public void testClassTransforms() throws Exception {
+ RestClient client = new TestRestClient(JsonSerializer.class, JsonParser.class);
+ String r;
+ r = client.doGet("/testBeanContext/testClassTransforms/2001-07-04T15:30:45Z?d2=2001-07-05T15:30:45Z").setHeader("X-D3", "2001-07-06T15:30:45Z").getResponseAsString();
+ assertEquals("d1=2001-07-04T15:30:45Z,d2=2001-07-05T15:30:45Z,d3=2001-07-06T15:30:45Z", r);
+
+ client.closeQuietly();
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestCallbackStringsTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestCallbackStringsTest.java b/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestCallbackStringsTest.java
new file mode 100755
index 0000000..2d8ccca
--- /dev/null
+++ b/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestCallbackStringsTest.java
@@ -0,0 +1,50 @@
+/***************************************************************************************************************************
+ * 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.juneau.server;
+
+import static org.junit.Assert.*;
+
+import org.apache.juneau.client.*;
+import org.junit.*;
+
+public class TestCallbackStringsTest {
+
+ //====================================================================================================
+ // Basic tests using &Content parameter
+ //====================================================================================================
+ @Test
+ public void test() throws Exception {
+ RestClient c = new TestRestClient().setAccept("text/json+simple");
+ String r;
+
+ r = c.doCallback("GET /testCallback").getResponseAsString();
+ assertEquals("{method:'GET',headers:{},content:''}", r);
+
+ r = c.doCallback("GET /testCallback some sample content").getResponseAsString();
+ assertEquals("{method:'GET',headers:{},content:'some sample content'}", r);
+
+ r = c.doCallback("GET {Foo-X:123,Foo-Y:'abc'} /testCallback").getResponseAsString();
+ assertEquals("{method:'GET',headers:{'Foo-X':'123','Foo-Y':'abc'},content:''}", r);
+
+ r = c.doCallback("GET { Foo-X : 123, Foo-Y : 'abc' } /testCallback").getResponseAsString();
+ assertEquals("{method:'GET',headers:{'Foo-X':'123','Foo-Y':'abc'},content:''}", r);
+
+ r = c.doCallback("GET {Foo-X:123,Foo-Y:'abc'} /testCallback some sample content ").getResponseAsString();
+ assertEquals("{method:'GET',headers:{'Foo-X':'123','Foo-Y':'abc'},content:'some sample content'}", r);
+
+ r = c.doCallback("PUT {Foo-X:123,Foo-Y:'abc'} /testCallback some sample content ").getResponseAsString();
+ assertEquals("{method:'PUT',headers:{'Foo-X':'123','Foo-Y':'abc'},content:'some sample content'}", r);
+
+ c.closeQuietly();
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestCharsetEncodingsTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestCharsetEncodingsTest.java b/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestCharsetEncodingsTest.java
new file mode 100755
index 0000000..996f283
--- /dev/null
+++ b/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestCharsetEncodingsTest.java
@@ -0,0 +1,96 @@
+/***************************************************************************************************************************
+ * 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.juneau.server;
+
+import static javax.servlet.http.HttpServletResponse.*;
+import static org.apache.juneau.server.TestUtils.*;
+import static org.junit.Assert.*;
+
+import java.io.*;
+
+import org.apache.juneau.client.*;
+import org.apache.juneau.internal.*;
+import org.junit.*;
+
+
+public class TestCharsetEncodingsTest {
+
+ private static boolean debug = false;
+
+ /**
+ * Basic tests to ensure that the correct charsets are found and used
+ * under a variety of scenarios.
+ */
+ @Test
+ public void test() throws Exception {
+ String url = "/testCharsetEncodings";
+ RestClient client = new TestRestClient().setAccept("text/s").setContentType("text/p");
+ InputStream is;
+ String r;
+
+ r = client.doPut(url, new StringReader("foo")).getResponseAsString();
+ if (debug) System.err.println(r);
+ assertEquals("utf-8/foo/utf-8", r);
+
+ is = client.doPut(url, new StringReader("foo")).getInputStream();
+ r = IOUtils.read(new InputStreamReader(is, "utf-8"));
+ if (debug) System.err.println(r);
+ assertEquals("utf-8/foo/utf-8", r);
+
+ client.setHeader("Accept-Charset", "utf-8").setContentType("text/p;charset=utf-8");
+ is = client.doPut(url, new StringReader("foo")).getInputStream();
+ r = IOUtils.read(new InputStreamReader(is, "utf-8"));
+ if (debug) System.err.println(r);
+ assertEquals("utf-8/foo/utf-8", r);
+
+ client.setHeader("Accept-Charset", "Shift_JIS").setContentType("text/p;charset=shift_jis");
+ is = client.doPut(url, new StringReader("foo")).getInputStream();
+ r = IOUtils.read(new InputStreamReader(is, "Shift_JIS"));
+ if (debug) System.err.println(r);
+ assertEquals("shift_jis/foo/shift_jis", r);
+
+ try {
+ client.setHeader("Accept-Charset", "BAD").setContentType("text/p;charset=sjis");
+ is = client.doPut(url + "?noTrace=true", new StringReader("foo")).getInputStream();
+ r = IOUtils.read(new InputStreamReader(is, "sjis"));
+ if (debug) System.err.println(r);
+ fail("Exception expected");
+ } catch (RestCallException e) {
+ checkErrorResponse(debug, e, SC_NOT_ACCEPTABLE, "No supported charsets in header 'Accept-Charset': 'BAD'");
+ }
+
+ client.setAccept("text/s").setHeader("Accept-Charset", "utf-8").setContentType("text/p");
+ is = client.doPut(url+"?Content-Type=text/p", new StringReader("foo")).getInputStream();
+ r = IOUtils.read(new InputStreamReader(is, "utf-8"));
+ if (debug) System.err.println(r);
+ assertEquals("utf-8/foo/utf-8", r);
+
+ client.setAccept("text/s").setContentType("text/bad").setHeader("Accept-Charset", "utf-8");
+ is = client.doPut(url+"?Content-Type=text/p;charset=utf-8", new StringReader("foo")).getInputStream();
+ r = IOUtils.read(new InputStreamReader(is, "utf-8"));
+ if (debug) System.err.println(r);
+ assertEquals("utf-8/foo/utf-8", r);
+
+ try {
+ client.setAccept("text/s").setContentType("text/p").setHeader("Accept-Charset", "utf-8");
+ is = client.doPut(url+"?Content-Type=text/p;charset=BAD&noTrace=true", new StringReader("foo")).getInputStream();
+ r = IOUtils.read(new InputStreamReader(is, "utf-8"));
+ if (debug) System.err.println(r);
+ assertEquals("utf-8/foo/utf-8", r);
+ fail("Exception expected");
+ } catch (RestCallException e) {
+ checkErrorResponse(debug, e, SC_UNSUPPORTED_MEDIA_TYPE, "Unsupported charset in header 'Content-Type': 'text/p;charset=BAD'");
+ }
+ client.closeQuietly();
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestClientVersionTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestClientVersionTest.java b/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestClientVersionTest.java
new file mode 100644
index 0000000..96a6304
--- /dev/null
+++ b/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestClientVersionTest.java
@@ -0,0 +1,90 @@
+/***************************************************************************************************************************
+ * 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.juneau.server;
+
+import static org.junit.Assert.*;
+
+import org.apache.juneau.client.*;
+import org.apache.juneau.plaintext.*;
+import org.junit.*;
+
+public class TestClientVersionTest {
+
+ private static String URL = "/testClientVersion";
+
+ //====================================================================================================
+ // Basic tests - default X-Client-Version header.
+ //====================================================================================================
+ @Test
+ public void testDefaultHeader() throws Exception {
+ RestClient c = new TestRestClient(PlainTextSerializer.class, PlainTextParser.class);
+ String url = URL + "/defaultHeader";
+
+ assertEquals("no-version", c.doGet(url).getResponseAsString());
+
+ for (String s : "0, 0.0, 0.1, .1, .9, .99".split("\\s*,\\s*")) {
+ c.setClientVersion(s);
+ assertEquals("[0.0,1.0)", c.doGet(url).getResponseAsString());
+ }
+
+ for (String s : "1, 1.0, 1.0.0, 1.0.1".split("\\s*,\\s*")) {
+ c.setClientVersion(s);
+ assertEquals("[1.0,1.0]", c.doGet(url).getResponseAsString());
+ }
+
+ for (String s : "1.1, 1.1.1, 1.2, 1.9.9".split("\\s*,\\s*")) {
+ c.setClientVersion(s);
+ assertEquals("[1.1,2)", c.doGet(url).getResponseAsString());
+ }
+
+ for (String s : "2, 2.0, 2.1, 9, 9.9".split("\\s*,\\s*")) {
+ c.setClientVersion(s);
+ assertEquals("2", c.doGet(url).getResponseAsString());
+ }
+
+ c.closeQuietly();
+ }
+
+ //====================================================================================================
+ // Basic tests - Custom-Client-Version header.
+ //====================================================================================================
+ @Test
+ public void testCustomHeader() throws Exception {
+ RestClient c = new TestRestClient(PlainTextSerializer.class, PlainTextParser.class);
+ String url = URL + "/customHeader";
+
+ assertEquals("no-version", c.doGet(url).getResponseAsString());
+
+ for (String s : "0, 0.0, 0.1, .1, .9, .99".split("\\s*,\\s*")) {
+ c.setHeader("Custom-Client-Version", s);
+ assertEquals("[0.0,1.0)", c.doGet(url).getResponseAsString());
+ }
+
+ for (String s : "1, 1.0, 1.0.0, 1.0.1".split("\\s*,\\s*")) {
+ c.setHeader("Custom-Client-Version", s);
+ assertEquals("[1.0,1.0]", c.doGet(url).getResponseAsString());
+ }
+
+ for (String s : "1.1, 1.1.1, 1.2, 1.9.9".split("\\s*,\\s*")) {
+ c.setHeader("Custom-Client-Version", s);
+ assertEquals("[1.1,2)", c.doGet(url).getResponseAsString());
+ }
+
+ for (String s : "2, 2.0, 2.1, 9, 9.9".split("\\s*,\\s*")) {
+ c.setHeader("Custom-Client-Version", s);
+ assertEquals("2", c.doGet(url).getResponseAsString());
+ }
+
+ c.closeQuietly();
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestConfigTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestConfigTest.java b/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestConfigTest.java
new file mode 100755
index 0000000..a417093
--- /dev/null
+++ b/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestConfigTest.java
@@ -0,0 +1,58 @@
+/***************************************************************************************************************************
+ * 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.juneau.server;
+
+import static org.apache.juneau.server.TestUtils.*;
+import static org.junit.Assert.*;
+
+import org.apache.juneau.client.*;
+import org.apache.juneau.ini.*;
+import org.apache.juneau.json.*;
+import org.junit.*;
+
+public class TestConfigTest {
+
+ private static String URL = "/testConfig";
+
+ //====================================================================================================
+ // Basic tests
+ //====================================================================================================
+ @Test
+ public void test() throws Exception {
+ RestClient c = new TestRestClient(JsonSerializer.class, JsonParser.class).setAccept("text/json+simple");
+
+ ConfigFile cf = c.doGet(URL).getResponse(ConfigFileImpl.class);
+
+ assertObjectEquals("{int1:'1',int2:'1,2,3',int3:'$C{Test/int1, -1}',int4:'$C{Test/int3, -1}',int5:'$C{XXX, -1}',boolean1:'true',boolean2:'true,true',path:'$E{PATH}',mainClass:'$MF{Main-Class}',importPackage:'$MF{Import-Package}'}", cf.get("Test"));
+
+ assertEquals("'1'", c.doGet(URL + "/Test%2Fint1/" + getName(String.class)).getResponseAsString());
+ assertEquals("['1']", c.doGet(URL + "/Test%2Fint1/" + getName(String[].class)).getResponseAsString());
+ assertEquals("'1,2,3'", c.doGet(URL + "/Test%2Fint2/" + getName(String.class)).getResponseAsString());
+ assertEquals("['1','2','3']", c.doGet(URL + "/Test%2Fint2/" + getName(String[].class)).getResponseAsString());
+ assertEquals("[1,2,3]", c.doGet(URL + "/Test%2Fint2/" + getName(int[].class)).getResponseAsString());
+ assertEquals("[1,2,3]", c.doGet(URL + "/Test%2Fint2/" + getName(Integer[].class)).getResponseAsString());
+ assertEquals("[1]", c.doGet(URL + "/Test%2Fint3/" + getName(int[].class)).getResponseAsString());
+ assertEquals("[1]", c.doGet(URL + "/Test%2Fint4/" + getName(int[].class)).getResponseAsString());
+ assertEquals("[-1]", c.doGet(URL + "/Test%2Fint5/" + getName(int[].class)).getResponseAsString());
+ assertEquals("true", c.doGet(URL + "/Test%2Fboolean1/" + getName(Boolean.class)).getResponseAsString());
+ assertEquals("[true,true]", c.doGet(URL + "/Test%2Fboolean2/" + getName(Boolean[].class)).getResponseAsString());
+ assertTrue(c.doGet(URL + "/Test%2Fpath/" + getName(String.class)).getResponseAsString().length() > 10);
+ assertEquals("'org.apache.juneau.microservice.RestMicroservice'", c.doGet(URL + "/Test%2FmainClass/" + getName(String.class)).getResponseAsString());
+
+ c.closeQuietly();
+ }
+
+ private String getName(Class<?> c) {
+ return RestUtils.encode(c.getName());
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestContentTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestContentTest.java b/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestContentTest.java
new file mode 100755
index 0000000..84a6010
--- /dev/null
+++ b/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestContentTest.java
@@ -0,0 +1,706 @@
+/***************************************************************************************************************************
+ * 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.juneau.server;
+
+import static org.junit.Assert.*;
+
+import java.io.*;
+import java.net.*;
+
+import org.apache.juneau.client.*;
+import org.apache.juneau.json.*;
+import org.apache.juneau.plaintext.*;
+import org.apache.juneau.urlencoding.*;
+import org.junit.*;
+
+public class TestContentTest {
+
+ private static String URL = "/testContent";
+
+ //====================================================================================================
+ // Basic tests using &Content parameter
+ //====================================================================================================
+ @Test
+ public void testUsingContentParam() throws Exception {
+ RestClient c = new TestRestClient().setAccept("text/json+simple");
+ String r;
+
+ // @RestMethod(name="POST", path="/boolean")
+ // public boolean testBool(@Content boolean b) {
+ // return b;
+ // }
+ r = c.doPost(URL + "/boolean?content=true", null).getResponseAsString();
+ assertEquals("true", r);
+ r = c.doPost(URL + "/boolean?content=(true)", null).getResponseAsString();
+ assertEquals("true", r);
+ r = c.doPost(URL + "/boolean?content=$b(true)", null).getResponseAsString();
+ assertEquals("true", r);
+ r = c.doPost(URL + "/boolean?content=false", null).getResponseAsString();
+ assertEquals("false", r);
+ r = c.doPost(URL + "/boolean?content=(false)", null).getResponseAsString();
+ assertEquals("false", r);
+ r = c.doPost(URL + "/boolean?content=$b(false)", null).getResponseAsString();
+ assertEquals("false", r);
+ try {
+ r = c.doPost(URL + "/boolean?content=%00&noTrace=true", null).getResponseAsString();
+ fail("Exception expected!");
+ } catch (RestCallException e) {
+ assertEquals(400, e.getResponseCode());
+ }
+ try {
+ r = c.doPost(URL + "/boolean?content=bad&noTrace=true", null).getResponseAsString();
+ fail("Exception expected!");
+ } catch (RestCallException e) {
+ assertEquals(400, e.getResponseCode());
+ }
+
+
+ // @RestMethod(name="POST", path="/Boolean")
+ // public Boolean testBoolean(@Content Boolean b) {
+ // return b;
+ // }
+ r = c.doPost(URL + "/Boolean?content=true", null).getResponseAsString();
+ assertEquals("true", r);
+ r = c.doPost(URL + "/Boolean?content=(true)", null).getResponseAsString();
+ assertEquals("true", r);
+ r = c.doPost(URL + "/Boolean?content=$b(true)", null).getResponseAsString();
+ assertEquals("true", r);
+ r = c.doPost(URL + "/Boolean?content=false", null).getResponseAsString();
+ assertEquals("false", r);
+ r = c.doPost(URL + "/Boolean?content=(false)", null).getResponseAsString();
+ assertEquals("false", r);
+ r = c.doPost(URL + "/Boolean?content=$b(false)", null).getResponseAsString();
+ assertEquals("false", r);
+ r = c.doPost(URL + "/Boolean?content=%00", null).getResponseAsString();
+ assertEquals("null", r);
+ try {
+ r = c.doPost(URL + "/Boolean?content=bad&noTrace=true", null).getResponseAsString();
+ fail("Exception expected!");
+ } catch (RestCallException e) {
+ assertEquals(400, e.getResponseCode());
+ }
+
+ // @RestMethod(name="POST", path="/int")
+ // public int testInt(@Content int i) {
+ // return i;
+ // }
+ r = c.doPost(URL + "/int?content=-123", null).getResponseAsString();
+ assertEquals("-123", r);
+ r = c.doPost(URL + "/int?content=(-123)", null).getResponseAsString();
+ assertEquals("-123", r);
+ r = c.doPost(URL + "/int?content=$n(-123)", null).getResponseAsString();
+ assertEquals("-123", r);
+ try {
+ r = c.doPost(URL + "/int?content=%00&noTrace=true", null).getResponseAsString();
+ fail("Exception expected!");
+ } catch (RestCallException e) {
+ assertEquals(400, e.getResponseCode());
+ }
+ try {
+ r = c.doPost(URL + "/int?content=bad&noTrace=true", null).getResponseAsString();
+ fail("Exception expected!");
+ } catch (RestCallException e) {
+ assertEquals(400, e.getResponseCode());
+ }
+
+ // @RestMethod(name="POST", path="/Integer")
+ // public Integer testInteger(@Content Integer i) {
+ // return i;
+ // }
+ r = c.doPost(URL + "/Integer?content=-123", null).getResponseAsString();
+ assertEquals("-123", r);
+ r = c.doPost(URL + "/Integer?content=(-123)", null).getResponseAsString();
+ assertEquals("-123", r);
+ r = c.doPost(URL + "/Integer?content=$n(-123)", null).getResponseAsString();
+ assertEquals("-123", r);
+ r = c.doPost(URL + "/Integer?content=%00", null).getResponseAsString();
+ assertEquals("null", r);
+ try {
+ r = c.doPost(URL + "/Integer?content=bad&noTrace=true", null).getResponseAsString();
+ fail("Exception expected!");
+ } catch (RestCallException e) {
+ assertEquals(400, e.getResponseCode());
+ }
+
+ // @RestMethod(name="POST", path="/float")
+ // public float testFloat(@Content float f) {
+ // return f;
+ // }
+ r = c.doPost(URL + "/float?content=-1.23", null).getResponseAsString();
+ assertEquals("-1.23", r);
+ r = c.doPost(URL + "/float?content=(-1.23)", null).getResponseAsString();
+ assertEquals("-1.23", r);
+ r = c.doPost(URL + "/float?content=$n(-1.23)", null).getResponseAsString();
+ assertEquals("-1.23", r);
+ try {
+ r = c.doPost(URL + "/float?content=%00&noTrace=true", null).getResponseAsString();
+ fail("Exception expected!");
+ } catch (RestCallException e) {
+ assertEquals(400, e.getResponseCode());
+ }
+ try {
+ r = c.doPost(URL + "/float?content=bad&noTrace=true", null).getResponseAsString();
+ fail("Exception expected!");
+ } catch (RestCallException e) {
+ assertEquals(400, e.getResponseCode());
+ }
+
+ // @RestMethod(name="POST", path="/Float")
+ // public Float testFloat2(@Content Float f) {
+ // return f;
+ // }
+ r = c.doPost(URL + "/Float?content=-1.23", null).getResponseAsString();
+ assertEquals("-1.23", r);
+ r = c.doPost(URL + "/Float?content=(-1.23)", null).getResponseAsString();
+ assertEquals("-1.23", r);
+ r = c.doPost(URL + "/Float?content=$n(-1.23)", null).getResponseAsString();
+ assertEquals("-1.23", r);
+ r = c.doPost(URL + "/Float?content=%00", null).getResponseAsString();
+ assertEquals("null", r);
+ try {
+ r = c.doPost(URL + "/Float?content=bad&noTrace=true", null).getResponseAsString();
+ fail("Exception expected!");
+ } catch (RestCallException e) {
+ assertEquals(400, e.getResponseCode());
+ }
+
+ // @RestMethod(name="POST", path="/Map")
+ // public TreeMap<String,String> testMap(@Content TreeMap<String,String> m) {
+ // return m;
+ // }
+ r = c.doPost(URL + "/Map?content=(a=b,c=d)", null).getResponseAsString();
+ assertEquals("{a:'b',c:'d'}", r);
+ r = c.doPost(URL + "/Map?content=%00", null).getResponseAsString();
+ assertEquals("null", r);
+ try {
+ r = c.doPost(URL + "/Map?content=bad&noTrace=true", null).getResponseAsString();
+ fail("Exception expected!");
+ } catch (RestCallException e) {
+ assertEquals(400, e.getResponseCode());
+ }
+
+ // @RestMethod(name="POST", path="/B")
+ // public DTO2s.B testPojo1(@Content DTO2s.B b) {
+ // return b;
+ // }
+ DTOs.B b = DTOs.B.create();
+ r = c.doPost(URL + "/B?content=" + UonSerializer.DEFAULT.serialize(b), null).getResponseAsString();
+ assertEquals("{f1:['a','b'],f2:['c','d'],f3:[1,2],f4:[3,4],f5:[['e','f'],['g','h']],f6:[['i','j'],['k','l']],f7:[{a:'a',b:1,c:true},{a:'a',b:1,c:true}],f8:[{a:'a',b:1,c:true},{a:'a',b:1,c:true}],f9:[[{a:'a',b:1,c:true}],[{a:'a',b:1,c:true}]],f10:[[{a:'a',b:1,c:true}],[{a:'a',b:1,c:true}]],f11:['a','b'],f12:['c','d'],f13:[1,2],f14:[3,4],f15:[['e','f'],['g','h']],f16:[['i','j'],['k','l']],f17:[{a:'a',b:1,c:true},{a:'a',b:1,c:true}],f18:[{a:'a',b:1,c:true},{a:'a',b:1,c:true}],f19:[[{a:'a',b:1,c:true}],[{a:'a',b:1,c:true}]],f20:[[{a:'a',b:1,c:true}],[{a:'a',b:1,c:true}]]}", r);
+ r = c.doPost(URL + "/B?content=" + UonSerializer.DEFAULT_SIMPLE.serialize(b), null).getResponseAsString();
+ assertEquals("{f1:['a','b'],f2:['c','d'],f3:[1,2],f4:[3,4],f5:[['e','f'],['g','h']],f6:[['i','j'],['k','l']],f7:[{a:'a',b:1,c:true},{a:'a',b:1,c:true}],f8:[{a:'a',b:1,c:true},{a:'a',b:1,c:true}],f9:[[{a:'a',b:1,c:true}],[{a:'a',b:1,c:true}]],f10:[[{a:'a',b:1,c:true}],[{a:'a',b:1,c:true}]],f11:['a','b'],f12:['c','d'],f13:[1,2],f14:[3,4],f15:[['e','f'],['g','h']],f16:[['i','j'],['k','l']],f17:[{a:'a',b:1,c:true},{a:'a',b:1,c:true}],f18:[{a:'a',b:1,c:true},{a:'a',b:1,c:true}],f19:[[{a:'a',b:1,c:true}],[{a:'a',b:1,c:true}]],f20:[[{a:'a',b:1,c:true}],[{a:'a',b:1,c:true}]]}", r);
+
+ // @RestMethod(name="POST", path="/C")
+ // public DTO2s.C testPojo2(@Content DTO2s.C c) {
+ // return c;
+ // }
+ DTOs.C x = DTOs.C.create();
+ r = c.doPost(URL + "/C?content=" + UonSerializer.DEFAULT.serialize(x), null).getResponseAsString();
+ assertEquals("{f1:['a','b'],f2:['c','d'],f3:[1,2],f4:[3,4],f5:[['e','f'],['g','h']],f6:[['i','j'],['k','l']],f7:[{a:'a',b:1,c:true},{a:'a',b:1,c:true}],f8:[{a:'a',b:1,c:true},{a:'a',b:1,c:true}],f9:[[{a:'a',b:1,c:true}],[{a:'a',b:1,c:true}]],f10:[[{a:'a',b:1,c:true}],[{a:'a',b:1,c:true}]],f11:['a','b'],f12:['c','d'],f13:[1,2],f14:[3,4],f15:[['e','f'],['g','h']],f16:[['i','j'],['k','l']],f17:[{a:'a',b:1,c:true},{a:'a',b:1,c:true}],f18:[{a:'a',b:1,c:true},{a:'a',b:1,c:true}],f19:[[{a:'a',b:1,c:true}],[{a:'a',b:1,c:true}]],f20:[[{a:'a',b:1,c:true}],[{a:'a',b:1,c:true}]]}", r);
+ r = c.doPost(URL + "/C?content=" + UonSerializer.DEFAULT_SIMPLE.serialize(x), null).getResponseAsString();
+ assertEquals("{f1:['a','b'],f2:['c','d'],f3:[1,2],f4:[3,4],f5:[['e','f'],['g','h']],f6:[['i','j'],['k','l']],f7:[{a:'a',b:1,c:true},{a:'a',b:1,c:true}],f8:[{a:'a',b:1,c:true},{a:'a',b:1,c:true}],f9:[[{a:'a',b:1,c:true}],[{a:'a',b:1,c:true}]],f10:[[{a:'a',b:1,c:true}],[{a:'a',b:1,c:true}]],f11:['a','b'],f12:['c','d'],f13:[1,2],f14:[3,4],f15:[['e','f'],['g','h']],f16:[['i','j'],['k','l']],f17:[{a:'a',b:1,c:true},{a:'a',b:1,c:true}],f18:[{a:'a',b:1,c:true},{a:'a',b:1,c:true}],f19:[[{a:'a',b:1,c:true}],[{a:'a',b:1,c:true}]],f20:[[{a:'a',b:1,c:true}],[{a:'a',b:1,c:true}]]}", r);
+
+ c.closeQuietly();
+ }
+
+ //====================================================================================================
+ // Basic tests using &Content parameter with &Accept=text/json
+ //====================================================================================================
+ @Test
+ public void testUsingContentParamJsonHeader() throws Exception {
+ RestClient c = new TestRestClient().setAccept("text/json+simple").setHeader("Content-Type", "text/json");
+ String r;
+
+ // @RestMethod(name="POST", path="/boolean")
+ // public boolean testBool(@Content boolean b) {
+ // return b;
+ // }
+ r = c.doPost(URL + "/boolean?content=true", null).getResponseAsString();
+ assertEquals("true", r);
+ r = c.doPost(URL + "/boolean?content=false", null).getResponseAsString();
+ assertEquals("false", r);
+ try {
+ r = c.doPost(URL + "/boolean?content=null&noTrace=true", null).getResponseAsString();
+ fail("Exception expected!");
+ } catch (RestCallException e) {
+ assertEquals(400, e.getResponseCode());
+ }
+ try {
+ r = c.doPost(URL + "/boolean?content=bad&noTrace=true", null).getResponseAsString();
+ fail("Exception expected!");
+ } catch (RestCallException e) {
+ assertEquals(400, e.getResponseCode());
+ }
+
+
+ // @RestMethod(name="POST", path="/Boolean")
+ // public Boolean testBoolean(@Content Boolean b) {
+ // return b;
+ // }
+ r = c.doPost(URL + "/Boolean?content=true", null).getResponseAsString();
+ assertEquals("true", r);
+ r = c.doPost(URL + "/Boolean?content=false", null).getResponseAsString();
+ assertEquals("false", r);
+ r = c.doPost(URL + "/Boolean?content=null", null).getResponseAsString();
+ assertEquals("null", r);
+ try {
+ r = c.doPost(URL + "/Boolean?content=bad&noTrace=true", null).getResponseAsString();
+ fail("Exception expected!");
+ } catch (RestCallException e) {
+ assertEquals(400, e.getResponseCode());
+ }
+
+ // @RestMethod(name="POST", path="/int")
+ // public int testInt(@Content int i) {
+ // return i;
+ // }
+ r = c.doPost(URL + "/int?content=-123", null).getResponseAsString();
+ assertEquals("-123", r);
+ try {
+ r = c.doPost(URL + "/int?content=null&noTrace=true", null).getResponseAsString();
+ fail("Exception expected!");
+ } catch (RestCallException e) {
+ assertEquals(400, e.getResponseCode());
+ }
+ try {
+ r = c.doPost(URL + "/int?content=bad&noTrace=true", null).getResponseAsString();
+ fail("Exception expected!");
+ } catch (RestCallException e) {
+ assertEquals(400, e.getResponseCode());
+ }
+
+ // @RestMethod(name="POST", path="/Integer")
+ // public Integer testInteger(@Content Integer i) {
+ // return i;
+ // }
+ r = c.doPost(URL + "/Integer?content=-123", null).getResponseAsString();
+ assertEquals("-123", r);
+ r = c.doPost(URL + "/Integer?content=null", null).getResponseAsString();
+ assertEquals("null", r);
+ try {
+ r = c.doPost(URL + "/Integer?content=bad&noTrace=true", null).getResponseAsString();
+ fail("Exception expected!");
+ } catch (RestCallException e) {
+ assertEquals(400, e.getResponseCode());
+ }
+
+ // @RestMethod(name="POST", path="/float")
+ // public float testFloat(@Content float f) {
+ // return f;
+ // }
+ r = c.doPost(URL + "/float?content=-1.23", null).getResponseAsString();
+ assertEquals("-1.23", r);
+ try {
+ r = c.doPost(URL + "/float?content=null&noTrace=true", null).getResponseAsString();
+ fail("Exception expected!");
+ } catch (RestCallException e) {
+ assertEquals(400, e.getResponseCode());
+ }
+ try {
+ r = c.doPost(URL + "/float?content=bad&noTrace=true", null).getResponseAsString();
+ fail("Exception expected!");
+ } catch (RestCallException e) {
+ assertEquals(400, e.getResponseCode());
+ }
+
+ // @RestMethod(name="POST", path="/Float")
+ // public Float testFloat2(@Content Float f) {
+ // return f;
+ // }
+ r = c.doPost(URL + "/Float?content=-1.23", null).getResponseAsString();
+ assertEquals("-1.23", r);
+ r = c.doPost(URL + "/Float?content=null", null).getResponseAsString();
+ assertEquals("null", r);
+ try {
+ r = c.doPost(URL + "/Float?content=bad&noTrace=true", null).getResponseAsString();
+ fail("Exception expected!");
+ } catch (RestCallException e) {
+ assertEquals(400, e.getResponseCode());
+ }
+
+ // @RestMethod(name="POST", path="/Map")
+ // public TreeMap<String,String> testMap(@Content TreeMap<String,String> m) {
+ // return m;
+ // }
+ r = c.doPost(URL + "/Map?content=" + encode("{a:'b',c:'d'}"), null).getResponseAsString();
+ assertEquals("{a:'b',c:'d'}", r);
+ r = c.doPost(URL + "/Map?content=null", null).getResponseAsString();
+ assertEquals("null", r);
+ try {
+ r = c.doPost(URL + "/Map?content=bad&noTrace=true", null).getResponseAsString();
+ fail("Exception expected!");
+ } catch (RestCallException e) {
+ assertEquals(400, e.getResponseCode());
+ }
+
+ // @RestMethod(name="POST", path="/B")
+ // public DTO2s.B testPojo1(@Content DTO2s.B b) {
+ // return b;
+ // }
+ DTOs.B b = DTOs.B.create();
+ r = c.doPost(URL + "/B?content=" + encode(JsonSerializer.DEFAULT_LAX.serialize(b)), null).getResponseAsString();
+ assertEquals("{f1:['a','b'],f2:['c','d'],f3:[1,2],f4:[3,4],f5:[['e','f'],['g','h']],f6:[['i','j'],['k','l']],f7:[{a:'a',b:1,c:true},{a:'a',b:1,c:true}],f8:[{a:'a',b:1,c:true},{a:'a',b:1,c:true}],f9:[[{a:'a',b:1,c:true}],[{a:'a',b:1,c:true}]],f10:[[{a:'a',b:1,c:true}],[{a:'a',b:1,c:true}]],f11:['a','b'],f12:['c','d'],f13:[1,2],f14:[3,4],f15:[['e','f'],['g','h']],f16:[['i','j'],['k','l']],f17:[{a:'a',b:1,c:true},{a:'a',b:1,c:true}],f18:[{a:'a',b:1,c:true},{a:'a',b:1,c:true}],f19:[[{a:'a',b:1,c:true}],[{a:'a',b:1,c:true}]],f20:[[{a:'a',b:1,c:true}],[{a:'a',b:1,c:true}]]}", r);
+
+ // @RestMethod(name="POST", path="/C")
+ // public DTO2s.C testPojo2(@Content DTO2s.C c) {
+ // return c;
+ // }
+ DTOs.C x = DTOs.C.create();
+ r = c.doPost(URL + "/C?content=" + encode(JsonSerializer.DEFAULT_LAX.serialize(x)), null).getResponseAsString();
+ assertEquals("{f1:['a','b'],f2:['c','d'],f3:[1,2],f4:[3,4],f5:[['e','f'],['g','h']],f6:[['i','j'],['k','l']],f7:[{a:'a',b:1,c:true},{a:'a',b:1,c:true}],f8:[{a:'a',b:1,c:true},{a:'a',b:1,c:true}],f9:[[{a:'a',b:1,c:true}],[{a:'a',b:1,c:true}]],f10:[[{a:'a',b:1,c:true}],[{a:'a',b:1,c:true}]],f11:['a','b'],f12:['c','d'],f13:[1,2],f14:[3,4],f15:[['e','f'],['g','h']],f16:[['i','j'],['k','l']],f17:[{a:'a',b:1,c:true},{a:'a',b:1,c:true}],f18:[{a:'a',b:1,c:true},{a:'a',b:1,c:true}],f19:[[{a:'a',b:1,c:true}],[{a:'a',b:1,c:true}]],f20:[[{a:'a',b:1,c:true}],[{a:'a',b:1,c:true}]]}", r);
+
+ c.closeQuietly();
+ }
+
+ //====================================================================================================
+ // Basic tests using &Content parameter with &Accept=text/json
+ //====================================================================================================
+ @Test
+ public void testUsingContentParamJsonParam() throws Exception {
+ RestClient c = new TestRestClient().setAccept("text/json+simple");
+ String r;
+
+ // @RestMethod(name="POST", path="/boolean")
+ // public boolean testBool(@Content boolean b) {
+ // return b;
+ // }
+ r = c.doPost(URL + "/boolean?content=true&Content-Type=text/json", null).getResponseAsString();
+ assertEquals("true", r);
+ r = c.doPost(URL + "/boolean?content=false&Content-Type=text/json", null).getResponseAsString();
+ assertEquals("false", r);
+ try {
+ r = c.doPost(URL + "/boolean?content=null&Content-Type=text/json&noTrace=true", null).getResponseAsString();
+ fail("Exception expected!");
+ } catch (RestCallException e) {
+ assertEquals(400, e.getResponseCode());
+ }
+ try {
+ r = c.doPost(URL + "/boolean?content=bad&Content-Type=text/json&noTrace=true", null).getResponseAsString();
+ fail("Exception expected!");
+ } catch (RestCallException e) {
+ assertEquals(400, e.getResponseCode());
+ }
+
+
+ // @RestMethod(name="POST", path="/Boolean")
+ // public Boolean testBoolean(@Content Boolean b) {
+ // return b;
+ // }
+ r = c.doPost(URL + "/Boolean?content=true&Content-Type=text/json", null).getResponseAsString();
+ assertEquals("true", r);
+ r = c.doPost(URL + "/Boolean?content=false&Content-Type=text/json", null).getResponseAsString();
+ assertEquals("false", r);
+ r = c.doPost(URL + "/Boolean?content=null&Content-Type=text/json", null).getResponseAsString();
+ assertEquals("null", r);
+ try {
+ r = c.doPost(URL + "/Boolean?content=bad&Content-Type=text/json&noTrace=true", null).getResponseAsString();
+ fail("Exception expected!");
+ } catch (RestCallException e) {
+ assertEquals(400, e.getResponseCode());
+ }
+
+ // @RestMethod(name="POST", path="/int")
+ // public int testInt(@Content int i) {
+ // return i;
+ // }
+ r = c.doPost(URL + "/int?content=-123&Content-Type=text/json", null).getResponseAsString();
+ assertEquals("-123", r);
+ try {
+ r = c.doPost(URL + "/int?content=null&Content-Type=text/json&noTrace=true", null).getResponseAsString();
+ fail("Exception expected!");
+ } catch (RestCallException e) {
+ assertEquals(400, e.getResponseCode());
+ }
+ try {
+ r = c.doPost(URL + "/int?content=bad&Content-Type=text/json&noTrace=true", null).getResponseAsString();
+ fail("Exception expected!");
+ } catch (RestCallException e) {
+ assertEquals(400, e.getResponseCode());
+ }
+
+ // @RestMethod(name="POST", path="/Integer")
+ // public Integer testInteger(@Content Integer i) {
+ // return i;
+ // }
+ r = c.doPost(URL + "/Integer?content=-123&Content-Type=text/json", null).getResponseAsString();
+ assertEquals("-123", r);
+ r = c.doPost(URL + "/Integer?content=null&Content-Type=text/json", null).getResponseAsString();
+ assertEquals("null", r);
+ try {
+ r = c.doPost(URL + "/Integer?content=bad&Content-Type=text/json&noTrace=true", null).getResponseAsString();
+ fail("Exception expected!");
+ } catch (RestCallException e) {
+ assertEquals(400, e.getResponseCode());
+ }
+
+ // @RestMethod(name="POST", path="/float")
+ // public float testFloat(@Content float f) {
+ // return f;
+ // }
+ r = c.doPost(URL + "/float?content=-1.23&Content-Type=text/json", null).getResponseAsString();
+ assertEquals("-1.23", r);
+ try {
+ r = c.doPost(URL + "/float?content=null&Content-Type=text/json&noTrace=true", null).getResponseAsString();
+ fail("Exception expected!");
+ } catch (RestCallException e) {
+ assertEquals(400, e.getResponseCode());
+ }
+ try {
+ r = c.doPost(URL + "/float?content=bad&Content-Type=text/json&noTrace=true", null).getResponseAsString();
+ fail("Exception expected!");
+ } catch (RestCallException e) {
+ assertEquals(400, e.getResponseCode());
+ }
+
+ // @RestMethod(name="POST", path="/Float")
+ // public Float testFloat2(@Content Float f) {
+ // return f;
+ // }
+ r = c.doPost(URL + "/Float?content=-1.23&Content-Type=text/json", null).getResponseAsString();
+ assertEquals("-1.23", r);
+ r = c.doPost(URL + "/Float?content=null&Content-Type=text/json", null).getResponseAsString();
+ assertEquals("null", r);
+ try {
+ r = c.doPost(URL + "/Float?content=bad&Content-Type=text/json&noTrace=true", null).getResponseAsString();
+ fail("Exception expected!");
+ } catch (RestCallException e) {
+ assertEquals(400, e.getResponseCode());
+ }
+
+ // @RestMethod(name="POST", path="/Map")
+ // public TreeMap<String,String> testMap(@Content TreeMap<String,String> m) {
+ // return m;
+ // }
+ r = c.doPost(URL + "/Map?content=" + encode("{a:'b',c:'d'}") + "&Content-Type=text/json", null).getResponseAsString();
+ assertEquals("{a:'b',c:'d'}", r);
+ r = c.doPost(URL + "/Map?content=null&Content-Type=text/json", null).getResponseAsString();
+ assertEquals("null", r);
+ try {
+ r = c.doPost(URL + "/Map?content=bad&Content-Type=text/json&noTrace=true", null).getResponseAsString();
+ fail("Exception expected!");
+ } catch (RestCallException e) {
+ assertEquals(400, e.getResponseCode());
+ }
+
+ // @RestMethod(name="POST", path="/B")
+ // public DTO2s.B testPojo1(@Content DTO2s.B b) {
+ // return b;
+ // }
+ DTOs.B b = DTOs.B.create();
+ r = c.doPost(URL + "/B?content=" + encode(JsonSerializer.DEFAULT_LAX.serialize(b)) + "&Content-Type=text/json", null).getResponseAsString();
+ assertEquals("{f1:['a','b'],f2:['c','d'],f3:[1,2],f4:[3,4],f5:[['e','f'],['g','h']],f6:[['i','j'],['k','l']],f7:[{a:'a',b:1,c:true},{a:'a',b:1,c:true}],f8:[{a:'a',b:1,c:true},{a:'a',b:1,c:true}],f9:[[{a:'a',b:1,c:true}],[{a:'a',b:1,c:true}]],f10:[[{a:'a',b:1,c:true}],[{a:'a',b:1,c:true}]],f11:['a','b'],f12:['c','d'],f13:[1,2],f14:[3,4],f15:[['e','f'],['g','h']],f16:[['i','j'],['k','l']],f17:[{a:'a',b:1,c:true},{a:'a',b:1,c:true}],f18:[{a:'a',b:1,c:true},{a:'a',b:1,c:true}],f19:[[{a:'a',b:1,c:true}],[{a:'a',b:1,c:true}]],f20:[[{a:'a',b:1,c:true}],[{a:'a',b:1,c:true}]]}", r);
+
+ // @RestMethod(name="POST", path="/C")
+ // public DTO2s.C testPojo2(@Content DTO2s.C c) {
+ // return c;
+ // }
+ DTOs.C x = DTOs.C.create();
+ r = c.doPost(URL + "/C?content=" + encode(JsonSerializer.DEFAULT_LAX.serialize(x)) + "&Content-Type=text/json", null).getResponseAsString();
+ assertEquals("{f1:['a','b'],f2:['c','d'],f3:[1,2],f4:[3,4],f5:[['e','f'],['g','h']],f6:[['i','j'],['k','l']],f7:[{a:'a',b:1,c:true},{a:'a',b:1,c:true}],f8:[{a:'a',b:1,c:true},{a:'a',b:1,c:true}],f9:[[{a:'a',b:1,c:true}],[{a:'a',b:1,c:true}]],f10:[[{a:'a',b:1,c:true}],[{a:'a',b:1,c:true}]],f11:['a','b'],f12:['c','d'],f13:[1,2],f14:[3,4],f15:[['e','f'],['g','h']],f16:[['i','j'],['k','l']],f17:[{a:'a',b:1,c:true},{a:'a',b:1,c:true}],f18:[{a:'a',b:1,c:true},{a:'a',b:1,c:true}],f19:[[{a:'a',b:1,c:true}],[{a:'a',b:1,c:true}]],f20:[[{a:'a',b:1,c:true}],[{a:'a',b:1,c:true}]]}", r);
+
+ c.closeQuietly();
+ }
+
+ //====================================================================================================
+ // Basic tests using HTTP body content
+ //====================================================================================================
+ @Test
+ public void testUsingContent() throws Exception {
+ RestClient c = new TestRestClient().setAccept("text/json+simple").setHeader("Content-Type", "text/uon").setSerializer(PlainTextSerializer.class);
+ String r;
+
+ // @RestMethod(name="POST", path="/boolean")
+ // public boolean testBool(@Content boolean b) {
+ // return b;
+ // }
+ r = c.doPost(URL + "/boolean", "true").getResponseAsString();
+ assertEquals("true", r);
+ r = c.doPost(URL + "/boolean", "(true)").getResponseAsString();
+ assertEquals("true", r);
+ r = c.doPost(URL + "/boolean", "$b(true)").getResponseAsString();
+ assertEquals("true", r);
+ r = c.doPost(URL + "/boolean", "false").getResponseAsString();
+ assertEquals("false", r);
+ r = c.doPost(URL + "/boolean", "(false)").getResponseAsString();
+ assertEquals("false", r);
+ r = c.doPost(URL + "/boolean", "$b(false)").getResponseAsString();
+ assertEquals("false", r);
+ try {
+ r = c.doPost(URL + "/boolean?noTrace=true", "%00").getResponseAsString();
+ fail("Exception expected!");
+ } catch (RestCallException e) {
+ assertEquals(400, e.getResponseCode());
+ }
+ try {
+ r = c.doPost(URL + "/boolean?noTrace=true", "bad").getResponseAsString();
+ fail("Exception expected!");
+ } catch (RestCallException e) {
+ assertEquals(400, e.getResponseCode());
+ }
+
+
+ // @RestMethod(name="POST", path="/Boolean")
+ // public Boolean testBoolean(@Content Boolean b) {
+ // return b;
+ // }
+ r = c.doPost(URL + "/Boolean", "true").getResponseAsString();
+ assertEquals("true", r);
+ r = c.doPost(URL + "/Boolean", "(true)").getResponseAsString();
+ assertEquals("true", r);
+ r = c.doPost(URL + "/Boolean", "$b(true)").getResponseAsString();
+ assertEquals("true", r);
+ r = c.doPost(URL + "/Boolean", "false").getResponseAsString();
+ assertEquals("false", r);
+ r = c.doPost(URL + "/Boolean", "(false)").getResponseAsString();
+ assertEquals("false", r);
+ r = c.doPost(URL + "/Boolean", "$b(false)").getResponseAsString();
+ assertEquals("false", r);
+ r = c.doPost(URL + "/Boolean", "\u0000").getResponseAsString();
+ assertEquals("null", r);
+ try {
+ r = c.doPost(URL + "/Boolean?noTrace=true", "bad").getResponseAsString();
+ fail("Exception expected!");
+ } catch (RestCallException e) {
+ assertEquals(400, e.getResponseCode());
+ }
+
+ // @RestMethod(name="POST", path="/int")
+ // public int testInt(@Content int i) {
+ // return i;
+ // }
+ r = c.doPost(URL + "/int", "-123").getResponseAsString();
+ assertEquals("-123", r);
+ r = c.doPost(URL + "/int", "(-123)").getResponseAsString();
+ assertEquals("-123", r);
+ r = c.doPost(URL + "/int", "$n(-123)").getResponseAsString();
+ assertEquals("-123", r);
+ try {
+ r = c.doPost(URL + "/int?noTrace=true", "%00").getResponseAsString();
+ fail("Exception expected!");
+ } catch (RestCallException e) {
+ assertEquals(400, e.getResponseCode());
+ }
+ try {
+ r = c.doPost(URL + "/int?noTrace=true", "bad").getResponseAsString();
+ fail("Exception expected!");
+ } catch (RestCallException e) {
+ assertEquals(400, e.getResponseCode());
+ }
+
+ // @RestMethod(name="POST", path="/Integer")
+ // public Integer testInteger(@Content Integer i) {
+ // return i;
+ // }
+ r = c.doPost(URL + "/Integer", "-123").getResponseAsString();
+ assertEquals("-123", r);
+ r = c.doPost(URL + "/Integer", "(-123)").getResponseAsString();
+ assertEquals("-123", r);
+ r = c.doPost(URL + "/Integer", "$n(-123)").getResponseAsString();
+ assertEquals("-123", r);
+ r = c.doPost(URL + "/Integer", "\u0000").getResponseAsString();
+ assertEquals("null", r);
+ try {
+ r = c.doPost(URL + "/Integer?noTrace=true", "bad").getResponseAsString();
+ fail("Exception expected!");
+ } catch (RestCallException e) {
+ assertEquals(400, e.getResponseCode());
+ }
+
+ // @RestMethod(name="POST", path="/float")
+ // public float testFloat(@Content float f) {
+ // return f;
+ // }
+ r = c.doPost(URL + "/float", "-1.23").getResponseAsString();
+ assertEquals("-1.23", r);
+ r = c.doPost(URL + "/float", "(-1.23)").getResponseAsString();
+ assertEquals("-1.23", r);
+ r = c.doPost(URL + "/float", "$n(-1.23)").getResponseAsString();
+ assertEquals("-1.23", r);
+ try {
+ r = c.doPost(URL + "/float?noTrace=true", "\u0000").getResponseAsString();
+ fail("Exception expected!");
+ } catch (RestCallException e) {
+ assertEquals(400, e.getResponseCode());
+ }
+ try {
+ r = c.doPost(URL + "/float?noTrace=true", "bad").getResponseAsString();
+ fail("Exception expected!");
+ } catch (RestCallException e) {
+ assertEquals(400, e.getResponseCode());
+ }
+
+ // @RestMethod(name="POST", path="/Float")
+ // public Float testFloat2(@Content Float f) {
+ // return f;
+ // }
+ r = c.doPost(URL + "/Float", "-1.23").getResponseAsString();
+ assertEquals("-1.23", r);
+ r = c.doPost(URL + "/Float", "(-1.23)").getResponseAsString();
+ assertEquals("-1.23", r);
+ r = c.doPost(URL + "/Float", "$n(-1.23)").getResponseAsString();
+ assertEquals("-1.23", r);
+ r = c.doPost(URL + "/Float", "\u0000").getResponseAsString();
+ assertEquals("null", r);
+ try {
+ r = c.doPost(URL + "/Float?noTrace=true", "bad").getResponseAsString();
+ fail("Exception expected!");
+ } catch (RestCallException e) {
+ assertEquals(400, e.getResponseCode());
+ }
+
+ // @RestMethod(name="POST", path="/Map")
+ // public TreeMap<String,String> testMap(@Content TreeMap<String,String> m) {
+ // return m;
+ // }
+ r = c.doPost(URL + "/Map", "(a=b,c=d)").getResponseAsString();
+ assertEquals("{a:'b',c:'d'}", r);
+ r = c.doPost(URL + "/Map", "\u0000").getResponseAsString();
+ assertEquals("null", r);
+ try {
+ r = c.doPost(URL + "/Map?noTrace=true", "bad").getResponseAsString();
+ fail("Exception expected!");
+ } catch (RestCallException e) {
+ assertEquals(400, e.getResponseCode());
+ }
+
+ // @RestMethod(name="POST", path="/B")
+ // public DTO2s.B testPojo1(@Content DTO2s.B b) {
+ // return b;
+ // }
+ DTOs.B b = DTOs.B.create();
+ r = c.doPost(URL + "/B", "" + UonSerializer.DEFAULT.serialize(b)).getResponseAsString();
+ assertEquals("{f1:['a','b'],f2:['c','d'],f3:[1,2],f4:[3,4],f5:[['e','f'],['g','h']],f6:[['i','j'],['k','l']],f7:[{a:'a',b:1,c:true},{a:'a',b:1,c:true}],f8:[{a:'a',b:1,c:true},{a:'a',b:1,c:true}],f9:[[{a:'a',b:1,c:true}],[{a:'a',b:1,c:true}]],f10:[[{a:'a',b:1,c:true}],[{a:'a',b:1,c:true}]],f11:['a','b'],f12:['c','d'],f13:[1,2],f14:[3,4],f15:[['e','f'],['g','h']],f16:[['i','j'],['k','l']],f17:[{a:'a',b:1,c:true},{a:'a',b:1,c:true}],f18:[{a:'a',b:1,c:true},{a:'a',b:1,c:true}],f19:[[{a:'a',b:1,c:true}],[{a:'a',b:1,c:true}]],f20:[[{a:'a',b:1,c:true}],[{a:'a',b:1,c:true}]]}", r);
+ r = c.doPost(URL + "/B", "" + UonSerializer.DEFAULT_SIMPLE.serialize(b)).getResponseAsString();
+ assertEquals("{f1:['a','b'],f2:['c','d'],f3:[1,2],f4:[3,4],f5:[['e','f'],['g','h']],f6:[['i','j'],['k','l']],f7:[{a:'a',b:1,c:true},{a:'a',b:1,c:true}],f8:[{a:'a',b:1,c:true},{a:'a',b:1,c:true}],f9:[[{a:'a',b:1,c:true}],[{a:'a',b:1,c:true}]],f10:[[{a:'a',b:1,c:true}],[{a:'a',b:1,c:true}]],f11:['a','b'],f12:['c','d'],f13:[1,2],f14:[3,4],f15:[['e','f'],['g','h']],f16:[['i','j'],['k','l']],f17:[{a:'a',b:1,c:true},{a:'a',b:1,c:true}],f18:[{a:'a',b:1,c:true},{a:'a',b:1,c:true}],f19:[[{a:'a',b:1,c:true}],[{a:'a',b:1,c:true}]],f20:[[{a:'a',b:1,c:true}],[{a:'a',b:1,c:true}]]}", r);
+
+ // @RestMethod(name="POST", path="/C")
+ // public DTO2s.C testPojo2(@Content DTO2s.C c) {
+ // return c;
+ // }
+ DTOs.C x = DTOs.C.create();
+ r = c.doPost(URL + "/C", "" + UonSerializer.DEFAULT.serialize(x)).getResponseAsString();
+ assertEquals("{f1:['a','b'],f2:['c','d'],f3:[1,2],f4:[3,4],f5:[['e','f'],['g','h']],f6:[['i','j'],['k','l']],f7:[{a:'a',b:1,c:true},{a:'a',b:1,c:true}],f8:[{a:'a',b:1,c:true},{a:'a',b:1,c:true}],f9:[[{a:'a',b:1,c:true}],[{a:'a',b:1,c:true}]],f10:[[{a:'a',b:1,c:true}],[{a:'a',b:1,c:true}]],f11:['a','b'],f12:['c','d'],f13:[1,2],f14:[3,4],f15:[['e','f'],['g','h']],f16:[['i','j'],['k','l']],f17:[{a:'a',b:1,c:true},{a:'a',b:1,c:true}],f18:[{a:'a',b:1,c:true},{a:'a',b:1,c:true}],f19:[[{a:'a',b:1,c:true}],[{a:'a',b:1,c:true}]],f20:[[{a:'a',b:1,c:true}],[{a:'a',b:1,c:true}]]}", r);
+ r = c.doPost(URL + "/C", "" + UonSerializer.DEFAULT_SIMPLE.serialize(x)).getResponseAsString();
+ assertEquals("{f1:['a','b'],f2:['c','d'],f3:[1,2],f4:[3,4],f5:[['e','f'],['g','h']],f6:[['i','j'],['k','l']],f7:[{a:'a',b:1,c:true},{a:'a',b:1,c:true}],f8:[{a:'a',b:1,c:true},{a:'a',b:1,c:true}],f9:[[{a:'a',b:1,c:true}],[{a:'a',b:1,c:true}]],f10:[[{a:'a',b:1,c:true}],[{a:'a',b:1,c:true}]],f11:['a','b'],f12:['c','d'],f13:[1,2],f14:[3,4],f15:[['e','f'],['g','h']],f16:[['i','j'],['k','l']],f17:[{a:'a',b:1,c:true},{a:'a',b:1,c:true}],f18:[{a:'a',b:1,c:true},{a:'a',b:1,c:true}],f19:[[{a:'a',b:1,c:true}],[{a:'a',b:1,c:true}]],f20:[[{a:'a',b:1,c:true}],[{a:'a',b:1,c:true}]]}", r);
+
+ c.closeQuietly();
+ }
+
+
+ private String encode(String s) {
+ try {
+ return URLEncoder.encode(s, "UTF-8");
+ } catch (UnsupportedEncodingException e) {
+ throw new RuntimeException(e);
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestDefaultContentTypesTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestDefaultContentTypesTest.java b/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestDefaultContentTypesTest.java
new file mode 100755
index 0000000..613619f
--- /dev/null
+++ b/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestDefaultContentTypesTest.java
@@ -0,0 +1,497 @@
+/***************************************************************************************************************************
+ * 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.juneau.server;
+
+import static javax.servlet.http.HttpServletResponse.*;
+import static org.apache.juneau.server.TestUtils.*;
+import static org.junit.Assert.*;
+
+import org.apache.juneau.client.*;
+import org.apache.juneau.json.*;
+import org.junit.*;
+
+
+public class TestDefaultContentTypesTest {
+
+ private static String URL = "/testDefaultContentTypes";
+ private static boolean debug = false;
+
+ //====================================================================================================
+ // Test that default Accept and Content-Type headers on servlet annotation are picked up.
+ //====================================================================================================
+ @Test
+ public void testDefaultHeadersOnServletAnnotation() throws Exception {
+ RestClient client = new TestRestClient(JsonSerializer.DEFAULT, JsonParser.DEFAULT);
+ String r;
+
+ String url = URL + "/testDefaultHeadersOnServletAnnotation";
+
+ client.setAccept("").setContentType("");
+ r = client.doPut(url, "").getResponseAsString();
+ assertEquals("s2/p2", r);
+
+ client.setAccept("text/s1").setContentType("");
+ r = client.doPut(url, "").getResponseAsString();
+ assertEquals("s1/p2", r);
+
+ client.setAccept("").setContentType("text/p1");
+ r = client.doPut(url, "").getResponseAsString();
+ assertEquals("s2/p1", r);
+
+ client.setAccept("text/s1").setContentType("text/p1");
+ r = client.doPut(url, "").getResponseAsString();
+ assertEquals("s1/p1", r);
+
+ client.setAccept("text/s2").setContentType("");
+ r = client.doPut(url, "").getResponseAsString();
+ assertEquals("s2/p2", r);
+
+ client.setAccept("").setContentType("text/p2");
+ r = client.doPut(url, "").getResponseAsString();
+ assertEquals("s2/p2", r);
+
+ client.setAccept("text/s2").setContentType("text/p2");
+ r = client.doPut(url, "").getResponseAsString();
+ assertEquals("s2/p2", r);
+
+ try {
+ client.setAccept("text/s3").setContentType("");
+ r = client.doPut(url+"?noTrace=true", "").getResponseAsString();
+ fail("Exception expected");
+ } catch (RestCallException e) {
+ checkErrorResponse(debug, e, SC_NOT_ACCEPTABLE,
+ "Unsupported media-type in request header 'Accept': 'text/s3'",
+ "Supported media-types: [text/s1, text/s2]"
+ );
+ }
+
+ try {
+ client.setAccept("").setContentType("text/p3");
+ r = client.doPut(url+"?noTrace=true", "").getResponseAsString();
+ fail("Exception expected");
+ } catch (RestCallException e) {
+ checkErrorResponse(debug, e, SC_UNSUPPORTED_MEDIA_TYPE,
+ "Unsupported media-type in request header 'Content-Type': 'text/p3'",
+ "Supported media-types: [text/p1, text/p2]"
+ );
+ }
+
+ try {
+ client.setAccept("text/s3").setContentType("text/p3");
+ r = client.doPut(url+"?noTrace=true", "").getResponseAsString();
+ fail("Exception expected");
+ } catch (RestCallException e) {
+ checkErrorResponse(debug, e, SC_UNSUPPORTED_MEDIA_TYPE,
+ "Unsupported media-type in request header 'Content-Type': 'text/p3'",
+ "Supported media-types: [text/p1, text/p2]"
+ );
+ }
+
+ client.closeQuietly();
+ }
+
+ //====================================================================================================
+ // Test that default Accept and Content-Type headers on servlet annotation are picked up
+ // when @RestMethod.parsers/serializers annotations are used.
+ //====================================================================================================
+ @Test
+ public void testRestMethodParsersSerializers() throws Exception {
+ RestClient client = new TestRestClient(JsonSerializer.DEFAULT, JsonParser.DEFAULT);
+ String r;
+
+ String url = URL + "/testRestMethodParsersSerializers";
+
+ try {
+ client.setAccept("").setContentType("");
+ r = client.doPut(url+"?noTrace=true", "").getResponseAsString();
+ fail("Exception expected");
+ } catch (RestCallException e) {
+ checkErrorResponse(debug, e, SC_UNSUPPORTED_MEDIA_TYPE,
+ "Unsupported media-type in request header 'Content-Type': 'text/p2'",
+ "Supported media-types: [text/p3]"
+ );
+ }
+
+ try {
+ client.setAccept("text/s1").setContentType("");
+ r = client.doPut(url+"?noTrace=true", "").getResponseAsString();
+ fail("Exception expected");
+ } catch (RestCallException e) {
+ checkErrorResponse(debug, e, SC_UNSUPPORTED_MEDIA_TYPE,
+ "Unsupported media-type in request header 'Content-Type': 'text/p2'",
+ "Supported media-types: [text/p3]"
+ );
+ }
+
+ try {
+ client.setAccept("").setContentType("text/p1");
+ r = client.doPut(url+"?noTrace=true", "").getResponseAsString();
+ fail("Exception expected");
+ } catch (RestCallException e) {
+ checkErrorResponse(debug, e, SC_UNSUPPORTED_MEDIA_TYPE,
+ "Unsupported media-type in request header 'Content-Type': 'text/p1'",
+ "Supported media-types: [text/p3]"
+ );
+ }
+
+ try {
+ client.setAccept("text/s1").setContentType("text/p1");
+ r = client.doPut(url+"?noTrace=true", "").getResponseAsString();
+ fail("Exception expected");
+ } catch (RestCallException e) {
+ checkErrorResponse(debug, e, SC_UNSUPPORTED_MEDIA_TYPE,
+ "Unsupported media-type in request header 'Content-Type': 'text/p1'",
+ "Supported media-types: [text/p3]"
+ );
+ }
+
+ try {
+ client.setAccept("text/s2").setContentType("");
+ r = client.doPut(url+"?noTrace=true", "").getResponseAsString();
+ fail("Exception expected");
+ } catch (RestCallException e) {
+ checkErrorResponse(debug, e, SC_UNSUPPORTED_MEDIA_TYPE,
+ "Unsupported media-type in request header 'Content-Type': 'text/p2'",
+ "Supported media-types: [text/p3]"
+ );
+ }
+
+ try {
+ client.setAccept("").setContentType("text/p2");
+ r = client.doPut(url+"?noTrace=true", "").getResponseAsString();
+ fail("Exception expected");
+ } catch (RestCallException e) {
+ checkErrorResponse(debug, e, SC_UNSUPPORTED_MEDIA_TYPE,
+ "Unsupported media-type in request header 'Content-Type': 'text/p2'",
+ "Supported media-types: [text/p3]"
+ );
+ }
+
+ try {
+ client.setAccept("text/s2").setContentType("text/p2");
+ r = client.doPut(url+"?noTrace=true", "").getResponseAsString();
+ fail("Exception expected");
+ } catch (RestCallException e) {
+ checkErrorResponse(debug, e, SC_UNSUPPORTED_MEDIA_TYPE,
+ "Unsupported media-type in request header 'Content-Type': 'text/p2'",
+ "Supported media-types: [text/p3]"
+ );
+ }
+
+ try {
+ client.setAccept("text/s3").setContentType("");
+ r = client.doPut(url+"?noTrace=true", "").getResponseAsString();
+ fail("Exception expected");
+ } catch (RestCallException e) {
+ checkErrorResponse(debug, e, SC_UNSUPPORTED_MEDIA_TYPE,
+ "Unsupported media-type in request header 'Content-Type': 'text/p2'",
+ "Supported media-types: [text/p3]"
+ );
+ }
+
+ try {
+ client.setAccept("").setContentType("text/p3");
+ r = client.doPut(url+"?noTrace=true", "").getResponseAsString();
+ fail("Exception expected");
+ } catch (RestCallException e) {
+ checkErrorResponse(debug, e, SC_NOT_ACCEPTABLE,
+ "Unsupported media-type in request header 'Accept': 'text/s2'",
+ "Supported media-types: [text/s3]"
+ );
+ }
+
+ client.setAccept("text/s3").setContentType("text/p3");
+ r = client.doPut(url, "").getResponseAsString();
+ assertEquals("s3/p3", r);
+
+ client.closeQuietly();
+ }
+
+ //====================================================================================================
+ // Test that default Accept and Content-Type headers on servlet annotation are picked up
+ // when @RestMethod.addParsers/addSerializers annotations are used.
+ //====================================================================================================
+ @Test
+ public void testRestMethodAddParsersSerializers() throws Exception {
+ RestClient client = new TestRestClient(JsonSerializer.DEFAULT, JsonParser.DEFAULT);
+ String r;
+
+ String url = URL + "/testRestMethodAddParsersSerializers";
+
+ client.setAccept("").setContentType("");
+ r = client.doPut(url, "").getResponseAsString();
+ assertEquals("s2/p2", r);
+
+ client.setAccept("text/s1").setContentType("");
+ r = client.doPut(url, "").getResponseAsString();
+ assertEquals("s1/p2", r);
+
+ client.setAccept("").setContentType("text/p1");
+ r = client.doPut(url, "").getResponseAsString();
+ assertEquals("s2/p1", r);
+
+ client.setAccept("text/s1").setContentType("text/p1");
+ r = client.doPut(url, "").getResponseAsString();
+ assertEquals("s1/p1", r);
+
+ client.setAccept("text/s2").setContentType("");
+ r = client.doPut(url, "").getResponseAsString();
+ assertEquals("s2/p2", r);
+
+ client.setAccept("").setContentType("text/p2");
+ r = client.doPut(url, "").getResponseAsString();
+ assertEquals("s2/p2", r);
+
+ client.setAccept("text/s2").setContentType("text/p2");
+ r = client.doPut(url, "").getResponseAsString();
+ assertEquals("s2/p2", r);
+
+ client.setAccept("text/s3").setContentType("");
+ r = client.doPut(url, "").getResponseAsString();
+ assertEquals("s3/p2", r);
+
+ client.setAccept("").setContentType("text/p3");
+ r = client.doPut(url, "").getResponseAsString();
+ assertEquals("s2/p3", r);
+
+ client.setAccept("text/s3").setContentType("text/p3");
+ r = client.doPut(url, "").getResponseAsString();
+ assertEquals("s3/p3", r);
+
+ try {
+ client.setAccept("").setContentType("text/p4");
+ r = client.doPut(url+"?noTrace=true", "").getResponseAsString();
+ fail("Exception expected");
+ } catch (RestCallException e) {
+ // Note that parsers defined on method are listed before parsers defined on class.
+ checkErrorResponse(debug, e, SC_UNSUPPORTED_MEDIA_TYPE,
+ "Unsupported media-type in request header 'Content-Type': 'text/p4'",
+ "Supported media-types: [text/p3, text/p1, text/p2]"
+ );
+ }
+
+ try {
+ client.setAccept("text/s4").setContentType("");
+ r = client.doPut(url+"?noTrace=true", "").getResponseAsString();
+ fail("Exception expected");
+ } catch (RestCallException e) {
+ // Note that serializers defined on method are listed before serializers defined on class.
+ checkErrorResponse(debug, e, SC_NOT_ACCEPTABLE,
+ "Unsupported media-type in request header 'Accept': 'text/s4'",
+ "Supported media-types: [text/s3, text/s1, text/s2]"
+ );
+ }
+
+ client.closeQuietly();
+ }
+
+ //====================================================================================================
+ // Various Accept incantations.
+ //====================================================================================================
+ @Test
+ public void testAccept() throws Exception {
+ RestClient client = new TestRestClient(JsonSerializer.DEFAULT, JsonParser.DEFAULT).setContentType("text/p1");
+ String r;
+
+ String url = URL + "/testAccept";
+
+ // "*/*" should match the first serializer, not the default serializer.
+ client.setAccept("*/*");
+ r = client.doPut(url, "").getResponseAsString();
+ assertEquals("s1/p1", r);
+
+ // "text/*" should match the first serializer, not the default serializer.
+ client.setAccept("text/*");
+ r = client.doPut(url, "").getResponseAsString();
+ assertEquals("s1/p1", r);
+
+ try {
+ client.setAccept("bad/*");
+ r = client.doPut(url+"?noTrace=true", "").getResponseAsString();
+ fail("Exception expected");
+ } catch (RestCallException e) {
+ checkErrorResponse(debug, e, SC_NOT_ACCEPTABLE,
+ "Unsupported media-type in request header 'Accept': 'bad/*'",
+ "Supported media-types: [text/s1, text/s2]"
+ );
+ }
+
+ client.setAccept("bad/*,text/*");
+ r = client.doPut(url, "").getResponseAsString();
+ assertEquals("s1/p1", r);
+
+ client.setAccept("text/*,bad/*");
+ r = client.doPut(url, "").getResponseAsString();
+ assertEquals("s1/p1", r);
+
+ client.setAccept("text/s1;q=0.5,text/s2");
+ r = client.doPut(url, "").getResponseAsString();
+ assertEquals("s2/p1", r);
+
+ client.setAccept("text/s1,text/s2;q=0.5");
+ r = client.doPut(url, "").getResponseAsString();
+ assertEquals("s1/p1", r);
+
+ client.closeQuietly();
+ }
+
+ //====================================================================================================
+ // Test that default Accept and Content-Type headers on method annotation are picked up
+ // when @RestMethod.parsers/serializers annotations are used.
+ //====================================================================================================
+ @Test
+ public void testRestMethodParserSerializerAnnotations() throws Exception {
+ RestClient client = new TestRestClient(JsonSerializer.DEFAULT, JsonParser.DEFAULT);
+ String r;
+
+ String url = URL + "/testRestMethodParserSerializerAnnotations";
+
+ client.setAccept("").setContentType("");
+ r = client.doPut(url, "").getResponseAsString();
+ assertEquals("s3/p3", r);
+
+ try {
+ client.setAccept("text/s1").setContentType("");
+ r = client.doPut(url+"?noTrace=true", "").getResponseAsString();
+ fail("Exception expected");
+ } catch (RestCallException e) {
+ checkErrorResponse(debug, e, SC_NOT_ACCEPTABLE,
+ "Unsupported media-type in request header 'Accept': 'text/s1'",
+ "Supported media-types: [text/s3]"
+ );
+ }
+
+ try {
+ client.setAccept("").setContentType("text/p1");
+ r = client.doPut(url+"?noTrace=true", "").getResponseAsString();
+ fail("Exception expected");
+ } catch (RestCallException e) {
+ checkErrorResponse(debug, e, SC_UNSUPPORTED_MEDIA_TYPE,
+ "Unsupported media-type in request header 'Content-Type': 'text/p1'",
+ "Supported media-types: [text/p3]"
+ );
+ }
+
+ try {
+ client.setAccept("text/s1").setContentType("text/p1");
+ r = client.doPut(url+"?noTrace=true", "").getResponseAsString();
+ fail("Exception expected");
+ } catch (RestCallException e) {
+ checkErrorResponse(debug, e, SC_UNSUPPORTED_MEDIA_TYPE,
+ "Unsupported media-type in request header 'Content-Type': 'text/p1'",
+ "Supported media-types: [text/p3]"
+ );
+ }
+
+ try {
+ client.setAccept("text/s2").setContentType("");
+ r = client.doPut(url+"?noTrace=true", "").getResponseAsString();
+ fail("Exception expected");
+ } catch (RestCallException e) {
+ checkErrorResponse(debug, e, SC_NOT_ACCEPTABLE,
+ "Unsupported media-type in request header 'Accept': 'text/s2'",
+ "Supported media-types: [text/s3]"
+ );
+ }
+
+ try {
+ client.setAccept("").setContentType("text/p2");
+ r = client.doPut(url+"?noTrace=true", "").getResponseAsString();
+ fail("Exception expected");
+ } catch (RestCallException e) {
+ checkErrorResponse(debug, e, SC_UNSUPPORTED_MEDIA_TYPE,
+ "Unsupported media-type in request header 'Content-Type': 'text/p2'",
+ "Supported media-types: [text/p3]"
+ );
+ }
+
+ try {
+ client.setAccept("text/s2").setContentType("text/p2");
+ r = client.doPut(url+"?noTrace=true", "").getResponseAsString();
+ fail("Exception expected");
+ } catch (RestCallException e) {
+ checkErrorResponse(debug, e, SC_UNSUPPORTED_MEDIA_TYPE,
+ "Unsupported media-type in request header 'Content-Type': 'text/p2'",
+ "Supported media-types: [text/p3]"
+ );
+ }
+
+ client.setAccept("text/s3").setContentType("");
+ r = client.doPut(url, "").getResponseAsString();
+ assertEquals("s3/p3", r);
+
+ client.setAccept("").setContentType("text/p3");
+ r = client.doPut(url, "").getResponseAsString();
+ assertEquals("s3/p3", r);
+
+ client.setAccept("text/s3").setContentType("text/p3");
+ r = client.doPut(url, "").getResponseAsString();
+ assertEquals("s3/p3", r);
+
+ client.closeQuietly();
+ }
+
+ //====================================================================================================
+ // Test that default Accept and Content-Type headers on method annotation are picked up
+ // when @RestMethod.addParsers/addSerializers annotations are used.
+ //====================================================================================================
+ @Test
+ public void testRestMethodAddParsersSerializersAnnotations() throws Exception {
+ RestClient client = new TestRestClient(JsonSerializer.DEFAULT, JsonParser.DEFAULT);
+ String r;
+
+ String url = URL + "/testRestMethodAddParsersSerializersAnnotations";
+
+ client.setAccept("").setContentType("");
+ r = client.doPut(url, "").getResponseAsString();
+ assertEquals("s3/p3", r);
+
+ client.setAccept("text/s1").setContentType("");
+ r = client.doPut(url, "").getResponseAsString();
+ assertEquals("s1/p3", r);
+
+ client.setAccept("").setContentType("text/p1");
+ r = client.doPut(url, "").getResponseAsString();
+ assertEquals("s3/p1", r);
+
+ client.setAccept("text/s1").setContentType("text/p1");
+ r = client.doPut(url, "").getResponseAsString();
+ assertEquals("s1/p1", r);
+
+ client.setAccept("text/s2").setContentType("");
+ r = client.doPut(url, "").getResponseAsString();
+ assertEquals("s2/p3", r);
+
+ client.setAccept("").setContentType("text/p2");
+ r = client.doPut(url, "").getResponseAsString();
+ assertEquals("s3/p2", r);
+
+ client.setAccept("text/s2").setContentType("text/p2");
+ r = client.doPut(url, "").getResponseAsString();
+ assertEquals("s2/p2", r);
+
+ client.setAccept("text/s3").setContentType("");
+ r = client.doPut(url, "").getResponseAsString();
+ assertEquals("s3/p3", r);
+
+ client.setAccept("").setContentType("text/p3");
+ r = client.doPut(url, "").getResponseAsString();
+ assertEquals("s3/p3", r);
+
+ client.setAccept("text/s3").setContentType("text/p3");
+ r = client.doPut(url, "").getResponseAsString();
+ assertEquals("s3/p3", r);
+
+ client.closeQuietly();
+ }
+}
[15/44] incubator-juneau git commit: Rename CT_* testcases.
Posted by ja...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/jena/CommonParserTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/jena/CommonParserTest.java b/org.apache.juneau/src/test/java/org/apache/juneau/jena/CommonParserTest.java
new file mode 100755
index 0000000..76e6a73
--- /dev/null
+++ b/org.apache.juneau/src/test/java/org/apache/juneau/jena/CommonParserTest.java
@@ -0,0 +1,208 @@
+/***************************************************************************************************************************
+ * 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.juneau.jena;
+
+import static org.apache.juneau.BeanContext.*;
+import static org.apache.juneau.jena.RdfCommonContext.*;
+import static org.apache.juneau.jena.RdfSerializerContext.*;
+import static org.apache.juneau.serializer.SerializerContext.*;
+import static org.junit.Assert.*;
+
+import java.util.*;
+
+import org.apache.juneau.*;
+import org.apache.juneau.parser.*;
+import org.apache.juneau.serializer.*;
+import org.junit.*;
+
+@SuppressWarnings({"rawtypes","serial"})
+public class CommonParserTest {
+
+ private String wrap(String in) {
+ return ""
+ + "<rdf:RDF"
+ + " xmlns:rdf='http://www.w3.org/1999/02/22-rdf-syntax-ns#'"
+ + " xmlns:j='http://www.ibm.com/juneau/'"
+ + " xmlns:jp='http://www.ibm.com/juneaubp/'>"
+ + in
+ + "</rdf:RDF>";
+ }
+
+ private String strip(String s) {
+ return s.replaceFirst("<rdf:RDF[^>]+>\\s*", "").replaceAll("</rdf:RDF>$", "").trim().replaceAll("[\\r\\n]", "");
+ }
+
+ private RdfSerializer getBasicSerializer() {
+ return new RdfSerializer()
+ .setProperty(SERIALIZER_quoteChar, '\'')
+ .setProperty(RDF_addLiteralTypes, true)
+ .setProperty(SERIALIZER_useIndentation, false)
+ .setProperty(RDF_rdfxml_allowBadUris, true)
+ .setProperty(RDF_rdfxml_showDoctypeDeclaration, false)
+ .setProperty(RDF_rdfxml_showXmlDeclaration, false);
+ }
+
+ //====================================================================================================
+ // testBasicFromSerializer
+ //====================================================================================================
+ @Test
+ public void testFromSerializer() throws Exception {
+ WriterSerializer s = getBasicSerializer();
+ ReaderParser p = new RdfParser.Xml().setProperty(RdfParserContext.RDF_trimWhitespace, true).setClassLoader(getClass().getClassLoader());
+ Map m = null;
+ String in;
+ Integer one = Integer.valueOf(1);
+
+ in = wrap("<rdf:Description><jp:a rdf:datatype='http://www.w3.org/2001/XMLSchema#int'>1</jp:a></rdf:Description>");
+ m = (Map)p.parse(in, Object.class);
+ assertEquals(one, m.get("a"));
+
+ in = wrap("<rdf:Description><jp:a rdf:datatype='http://www.w3.org/2001/XMLSchema#int'>1</jp:a><jp:b>foo bar</jp:b><jp:c rdf:datatype='http://www.w3.org/2001/XMLSchema#boolean'>false</jp:c></rdf:Description>");
+ m = (Map)p.parse(in, Object.class);
+ assertEquals(one, m.get("a"));
+ assertEquals("foo bar", m.get("b"));
+ in = wrap("<rdf:Description><jp:a rdf:datatype='http://www.w3.org/2001/XMLSchema#int'> 1 </jp:a><jp:b> foo bar </jp:b><jp:c rdf:datatype='http://www.w3.org/2001/XMLSchema#boolean'> false </jp:c></rdf:Description>");
+ m = (Map)p.parse(in, Object.class);
+ assertEquals(one, m.get("a"));
+ assertEquals("foo bar", m.get("b"));
+ assertEquals(false, m.get("c"));
+
+ in = wrap("<rdf:Description><jp:x>org.apache.juneau.test.Person</jp:x><jp:addresses><rdf:Seq><rdf:li rdf:parseType='Resource'><jp:x>org.apache.juneau.test.Address</jp:x><jp:city>city A</jp:city><jp:state>state A</jp:state><jp:street>street A</jp:street><jp:zip rdf:datatype='http://www.w3.org/2001/XMLSchema#int'>12345</jp:zip></rdf:li></rdf:Seq></jp:addresses></rdf:Description>");
+ m = (Map)p.parse(in, Object.class);
+ assertEquals("org.apache.juneau.test.Person", m.get("x"));
+ List l = (List)m.get("addresses");
+ assertNotNull(l);
+ m = (Map)l.get(0);
+ assertNotNull(m);
+ assertEquals("org.apache.juneau.test.Address", m.get("x"));
+ assertEquals("city A", m.get("city"));
+ assertEquals("state A", m.get("state"));
+ assertEquals("street A", m.get("street"));
+ assertEquals(12345, m.get("zip"));
+
+ in = wrap("<rdf:Seq><rdf:li rdf:parseType='Resource'><jp:attribute>value</jp:attribute></rdf:li><rdf:li rdf:parseType='Resource'><jp:attribute>value</jp:attribute></rdf:li></rdf:Seq>");
+ ObjectList jl = (ObjectList)p.parse(in, Object.class);
+ assertEquals("value", jl.getObjectMap(0).getString("attribute"));
+ assertEquals("value", jl.getObjectMap(1).getString("attribute"));
+
+ // Verify that all the following return null.
+ assertNull(p.parse((CharSequence)null, Object.class));
+ assertNull(p.parse(wrap(""), Object.class));
+ assertNull(p.parse(wrap(" "), Object.class));
+ assertNull(p.parse(wrap(" \t"), Object.class));
+ assertNull(p.parse(wrap(" <!--foo-->"), Object.class));
+ assertNull(p.parse(wrap(" <!--foo--> "), Object.class));
+ assertNull(p.parse(wrap(" //foo "), Object.class));
+
+
+ A1 t1 = new A1();
+ A2 t2 = new A2();
+ t2.add(new A3("name0","value0"));
+ t2.add(new A3("name1","value1"));
+ t1.list = t2;
+
+ s.setProperty(SERIALIZER_addClassAttrs, true);
+ in = strip(s.serialize(t1));
+ assertEquals("<rdf:Description><j:class>"+A1.class.getName()+"</j:class><jp:list><rdf:Seq><rdf:li rdf:parseType='Resource'><jp:name>name0</jp:name><jp:value>value0</jp:value></rdf:li><rdf:li rdf:parseType='Resource'><jp:name>name1</jp:name><jp:value>value1</jp:value></rdf:li></rdf:Seq></jp:list></rdf:Description>", in);
+ in = wrap(in);
+ t1 = (A1)p.parse(in, Object.class);
+ assertEquals("value1", t1.list.get(1).value);
+ t1 = p.parse(in, A1.class);
+ assertEquals("value1", t1.list.get(1).value);
+ }
+
+ public static class A1 {
+ public A2 list;
+ }
+
+ public static class A2 extends LinkedList<A3> {
+ }
+
+ public static class A3 {
+ public String name, value;
+ public A3(){}
+ public A3(String name, String value) {
+ this.name = name;
+ this.value = value;
+ }
+ }
+
+ //====================================================================================================
+ // Correct handling of unknown properties.
+ //====================================================================================================
+ @Test
+ public void testCorrectHandlingOfUnknownProperties() throws Exception {
+ ReaderParser p = new RdfParser.Xml().setProperty(BEAN_ignoreUnknownBeanProperties, true);
+ B t;
+
+ String in = wrap("<rdf:Description><jp:a rdf:datatype='http://www.w3.org/2001/XMLSchema#int'>1</jp:a><jp:unknownProperty>foo</jp:unknownProperty><jp:b rdf:datatype='http://www.w3.org/2001/XMLSchema#int'>2</jp:b></rdf:Description>");
+ t = p.parse(in, B.class);
+ assertEquals(t.a, 1);
+ assertEquals(t.b, 2);
+
+ try {
+ p = new RdfParser.Xml();
+ p.parse(in, B.class);
+ fail("Exception expected");
+ } catch (ParseException e) {}
+ }
+
+ public static class B {
+ public int a, b;
+ }
+
+ //====================================================================================================
+ // Writing to Collection properties with no setters.
+ //====================================================================================================
+ @Test
+ public void testCollectionPropertiesWithNoSetters() throws Exception {
+ RdfParser p = new RdfParser.Xml();
+ String in = wrap("<rdf:Description><jp:ints><rdf:Seq><rdf:li>1</rdf:li><rdf:li>2</rdf:li></rdf:Seq></jp:ints><jp:beans><rdf:Seq><rdf:li rdf:parseType='Resource'><jp:a>1</jp:a><jp:b>2</jp:b></rdf:li></rdf:Seq></jp:beans></rdf:Description>");
+ C t = p.parse(in, C.class);
+ assertEquals(t.getInts().size(), 2);
+ assertEquals(t.getBeans().get(0).b, 2);
+ }
+
+ public static class C {
+ private Collection<Integer> ints = new LinkedList<Integer>();
+ private List<B> beans = new LinkedList<B>();
+ public Collection<Integer> getInts() {
+ return ints;
+ }
+ public List<B> getBeans() {
+ return beans;
+ }
+ }
+
+ //====================================================================================================
+ // Parser listeners.
+ //====================================================================================================
+ @Test
+ public void testParserListeners() throws Exception {
+ final List<String> events = new LinkedList<String>();
+ RdfParser p = new RdfParser.Xml().setProperty(BEAN_ignoreUnknownBeanProperties, true);
+ p.addListener(
+ new ParserListener() {
+ @Override /* ParserListener */
+ public <T> void onUnknownProperty(String propertyName, Class<T> beanClass, T bean, int line, int col) {
+ events.add(propertyName + "," + line + "," + col);
+ }
+ }
+ );
+
+ String in = wrap("<rdf:Description><jp:a rdf:datatype='http://www.w3.org/2001/XMLSchema#int'>1</jp:a><jp:unknownProperty>foo</jp:unknownProperty><jp:b rdf:datatype='http://www.w3.org/2001/XMLSchema#int'>2</jp:b></rdf:Description>");
+ p.parse(in, B.class);
+ assertEquals(1, events.size());
+ assertEquals("unknownProperty,-1,-1", events.get(0));
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/jena/CommonTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/jena/CommonTest.java b/org.apache.juneau/src/test/java/org/apache/juneau/jena/CommonTest.java
new file mode 100755
index 0000000..664ce71
--- /dev/null
+++ b/org.apache.juneau/src/test/java/org/apache/juneau/jena/CommonTest.java
@@ -0,0 +1,513 @@
+/***************************************************************************************************************************
+ * 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.juneau.jena;
+
+import static org.apache.juneau.TestUtils.*;
+import static org.apache.juneau.jena.RdfCommonContext.*;
+import static org.apache.juneau.serializer.SerializerContext.*;
+import static org.junit.Assert.*;
+
+import java.net.*;
+import java.net.URI;
+import java.util.*;
+
+import org.apache.juneau.*;
+import org.apache.juneau.annotation.*;
+import org.apache.juneau.internal.*;
+import org.apache.juneau.serializer.*;
+import org.apache.juneau.testbeans.*;
+import org.apache.juneau.xml.*;
+import org.junit.*;
+
+@SuppressWarnings({"unchecked","serial"})
+public class CommonTest {
+
+ private RdfSerializer getBasicSerializer() {
+ return new RdfSerializer()
+ .setProperty(SERIALIZER_quoteChar, '\'')
+ .setProperty(SERIALIZER_useIndentation, false)
+ .setProperty(RDF_rdfxml_allowBadUris, true)
+ .setProperty(RDF_rdfxml_showDoctypeDeclaration, false)
+ .setProperty(RDF_rdfxml_showXmlDeclaration, false);
+ }
+
+ private String strip(String s) {
+ return s.replaceFirst("<rdf:RDF[^>]+>\\s*", "").replaceAll("</rdf:RDF>$", "").trim().replaceAll("[\\r\\n]", "");
+ }
+
+ //====================================================================================================
+ // Trim nulls from beans
+ //====================================================================================================
+ @Test
+ public void testTrimNullsFromBeans() throws Exception {
+ RdfSerializer s = getBasicSerializer();
+ RdfParser p = RdfParser.DEFAULT_XML;
+ A t1 = A.create(), t2;
+
+ s.setProperty(SERIALIZER_trimNullProperties, false);
+ String r = s.serialize(t1);
+ assertEquals("<rdf:Description><jp:s1 rdf:resource='http://www.w3.org/1999/02/22-rdf-syntax-ns#nil'/><jp:s2>s2</jp:s2></rdf:Description>", strip(r));
+ t2 = p.parse(r, A.class);
+ assertEqualObjects(t1, t2);
+
+ s.setProperty(SERIALIZER_trimNullProperties, true);
+ r = s.serialize(t1);
+ assertEquals("<rdf:Description><jp:s2>s2</jp:s2></rdf:Description>", strip(r));
+ t2 = p.parse(r, A.class);
+ assertEqualObjects(t1, t2);
+ }
+
+ public static class A {
+ public String s1, s2;
+
+ public static A create() {
+ A t = new A();
+ t.s2 = "s2";
+ return t;
+ }
+ }
+
+ //====================================================================================================
+ // Trim empty maps
+ //====================================================================================================
+ @Test
+ public void testTrimEmptyMaps() throws Exception {
+ RdfSerializer s = getBasicSerializer();
+ RdfParser p = RdfParser.DEFAULT_XML;
+ B t1 = B.create(), t2;
+ String r;
+
+ s.setProperty(SERIALIZER_trimEmptyMaps, false);
+ r = s.serialize(t1);
+ assertEquals("<rdf:Description><jp:f1 rdf:parseType='Resource'></jp:f1><jp:f2 rdf:parseType='Resource'><jp:f2a rdf:resource='http://www.w3.org/1999/02/22-rdf-syntax-ns#nil'/><jp:f2b rdf:parseType='Resource'><jp:s2>s2</jp:s2></jp:f2b></jp:f2></rdf:Description>", strip(r));
+ t2 = p.parse(r, B.class);
+ assertEqualObjects(t1, t2);
+
+ s.setProperty(SERIALIZER_trimEmptyMaps, true);
+ r = s.serialize(t1);
+ assertEquals("<rdf:Description><jp:f2 rdf:parseType='Resource'><jp:f2a rdf:resource='http://www.w3.org/1999/02/22-rdf-syntax-ns#nil'/><jp:f2b rdf:parseType='Resource'><jp:s2>s2</jp:s2></jp:f2b></jp:f2></rdf:Description>", strip(r));
+ t2 = p.parse(r, B.class);
+ assertNull(t2.f1);
+ }
+
+ public static class B {
+ public TreeMap<String,A> f1, f2;
+
+ public static B create() {
+ B t = new B();
+ t.f1 = new TreeMap<String,A>();
+ t.f2 = new TreeMap<String,A>(){{put("f2a",null);put("f2b",A.create());}};
+ return t;
+ }
+ }
+
+ //====================================================================================================
+ // Trim empty lists
+ //====================================================================================================
+ @Test
+ public void testTrimEmptyLists() throws Exception {
+ RdfSerializer s = getBasicSerializer();
+ RdfParser p = RdfParser.DEFAULT_XML;
+ C t1 = C.create(), t2;
+ String r;
+
+ s.setProperty(SERIALIZER_trimEmptyLists, false);
+ r = s.serialize(t1);
+ assertEquals("<rdf:Description><jp:f1><rdf:Seq/></jp:f1><jp:f2><rdf:Seq><rdf:li rdf:resource='http://www.w3.org/1999/02/22-rdf-syntax-ns#nil'/><rdf:li rdf:parseType='Resource'><jp:s2>s2</jp:s2></rdf:li></rdf:Seq></jp:f2></rdf:Description>", strip(r));
+ t2 = p.parse(r, C.class);
+ assertEqualObjects(t1, t2);
+
+ s.setProperty(SERIALIZER_trimEmptyLists, true);
+ r = s.serialize(t1);
+ assertEquals("<rdf:Description><jp:f2><rdf:Seq><rdf:li rdf:resource='http://www.w3.org/1999/02/22-rdf-syntax-ns#nil'/><rdf:li rdf:parseType='Resource'><jp:s2>s2</jp:s2></rdf:li></rdf:Seq></jp:f2></rdf:Description>", strip(r));
+ t2 = p.parse(r, C.class);
+ assertNull(t2.f1);
+ t2 = p.parse(r, C.class);
+ }
+
+ public static class C {
+ public List<A> f1, f2;
+
+ public static C create() {
+ C t = new C();
+ t.f1 = new LinkedList<A>();
+ t.f2 = new LinkedList<A>(){{add(null);add(A.create());}};
+ return t;
+ }
+ }
+
+ //====================================================================================================
+ // Trim empty arrays
+ //====================================================================================================
+ @Test
+ public void testTrimEmptyArrays() throws Exception {
+ RdfSerializer s = getBasicSerializer();
+ RdfParser p = RdfParser.DEFAULT_XML;
+ D t1 = D.create(), t2;
+ String r;
+
+ s.setProperty(SERIALIZER_trimEmptyLists, false);
+ r = s.serialize(t1);
+ assertEquals("<rdf:Description><jp:f1><rdf:Seq/></jp:f1><jp:f2><rdf:Seq><rdf:li rdf:resource='http://www.w3.org/1999/02/22-rdf-syntax-ns#nil'/><rdf:li rdf:parseType='Resource'><jp:s2>s2</jp:s2></rdf:li></rdf:Seq></jp:f2></rdf:Description>", strip(r));
+ t2 = p.parse(r, D.class);
+ assertEqualObjects(t1, t2);
+
+ s.setProperty(SERIALIZER_trimEmptyLists, true);
+ r = s.serialize(t1);
+ assertEquals("<rdf:Description><jp:f2><rdf:Seq><rdf:li rdf:resource='http://www.w3.org/1999/02/22-rdf-syntax-ns#nil'/><rdf:li rdf:parseType='Resource'><jp:s2>s2</jp:s2></rdf:li></rdf:Seq></jp:f2></rdf:Description>", strip(r));
+ t2 = p.parse(r, D.class);
+ assertNull(t2.f1);
+ }
+
+ public static class D {
+ public A[] f1, f2;
+
+ public static D create() {
+ D t = new D();
+ t.f1 = new A[]{};
+ t.f2 = new A[]{null, A.create()};
+ return t;
+ }
+ }
+
+ //====================================================================================================
+ // @BeanProperty.properties annotation.
+ //====================================================================================================
+ @Test
+ public void testBeanPropertyProperties() throws Exception {
+ RdfSerializer s = getBasicSerializer();
+ RdfParser p = RdfParser.DEFAULT_XML;
+ E1 t1 = E1.create(), t2;
+ String r;
+
+ r = s.serialize(t1);
+ assertEquals("<rdf:Description><jp:x1 rdf:parseType='Resource'><jp:f1>1</jp:f1></jp:x1><jp:x2 rdf:parseType='Resource'><jp:f1>1</jp:f1></jp:x2><jp:x3><rdf:Seq><rdf:li rdf:parseType='Resource'><jp:f1>1</jp:f1></rdf:li></rdf:Seq></jp:x3><jp:x4><rdf:Seq><rdf:li rdf:parseType='Resource'><jp:f1>1</jp:f1></rdf:li></rdf:Seq></jp:x4><jp:x5><rdf:Seq><rdf:li rdf:parseType='Resource'><jp:f1>1</jp:f1></rdf:li></rdf:Seq></jp:x5><jp:x6><rdf:Seq><rdf:li rdf:parseType='Resource'><jp:f1>1</jp:f1></rdf:li></rdf:Seq></jp:x6></rdf:Description>", strip(r));
+ t2 = p.parse(r, E1.class);
+ assertEqualObjects(t1, t2);
+ }
+
+ public static class E1 {
+ @BeanProperty(properties={"f1"}) public E2 x1;
+ @BeanProperty(properties={"f1"}) public Map<String,Integer> x2;
+ @BeanProperty(properties={"f1"}) public E2[] x3;
+ @BeanProperty(properties={"f1"}) public List<E2> x4;
+ @BeanProperty(properties={"f1"}) public ObjectMap[] x5;
+ @BeanProperty(properties={"f1"}) public List<ObjectMap> x6;
+
+ public static E1 create() {
+ E1 t = new E1();
+ t.x1 = new E2();
+ t.x2 = new LinkedHashMap<String,Integer>() {{ put("f1",1); put("f2",2); }};
+ t.x3 = new E2[] {new E2()};
+ t.x4 = new LinkedList<E2>() {{ add(new E2()); }};
+ t.x5 = new ObjectMap[] {new ObjectMap().append("f1","1").append("f2","2")};
+ t.x6 = new LinkedList<ObjectMap>() {{ add(new ObjectMap().append("f1","1").append("f2","2")); }};
+ return t;
+ }
+ }
+
+ public static class E2 {
+ public int f1 = 1;
+ public int f2 = 2;
+ }
+
+ //====================================================================================================
+ // @BeanProperty.properties annotation on list of beans.
+ //====================================================================================================
+ @Test
+ public void testBeanPropertyProperiesOnListOfBeans() throws Exception {
+ RdfSerializer s = getBasicSerializer();
+ RdfParser p = RdfParser.DEFAULT_XML;
+ List<F> l1 = new LinkedList<F>(), l2;
+ F t = F.create();
+ t.x1.add(F.create());
+ l1.add(t);
+
+ String r = s.serialize(l1);
+ assertEquals("<rdf:Seq><rdf:li rdf:parseType='Resource'><jp:x1><rdf:Seq><rdf:li rdf:parseType='Resource'><jp:x2>2</jp:x2></rdf:li></rdf:Seq></jp:x1><jp:x2>2</jp:x2></rdf:li></rdf:Seq>", strip(r));
+ ClassMeta<LinkedList<F>> cm = p.getBeanContext().getCollectionClassMeta(LinkedList.class, F.class);
+ l2 = p.parse(r, cm);
+ assertEqualObjects(l1, l2);
+ }
+
+ public static class F {
+ @BeanProperty(properties={"x2"}) public List<F> x1;
+ public int x2;
+
+ public static F create() {
+ F t = new F();
+ t.x1 = new LinkedList<F>();
+ t.x2 = 2;
+ return t;
+ }
+ }
+
+ //====================================================================================================
+ // Test URIAttr - Test that URLs and URIs are serialized and parsed correctly.
+ //====================================================================================================
+ @Test
+ public void testURIAttr() throws Exception {
+ RdfSerializer s = getBasicSerializer();
+ RdfParser p = RdfParser.DEFAULT_XML;
+
+ G t = new G();
+ t.uri = new URI("http://uri");
+ t.f1 = new URI("http://f1");
+ t.f2 = new URL("http://f2");
+
+ String xml = s.serialize(t);
+ t = p.parse(xml, G.class);
+ assertEquals("http://uri", t.uri.toString());
+ assertEquals("http://f1", t.f1.toString());
+ assertEquals("http://f2", t.f2.toString());
+ }
+
+ public static class G {
+ @BeanProperty(beanUri=true) public URI uri;
+ public URI f1;
+ public URL f2;
+ }
+
+ //====================================================================================================
+ // Test URIs with URI_CONTEXT and URI_AUTHORITY
+ //====================================================================================================
+ @Test
+ public void testUris() throws Exception {
+ WriterSerializer s = getBasicSerializer();
+ TestURI t = new TestURI();
+ String r;
+ String expected = "";
+
+ s.setProperty(SERIALIZER_relativeUriBase, null);
+ r = stripAndSort(s.serialize(t));
+ expected = ""
+ +"</rdf:Description>>"
+ +"\n<<rdf:Description rdf:about='f0/x0'>"
+ +"\n<jp:f1 rdf:resource='f1/x1'/>"
+ +"\n<jp:f2 rdf:resource='/f2/x2'/>"
+ +"\n<jp:f3 rdf:resource='http://www.ibm.com/f3/x3'/>"
+ +"\n<jp:f4 rdf:resource='f4/x4'/>"
+ +"\n<jp:f5 rdf:resource='/f5/x5'/>"
+ +"\n<jp:f6 rdf:resource='http://www.ibm.com/f6/x6'/>"
+ +"\n<jp:f7 rdf:resource='http://www.ibm.com/f7/x7'/>"
+ +"\n<jp:f8 rdf:resource='f8/x8'/>"
+ +"\n<jp:f9 rdf:resource='f9/x9'/>"
+ +"\n<jp:fa>http://www.ibm.com/fa/xa#MY_LABEL</jp:fa>"
+ +"\n<jp:fb>http://www.ibm.com/fb/xb?label=MY_LABEL&foo=bar</jp:fb>"
+ +"\n<jp:fc>http://www.ibm.com/fc/xc?foo=bar&label=MY_LABEL</jp:fc>"
+ +"\n<jp:fd>http://www.ibm.com/fd/xd?label2=MY_LABEL&foo=bar</jp:fd>"
+ +"\n<jp:fe>http://www.ibm.com/fe/xe?foo=bar&label2=MY_LABEL</jp:fe>"
+ ;
+ assertEquals(expected, r);
+
+ s.setProperty(SERIALIZER_relativeUriBase, ""); // Same as null.
+ r = stripAndSort(s.serialize(t));
+ assertEquals(expected, r);
+
+ s.setProperty(SERIALIZER_relativeUriBase, "/cr");
+ r = stripAndSort(s.serialize(t));
+ expected = ""
+ +"</rdf:Description>>"
+ +"\n<<rdf:Description rdf:about='/cr/f0/x0'>"
+ +"\n<jp:f1 rdf:resource='/cr/f1/x1'/>"
+ +"\n<jp:f2 rdf:resource='/f2/x2'/>"
+ +"\n<jp:f3 rdf:resource='http://www.ibm.com/f3/x3'/>"
+ +"\n<jp:f4 rdf:resource='/cr/f4/x4'/>"
+ +"\n<jp:f5 rdf:resource='/f5/x5'/>"
+ +"\n<jp:f6 rdf:resource='http://www.ibm.com/f6/x6'/>"
+ +"\n<jp:f7 rdf:resource='http://www.ibm.com/f7/x7'/>"
+ +"\n<jp:f8 rdf:resource='/cr/f8/x8'/>"
+ +"\n<jp:f9 rdf:resource='/cr/f9/x9'/>"
+ +"\n<jp:fa>http://www.ibm.com/fa/xa#MY_LABEL</jp:fa>"
+ +"\n<jp:fb>http://www.ibm.com/fb/xb?label=MY_LABEL&foo=bar</jp:fb>"
+ +"\n<jp:fc>http://www.ibm.com/fc/xc?foo=bar&label=MY_LABEL</jp:fc>"
+ +"\n<jp:fd>http://www.ibm.com/fd/xd?label2=MY_LABEL&foo=bar</jp:fd>"
+ +"\n<jp:fe>http://www.ibm.com/fe/xe?foo=bar&label2=MY_LABEL</jp:fe>"
+ ;
+ assertEquals(expected, r);
+
+ s.setProperty(SERIALIZER_relativeUriBase, "/cr/"); // Same as above
+ r = stripAndSort(s.serialize(t));
+ assertEquals(expected, r);
+
+ s.setProperty(SERIALIZER_relativeUriBase, "/");
+ r = stripAndSort(s.serialize(t));
+ expected = ""
+ +"</rdf:Description>>"
+ +"\n<<rdf:Description rdf:about='/f0/x0'>"
+ +"\n<jp:f1 rdf:resource='/f1/x1'/>"
+ +"\n<jp:f2 rdf:resource='/f2/x2'/>"
+ +"\n<jp:f3 rdf:resource='http://www.ibm.com/f3/x3'/>"
+ +"\n<jp:f4 rdf:resource='/f4/x4'/>"
+ +"\n<jp:f5 rdf:resource='/f5/x5'/>"
+ +"\n<jp:f6 rdf:resource='http://www.ibm.com/f6/x6'/>"
+ +"\n<jp:f7 rdf:resource='http://www.ibm.com/f7/x7'/>"
+ +"\n<jp:f8 rdf:resource='/f8/x8'/>"
+ +"\n<jp:f9 rdf:resource='/f9/x9'/>"
+ +"\n<jp:fa>http://www.ibm.com/fa/xa#MY_LABEL</jp:fa>"
+ +"\n<jp:fb>http://www.ibm.com/fb/xb?label=MY_LABEL&foo=bar</jp:fb>"
+ +"\n<jp:fc>http://www.ibm.com/fc/xc?foo=bar&label=MY_LABEL</jp:fc>"
+ +"\n<jp:fd>http://www.ibm.com/fd/xd?label2=MY_LABEL&foo=bar</jp:fd>"
+ +"\n<jp:fe>http://www.ibm.com/fe/xe?foo=bar&label2=MY_LABEL</jp:fe>"
+ ;
+ assertEquals(expected, r);
+
+ s.setProperty(SERIALIZER_relativeUriBase, null);
+
+ s.setProperty(SERIALIZER_absolutePathUriBase, "http://foo");
+ r = stripAndSort(s.serialize(t));
+ expected = ""
+ +"</rdf:Description>>"
+ +"\n<<rdf:Description rdf:about='f0/x0'>"
+ +"\n<jp:f1 rdf:resource='f1/x1'/>"
+ +"\n<jp:f2 rdf:resource='http://foo/f2/x2'/>"
+ +"\n<jp:f3 rdf:resource='http://www.ibm.com/f3/x3'/>"
+ +"\n<jp:f4 rdf:resource='f4/x4'/>"
+ +"\n<jp:f5 rdf:resource='http://foo/f5/x5'/>"
+ +"\n<jp:f6 rdf:resource='http://www.ibm.com/f6/x6'/>"
+ +"\n<jp:f7 rdf:resource='http://www.ibm.com/f7/x7'/>"
+ +"\n<jp:f8 rdf:resource='f8/x8'/>"
+ +"\n<jp:f9 rdf:resource='f9/x9'/>"
+ +"\n<jp:fa>http://www.ibm.com/fa/xa#MY_LABEL</jp:fa>"
+ +"\n<jp:fb>http://www.ibm.com/fb/xb?label=MY_LABEL&foo=bar</jp:fb>"
+ +"\n<jp:fc>http://www.ibm.com/fc/xc?foo=bar&label=MY_LABEL</jp:fc>"
+ +"\n<jp:fd>http://www.ibm.com/fd/xd?label2=MY_LABEL&foo=bar</jp:fd>"
+ +"\n<jp:fe>http://www.ibm.com/fe/xe?foo=bar&label2=MY_LABEL</jp:fe>"
+ ;
+ assertEquals(expected, r);
+
+ s.setProperty(SERIALIZER_absolutePathUriBase, "http://foo/");
+ r = stripAndSort(s.serialize(t));
+ assertEquals(expected, r);
+
+ s.setProperty(SERIALIZER_absolutePathUriBase, ""); // Same as null.
+ r = stripAndSort(s.serialize(t));
+ expected = ""
+ +"</rdf:Description>>"
+ +"\n<<rdf:Description rdf:about='f0/x0'>"
+ +"\n<jp:f1 rdf:resource='f1/x1'/>"
+ +"\n<jp:f2 rdf:resource='/f2/x2'/>"
+ +"\n<jp:f3 rdf:resource='http://www.ibm.com/f3/x3'/>"
+ +"\n<jp:f4 rdf:resource='f4/x4'/>"
+ +"\n<jp:f5 rdf:resource='/f5/x5'/>"
+ +"\n<jp:f6 rdf:resource='http://www.ibm.com/f6/x6'/>"
+ +"\n<jp:f7 rdf:resource='http://www.ibm.com/f7/x7'/>"
+ +"\n<jp:f8 rdf:resource='f8/x8'/>"
+ +"\n<jp:f9 rdf:resource='f9/x9'/>"
+ +"\n<jp:fa>http://www.ibm.com/fa/xa#MY_LABEL</jp:fa>"
+ +"\n<jp:fb>http://www.ibm.com/fb/xb?label=MY_LABEL&foo=bar</jp:fb>"
+ +"\n<jp:fc>http://www.ibm.com/fc/xc?foo=bar&label=MY_LABEL</jp:fc>"
+ +"\n<jp:fd>http://www.ibm.com/fd/xd?label2=MY_LABEL&foo=bar</jp:fd>"
+ +"\n<jp:fe>http://www.ibm.com/fe/xe?foo=bar&label2=MY_LABEL</jp:fe>"
+ ;
+ assertEquals(expected, r);
+ }
+
+ private String stripAndSort(String s) {
+ s = strip(s);
+ Set<String> set = new TreeSet<String>();
+ for (String s2 : s.split("><"))
+ set.add('<' + s2 + '>');
+ return StringUtils.join(set, "\n");
+ }
+
+ //====================================================================================================
+ // Validate that you cannot update properties on locked serializer.
+ //====================================================================================================
+ @Test
+ public void testLockedSerializer() throws Exception {
+ RdfSerializer s = getBasicSerializer().lock();
+ try {
+ s.setProperty(XmlSerializerContext.XML_enableNamespaces, true);
+ fail("Locked exception not thrown");
+ } catch (LockedException e) {}
+ try {
+ s.setProperty(SerializerContext.SERIALIZER_addClassAttrs, true);
+ fail("Locked exception not thrown");
+ } catch (LockedException e) {}
+ try {
+ s.setProperty(BeanContext.BEAN_beanMapPutReturnsOldValue, true);
+ fail("Locked exception not thrown");
+ } catch (LockedException e) {}
+ }
+
+ //====================================================================================================
+ // Recursion
+ //====================================================================================================
+ @Test
+ public void testRecursion() throws Exception {
+ WriterSerializer s = new RdfSerializer.XmlAbbrev().setProperty(SERIALIZER_quoteChar, '\'');
+
+ R1 r1 = new R1();
+ R2 r2 = new R2();
+ R3 r3 = new R3();
+ r1.r2 = r2;
+ r2.r3 = r3;
+ r3.r1 = r1;
+
+ // No recursion detection
+ try {
+ s.serialize(r1);
+ fail("Exception expected!");
+ } catch (Exception e) {
+ String msg = e.getLocalizedMessage();
+ assertTrue(msg.contains("It's recommended you use the SerializerContext.SERIALIZER_detectRecursions setting to help locate the loop."));
+ }
+
+ // Recursion detection, no ignore
+ s.setProperty(SERIALIZER_detectRecursions, true);
+ try {
+ s.serialize(r1);
+ fail("Exception expected!");
+ } catch (Exception e) {
+ String msg = e.getLocalizedMessage();
+ assertTrue(msg.contains("[0]root:org.apache.juneau.jena.CommonTest$R1"));
+ assertTrue(msg.contains("->[1]r2:org.apache.juneau.jena.CommonTest$R2"));
+ assertTrue(msg.contains("->[2]r3:org.apache.juneau.jena.CommonTest$R3"));
+ assertTrue(msg.contains("->[3]r1:org.apache.juneau.jena.CommonTest$R1"));
+ }
+
+ s.setProperty(SERIALIZER_ignoreRecursions, true);
+ String r = s.serialize(r1).replace("\r", "");
+ // Note...the order of the namespaces is not always the same depending on the JVM.
+ // The Jena libraries appear to use a hashmap for these.
+ assertTrue(r.contains(
+ "<rdf:Description>\n"+
+ "<jp:name>foo</jp:name>\n"+
+ "<jp:r2 rdf:parseType='Resource'>\n"+
+ "<jp:name>bar</jp:name>\n"+
+ "<jp:r3 rdf:parseType='Resource'>\n"+
+ "<jp:name>baz</jp:name>\n"+
+ "</jp:r3>\n"+
+ "</jp:r2>\n"+
+ "</rdf:Description>\n"+
+ "</rdf:RDF>\n"
+ ));
+ assertTrue(r.contains("xmlns:rdf='http://www.w3.org/1999/02/22-rdf-syntax-ns#"));
+ assertTrue(r.contains("xmlns:j='http://www.ibm.com/juneau/"));
+ assertTrue(r.contains("xmlns:jp='http://www.ibm.com/juneaubp/"));
+ }
+
+ public static class R1 {
+ public String name = "foo";
+ public R2 r2;
+ }
+ public static class R2 {
+ public String name = "bar";
+ public R3 r3;
+ }
+ public static class R3 {
+ public String name = "baz";
+ public R1 r1;
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/jena/CommonXmlTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/jena/CommonXmlTest.java b/org.apache.juneau/src/test/java/org/apache/juneau/jena/CommonXmlTest.java
new file mode 100755
index 0000000..447d803
--- /dev/null
+++ b/org.apache.juneau/src/test/java/org/apache/juneau/jena/CommonXmlTest.java
@@ -0,0 +1,95 @@
+/***************************************************************************************************************************
+ * 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.juneau.jena;
+
+import static org.apache.juneau.TestUtils.*;
+import static org.apache.juneau.jena.RdfCommonContext.*;
+import static org.apache.juneau.serializer.SerializerContext.*;
+import static org.junit.Assert.*;
+
+import java.net.*;
+
+import org.apache.juneau.annotation.*;
+import org.junit.*;
+
+public class CommonXmlTest {
+
+ private RdfSerializer getBasicSerializer() {
+ return new RdfSerializer()
+ .setProperty(SERIALIZER_quoteChar, '\'')
+ .setProperty(SERIALIZER_useIndentation, false)
+ .setProperty(RDF_rdfxml_allowBadUris, true)
+ .setProperty(RDF_rdfxml_showDoctypeDeclaration, false)
+ .setProperty(RDF_rdfxml_showXmlDeclaration, false);
+ }
+
+ private String strip(String s) {
+ return s.replaceFirst("<rdf:RDF[^>]+>\\s*", "").replaceAll("</rdf:RDF>$", "").trim().replaceAll("[\\r\\n]", "");
+ }
+
+ //====================================================================================================
+ // Bean.uri annotation
+ //====================================================================================================
+ @Test
+ public void testBeanUriAnnotation() throws Exception {
+ RdfSerializer s = getBasicSerializer();
+ RdfParser p = RdfParser.DEFAULT_XML;
+ A t1 = A.create(), t2;
+ String r;
+
+ r = s.serialize(t1);
+ assertEquals("<rdf:Description rdf:about='http://foo'><jp:name>bar</jp:name></rdf:Description>", strip(r));
+ t2 = p.parse(r, A.class);
+ assertEqualObjects(t1, t2);
+ }
+
+ public static class A {
+ @BeanProperty(beanUri=true) public URL url;
+ public String name;
+
+ public static A create() throws Exception {
+ A t = new A();
+ t.url = new URL("http://foo");
+ t.name = "bar";
+ return t;
+ }
+ }
+
+ //====================================================================================================
+ // Bean.uri annotation, only uri property
+ //====================================================================================================
+ @Test
+ public void testBeanUriAnnotationOnlyUriProperty() throws Exception {
+ RdfSerializer s = getBasicSerializer();
+ RdfParser p = RdfParser.DEFAULT_XML;
+ B t1 = B.create(), t2;
+ String r;
+
+ r = s.serialize(t1);
+ assertEquals("<rdf:Description rdf:about='http://foo'><jp:url2 rdf:resource='http://foo/2'/></rdf:Description>", strip(r));
+ t2 = p.parse(r, B.class);
+ assertEqualObjects(t1, t2);
+ }
+
+ public static class B {
+ @BeanProperty(beanUri=true) public URL url;
+ public URL url2;
+
+ public static B create() throws Exception {
+ B t = new B();
+ t.url = new URL("http://foo");
+ t.url2 = new URL("http://foo/2");
+ return t;
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/jena/RdfParserTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/jena/RdfParserTest.java b/org.apache.juneau/src/test/java/org/apache/juneau/jena/RdfParserTest.java
new file mode 100755
index 0000000..279228f
--- /dev/null
+++ b/org.apache.juneau/src/test/java/org/apache/juneau/jena/RdfParserTest.java
@@ -0,0 +1,149 @@
+/***************************************************************************************************************************
+ * 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.juneau.jena;
+
+import static org.apache.juneau.TestUtils.*;
+import static org.apache.juneau.jena.RdfCommonContext.*;
+import static org.apache.juneau.jena.RdfSerializerContext.*;
+import static org.apache.juneau.serializer.SerializerContext.*;
+import static org.junit.Assert.*;
+
+import java.net.URI;
+import java.text.*;
+import java.util.*;
+
+import org.apache.juneau.*;
+import org.apache.juneau.annotation.*;
+import org.apache.juneau.jena.annotation.*;
+import org.apache.juneau.json.*;
+import org.apache.juneau.transforms.*;
+import org.junit.*;
+
+public class RdfParserTest {
+
+ @Test
+ public void testParseIntoGenericPojos() throws Exception {
+ A a = new A().init();
+
+ // Create a new serializer with readable output.
+ RdfSerializer s = new RdfSerializer.XmlAbbrev()
+ .setProperty(RDF_rdfxml_tab, 3)
+ .setProperty(SERIALIZER_quoteChar, '\'')
+ .setProperty(RDF_addRootProperty, true);
+
+ String expected =
+ "<rdf:RDF a='http://ns/' a1='http://ns2/' j='http://www.ibm.com/juneau/' jp='http://www.ibm.com/juneaubp/' rdf='http://www.w3.org/1999/02/22-rdf-syntax-ns#'>"
+ + "\n <rdf:Description about='http://test/a'>"
+ + "\n <a:f1>1</a:f1>"
+ + "\n <a:f2>f2</a:f2>"
+ + "\n <a:f4a rdf:resource='http://test/a'/>"
+ + "\n <a:f4b rdf:resource='http://test/external'/>"
+ + "\n <a:f5>1999-01-01T00:00:00Z</a:f5>"
+ + "\n <a:f6>"
+ + "\n <rdf:Seq>"
+ + "\n <rdf:li>"
+ + "\n <rdf:Description about='http://test/a/a1'>"
+ + "\n <a1:f1>1</a1:f1>"
+ + "\n <a1:f2>f2</a1:f2>"
+ + "\n <a1:f4a rdf:resource='http://test/a'/>"
+ + "\n <a1:f4b rdf:resource='http://test/external'/>"
+ + "\n <a1:f5>1999-01-01T00:00:00Z</a1:f5>"
+ + "\n </rdf:Description>"
+ + "\n </rdf:li>"
+ + "\n </rdf:Seq>"
+ + "\n </a:f6>"
+ + "\n <j:root>true</j:root>"
+ + "\n </rdf:Description>"
+ + "\n</rdf:RDF>";
+
+ String rdfXml = s.serialize(a);
+ assertXmlEquals(expected, rdfXml);
+
+ A a2 = RdfParser.DEFAULT_XML.parse(rdfXml, A.class);
+
+ assertEqualObjects(a, a2);
+
+ ObjectMap m = RdfParser.DEFAULT_XML.parse(rdfXml, ObjectMap.class);
+ String json = JsonSerializer.DEFAULT_LAX_READABLE.serialize(m);
+
+ String e = ""
+ + "{\n"
+ + " uri: 'http://test/a', \n"
+ + " f6: [\n"
+ + " {\n"
+ + " uri: 'http://test/a/a1', \n"
+ + " f5: '1999-01-01T00:00:00Z', \n"
+ + " f4b: 'http://test/external', \n"
+ + " f4a: 'http://test/a', \n"
+ + " f2: 'f2', \n"
+ + " f1: '1'\n"
+ + " }\n"
+ + " ], \n"
+ + " f5: '1999-01-01T00:00:00Z', \n"
+ + " f4b: 'http://test/external', \n"
+ + " f4a: 'http://test/a', \n"
+ + " f2: 'f2', \n"
+ + " f1: '1', \n"
+ + " root: 'true'\n"
+ + "}";
+ assertEquals(e, json.replace("\r", ""));
+
+ }
+
+ @Rdf(prefix="a", namespace="http://ns/")
+ public static class A {
+ public int f1;
+ public String f2;
+ @BeanProperty(beanUri=true) public URI f3;
+ public URI f4a, f4b;
+ @BeanProperty(transform=CalendarTransform.ISO8601DTZ.class) public Calendar f5;
+ public LinkedList<A1> f6 = new LinkedList<A1>();
+
+ public A init() throws Exception {
+ f1 = 1;
+ f2 = "f2";
+ f3 = new URI("http://test/a"); // Bean URI.
+ f4a = new URI("http://test/a"); // Points to itself.
+ f4b = new URI("http://test/external");
+ f5 = new GregorianCalendar();
+ DateFormat df = DateFormat.getDateInstance(DateFormat.MEDIUM);
+ df.setTimeZone(TimeZone.getTimeZone("GMT"));
+ f5.setTime(df.parse("Jan 1, 1999"));
+ f6 = new LinkedList<A1>();
+ f6.add(new A1().init());
+ return this;
+ }
+ }
+
+ @Rdf(prefix="a1", namespace="http://ns2/")
+ public static class A1 {
+ public int f1;
+ public String f2;
+ @BeanProperty(beanUri=true) public URI f3;
+ public URI f4a, f4b;
+ @BeanProperty(transform=CalendarTransform.ISO8601DTZ.class) public Calendar f5;
+
+ public A1 init() throws Exception {
+ f1 = 1;
+ f2 = "f2";
+ f3 = new URI("http://test/a/a1");
+ f4a = new URI("http://test/a");
+ f4b = new URI("http://test/external");
+ f5 = new GregorianCalendar();
+ DateFormat df = DateFormat.getDateInstance(DateFormat.MEDIUM);
+ df.setTimeZone(TimeZone.getTimeZone("GMT"));
+ f5.setTime(df.parse("Jan 1, 1999"));
+ return this;
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/jena/RdfTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/jena/RdfTest.java b/org.apache.juneau/src/test/java/org/apache/juneau/jena/RdfTest.java
new file mode 100755
index 0000000..9b2a980
--- /dev/null
+++ b/org.apache.juneau/src/test/java/org/apache/juneau/jena/RdfTest.java
@@ -0,0 +1,597 @@
+/***************************************************************************************************************************
+ * 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.juneau.jena;
+
+import static org.apache.juneau.TestUtils.*;
+import static org.apache.juneau.jena.RdfCommonContext.*;
+import static org.apache.juneau.jena.RdfSerializerContext.*;
+import static org.apache.juneau.serializer.SerializerContext.*;
+
+import java.net.URI;
+import java.util.*;
+
+import org.apache.juneau.annotation.*;
+import org.apache.juneau.jena.annotation.*;
+import org.apache.juneau.parser.*;
+import org.apache.juneau.serializer.*;
+import org.junit.*;
+
+@SuppressWarnings("serial")
+public class RdfTest {
+
+ @Test
+ public void testCollectionFormatProperties() throws Exception {
+ A a = new A().init(), a2;
+ String rdfXml;
+ String expected;
+
+ RdfSerializer s = new RdfSerializer.XmlAbbrev()
+ .setProperty(RDF_rdfxml_tab, 3)
+ .setProperty(SERIALIZER_quoteChar, '\'')
+ .setProperty(RDF_addRootProperty, true);
+ RdfParser p = RdfParser.DEFAULT_XML.clone();
+
+ //--------------------------------------------------------------------------------
+ // Normal format - Sequence
+ //--------------------------------------------------------------------------------
+ expected =
+ "<rdf:RDF a='http://ns/' j='http://www.ibm.com/juneau/' jp='http://www.ibm.com/juneaubp/' rdf='http://www.w3.org/1999/02/22-rdf-syntax-ns#'>"
+ + "\n <rdf:Description about='http://test/a'>"
+ + "\n <a:f2>"
+ + "\n <rdf:Seq>"
+ + "\n <rdf:li>f2a</rdf:li>"
+ + "\n <rdf:li>f2b</rdf:li>"
+ + "\n </rdf:Seq>"
+ + "\n </a:f2>"
+ + "\n <a:f3>"
+ + "\n <rdf:Seq>"
+ + "\n <rdf:li>1</rdf:li>"
+ + "\n <rdf:li>2</rdf:li>"
+ + "\n </rdf:Seq>"
+ + "\n </a:f3>"
+ + "\n <j:root>true</j:root>"
+ + "\n </rdf:Description>"
+ + "\n</rdf:RDF>";
+ rdfXml = s.serialize(a);
+ assertXmlEquals(expected, rdfXml);
+
+ a2 = p.parse(rdfXml, A.class);
+ assertEqualObjects(a, a2);
+
+ //--------------------------------------------------------------------------------
+ // Explicit sequence
+ //--------------------------------------------------------------------------------
+ s.setProperty(RDF_collectionFormat, RdfCollectionFormat.SEQ);
+ expected =
+ "<rdf:RDF a='http://ns/' j='http://www.ibm.com/juneau/' jp='http://www.ibm.com/juneaubp/' rdf='http://www.w3.org/1999/02/22-rdf-syntax-ns#'>"
+ + "\n <rdf:Description about='http://test/a'>"
+ + "\n <a:f2>"
+ + "\n <rdf:Seq>"
+ + "\n <rdf:li>f2a</rdf:li>"
+ + "\n <rdf:li>f2b</rdf:li>"
+ + "\n </rdf:Seq>"
+ + "\n </a:f2>"
+ + "\n <a:f3>"
+ + "\n <rdf:Seq>"
+ + "\n <rdf:li>1</rdf:li>"
+ + "\n <rdf:li>2</rdf:li>"
+ + "\n </rdf:Seq>"
+ + "\n </a:f3>"
+ + "\n <j:root>true</j:root>"
+ + "\n </rdf:Description>"
+ + "\n</rdf:RDF>";
+ rdfXml = s.serialize(a);
+ assertXmlEquals(expected, rdfXml);
+
+ a2 = p.parse(rdfXml, A.class);
+ assertEqualObjects(a, a2);
+
+ //--------------------------------------------------------------------------------
+ // Bag
+ //--------------------------------------------------------------------------------
+ s.setProperty(RDF_collectionFormat, RdfCollectionFormat.BAG);
+ expected =
+ "<rdf:RDF a='http://ns/' j='http://www.ibm.com/juneau/' jp='http://www.ibm.com/juneaubp/' rdf='http://www.w3.org/1999/02/22-rdf-syntax-ns#'>"
+ + "\n <rdf:Description about='http://test/a'>"
+ + "\n <a:f2>"
+ + "\n <rdf:Bag>"
+ + "\n <rdf:li>f2a</rdf:li>"
+ + "\n <rdf:li>f2b</rdf:li>"
+ + "\n </rdf:Bag>"
+ + "\n </a:f2>"
+ + "\n <a:f3>"
+ + "\n <rdf:Bag>"
+ + "\n <rdf:li>1</rdf:li>"
+ + "\n <rdf:li>2</rdf:li>"
+ + "\n </rdf:Bag>"
+ + "\n </a:f3>"
+ + "\n <j:root>true</j:root>"
+ + "\n </rdf:Description>"
+ + "\n</rdf:RDF>";
+ rdfXml = s.serialize(a);
+ assertXmlEquals(expected, rdfXml);
+
+ a2 = p.parse(rdfXml, A.class);
+ assertEqualObjects(a, a2);
+
+ //--------------------------------------------------------------------------------
+ // List
+ //--------------------------------------------------------------------------------
+ s.setProperty(RDF_collectionFormat, RdfCollectionFormat.LIST);
+ expected =
+ "<rdf:RDF a='http://ns/' j='http://www.ibm.com/juneau/' jp='http://www.ibm.com/juneaubp/' rdf='http://www.w3.org/1999/02/22-rdf-syntax-ns#'>"
+ + "\n <rdf:Description about='http://test/a'>"
+ + "\n <a:f2 parseType='Resource'>"
+ + "\n <rdf:first>f2a</rdf:first>"
+ + "\n <rdf:rest parseType='Resource'>"
+ + "\n <rdf:first>f2b</rdf:first>"
+ + "\n <rdf:rest resource='http://www.w3.org/1999/02/22-rdf-syntax-ns#nil'/>"
+ + "\n </rdf:rest>"
+ + "\n </a:f2>"
+ + "\n <a:f3 parseType='Resource'>"
+ + "\n <rdf:first>1</rdf:first>"
+ + "\n <rdf:rest parseType='Resource'>"
+ + "\n <rdf:first>2</rdf:first>"
+ + "\n <rdf:rest resource='http://www.w3.org/1999/02/22-rdf-syntax-ns#nil'/>"
+ + "\n </rdf:rest>"
+ + "\n </a:f3>"
+ + "\n <j:root>true</j:root>"
+ + "\n </rdf:Description>"
+ + "\n</rdf:RDF>";
+ rdfXml = s.serialize(a);
+ assertXmlEquals(expected, rdfXml);
+
+ a2 = p.parse(rdfXml, A.class);
+ assertEqualObjects(a, a2);
+
+ //--------------------------------------------------------------------------------
+ // Multi-properties
+ //--------------------------------------------------------------------------------
+ s.setProperty(RDF_collectionFormat, RdfCollectionFormat.MULTI_VALUED);
+ expected =
+ "<rdf:RDF a='http://ns/' j='http://www.ibm.com/juneau/' jp='http://www.ibm.com/juneaubp/' rdf='http://www.w3.org/1999/02/22-rdf-syntax-ns#'>"
+ + "\n <rdf:Description about='http://test/a'>"
+ + "\n <a:f2>f2a</a:f2>"
+ + "\n <a:f2>f2b</a:f2>"
+ + "\n <a:f3>1</a:f3>"
+ + "\n <a:f3>2</a:f3>"
+ + "\n <j:root>true</j:root>"
+ + "\n </rdf:Description>"
+ + "\n</rdf:RDF>";
+ rdfXml = s.serialize(a);
+ assertXmlEquals(expected, rdfXml);
+
+ // Note - Must specify collection format on parser for it to be able to understand this layout.
+ p.setProperty(RDF_collectionFormat, RdfCollectionFormat.MULTI_VALUED);
+ a2 = p.parse(rdfXml, A.class);
+ assertEqualObjects(a, a2);
+ }
+
+ @Rdf(prefix="a", namespace="http://ns/")
+ public static class A {
+ @BeanProperty(beanUri=true) public URI f1;
+ public String[] f2;
+ public List<Integer> f3;
+
+ public A init() throws Exception {
+ f1 = new URI("http://test/a");
+ f2 = new String[]{"f2a","f2b"};
+ f3 = Arrays.asList(new Integer[]{1,2});
+ return this;
+ }
+ }
+
+ @Test
+ public void testCollectionFormatAnnotations() throws Exception {
+ B b = new B().init(), b2;
+ String rdfXml, expected;
+ RdfSerializer s = new RdfSerializer.XmlAbbrev()
+ .setProperty(RDF_rdfxml_tab, 3)
+ .setProperty(SERIALIZER_quoteChar, '\'')
+ .setProperty(RDF_addRootProperty, true);
+ RdfParser p = RdfParser.DEFAULT_XML.clone();
+
+ //--------------------------------------------------------------------------------
+ // Normal format - Sequence
+ //--------------------------------------------------------------------------------
+
+ expected =
+ "<rdf:RDF b='http://ns/' j='http://www.ibm.com/juneau/' jp='http://www.ibm.com/juneaubp/' rdf='http://www.w3.org/1999/02/22-rdf-syntax-ns#'>"
+ + "\n <rdf:Description about='http://test/b'>"
+ + "\n <b:f2>"
+ + "\n <rdf:Seq>"
+ + "\n <rdf:li>f2a</rdf:li>"
+ + "\n <rdf:li>f2b</rdf:li>"
+ + "\n </rdf:Seq>"
+ + "\n </b:f2>"
+ + "\n <b:f3>"
+ + "\n <rdf:Bag>"
+ + "\n <rdf:li>f3a</rdf:li>"
+ + "\n <rdf:li>f3b</rdf:li>"
+ + "\n </rdf:Bag>"
+ + "\n </b:f3>"
+ + "\n <b:f4 parseType='Resource'>"
+ + "\n <rdf:first>f4a</rdf:first>"
+ + "\n <rdf:rest parseType='Resource'>"
+ + "\n <rdf:first>f4b</rdf:first>"
+ + "\n <rdf:rest resource='http://www.w3.org/1999/02/22-rdf-syntax-ns#nil'/>"
+ + "\n </rdf:rest>"
+ + "\n </b:f4>"
+ + "\n <b:f5>f5a</b:f5>"
+ + "\n <b:f5>f5b</b:f5>"
+ + "\n <b:f6>"
+ + "\n <rdf:Seq>"
+ + "\n <rdf:li>f6a</rdf:li>"
+ + "\n <rdf:li>f6b</rdf:li>"
+ + "\n </rdf:Seq>"
+ + "\n </b:f6>"
+ + "\n <b:f7>"
+ + "\n <rdf:Seq>"
+ + "\n <rdf:li>f7a</rdf:li>"
+ + "\n <rdf:li>f7b</rdf:li>"
+ + "\n </rdf:Seq>"
+ + "\n </b:f7>"
+ + "\n <b:f8>"
+ + "\n <rdf:Bag>"
+ + "\n <rdf:li>f8a</rdf:li>"
+ + "\n <rdf:li>f8b</rdf:li>"
+ + "\n </rdf:Bag>"
+ + "\n </b:f8>"
+ + "\n <b:f9 parseType='Resource'>"
+ + "\n <rdf:first>f9a</rdf:first>"
+ + "\n <rdf:rest parseType='Resource'>"
+ + "\n <rdf:first>f9b</rdf:first>"
+ + "\n <rdf:rest resource='http://www.w3.org/1999/02/22-rdf-syntax-ns#nil'/>"
+ + "\n </rdf:rest>"
+ + "\n </b:f9>"
+ + "\n <b:fa>faa</b:fa>"
+ + "\n <b:fa>fab</b:fa>"
+ + "\n <b:fb>"
+ + "\n <rdf:Seq>"
+ + "\n <rdf:li>fba</rdf:li>"
+ + "\n <rdf:li>fbb</rdf:li>"
+ + "\n </rdf:Seq>"
+ + "\n </b:fb>"
+ + "\n <j:root>true</j:root>"
+ + "\n </rdf:Description>"
+ + "\n</rdf:RDF>";
+ rdfXml = s.serialize(b);
+ assertXmlEquals(expected, rdfXml);
+
+ b2 = p.parse(rdfXml, B.class);
+ assertEqualObjects(b, b2, true);
+
+ //--------------------------------------------------------------------------------
+ // Default is Bag - Should only affect DEFAULT properties.
+ //--------------------------------------------------------------------------------
+ s.setProperty(RDF_collectionFormat, RdfCollectionFormat.BAG);
+ expected =
+ "<rdf:RDF b='http://ns/' j='http://www.ibm.com/juneau/' jp='http://www.ibm.com/juneaubp/' rdf='http://www.w3.org/1999/02/22-rdf-syntax-ns#'>"
+ + "\n <rdf:Description about='http://test/b'>"
+ + "\n <b:f2>"
+ + "\n <rdf:Seq>"
+ + "\n <rdf:li>f2a</rdf:li>"
+ + "\n <rdf:li>f2b</rdf:li>"
+ + "\n </rdf:Seq>"
+ + "\n </b:f2>"
+ + "\n <b:f3>"
+ + "\n <rdf:Bag>"
+ + "\n <rdf:li>f3a</rdf:li>"
+ + "\n <rdf:li>f3b</rdf:li>"
+ + "\n </rdf:Bag>"
+ + "\n </b:f3>"
+ + "\n <b:f4 parseType='Resource'>"
+ + "\n <rdf:first>f4a</rdf:first>"
+ + "\n <rdf:rest parseType='Resource'>"
+ + "\n <rdf:first>f4b</rdf:first>"
+ + "\n <rdf:rest resource='http://www.w3.org/1999/02/22-rdf-syntax-ns#nil'/>"
+ + "\n </rdf:rest>"
+ + "\n </b:f4>"
+ + "\n <b:f5>f5a</b:f5>"
+ + "\n <b:f5>f5b</b:f5>"
+ + "\n <b:f6>"
+ + "\n <rdf:Bag>"
+ + "\n <rdf:li>f6a</rdf:li>"
+ + "\n <rdf:li>f6b</rdf:li>"
+ + "\n </rdf:Bag>"
+ + "\n </b:f6>"
+ + "\n <b:f7>"
+ + "\n <rdf:Seq>"
+ + "\n <rdf:li>f7a</rdf:li>"
+ + "\n <rdf:li>f7b</rdf:li>"
+ + "\n </rdf:Seq>"
+ + "\n </b:f7>"
+ + "\n <b:f8>"
+ + "\n <rdf:Bag>"
+ + "\n <rdf:li>f8a</rdf:li>"
+ + "\n <rdf:li>f8b</rdf:li>"
+ + "\n </rdf:Bag>"
+ + "\n </b:f8>"
+ + "\n <b:f9 parseType='Resource'>"
+ + "\n <rdf:first>f9a</rdf:first>"
+ + "\n <rdf:rest parseType='Resource'>"
+ + "\n <rdf:first>f9b</rdf:first>"
+ + "\n <rdf:rest resource='http://www.w3.org/1999/02/22-rdf-syntax-ns#nil'/>"
+ + "\n </rdf:rest>"
+ + "\n </b:f9>"
+ + "\n <b:fa>faa</b:fa>"
+ + "\n <b:fa>fab</b:fa>"
+ + "\n <b:fb>"
+ + "\n <rdf:Bag>"
+ + "\n <rdf:li>fba</rdf:li>"
+ + "\n <rdf:li>fbb</rdf:li>"
+ + "\n </rdf:Bag>"
+ + "\n </b:fb>"
+ + "\n <j:root>true</j:root>"
+ + "\n </rdf:Description>"
+ + "\n</rdf:RDF>";
+
+ rdfXml = s.serialize(b);
+ assertXmlEquals(expected, rdfXml);
+
+ b2 = p.parse(rdfXml, B.class);
+ assertEqualObjects(b, b2, true);
+ }
+
+ @Rdf(prefix="b", namespace="http://ns/")
+ public static class B {
+ @BeanProperty(beanUri=true) public URI f1;
+
+ @Rdf(collectionFormat=RdfCollectionFormat.SEQ)
+ public String[] f2;
+
+ @Rdf(collectionFormat=RdfCollectionFormat.BAG)
+ public String[] f3;
+
+ @Rdf(collectionFormat=RdfCollectionFormat.LIST)
+ public String[] f4;
+
+ @Rdf(collectionFormat=RdfCollectionFormat.MULTI_VALUED)
+ public String[] f5;
+
+ @Rdf(collectionFormat=RdfCollectionFormat.DEFAULT)
+ public String[] f6;
+
+ public BA f7;
+ public BB f8;
+ public BC f9;
+ public BD fa;
+ public BE fb;
+
+ public B init() throws Exception {
+ f1 = new URI("http://test/b");
+ f2 = new String[]{"f2a","f2b"};
+ f3 = new String[]{"f3a","f3b"};
+ f4 = new String[]{"f4a","f4b"};
+ f5 = new String[]{"f5a","f5b"};
+ f6 = new String[]{"f6a","f6b"};
+ f7 = new BA().append("f7a","f7b");
+ f8 = new BB().append("f8a","f8b");
+ f9 = new BC().append("f9a","f9b");
+ fa = new BD().append("faa","fab");
+ fb = new BE().append("fba","fbb");
+ return this;
+ }
+ }
+
+ @Rdf(prefix="ba", namespace="http://ns/", collectionFormat=RdfCollectionFormat.SEQ)
+ public static class BA extends ArrayList<String> {
+ public BA append(String...s) {
+ this.addAll(Arrays.asList(s));
+ return this;
+ }
+ }
+
+ @Rdf(prefix="bb", namespace="http://ns/", collectionFormat=RdfCollectionFormat.BAG)
+ public static class BB extends ArrayList<String> {
+ public BB append(String...s) {
+ this.addAll(Arrays.asList(s));
+ return this;
+ }
+ }
+
+ @Rdf(prefix="bc", namespace="http://ns/", collectionFormat=RdfCollectionFormat.LIST)
+ public static class BC extends ArrayList<String> {
+ public BC append(String...s) {
+ this.addAll(Arrays.asList(s));
+ return this;
+ }
+ }
+
+ @Rdf(prefix="bd", namespace="http://ns/", collectionFormat=RdfCollectionFormat.MULTI_VALUED)
+ public static class BD extends ArrayList<String> {
+ public BD append(String...s) {
+ this.addAll(Arrays.asList(s));
+ return this;
+ }
+ }
+
+ @Rdf(prefix="bd", namespace="http://ns/", collectionFormat=RdfCollectionFormat.DEFAULT)
+ public static class BE extends ArrayList<String> {
+ public BE append(String...s) {
+ this.addAll(Arrays.asList(s));
+ return this;
+ }
+ }
+
+ @Test
+ public void testCollectionFormatAnnotationOnClass() throws Exception {
+ C c = new C().init(), c2;
+ String rdfXml, expected;
+ RdfSerializer s = new RdfSerializer.XmlAbbrev()
+ .setProperty(RDF_rdfxml_tab, 3)
+ .setProperty(SERIALIZER_quoteChar, '\'')
+ .setProperty(RDF_addRootProperty, true);
+ RdfParser p = RdfParser.DEFAULT_XML.clone();
+
+ //--------------------------------------------------------------------------------
+ // Default on class is Bag - Should only affect DEFAULT properties.
+ //--------------------------------------------------------------------------------
+ s.setProperty(RDF_collectionFormat, RdfCollectionFormat.BAG);
+ expected =
+ "<rdf:RDF b='http://ns/' j='http://www.ibm.com/juneau/' jp='http://www.ibm.com/juneaubp/' rdf='http://www.w3.org/1999/02/22-rdf-syntax-ns#'>"
+ + "\n <rdf:Description about='http://test/b'>"
+ + "\n <b:f2>"
+ + "\n <rdf:Seq>"
+ + "\n <rdf:li>f2a</rdf:li>"
+ + "\n <rdf:li>f2b</rdf:li>"
+ + "\n </rdf:Seq>"
+ + "\n </b:f2>"
+ + "\n <b:f3>"
+ + "\n <rdf:Bag>"
+ + "\n <rdf:li>f3a</rdf:li>"
+ + "\n <rdf:li>f3b</rdf:li>"
+ + "\n </rdf:Bag>"
+ + "\n </b:f3>"
+ + "\n <b:f4 parseType='Resource'>"
+ + "\n <rdf:first>f4a</rdf:first>"
+ + "\n <rdf:rest parseType='Resource'>"
+ + "\n <rdf:first>f4b</rdf:first>"
+ + "\n <rdf:rest resource='http://www.w3.org/1999/02/22-rdf-syntax-ns#nil'/>"
+ + "\n </rdf:rest>"
+ + "\n </b:f4>"
+ + "\n <b:f5>f5a</b:f5>"
+ + "\n <b:f5>f5b</b:f5>"
+ + "\n <b:f6>"
+ + "\n <rdf:Bag>"
+ + "\n <rdf:li>f6a</rdf:li>"
+ + "\n <rdf:li>f6b</rdf:li>"
+ + "\n </rdf:Bag>"
+ + "\n </b:f6>"
+ + "\n <b:f7>"
+ + "\n <rdf:Seq>"
+ + "\n <rdf:li>f7a</rdf:li>"
+ + "\n <rdf:li>f7b</rdf:li>"
+ + "\n </rdf:Seq>"
+ + "\n </b:f7>"
+ + "\n <b:f8>"
+ + "\n <rdf:Bag>"
+ + "\n <rdf:li>f8a</rdf:li>"
+ + "\n <rdf:li>f8b</rdf:li>"
+ + "\n </rdf:Bag>"
+ + "\n </b:f8>"
+ + "\n <b:f9 parseType='Resource'>"
+ + "\n <rdf:first>f9a</rdf:first>"
+ + "\n <rdf:rest parseType='Resource'>"
+ + "\n <rdf:first>f9b</rdf:first>"
+ + "\n <rdf:rest resource='http://www.w3.org/1999/02/22-rdf-syntax-ns#nil'/>"
+ + "\n </rdf:rest>"
+ + "\n </b:f9>"
+ + "\n <b:fa>faa</b:fa>"
+ + "\n <b:fa>fab</b:fa>"
+ + "\n <b:fb>"
+ + "\n <rdf:Bag>"
+ + "\n <rdf:li>fba</rdf:li>"
+ + "\n <rdf:li>fbb</rdf:li>"
+ + "\n </rdf:Bag>"
+ + "\n </b:fb>"
+ + "\n <j:root>true</j:root>"
+ + "\n </rdf:Description>"
+ + "\n</rdf:RDF>";
+
+ rdfXml = s.serialize(c);
+ assertXmlEquals(expected, rdfXml);
+
+ c2 = p.parse(rdfXml, C.class);
+ assertEqualObjects(c, c2, true);
+ }
+
+ @Rdf(collectionFormat=RdfCollectionFormat.BAG)
+ public static class C extends B {
+ @Override /* B */
+ public C init() throws Exception {
+ f1 = new URI("http://test/b");
+ f2 = new String[]{"f2a","f2b"};
+ f3 = new String[]{"f3a","f3b"};
+ f4 = new String[]{"f4a","f4b"};
+ f5 = new String[]{"f5a","f5b"};
+ f6 = new String[]{"f6a","f6b"};
+ f7 = new BA().append("f7a","f7b");
+ f8 = new BB().append("f8a","f8b");
+ f9 = new BC().append("f9a","f9b");
+ fa = new BD().append("faa","fab");
+ fb = new BE().append("fba","fbb");
+ return this;
+ }
+ }
+
+ @Test
+ @SuppressWarnings("unchecked")
+ public void testLooseCollectionsOfBeans() throws Exception {
+ WriterSerializer s = new RdfSerializer.XmlAbbrev().setProperty(RDF_looseCollection, true);
+ ReaderParser p = new RdfParser.Xml().setProperty(RDF_looseCollection, true);
+ String rdfXml, expected;
+
+ List<D> l = new LinkedList<D>();
+ l.add(new D().init(1));
+ l.add(new D().init(2));
+
+ rdfXml = s.serialize(l);
+ expected =
+ "<rdf:RDF j='http://www.ibm.com/juneau/' jp='http://www.ibm.com/juneaubp/' rdf='http://www.w3.org/1999/02/22-rdf-syntax-ns#'>"
+ + "\n <rdf:Description about='http://localhost/f1/2'>"
+ + "\n <jp:f2>f2</jp:f2>"
+ + "\n <jp:f3 resource='http://localhost/f3/2'/>"
+ + "\n </rdf:Description>"
+ + "\n <rdf:Description about='http://localhost/f1/1'>"
+ + "\n <jp:f2>f2</jp:f2>"
+ + "\n <jp:f3 resource='http://localhost/f3/1'/>"
+ + "\n </rdf:Description>"
+ + "\n</rdf:RDF>";
+ assertXmlEquals(expected, rdfXml);
+
+ l = p.parseCollection(rdfXml, LinkedList.class, D.class);
+ D[] da = l.toArray(new D[l.size()]);
+ rdfXml = s.serialize(da);
+ expected =
+ "<rdf:RDF j='http://www.ibm.com/juneau/' jp='http://www.ibm.com/juneaubp/' rdf='http://www.w3.org/1999/02/22-rdf-syntax-ns#'>"
+ + "\n <rdf:Description about='http://localhost/f1/2'>"
+ + "\n <jp:f2>f2</jp:f2>"
+ + "\n <jp:f3 resource='http://localhost/f3/2'/>"
+ + "\n </rdf:Description>"
+ + "\n <rdf:Description about='http://localhost/f1/1'>"
+ + "\n <jp:f2>f2</jp:f2>"
+ + "\n <jp:f3 resource='http://localhost/f3/1'/>"
+ + "\n </rdf:Description>"
+ + "\n</rdf:RDF>";
+ assertXmlEquals(expected, rdfXml);
+
+ da = p.parse(rdfXml, D[].class);
+ rdfXml = s.serialize(da);
+ expected =
+ "<rdf:RDF j='http://www.ibm.com/juneau/' jp='http://www.ibm.com/juneaubp/' rdf='http://www.w3.org/1999/02/22-rdf-syntax-ns#'>"
+ + "\n <rdf:Description about='http://localhost/f1/2'>"
+ + "\n <jp:f2>f2</jp:f2>"
+ + "\n <jp:f3 resource='http://localhost/f3/2'/>"
+ + "\n </rdf:Description>"
+ + "\n <rdf:Description about='http://localhost/f1/1'>"
+ + "\n <jp:f2>f2</jp:f2>"
+ + "\n <jp:f3 resource='http://localhost/f3/1'/>"
+ + "\n </rdf:Description>"
+ + "\n</rdf:RDF>";
+ assertXmlEquals(expected, rdfXml);
+ }
+
+ public static class D {
+ @BeanProperty(beanUri=true) public URI f1;
+ public String f2;
+ public URI f3;
+
+ public D init(int num) throws Exception {
+ f1 = new URI("http://localhost/f1/" + num);
+ f2 = "f2";
+ f3 = new URI("http://localhost/f3/" + num);
+ return this;
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/json/CT_Common.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/json/CT_Common.java b/org.apache.juneau/src/test/java/org/apache/juneau/json/CT_Common.java
deleted file mode 100755
index 57281e8..0000000
--- a/org.apache.juneau/src/test/java/org/apache/juneau/json/CT_Common.java
+++ /dev/null
@@ -1,501 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.json;
-
-import static org.apache.juneau.BeanContext.*;
-import static org.apache.juneau.TestUtils.*;
-import static org.apache.juneau.serializer.SerializerContext.*;
-import static org.junit.Assert.*;
-
-import java.net.*;
-import java.net.URI;
-import java.util.*;
-
-import org.apache.juneau.*;
-import org.apache.juneau.annotation.*;
-import org.apache.juneau.serializer.*;
-import org.apache.juneau.testbeans.*;
-import org.junit.*;
-
-@SuppressWarnings({"serial"})
-public class CT_Common {
-
- //====================================================================================================
- // Trim nulls from beans
- //====================================================================================================
- @Test
- public void testTrimNullsFromBeans() throws Exception {
- JsonSerializer s = new JsonSerializer.Simple();
- JsonParser p = JsonParser.DEFAULT;
- A t1 = A.create(), t2;
-
- s.setProperty(SERIALIZER_trimNullProperties, false);
- String r = s.serialize(t1);
- assertEquals("{s1:null,s2:'s2'}", r);
- t2 = p.parse(r, A.class);
- assertEqualObjects(t1, t2);
-
- s.setProperty(SERIALIZER_trimNullProperties, true);
- r = s.serialize(t1);
- assertEquals("{s2:'s2'}", r);
- t2 = p.parse(r, A.class);
- assertEqualObjects(t1, t2);
- }
-
- public static class A {
- public String s1, s2;
-
- public static A create() {
- A t = new A();
- t.s2 = "s2";
- return t;
- }
- }
-
- //====================================================================================================
- // Trim empty maps
- //====================================================================================================
- @Test
- public void testTrimEmptyMaps() throws Exception {
- JsonSerializer s = new JsonSerializer.Simple();
- JsonParser p = JsonParser.DEFAULT;
- B t1 = B.create(), t2;
- String r;
-
- s.setProperty(SERIALIZER_trimEmptyMaps, false);
- r = s.serialize(t1);
- assertEquals("{f1:{},f2:{f2a:null,f2b:{s2:'s2'}}}", r);
- t2 = p.parse(r, B.class);
- assertEqualObjects(t1, t2);
-
- s.setProperty(SERIALIZER_trimEmptyMaps, true);
- r = s.serialize(t1);
- assertEquals("{f2:{f2a:null,f2b:{s2:'s2'}}}", r);
- t2 = p.parse(r, B.class);
- assertNull(t2.f1);
- }
-
- public static class B {
- public TreeMap<String,A> f1, f2;
-
- public static B create() {
- B t = new B();
- t.f1 = new TreeMap<String,A>();
- t.f2 = new TreeMap<String,A>(){{put("f2a",null);put("f2b",A.create());}};
- return t;
- }
- }
-
- //====================================================================================================
- // Trim empty lists
- //====================================================================================================
- @Test
- public void testTrimEmptyLists() throws Exception {
- JsonSerializer s = new JsonSerializer.Simple();
- JsonParser p = JsonParser.DEFAULT;
- C t1 = C.create(), t2;
- String r;
-
- s.setProperty(SERIALIZER_trimEmptyLists, false);
- r = s.serialize(t1);
- assertEquals("{f1:[],f2:[null,{s2:'s2'}]}", r);
- t2 = p.parse(r, C.class);
- assertEqualObjects(t1, t2);
-
- s.setProperty(SERIALIZER_trimEmptyLists, true);
- r = s.serialize(t1);
- assertEquals("{f2:[null,{s2:'s2'}]}", r);
- t2 = p.parse(r, C.class);
- assertNull(t2.f1);
- }
-
- public static class C {
- public List<A> f1, f2;
-
- public static C create() {
- C t = new C();
- t.f1 = new LinkedList<A>();
- t.f2 = new LinkedList<A>(){{add(null);add(A.create());}};
- return t;
- }
- }
-
- //====================================================================================================
- // Trim empty arrays
- //====================================================================================================
- @Test
- public void testTrimEmptyArrays() throws Exception {
- JsonSerializer s = new JsonSerializer.Simple();
- JsonParser p = JsonParser.DEFAULT;
- D t1 = D.create(), t2;
- String r;
-
- s.setProperty(SERIALIZER_trimEmptyLists, false);
- r = s.serialize(t1);
- assertEquals("{f1:[],f2:[null,{s2:'s2'}]}", r);
- t2 = p.parse(r, D.class);
- assertEqualObjects(t1, t2);
-
- s.setProperty(SERIALIZER_trimEmptyLists, true);
- r = s.serialize(t1);
- assertEquals("{f2:[null,{s2:'s2'}]}", r);
- t2 = p.parse(r, D.class);
- assertNull(t2.f1);
- }
-
- public static class D {
- public A[] f1, f2;
-
- public static D create() {
- D t = new D();
- t.f1 = new A[]{};
- t.f2 = new A[]{null, A.create()};
- return t;
- }
- }
-
- //====================================================================================================
- // @BeanProperty.properties annotation.
- //====================================================================================================
- @Test
- public void testBeanPropertyProperies() throws Exception {
- JsonSerializer s = JsonSerializer.DEFAULT_LAX;
- E1 t = new E1();
- String r;
-
- r = s.serialize(t);
- assertEquals("{x1:{f1:1},x2:{f1:1},x3:[{f1:1}],x4:[{f1:1}],x5:[{f1:1}],x6:[{f1:1}]}", r);
- r = s.getSchemaSerializer().serialize(t);
- assertTrue(r.indexOf("f2") == -1);
- }
-
- public static class E1 {
- @BeanProperty(properties={"f1"}) public E2 x1 = new E2();
- @BeanProperty(properties={"f1"}) public Map<String,Integer> x2 = new LinkedHashMap<String,Integer>() {{
- put("f1",1); put("f2",2);
- }};
- @BeanProperty(properties={"f1"}) public E2[] x3 = {new E2()};
- @BeanProperty(properties={"f1"}) public List<E2> x4 = new LinkedList<E2>() {{
- add(new E2());
- }};
- @BeanProperty(properties={"f1"}) public ObjectMap[] x5 = {new ObjectMap().append("f1",1).append("f2",2)};
- @BeanProperty(properties={"f1"}) public List<ObjectMap> x6 = new LinkedList<ObjectMap>() {{
- add(new ObjectMap().append("f1",1).append("f2",2));
- }};
- }
-
- public static class E2 {
- public int f1 = 1;
- public int f2 = 2;
- }
-
- //====================================================================================================
- // @BeanProperty.properties annotation on list of beans.
- //====================================================================================================
- @Test
- public void testBeanPropertyProperiesOnListOfBeans() throws Exception {
- JsonSerializer s = JsonSerializer.DEFAULT_LAX;
- List<F> l = new LinkedList<F>();
- F t = new F();
- t.x1.add(new F());
- l.add(t);
- String json = s.serialize(l);
- assertEquals("[{x1:[{x2:2}],x2:2}]", json);
- }
-
- public static class F {
- @BeanProperty(properties={"x2"}) public List<F> x1 = new LinkedList<F>();
- public int x2 = 2;
- }
-
- //====================================================================================================
- // Test that URLs and URIs are serialized and parsed correctly.
- //====================================================================================================
- @Test
- public void testURIAttr() throws Exception {
- JsonSerializer s = JsonSerializer.DEFAULT_LAX;
- JsonParser p = JsonParser.DEFAULT;
-
- G t = new G();
- t.uri = new URI("http://uri");
- t.f1 = new URI("http://f1");
- t.f2 = new URL("http://f2");
-
- String json = s.serialize(t);
- t = p.parse(json, G.class);
- assertEquals("http://uri", t.uri.toString());
- assertEquals("http://f1", t.f1.toString());
- assertEquals("http://f2", t.f2.toString());
- }
-
- public static class G {
- @BeanProperty(beanUri=true) public URI uri;
- public URI f1;
- public URL f2;
- }
-
- //====================================================================================================
- // Test URIs with URI_CONTEXT and URI_AUTHORITY
- //====================================================================================================
- @Test
- public void testUris() throws Exception {
- WriterSerializer s = new JsonSerializer.Simple();
- TestURI t = new TestURI();
- String r;
- String expected = "";
-
- s.setProperty(SERIALIZER_relativeUriBase, null);
- r = s.serialize(t);
- expected = "{"
- +"f0:'f0/x0',"
- +"f1:'f1/x1',"
- +"f2:'/f2/x2',"
- +"f3:'http://www.ibm.com/f3/x3',"
- +"f4:'f4/x4',"
- +"f5:'/f5/x5',"
- +"f6:'http://www.ibm.com/f6/x6',"
- +"f7:'http://www.ibm.com/f7/x7',"
- +"f8:'f8/x8',"
- +"f9:'f9/x9',"
- +"fa:'http://www.ibm.com/fa/xa#MY_LABEL',"
- +"fb:'http://www.ibm.com/fb/xb?label=MY_LABEL&foo=bar',"
- +"fc:'http://www.ibm.com/fc/xc?foo=bar&label=MY_LABEL',"
- +"fd:'http://www.ibm.com/fd/xd?label2=MY_LABEL&foo=bar',"
- +"fe:'http://www.ibm.com/fe/xe?foo=bar&label2=MY_LABEL'"
- +"}";
- assertEquals(expected, r);
-
- s.setProperty(SERIALIZER_relativeUriBase, ""); // Same as null.
- r = s.serialize(t);
- assertEquals(expected, r);
-
- s.setProperty(SERIALIZER_relativeUriBase, "/cr");
- r = s.serialize(t);
- expected = "{"
- +"f0:'/cr/f0/x0',"
- +"f1:'/cr/f1/x1',"
- +"f2:'/f2/x2',"
- +"f3:'http://www.ibm.com/f3/x3',"
- +"f4:'/cr/f4/x4',"
- +"f5:'/f5/x5',"
- +"f6:'http://www.ibm.com/f6/x6',"
- +"f7:'http://www.ibm.com/f7/x7',"
- +"f8:'/cr/f8/x8',"
- +"f9:'/cr/f9/x9',"
- +"fa:'http://www.ibm.com/fa/xa#MY_LABEL',"
- +"fb:'http://www.ibm.com/fb/xb?label=MY_LABEL&foo=bar',"
- +"fc:'http://www.ibm.com/fc/xc?foo=bar&label=MY_LABEL',"
- +"fd:'http://www.ibm.com/fd/xd?label2=MY_LABEL&foo=bar',"
- +"fe:'http://www.ibm.com/fe/xe?foo=bar&label2=MY_LABEL'"
- +"}";
- assertEquals(expected, r);
-
- s.setProperty(SERIALIZER_relativeUriBase, "/cr/"); // Same as above
- r = s.serialize(t);
- assertEquals(expected, r);
-
- s.setProperty(SERIALIZER_relativeUriBase, "/");
- r = s.serialize(t);
- expected = "{"
- +"f0:'/f0/x0',"
- +"f1:'/f1/x1',"
- +"f2:'/f2/x2',"
- +"f3:'http://www.ibm.com/f3/x3',"
- +"f4:'/f4/x4',"
- +"f5:'/f5/x5',"
- +"f6:'http://www.ibm.com/f6/x6',"
- +"f7:'http://www.ibm.com/f7/x7',"
- +"f8:'/f8/x8',"
- +"f9:'/f9/x9',"
- +"fa:'http://www.ibm.com/fa/xa#MY_LABEL',"
- +"fb:'http://www.ibm.com/fb/xb?label=MY_LABEL&foo=bar',"
- +"fc:'http://www.ibm.com/fc/xc?foo=bar&label=MY_LABEL',"
- +"fd:'http://www.ibm.com/fd/xd?label2=MY_LABEL&foo=bar',"
- +"fe:'http://www.ibm.com/fe/xe?foo=bar&label2=MY_LABEL'"
- +"}";
- assertEquals(expected, r);
-
- s.setProperty(SERIALIZER_relativeUriBase, null);
-
- s.setProperty(SERIALIZER_absolutePathUriBase, "http://foo");
- r = s.serialize(t);
- expected = "{"
- +"f0:'f0/x0',"
- +"f1:'f1/x1',"
- +"f2:'http://foo/f2/x2',"
- +"f3:'http://www.ibm.com/f3/x3',"
- +"f4:'f4/x4',"
- +"f5:'http://foo/f5/x5',"
- +"f6:'http://www.ibm.com/f6/x6',"
- +"f7:'http://www.ibm.com/f7/x7',"
- +"f8:'f8/x8',"
- +"f9:'f9/x9',"
- +"fa:'http://www.ibm.com/fa/xa#MY_LABEL',"
- +"fb:'http://www.ibm.com/fb/xb?label=MY_LABEL&foo=bar',"
- +"fc:'http://www.ibm.com/fc/xc?foo=bar&label=MY_LABEL',"
- +"fd:'http://www.ibm.com/fd/xd?label2=MY_LABEL&foo=bar',"
- +"fe:'http://www.ibm.com/fe/xe?foo=bar&label2=MY_LABEL'"
- +"}";
- assertEquals(expected, r);
-
- s.setProperty(SERIALIZER_absolutePathUriBase, "http://foo/");
- r = s.serialize(t);
- assertEquals(expected, r);
-
- s.setProperty(SERIALIZER_absolutePathUriBase, ""); // Same as null.
- r = s.serialize(t);
- expected = "{"
- +"f0:'f0/x0',"
- +"f1:'f1/x1',"
- +"f2:'/f2/x2',"
- +"f3:'http://www.ibm.com/f3/x3',"
- +"f4:'f4/x4',"
- +"f5:'/f5/x5',"
- +"f6:'http://www.ibm.com/f6/x6',"
- +"f7:'http://www.ibm.com/f7/x7',"
- +"f8:'f8/x8',"
- +"f9:'f9/x9',"
- +"fa:'http://www.ibm.com/fa/xa#MY_LABEL',"
- +"fb:'http://www.ibm.com/fb/xb?label=MY_LABEL&foo=bar',"
- +"fc:'http://www.ibm.com/fc/xc?foo=bar&label=MY_LABEL',"
- +"fd:'http://www.ibm.com/fd/xd?label2=MY_LABEL&foo=bar',"
- +"fe:'http://www.ibm.com/fe/xe?foo=bar&label2=MY_LABEL'"
- +"}";
- assertEquals(expected, r);
- }
-
- //====================================================================================================
- // Validate that you cannot update properties on locked serializer.
- //====================================================================================================
- @Test
- public void testLockedSerializer() throws Exception {
- JsonSerializer s = new JsonSerializer().lock();
- try {
- s.setProperty(JsonSerializerContext.JSON_simpleMode, true);
- fail("Locked exception not thrown");
- } catch (LockedException e) {}
- try {
- s.setProperty(SerializerContext.SERIALIZER_addClassAttrs, true);
- fail("Locked exception not thrown");
- } catch (LockedException e) {}
- try {
- s.setProperty(BeanContext.BEAN_beanMapPutReturnsOldValue, true);
- fail("Locked exception not thrown");
- } catch (LockedException e) {}
- }
-
- //====================================================================================================
- // Recursion
- //====================================================================================================
- @Test
- public void testRecursion() throws Exception {
- JsonSerializer s = new JsonSerializer.Simple();
-
- R1 r1 = new R1();
- R2 r2 = new R2();
- R3 r3 = new R3();
- r1.r2 = r2;
- r2.r3 = r3;
- r3.r1 = r1;
-
- // No recursion detection
- try {
- s.serialize(r1);
- fail("Exception expected!");
- } catch (Exception e) {
- String msg = e.getLocalizedMessage();
- assertTrue(msg.contains("It's recommended you use the SerializerContext.SERIALIZER_detectRecursions setting to help locate the loop."));
- }
-
- // Recursion detection, no ignore
- s.setProperty(SERIALIZER_detectRecursions, true);
- try {
- s.serialize(r1);
- fail("Exception expected!");
- } catch (Exception e) {
- String msg = e.getLocalizedMessage();
- assertTrue(msg.contains("[0]root:org.apache.juneau.json.CT_Common$R1"));
- assertTrue(msg.contains("->[1]r2:org.apache.juneau.json.CT_Common$R2"));
- assertTrue(msg.contains("->[2]r3:org.apache.juneau.json.CT_Common$R3"));
- assertTrue(msg.contains("->[3]r1:org.apache.juneau.json.CT_Common$R1"));
- }
-
- s.setProperty(SERIALIZER_ignoreRecursions, true);
- assertEquals("{name:'foo',r2:{name:'bar',r3:{name:'baz'}}}", s.serialize(r1));
-
- // Make sure this doesn't blow up.
- s.getSchemaSerializer().serialize(r1);
- }
-
- public static class R1 {
- public String name = "foo";
- public R2 r2;
- }
- public static class R2 {
- public String name = "bar";
- public R3 r3;
- }
- public static class R3 {
- public String name = "baz";
- public R1 r1;
- }
-
- //====================================================================================================
- // Basic bean
- //====================================================================================================
- @Test
- public void testBasicBean() throws Exception {
- JsonSerializer s = new JsonSerializer.Simple().setProperty(SERIALIZER_trimNullProperties, false).setProperty(BEAN_sortProperties, true);
-
- J a = new J();
- a.setF1("J");
- a.setF2(100);
- a.setF3(true);
- assertEquals("C1", "{f1:'J',f2:100,f3:true}", s.serialize(a));
- }
-
- public static class J {
- private String f1 = null;
- private int f2 = -1;
- private boolean f3 = false;
-
- public String getF1() {
- return this.f1;
- }
-
- public void setF1(String f1) {
- this.f1 = f1;
- }
-
- public int getF2() {
- return this.f2;
- }
-
- public void setF2(int f2) {
- this.f2 = f2;
- }
-
- public boolean isF3() {
- return this.f3;
- }
-
- public void setF3(boolean f3) {
- this.f3 = f3;
- }
-
- @Override /* Object */
- public String toString() {
- return ("J(f1: " + this.getF1() + ", f2: " + this.getF2() + ")");
- }
- }
-}
[08/44] incubator-juneau git commit: Rename CT_* testcases.
Posted by ja...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/urlencoding/UrlEncodingParserTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/urlencoding/UrlEncodingParserTest.java b/org.apache.juneau/src/test/java/org/apache/juneau/urlencoding/UrlEncodingParserTest.java
new file mode 100755
index 0000000..b5dda1f
--- /dev/null
+++ b/org.apache.juneau/src/test/java/org/apache/juneau/urlencoding/UrlEncodingParserTest.java
@@ -0,0 +1,1000 @@
+/***************************************************************************************************************************
+ * 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.juneau.urlencoding;
+
+import static org.apache.juneau.TestUtils.*;
+import static org.junit.Assert.*;
+
+import java.util.*;
+
+import org.apache.juneau.*;
+import org.apache.juneau.parser.*;
+import org.junit.*;
+
+@SuppressWarnings({"rawtypes","unchecked","hiding"})
+public class UrlEncodingParserTest {
+
+ static UrlEncodingParser p = UrlEncodingParser.DEFAULT;
+
+ //====================================================================================================
+ // Basic test
+ //====================================================================================================
+ @Test
+ public void testBasic() throws Exception {
+
+ String t;
+ Map m;
+ List l;
+
+ // Simple string
+ // Top level
+ t = "_value=a";
+ assertEquals("a", p.parse(t, Object.class));
+ assertEquals("a", p.parse(t, String.class));
+ t = "_value=(a)";
+ assertEquals("a", p.parse(t, String.class));
+ assertEquals("a", p.parse(t, Object.class));
+ t = "_value=$s(a)";
+ assertEquals("a", p.parse(t, String.class));
+
+ t = "a";
+ assertEquals("a", p.parseParameter(t, Object.class));
+ assertEquals("a", p.parseParameter(t, String.class));
+ t = "(a)";
+ assertEquals("a", p.parseParameter(t, String.class));
+ assertEquals("a", p.parseParameter(t, Object.class));
+ t = "$s(a)";
+ assertEquals("a", p.parseParameter(t, String.class));
+
+ // 2nd level
+ t = "?a=a";
+ assertEquals("a", p.parse(t, Map.class).get("a"));
+
+ // Simple map
+ // Top level
+ t = "?a=b&c=$n(123)&d=$b(false)&e=$b(true)&f=%00";
+ m = p.parse(t, Map.class);
+ assertEquals("b", m.get("a"));
+ assertTrue(m.get("c") instanceof Number);
+ assertEquals(123, m.get("c"));
+ assertTrue(m.get("d") instanceof Boolean);
+ assertEquals(Boolean.FALSE, m.get("d"));
+ assertTrue(m.get("e") instanceof Boolean);
+ assertEquals(Boolean.TRUE, m.get("e"));
+ assertNull(m.get("f"));
+
+ t = "$o(a=b,c=$n(123),d=$b(false),e=$b(true),f=%00)";
+ m = p.parseParameter(t, Map.class);
+ assertEquals("b", m.get("a"));
+ assertTrue(m.get("c") instanceof Number);
+ assertEquals(123, m.get("c"));
+ assertTrue(m.get("d") instanceof Boolean);
+ assertEquals(Boolean.FALSE, m.get("d"));
+ assertTrue(m.get("e") instanceof Boolean);
+ assertEquals(Boolean.TRUE, m.get("e"));
+ assertEquals("%00", m.get("f"));
+
+ t = "$o(a=b,c=$n(123),d=$b(false),e=$b(true),f=\u0000)";
+ m = p.parseParameter(t, Map.class);
+ assertTrue(m.containsKey("f"));
+ assertNull(m.get("f"));
+
+ t = "?a=true";
+ m = p.parseMap(t, HashMap.class, String.class, Boolean.class);
+ assertTrue(m.get("a") instanceof Boolean);
+ assertEquals("true", m.get("a").toString());
+
+ // null
+ // Top level
+ t = "_value=%00";
+ assertNull(p.parse(t, Object.class));
+ t = "\u0000";
+ assertNull(p.parseParameter(t, Object.class));
+ t = "%00";
+ assertEquals("%00", p.parseParameter(t, Object.class));
+
+ // 2nd level
+ t = "?%00=%00";
+ m = p.parse(t, Map.class);
+ assertTrue(m.containsKey(null));
+ assertNull(m.get(null));
+
+ t = "?\u0000=\u0000";
+ m = p.parse(t, Map.class);
+ assertTrue(m.containsKey(null));
+ assertNull(m.get(null));
+
+ // 3rd level
+ t = "?%00=$o(%00=%00)";
+ m = p.parse(t, Map.class);
+ assertTrue(((Map)m.get(null)).containsKey(null));
+ assertNull(((Map)m.get(null)).get(null));
+
+ // Empty array
+ // Top level
+ t = "_value=$a()";
+ l = (List)p.parse(t, Object.class);
+ assertTrue(l.isEmpty());
+ t = "_value=()";
+ l = p.parse(t, List.class);
+ assertTrue(l.isEmpty());
+ t = "$a()";
+ l = (List)p.parseParameter(t, Object.class);
+ assertTrue(l.isEmpty());
+ t = "()";
+ l = p.parseParameter(t, List.class);
+ assertTrue(l.isEmpty());
+
+ // 2nd level in map
+ t = "?x=$a()";
+ m = p.parseMap(t, HashMap.class, String.class, List.class);
+ assertTrue(m.containsKey("x"));
+ assertTrue(((List)m.get("x")).isEmpty());
+ m = (Map)p.parse(t, Object.class);
+ assertTrue(m.containsKey("x"));
+ assertTrue(((List)m.get("x")).isEmpty());
+ t = "?x=()";
+ m = p.parseMap(t, HashMap.class, String.class, List.class);
+ assertTrue(m.containsKey("x"));
+ assertTrue(((List)m.get("x")).isEmpty());
+
+ // Empty 2 dimensional array
+ t = "_value=$a($a())";
+ l = (List)p.parse(t, Object.class);
+ assertTrue(l.size() == 1);
+ l = (List)l.get(0);
+ assertTrue(l.isEmpty());
+ t = "0=()";
+ l = p.parseCollection(t, LinkedList.class, List.class);
+ assertTrue(l.size() == 1);
+ l = (List)l.get(0);
+ assertTrue(l.isEmpty());
+ t = "$a($a())";
+ l = (List)p.parseParameter(t, Object.class);
+ assertTrue(l.size() == 1);
+ l = (List)l.get(0);
+ assertTrue(l.isEmpty());
+ t = "(())";
+ l = (List)p.parseParameter(t, p.getBeanContext().getCollectionClassMeta(LinkedList.class, List.class));
+ assertTrue(l.size() == 1);
+ l = (List)l.get(0);
+ assertTrue(l.isEmpty());
+
+ // Array containing empty string
+ // Top level
+ t = "_value=$a(())";
+ l = (List)p.parse(t, Object.class);
+ assertTrue(l.size() == 1);
+ assertEquals("", l.get(0));
+ t = "0=()";
+ l = p.parseCollection(t, List.class, String.class);
+ assertTrue(l.size() == 1);
+ assertEquals("", l.get(0));
+ t = "$a(())";
+ l = (List)p.parseParameter(t, Object.class);
+ assertTrue(l.size() == 1);
+ assertEquals("", l.get(0));
+ t = "(())";
+ l = (List)p.parseParameter(t, p.getBeanContext().getCollectionClassMeta(List.class, String.class));
+ assertTrue(l.size() == 1);
+ assertEquals("", l.get(0));
+
+ // 2nd level
+ t = "?()=$a(())";
+ m = (Map)p.parse(t, Object.class);
+ assertEquals("", ((List)m.get("")).get(0));
+ t = "?()=(())";
+ m = p.parseMap(t, HashMap.class, String.class, List.class);
+ assertEquals("", ((List)m.get("")).get(0));
+
+ // Array containing 3 empty strings
+ t = "_value=$a(,,)";
+ l = (List)p.parse(t, Object.class);
+ assertTrue(l.size() == 3);
+ assertEquals("", l.get(0));
+ assertEquals("", l.get(1));
+ assertEquals("", l.get(2));
+ t = "0=&1=&2=";
+ l = p.parseCollection(t, List.class, Object.class);
+ assertTrue(l.size() == 3);
+ assertEquals("", l.get(0));
+ assertEquals("", l.get(1));
+ assertEquals("", l.get(2));
+ t = "$a(,,)";
+ l = (List)p.parseParameter(t, Object.class);
+ assertTrue(l.size() == 3);
+ assertEquals("", l.get(0));
+ assertEquals("", l.get(1));
+ assertEquals("", l.get(2));
+ t = "(,,)";
+ l = (List)p.parseParameter(t, p.getBeanContext().getCollectionClassMeta(List.class, Object.class));
+ assertTrue(l.size() == 3);
+ assertEquals("", l.get(0));
+ assertEquals("", l.get(1));
+ assertEquals("", l.get(2));
+
+ // String containing \u0000
+ // Top level
+ t = "_value=$s(\u0000)";
+ assertEquals("\u0000", p.parse(t, Object.class));
+ t = "_value=(\u0000)";
+ assertEquals("\u0000", p.parse(t, String.class));
+ assertEquals("\u0000", p.parse(t, Object.class));
+ t = "$s(\u0000)";
+ assertEquals("\u0000", p.parseParameter(t, Object.class));
+ t = "(\u0000)";
+ assertEquals("\u0000", p.parseParameter(t, String.class));
+ assertEquals("\u0000", p.parseParameter(t, Object.class));
+
+ // 2nd level
+ t = "?(\u0000)=(\u0000)";
+ m = (Map)p.parse(t, Object.class);
+ assertTrue(m.size() == 1);
+ assertEquals("\u0000", m.get("\u0000"));
+ m = p.parseMap(t, HashMap.class, String.class, Object.class);
+ assertTrue(m.size() == 1);
+ assertEquals("\u0000", m.get("\u0000"));
+
+ // Boolean
+ // Top level
+ t = "_value=$b(false)";
+ Boolean b = (Boolean)p.parse(t, Object.class);
+ assertEquals(Boolean.FALSE, b);
+ b = p.parse(t, Boolean.class);
+ assertEquals(Boolean.FALSE, b);
+ t = "_value=false";
+ b = p.parse(t, Boolean.class);
+ assertEquals(Boolean.FALSE, b);
+ t = "$b(false)";
+ b = (Boolean)p.parseParameter(t, Object.class);
+ assertEquals(Boolean.FALSE, b);
+ b = p.parseParameter(t, Boolean.class);
+ assertEquals(Boolean.FALSE, b);
+ t = "false";
+ b = p.parseParameter(t, Boolean.class);
+ assertEquals(Boolean.FALSE, b);
+
+ // 2nd level
+ t = "?x=$b(false)";
+ m = (Map)p.parse(t, Object.class);
+ assertEquals(Boolean.FALSE, m.get("x"));
+ t = "?x=false";
+ m = p.parseMap(t, HashMap.class, String.class, Boolean.class);
+ assertEquals(Boolean.FALSE, m.get("x"));
+
+ // Number
+ // Top level
+ t = "_value=$n(123)";
+ Integer i = (Integer)p.parse(t, Object.class);
+ assertEquals(123, i.intValue());
+ i = p.parse(t, Integer.class);
+ assertEquals(123, i.intValue());
+ Double d = p.parse(t, Double.class);
+ assertEquals(123, d.intValue());
+ Float f = p.parse(t, Float.class);
+ assertEquals(123, f.intValue());
+ t = "_value=123";
+ i = p.parse(t, Integer.class);
+ assertEquals(123, i.intValue());
+ t = "$n(123)";
+ i = (Integer)p.parseParameter(t, Object.class);
+ assertEquals(123, i.intValue());
+ i = p.parseParameter(t, Integer.class);
+ assertEquals(123, i.intValue());
+ d = p.parseParameter(t, Double.class);
+ assertEquals(123, d.intValue());
+ f = p.parseParameter(t, Float.class);
+ assertEquals(123, f.intValue());
+ t = "123";
+ i = p.parseParameter(t, Integer.class);
+ assertEquals(123, i.intValue());
+
+ // 2nd level
+ t = "?x=$n(123)";
+ m = (Map)p.parse(t, Object.class);
+ assertEquals(123, ((Integer)m.get("x")).intValue());
+ m = p.parseMap(t, HashMap.class, String.class, Double.class);
+ assertEquals(123, ((Double)m.get("x")).intValue());
+
+ // Unencoded chars
+ // Top level
+ t = "_value=x;/?:@-_.!*'";
+ assertEquals("x;/?:@-_.!*'", p.parse(t, Object.class));
+ t = "x;/?:@-_.!*'";
+ assertEquals("x;/?:@-_.!*'", p.parseParameter(t, Object.class));
+
+ // 2nd level
+ t = "?x;/?:@-_.!*'=x;/?:@-_.!*'";
+ m = (Map)p.parse(t, Object.class);
+ assertEquals("x;/?:@-_.!*'", m.get("x;/?:@-_.!*'"));
+ m = p.parseMap(t, HashMap.class, String.class, Object.class);
+ assertEquals("x;/?:@-_.!*'", m.get("x;/?:@-_.!*'"));
+ m = p.parseMap(t, HashMap.class, String.class, String.class);
+ assertEquals("x;/?:@-_.!*'", m.get("x;/?:@-_.!*'"));
+
+ // Encoded chars
+ // Top level
+ t = "_value=x{}|\\^[]`<>#%\"&+";
+ try {
+ assertEquals("x{}|\\^[]`<>#%\"&+", p.parse(t, Object.class));
+ fail("Expected parse exception from invalid hex sequence.");
+ } catch (ParseException e) {
+ // Good.
+ }
+ t = "_value=x%7B%7D%7C%5C%5E%5B%5D%60%3C%3E%23%25%22%26%2B";
+ assertEquals("x{}|\\^[]`<>#%\"&+", p.parse(t, Object.class));
+ assertEquals("x{}|\\^[]`<>#%\"&+", p.parse(t, String.class));
+ t = "x{}|\\^[]`<>#%\"&+";
+ assertEquals("x{}|\\^[]`<>#%\"&+", p.parseParameter(t, Object.class));
+ t = "x%7B%7D%7C%5C%5E%5B%5D%60%3C%3E%23%25%22%26%2B";
+ assertEquals("x%7B%7D%7C%5C%5E%5B%5D%60%3C%3E%23%25%22%26%2B", p.parseParameter(t, Object.class));
+ assertEquals("x%7B%7D%7C%5C%5E%5B%5D%60%3C%3E%23%25%22%26%2B", p.parseParameter(t, String.class));
+
+ // 2nd level
+ t = "?x{}|\\^[]`<>#%\"&+=x{}|\\^[]`<>#%\"&+";
+ try {
+ m = (Map)p.parse(t, Object.class);
+ fail("Expected parse exception from invalid hex sequence.");
+ } catch (ParseException e) {
+ // Good.
+ }
+ t = "?x%7B%7D%7C%5C%5E%5B%5D%60%3C%3E%23%25%22%26%2B=x%7B%7D%7C%5C%5E%5B%5D%60%3C%3E%23%25%22%26%2B";
+ m = (Map)p.parse(t, Object.class);
+ assertEquals("x{}|\\^[]`<>#%\"&+", m.get("x{}|\\^[]`<>#%\"&+"));
+
+ // Special chars
+ // These characters are escaped and not encoded.
+ // Top level
+ t = "_value=x~$~,~(~)";
+ assertEquals("x$,()", p.parse(t, Object.class));
+ t = "x~$~,~(~)";
+ assertEquals("x$,()", p.parseParameter(t, Object.class));
+ t = "_value=x~~$~~,~~(~~)";
+ assertEquals("x~$~,~(~)", p.parse(t, Object.class));
+ t = "x~~$~~,~~(~~)";
+ assertEquals("x~$~,~(~)", p.parseParameter(t, Object.class));
+
+ // At secondary levels, these characters are escaped and not encoded.
+ // 2nd level
+ t = "?x~$~,~(~)=x~$~,~(~)";
+ m = (Map)p.parse(t, Object.class);
+ assertEquals("x$,()", m.get("x$,()"));
+ t = "?x~~$~~,~~(~~)=x~~$~~,~~(~~)";
+ m = (Map)p.parse(t, Object.class);
+ assertEquals("x~$~,~(~)", m.get("x~$~,~(~)"));
+
+ // Equals sign
+ // Gets encoded at top level, and encoded+escaped at 2nd level.
+ // Top level
+ t = "_value=x=";
+ assertEquals("x=", p.parse(t, Object.class));
+ t = "_value=x%3D";
+ assertEquals("x=", p.parse(t, Object.class));
+ t = "x=";
+ assertEquals("x=", p.parseParameter(t, Object.class));
+ t = "x%3D";
+ assertEquals("x%3D", p.parseParameter(t, Object.class));
+
+ // 2nd level
+ t = "?x~%3D=x~%3D";
+ m = (Map)p.parse(t, Object.class);
+ assertEquals("x=", m.get("x="));
+ t = "?x~~%3D=x~~%3D";
+ m = (Map)p.parse(t, Object.class);
+ assertEquals("x~=", m.get("x~="));
+
+ // String starting with parenthesis
+ // Top level
+ t = "_value=~(~)";
+ assertEquals("()", p.parse(t, Object.class));
+ assertEquals("()", p.parse(t, String.class));
+ t = "_value=(~(~))";
+ assertEquals("()", p.parse(t, Object.class));
+ assertEquals("()", p.parse(t, String.class));
+ t = "_value=(~(~))";
+ assertEquals("()", p.parse(t, Object.class));
+ assertEquals("()", p.parse(t, String.class));
+ t = "~(~)";
+ assertEquals("()", p.parseParameter(t, Object.class));
+ assertEquals("()", p.parseParameter(t, String.class));
+ t = "(~(~))";
+ assertEquals("()", p.parseParameter(t, Object.class));
+ assertEquals("()", p.parseParameter(t, String.class));
+ t = "(~(~))";
+ assertEquals("()", p.parseParameter(t, Object.class));
+ assertEquals("()", p.parseParameter(t, String.class));
+
+ // 2nd level
+ t = "?(~(~))=(~(~))";
+ m = (Map)p.parse(t, Object.class);
+ assertEquals("()", m.get("()"));
+ t = "?(~(~))=(~(~))";
+ m = p.parseMap(t, HashMap.class, String.class, Object.class);
+ assertEquals("()", m.get("()"));
+
+ // String starting with $
+ // Top level
+ t = "_value=(~$a)";
+ assertEquals("$a", p.parse(t, Object.class));
+ t = "_value=(~$a)";
+ assertEquals("$a", p.parse(t, Object.class));
+ t = "(~$a)";
+ assertEquals("$a", p.parseParameter(t, Object.class));
+ t = "(~$a)";
+ assertEquals("$a", p.parseParameter(t, Object.class));
+
+ // 2nd level
+ t = "?(~$a)=(~$a)";
+ m = (Map)p.parse(t, Object.class);
+ assertEquals("$a", m.get("$a"));
+ m = p.parseMap(t, HashMap.class, String.class, Object.class);
+ assertEquals("$a", m.get("$a"));
+
+ // Blank string
+ // Top level
+ t = "_value=";
+ assertEquals("", p.parse(t, Object.class));
+ t = "";
+ assertEquals("", p.parseParameter(t, Object.class));
+
+ // 2nd level
+ t = "?=";
+ m = (Map)p.parse(t, Object.class);
+ assertEquals("", m.get(""));
+ m = p.parseMap(t, HashMap.class, String.class, Object.class);
+ assertEquals("", m.get(""));
+
+ // 3rd level
+ t = "?=$o(=)";
+ m = (Map)p.parse(t, Object.class);
+ assertEquals("", ((Map)m.get("")).get(""));
+ t = "?=(=)";
+ m = p.parseMap(t, HashMap.class, String.class, HashMap.class);
+ assertEquals("", ((Map)m.get("")).get(""));
+
+ // Newline character
+ // Top level
+ t = "_value=(%0A)";
+ assertEquals("\n", p.parse(t, Object.class));
+ t = "(%0A)";
+ assertEquals("%0A", p.parseParameter(t, Object.class));
+ t = "(\n)";
+ assertEquals("\n", p.parseParameter(t, Object.class));
+
+ // 2nd level
+ t = "?%0A=(%0A)";
+ m = (Map)p.parse(t, Object.class);
+ assertEquals("\n", m.get("\n"));
+
+ // 3rd level
+ t = "?%0A=$o((%0A)=(%0A))";
+ m = (Map)p.parse(t, Object.class);
+ assertEquals("\n", ((Map)m.get("\n")).get("\n"));
+ }
+
+ //====================================================================================================
+ // Unicode character test
+ //====================================================================================================
+ @Test
+ public void testUnicodeChars() throws Exception {
+ String t;
+ Map m;
+
+ // 2-byte UTF-8 character
+ // Top level
+ t = "_value=�";
+ assertEquals("�", p.parse(t, Object.class));
+ assertEquals("�", p.parse(t, String.class));
+ t = "_value=%C2%A2";
+ assertEquals("�", p.parse(t, Object.class));
+ assertEquals("�", p.parse(t, String.class));
+ t = "�";
+ assertEquals("�", p.parseParameter(t, Object.class));
+ assertEquals("�", p.parseParameter(t, String.class));
+ t = "%C2%A2";
+ assertEquals("%C2%A2", p.parseParameter(t, Object.class));
+ assertEquals("%C2%A2", p.parseParameter(t, String.class));
+
+ // 2nd level
+ t = "?%C2%A2=%C2%A2";
+ m = (Map)p.parse(t, Object.class);
+ assertEquals("�", m.get("�"));
+
+ // 3rd level
+ t = "?%C2%A2=$o(%C2%A2=%C2%A2)";
+ m = (Map)p.parse(t, Object.class);
+ assertEquals("�", ((Map)m.get("�")).get("�"));
+
+ // 3-byte UTF-8 character
+ // Top level
+ t = "_value=\u20ac";
+ assertEquals("\u20ac", p.parse(t, Object.class));
+ assertEquals("\u20ac", p.parse(t, String.class));
+ t = "_value=%E2%82%AC";
+ assertEquals("\u20ac", p.parse(t, Object.class));
+ assertEquals("\u20ac", p.parse(t, String.class));
+ t = "\u20ac";
+ assertEquals("\u20ac", p.parseParameter(t, Object.class));
+ assertEquals("\u20ac", p.parseParameter(t, String.class));
+ t = "%E2%82%AC";
+ assertEquals("%E2%82%AC", p.parseParameter(t, Object.class));
+ assertEquals("%E2%82%AC", p.parseParameter(t, String.class));
+
+ // 2nd level
+ t = "?%E2%82%AC=%E2%82%AC";
+ m = (Map)p.parse(t, Object.class);
+ assertEquals("\u20ac", m.get("\u20ac"));
+
+ // 3rd level
+ t = "?%E2%82%AC=$o(%E2%82%AC=%E2%82%AC)";
+ m = (Map)p.parse(t, Object.class);
+ assertEquals("\u20ac", ((Map)m.get("\u20ac")).get("\u20ac"));
+
+ // 4-byte UTF-8 character
+ // Top level
+ t = "_value=\U00024b62";
+ assertEquals("\U00024b62", p.parse(t, Object.class));
+ assertEquals("\U00024b62", p.parse(t, String.class));
+ t = "_value=%F0%A4%AD%A2";
+ assertEquals("\U00024b62", p.parse(t, Object.class));
+ assertEquals("\U00024b62", p.parse(t, String.class));
+ t = "\U00024b62";
+ assertEquals("\U00024b62", p.parseParameter(t, Object.class));
+ assertEquals("\U00024b62", p.parseParameter(t, String.class));
+ t = "%F0%A4%AD%A2";
+ assertEquals("%F0%A4%AD%A2", p.parseParameter(t, Object.class));
+ assertEquals("%F0%A4%AD%A2", p.parseParameter(t, String.class));
+
+ // 2nd level
+ t = "?%F0%A4%AD%A2=%F0%A4%AD%A2";
+ m = (Map)p.parse(t, Object.class);
+ assertEquals("\U00024b62", m.get("\U00024b62"));
+
+ // 3rd level
+ t = "?%F0%A4%AD%A2=$o(%F0%A4%AD%A2=%F0%A4%AD%A2)";
+ m = (Map)p.parse(t, Object.class);
+ assertEquals("\U00024b62", ((Map)m.get("\U00024b62")).get("\U00024b62"));
+ }
+
+ //====================================================================================================
+ // Test simple bean
+ //====================================================================================================
+ @Test
+ public void testSimpleBean() throws Exception {
+ UrlEncodingParser p = UrlEncodingParser.DEFAULT;
+ A t;
+
+ String s = "?f1=foo&f2=123";
+ t = p.parse(s, A.class);
+ assertEquals("foo", t.f1);
+ assertEquals(123, t.f2);
+
+ s = "(f1=foo,f2=123)";
+ t = p.parseParameter(s, A.class);
+ assertEquals("foo", t.f1);
+ assertEquals(123, t.f2);
+
+ s = "$o(f1=foo,f2=123)";
+ t = p.parseParameter(s, A.class);
+ assertEquals("foo", t.f1);
+ assertEquals(123, t.f2);
+ }
+
+ public static class A {
+ public String f1;
+ public int f2;
+ }
+
+ //====================================================================================================
+ // Test URL-encoded strings with no-value parameters.
+ //====================================================================================================
+ @Test
+ public void testNoValues() throws Exception {
+ UrlEncodingParser p = UrlEncodingParser.DEFAULT;
+ ObjectMap m;
+
+ String s = "?f1";
+ m = p.parse(s, ObjectMap.class);
+ assertTrue(m.containsKey("f1"));
+ assertNull(m.get("f1"));
+ s = "?f1=f2&f3";
+ m = p.parse(s, ObjectMap.class);
+ assertEquals("f2", m.get("f1"));
+ assertTrue(m.containsKey("f3"));
+ assertNull(m.get("f3"));
+ }
+
+ //====================================================================================================
+ // Test URL-encoded strings parsed into plain-text values using UrlEncodingParser.parseIntoSimpleMap().
+ //====================================================================================================
+ @Test
+ public void testParseIntoSimpleMap() throws Exception {
+ UrlEncodingParser p = UrlEncodingParser.DEFAULT;
+ Map<String,String[]> m;
+
+ String s = "?f1=,()=&f2a=$b(true)&f2b=true&f3a=$n(123)&f3b=123&f4=$s(foo)";
+ m = p.parseIntoSimpleMap(s);
+ assertEquals(",()=", m.get("f1")[0]);
+ assertEquals("$b(true)", m.get("f2a")[0]);
+ assertEquals("true", m.get("f2b")[0]);
+ assertEquals("$n(123)", m.get("f3a")[0]);
+ assertEquals("123", m.get("f3b")[0]);
+ assertEquals("$s(foo)", m.get("f4")[0]);
+
+ s = "f1=v1&=";
+ m = p.parseIntoSimpleMap(s);
+ assertEquals("v1", m.get("f1")[0]);
+ assertEquals("", m.get("")[0]);
+
+ s = "f1=v1&f2&f3";
+ m = p.parseIntoSimpleMap(s);
+ assertEquals("v1", m.get("f1")[0]);
+ assertTrue(m.containsKey("f2"));
+ assertTrue(m.containsKey("f3"));
+ assertNull(m.get("f2"));
+ assertNull(m.get("f3"));
+ }
+
+ //====================================================================================================
+ // Test parsing URL-encoded strings with multiple values.
+ //====================================================================================================
+ @Test
+ public void testParseIntoSimpleMapMultiValues() throws Exception {
+ UrlEncodingParser p = UrlEncodingParser.DEFAULT;
+ Map<String,String[]> m;
+
+ String s = "?f1&f1&f2&f2=abc&f2=def&f2";
+ m = p.parseIntoSimpleMap(s);
+ assertObjectEquals("{f1:null,f2:['abc','def']}", m);
+ }
+
+ @Test
+ public void testEmptyString() throws Exception {
+ UrlEncodingParser p = UrlEncodingParser.DEFAULT;
+
+ String s = "";
+ B b = p.parse(s, B.class);
+ assertEquals("f1", b.f1);
+ }
+
+ public static class B {
+ public String f1 = "f1";
+ }
+
+ //====================================================================================================
+ // Test comma-delimited list parameters.
+ //====================================================================================================
+ @Test
+ public void testCommaDelimitedLists() throws Exception {
+ UrlEncodingParser p = UrlEncodingParser.DEFAULT;
+
+ String s = "?f1=1,2,3&f2=a,b,c&f3=true,false&f4=&f5";
+ C c = p.parse(s, C.class);
+ assertObjectEquals("{f1:[1,2,3],f2:['a','b','c'],f3:[true,false],f4:[]}", c);
+ }
+
+ public static class C {
+ public int[] f1;
+ public String[] f2;
+ public boolean[] f3;
+ public String[] f4;
+ public String[] f5;
+ }
+
+ //====================================================================================================
+ // Test comma-delimited list parameters with special characters.
+ //====================================================================================================
+ @Test
+ public void testCommaDelimitedListsWithSpecialChars() throws Exception {
+ UrlEncodingParser p = UrlEncodingParser.DEFAULT;
+ String s;
+ C1 c;
+
+ // In the string below, the ~ character should not be interpreted as an escape.
+ s = "?f1=a~b,a~b";
+ c = p.parse(s, C1.class);
+ assertObjectEquals("{f1:['a~b','a~b']}", c);
+
+ s = "?f1=(a~b,a~b)";
+ c = p.parse(s, C1.class);
+ assertObjectEquals("{f1:['a~b','a~b']}", c);
+
+ s = "?f1=((a~b),(a~b))";
+ c = p.parse(s, C1.class);
+ assertObjectEquals("{f1:['a~b','a~b']}", c);
+
+ s = "?f1=($s(a~b),$s(a~b))";
+ c = p.parse(s, C1.class);
+ assertObjectEquals("{f1:['a~b','a~b']}", c);
+
+ s = "?f1=$a($s(a~b),$s(a~b))";
+ c = p.parse(s, C1.class);
+ assertObjectEquals("{f1:['a~b','a~b']}", c);
+
+ s = "?f1=~~,~~";
+ c = p.parse(s, C1.class);
+ assertObjectEquals("{f1:['~','~']}", c);
+
+ s = "?f1=(~~,~~)";
+ c = p.parse(s, C1.class);
+ assertObjectEquals("{f1:['~','~']}", c);
+
+ s = "?f1=(~~~~~~,~~~~~~)";
+ c = p.parse(s, C1.class);
+ assertObjectEquals("{f1:['~~~','~~~']}", c);
+
+ s = "?f1=((~~~~~~),(~~~~~~))";
+ c = p.parse(s, C1.class);
+ assertObjectEquals("{f1:['~~~','~~~']}", c);
+
+ // The ~ should be treated as an escape if followed by any of the following characters: ,()~=
+ s = "?f1=~,~(~)~~~=~$,~,~(~)~~~=~$";
+ c = p.parse(s, C1.class);
+ assertObjectEquals("{f1:[',()~=$',',()~=$']}", c);
+
+ s = "?f1=(~,~(~)~~~=~$,~,~(~)~~~=~$)";
+ c = p.parse(s, C1.class);
+ assertObjectEquals("{f1:[',()~=$',',()~=$']}", c);
+
+ s = "?f1=((~,~(~)~~~=~$),(~,~(~)~~~=~$))";
+ c = p.parse(s, C1.class);
+ assertObjectEquals("{f1:[',()~=$',',()~=$']}", c);
+
+ s = "?a~b=a~b";
+ ObjectMap m = p.parse(s, ObjectMap.class);
+ assertEquals("{'a~b':'a~b'}", m.toString());
+
+ s = "?(a~b)=(a~b)";
+ m = p.parse(s, ObjectMap.class);
+ assertEquals("{'a~b':'a~b'}", m.toString());
+
+ s = "?$s(a~b)=$s(a~b)";
+ m = p.parse(s, ObjectMap.class);
+ assertEquals("{'a~b':'a~b'}", m.toString());
+
+ s = "?~~=~~";
+ m = p.parse(s, ObjectMap.class);
+ assertEquals("{'~':'~'}", m.toString());
+
+ s = "?(~~)=(~~)";
+ m = p.parse(s, ObjectMap.class);
+ assertEquals("{'~':'~'}", m.toString());
+
+ s = "?~~~~~~=~~~~~~";
+ m = p.parse(s, ObjectMap.class);
+ assertEquals("{'~~~':'~~~'}", m.toString());
+
+ s = "?(~~~~~~)=(~~~~~~)";
+ m = p.parse(s, ObjectMap.class);
+ assertEquals("{'~~~':'~~~'}", m.toString());
+
+ s = "?$s(~~~~~~)=$s(~~~~~~)";
+ m = p.parse(s, ObjectMap.class);
+ assertEquals("{'~~~':'~~~'}", m.toString());
+
+ s = "?~,~(~)~~~=~$=~,~(~)~~~=~$";
+ m = p.parse(s, ObjectMap.class);
+ assertEquals("{',()~=$':',()~=$'}", m.toString());
+
+ s = "?(~,~(~)~~~=~$)=(~,~(~)~~~=~$)";
+ m = p.parse(s, ObjectMap.class);
+ assertEquals("{',()~=$':',()~=$'}", m.toString());
+
+ s = "?$s(~,~(~)~~~=~$)=$s(~,~(~)~~~=~$)";
+ m = p.parse(s, ObjectMap.class);
+ assertEquals("{',()~=$':',()~=$'}", m.toString());
+
+ s = "?%7E%2C%7E%28%7E%29%7E%7E%7E%3D%7E%24=%7E%2C%7E%28%7E%29%7E%7E%7E%3D%7E%24";
+ m = p.parse(s, ObjectMap.class);
+ assertEquals("{',()~=$':',()~=$'}", m.toString());
+
+ s = "?(%7E%2C%7E%28%7E%29%7E%7E%7E%3D%7E%24)=(%7E%2C%7E%28%7E%29%7E%7E%7E%3D%7E%24)";
+ m = p.parse(s, ObjectMap.class);
+ assertEquals("{',()~=$':',()~=$'}", m.toString());
+
+ s = "?$s(%7E%2C%7E%28%7E%29%7E%7E%7E%3D%7E%24)=$s(%7E%2C%7E%28%7E%29%7E%7E%7E%3D%7E%24)";
+ m = p.parse(s, ObjectMap.class);
+ assertEquals("{',()~=$':',()~=$'}", m.toString());
+ }
+
+ public static class C1 {
+ public String[] f1;
+ }
+
+ //====================================================================================================
+ // Test comma-delimited list parameters.
+ //====================================================================================================
+ @Test
+ public void testWhitespace() throws Exception {
+ UrlEncodingParser p = UrlEncodingParser.DEFAULT_WS_AWARE;
+ String s;
+ ObjectMap m;
+
+ s = "?f1=foo\n\t&f2=bar\n\t";
+ m = p.parse(s, ObjectMap.class);
+ assertEquals("{f1:'foo',f2:'bar'}", m.toString());
+
+ s = "?f1=(\n\t)&f2=(\n\t)";
+ m = p.parse(s, ObjectMap.class);
+ assertEquals("\n\t", m.getString("f1"));
+ assertEquals("\n\t", m.getString("f2"));
+
+ s = "?f1=(\n\t)\n\t&f2=(\n\t)\n\t";
+ m = p.parse(s, ObjectMap.class);
+ assertEquals("\n\t", m.getString("f1"));
+ assertEquals("\n\t", m.getString("f2"));
+ assertEquals("{f1:'\\n\\t',f2:'\\n\\t'}", m.toString()); // Note that JsonSerializer escapes newlines and tabs.
+
+ s = "?f1=$s(\n\t)\n\t&f2=$s(\n\t)\n\t";
+ m = p.parse(s, ObjectMap.class);
+ assertEquals("\n\t", m.getString("f1"));
+ assertEquals("\n\t", m.getString("f2"));
+ assertEquals("{f1:'\\n\\t',f2:'\\n\\t'}", m.toString()); // Note that JsonSerializer escapes newlines and tabs.
+
+ s = "?f1=$o(\n\tf1a=a,\n\tf1b=b\n\t)\n\t&f2=$o(\n\tf2a=a,\n\tf2b=b\n\t)\n\t";
+ m = p.parse(s, ObjectMap.class);
+ assertEquals("{f1:{f1a:'a',f1b:'b'},f2:{f2a:'a',f2b:'b'}}", m.toString()); // Note that JsonSerializer escapes newlines and tabs.
+ D d = p.parse(s, D.class);
+ assertObjectEquals("{f1:{f1a:'a',f1b:'b'},f2:{f2a:'a',f2b:'b'}}", d); // Note that JsonSerializer escapes newlines and tabs.
+
+ s = "?f1=$o(\n\tf1a=(\n\t),\n\tf1b=(\n\t)\n\t)\n\t&f2=$o(\n\tf2a=(\n\t),\n\tf2b=(\n\t)\n\t)\n\t";
+ m = p.parse(s, ObjectMap.class);
+ assertEquals("{f1:{f1a:'\\n\\t',f1b:'\\n\\t'},f2:{f2a:'\\n\\t',f2b:'\\n\\t'}}", m.toString()); // Note that JsonSerializer escapes newlines and tabs.
+ d = p.parse(s, D.class);
+ assertObjectEquals("{f1:{f1a:'\\n\\t',f1b:'\\n\\t'},f2:{f2a:'\\n\\t',f2b:'\\n\\t'}}", d); // Note that JsonSerializer escapes newlines and tabs.
+
+ s = "?f1=$a(\n\tfoo,\n\tbar\n\t)\n\t&f2=$a(\n\tfoo,\n\tbar\n\t)\n\t";
+ m = p.parse(s, ObjectMap.class);
+ assertEquals("{f1:['foo','bar'],f2:['foo','bar']}", m.toString()); // Note that JsonSerializer escapes newlines and tabs.
+
+ s = "f1=a,\n\tb,\n\tc\n\t&f2=1,\n\t2,\n\t3\n\t&f3=true,\n\tfalse\n\t";
+ E e = p.parse(s, E.class);
+ assertObjectEquals("{f1:['a','b','c'],f2:[1,2,3],f3:[true,false]}", e);
+
+ s = "f1=a%2C%0D%0Ab%2C%0D%0Ac%0D%0A&f2=1%2C%0D%0A2%2C%0D%0A3%0D%0A&f3=true%2C%0D%0Afalse%0D%0A";
+ e = p.parse(s, E.class);
+ assertObjectEquals("{f1:['a','b','c'],f2:[1,2,3],f3:[true,false]}", e);
+ }
+
+ public static class D {
+ public D1 f1;
+ public D2 f2;
+ }
+
+ public static class D1 {
+ public String f1a, f1b;
+ }
+
+ public static class D2 {
+ public String f2a, f2b;
+ }
+
+ public static class E {
+ public String[] f1;
+ public int[] f2;
+ public boolean[] f3;
+ }
+
+ //====================================================================================================
+ // Multi-part parameters on beans via URLENC_expandedParams
+ //====================================================================================================
+ @Test
+ public void testMultiPartParametersOnBeansViaProperty() throws Exception {
+ UrlEncodingParser p;
+ String in;
+
+ p = UrlEncodingParser.DEFAULT.clone().setProperty(UrlEncodingContext.URLENC_expandedParams, true);
+ in = ""
+ + "f01=a&f01=b"
+ + "&f02=c&f02=d"
+ + "&f03=1&f03=2"
+ + "&f04=3&f04=4"
+ + "&f05=(e,f)&f05=(g,h)"
+ + "&f06=(i,j)&f06=(k,l)"
+ + "&f07=(a=a,b=1,c=true)&f07=(a=b,b=2,c=false)"
+ + "&f08=(a=a,b=1,c=true)&f08=(a=b,b=2,c=false)"
+ + "&f09=((a=a,b=1,c=true))&f09=((a=b,b=2,c=false))"
+ + "&f10=((a=a,b=1,c=true))&f10=((a=b,b=2,c=false))"
+ + "&f11=a&f11=b"
+ + "&f12=c&f12=d"
+ + "&f13=1&f13=2"
+ + "&f14=3&f14=4"
+ + "&f15=(e,f)&f15=(g,h)"
+ + "&f16=(i,j)&f16=(k,l)"
+ + "&f17=(a=a,b=1,c=true)&f17=(a=b,b=2,c=false)"
+ + "&f18=(a=a,b=1,c=true)&f18=(a=b,b=2,c=false)"
+ + "&f19=((a=a,b=1,c=true))&f19=((a=b,b=2,c=false))"
+ + "&f20=((a=a,b=1,c=true))&f20=((a=b,b=2,c=false))";
+
+ DTOs.B t = p.parse(in, DTOs.B.class);
+ String e = "{"
+ + "f01:['a','b'],"
+ + "f02:['c','d'],"
+ + "f03:[1,2],"
+ + "f04:[3,4],"
+ + "f05:[['e','f'],['g','h']],"
+ + "f06:[['i','j'],['k','l']],"
+ + "f07:[{a:'a',b:1,c:true},{a:'b',b:2,c:false}],"
+ + "f08:[{a:'a',b:1,c:true},{a:'b',b:2,c:false}],"
+ + "f09:[[{a:'a',b:1,c:true}],[{a:'b',b:2,c:false}]],"
+ + "f10:[[{a:'a',b:1,c:true}],[{a:'b',b:2,c:false}]],"
+ + "f11:['a','b'],"
+ + "f12:['c','d'],"
+ + "f13:[1,2],"
+ + "f14:[3,4],"
+ + "f15:[['e','f'],['g','h']],"
+ + "f16:[['i','j'],['k','l']],"
+ + "f17:[{a:'a',b:1,c:true},{a:'b',b:2,c:false}],"
+ + "f18:[{a:'a',b:1,c:true},{a:'b',b:2,c:false}],"
+ + "f19:[[{a:'a',b:1,c:true}],[{a:'b',b:2,c:false}]],"
+ + "f20:[[{a:'a',b:1,c:true}],[{a:'b',b:2,c:false}]]"
+ +"}";
+ assertSortedObjectEquals(e, t);
+ }
+
+ //====================================================================================================
+ // Multi-part parameters on beans via @UrlEncoding.expandedParams on class
+ //====================================================================================================
+ @Test
+ public void testMultiPartParametersOnBeansViaAnnotationOnClass() throws Exception {
+ UrlEncodingParser p;
+ String in;
+ p = UrlEncodingParser.DEFAULT;
+ in = ""
+ + "f01=a&f01=b"
+ + "&f02=c&f02=d"
+ + "&f03=1&f03=2"
+ + "&f04=3&f04=4"
+ + "&f05=(e,f)&f05=(g,h)"
+ + "&f06=(i,j)&f06=(k,l)"
+ + "&f07=(a=a,b=1,c=true)&f07=(a=b,b=2,c=false)"
+ + "&f08=(a=a,b=1,c=true)&f08=(a=b,b=2,c=false)"
+ + "&f09=((a=a,b=1,c=true))&f09=((a=b,b=2,c=false))"
+ + "&f10=((a=a,b=1,c=true))&f10=((a=b,b=2,c=false))"
+ + "&f11=a&f11=b"
+ + "&f12=c&f12=d"
+ + "&f13=1&f13=2"
+ + "&f14=3&f14=4"
+ + "&f15=(e,f)&f15=(g,h)"
+ + "&f16=(i,j)&f16=(k,l)"
+ + "&f17=(a=a,b=1,c=true)&f17=(a=b,b=2,c=false)"
+ + "&f18=(a=a,b=1,c=true)&f18=(a=b,b=2,c=false)"
+ + "&f19=((a=a,b=1,c=true))&f19=((a=b,b=2,c=false))"
+ + "&f20=((a=a,b=1,c=true))&f20=((a=b,b=2,c=false))";
+
+ DTOs.C t = p.parse(in, DTOs.C.class);
+ String e = "{"
+ + "f01:['a','b'],"
+ + "f02:['c','d'],"
+ + "f03:[1,2],"
+ + "f04:[3,4],"
+ + "f05:[['e','f'],['g','h']],"
+ + "f06:[['i','j'],['k','l']],"
+ + "f07:[{a:'a',b:1,c:true},{a:'b',b:2,c:false}],"
+ + "f08:[{a:'a',b:1,c:true},{a:'b',b:2,c:false}],"
+ + "f09:[[{a:'a',b:1,c:true}],[{a:'b',b:2,c:false}]],"
+ + "f10:[[{a:'a',b:1,c:true}],[{a:'b',b:2,c:false}]],"
+ + "f11:['a','b'],"
+ + "f12:['c','d'],"
+ + "f13:[1,2],"
+ + "f14:[3,4],"
+ + "f15:[['e','f'],['g','h']],"
+ + "f16:[['i','j'],['k','l']],"
+ + "f17:[{a:'a',b:1,c:true},{a:'b',b:2,c:false}],"
+ + "f18:[{a:'a',b:1,c:true},{a:'b',b:2,c:false}],"
+ + "f19:[[{a:'a',b:1,c:true}],[{a:'b',b:2,c:false}]],"
+ + "f20:[[{a:'a',b:1,c:true}],[{a:'b',b:2,c:false}]]"
+ +"}";
+ assertSortedObjectEquals(e, t);
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/urlencoding/UrlEncodingSerializerTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/urlencoding/UrlEncodingSerializerTest.java b/org.apache.juneau/src/test/java/org/apache/juneau/urlencoding/UrlEncodingSerializerTest.java
new file mode 100755
index 0000000..0fb8a05
--- /dev/null
+++ b/org.apache.juneau/src/test/java/org/apache/juneau/urlencoding/UrlEncodingSerializerTest.java
@@ -0,0 +1,497 @@
+/***************************************************************************************************************************
+ * 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.juneau.urlencoding;
+
+import static org.junit.Assert.*;
+
+import java.util.*;
+
+import org.apache.juneau.*;
+import org.junit.*;
+
+public class UrlEncodingSerializerTest {
+
+ static UrlEncodingSerializer s = UrlEncodingSerializer.DEFAULT;
+ static UrlEncodingSerializer ss = UrlEncodingSerializer.DEFAULT_SIMPLE;
+ static UrlEncodingSerializer sr = UrlEncodingSerializer.DEFAULT_READABLE;
+
+
+ //====================================================================================================
+ // Basic test
+ //====================================================================================================
+ @Test
+ public void testBasic() throws Exception {
+
+ Object t;
+
+ // Simple string
+ // Top level
+ t = "a";
+ assertEquals("_value=a", s.serialize(t));
+
+ // 2nd level
+ t = new ObjectMap("{a:'a'}");
+ assertEquals("a=a", s.serialize(t));
+ assertEquals("a=a", ss.serialize(t));
+ assertEquals("a=a", sr.serialize(t));
+
+ // Simple map
+ // Top level
+ t = new ObjectMap("{a:'b',c:123,d:false,e:true,f:null}");
+ assertEquals("a=b&c=$n(123)&d=$b(false)&e=$b(true)&f=%00", s.serialize(t));
+ assertEquals("a=b&c=123&d=false&e=true&f=%00", ss.serialize(t));
+ assertEquals("a=b\n&c=$n(123)\n&d=$b(false)\n&e=$b(true)\n&f=%00", sr.serialize(t));
+
+ // 2nd level
+ t = new ObjectMap("{a:{a:'b',c:123,d:false,e:true,f:null}}");
+ assertEquals("a=$o(a=b,c=$n(123),d=$b(false),e=$b(true),f=%00)", s.serialize(t));
+ assertEquals("a=(a=b,c=123,d=false,e=true,f=%00)", ss.serialize(t));
+ assertEquals("a=$o(\n\ta=b,\n\tc=$n(123),\n\td=$b(false),\n\te=$b(true),\n\tf=%00\n)", sr.serialize(t));
+
+ // Simple map with primitives as literals
+ t = new ObjectMap("{a:'b',c:'123',d:'false',e:'true',f:'null'}");
+ assertEquals("a=b&c=123&d=false&e=true&f=null", s.serialize(t));
+ assertEquals("a=b&c=123&d=false&e=true&f=null", ss.serialize(t));
+ assertEquals("a=b\n&c=123\n&d=false\n&e=true\n&f=null", sr.serialize(t));
+
+ // null
+ // Note that serializeParams is always encoded.
+ // Top level
+ t = null;
+ assertEquals("_value=%00", s.serialize(t));
+ assertEquals("_value=%00", ss.serialize(t));
+ assertEquals("_value=%00", sr.serialize(t));
+
+ // 2nd level
+ t = new ObjectMap("{null:null}");
+ assertEquals("%00=%00", s.serialize(t));
+ assertEquals("%00=%00", ss.serialize(t));
+ assertEquals("%00=%00", sr.serialize(t));
+
+ // 3rd level
+ t = new ObjectMap("{null:{null:null}}");
+ assertEquals("%00=$o(%00=%00)", s.serialize(t));
+ assertEquals("%00=(%00=%00)", ss.serialize(t));
+ assertEquals("%00=$o(\n\t%00=%00\n)", sr.serialize(t));
+
+ // Empty array
+ // Top level
+ t = new String[0];
+ assertEquals("_value=$a()", s.serialize(t));
+ assertEquals("_value=()", ss.serialize(t));
+ assertEquals("_value=$a()", sr.serialize(t));
+
+ // 2nd level in map
+ t = new ObjectMap("{x:[]}");
+ assertEquals("x=$a()", s.serialize(t));
+ assertEquals("x=()", ss.serialize(t));
+ assertEquals("x=$a()", sr.serialize(t));
+
+ // Empty 2 dimensional array
+ t = new String[1][0];
+ assertEquals("_value=$a($a())", s.serialize(t));
+ assertEquals("_value=(())", ss.serialize(t));
+ assertEquals("_value=$a(\n\t$a()\n)", sr.serialize(t));
+
+ // Array containing empty string
+ // Top level
+ t = new String[]{""};
+ assertEquals("_value=$a(())", s.serialize(t));
+ assertEquals("_value=(())", ss.serialize(t));
+ assertEquals("_value=$a(\n\t()\n)", sr.serialize(t));
+
+ // 2nd level
+ t = new ObjectMap("{x:['']}");
+ assertEquals("x=$a(())", s.serialize(t));
+ assertEquals("x=(())", ss.serialize(t));
+ assertEquals("x=$a(\n\t()\n)", sr.serialize(t));
+
+ // Array containing 3 empty strings
+ t = new String[]{"","",""};
+ assertEquals("_value=$a(,,)", s.serialize(t));
+ assertEquals("_value=(,,)", ss.serialize(t));
+ assertEquals("_value=$a(\n\t(),\n\t(),\n\t()\n)", sr.serialize(t));
+
+ // String containing \u0000
+ // Top level
+ t = "\u0000";
+ assertEquals("_value=(%00)", s.serialize(t));
+ assertEquals("_value=(%00)", ss.serialize(t));
+ assertEquals("_value=(%00)", sr.serialize(t));
+
+ // 2nd level
+ t = new ObjectMap("{'\u0000':'\u0000'}");
+ assertEquals("(%00)=(%00)", s.serialize(t));
+ assertEquals("(%00)=(%00)", ss.serialize(t));
+ assertEquals("(%00)=(%00)", sr.serialize(t));
+
+ // Boolean
+ // Top level
+ t = false;
+ assertEquals("_value=$b(false)", s.serialize(t));
+ assertEquals("_value=false", ss.serialize(t));
+ assertEquals("_value=$b(false)", sr.serialize(t));
+
+ // 2nd level
+ t = new ObjectMap("{x:false}");
+ assertEquals("x=$b(false)", s.serialize(t));
+ assertEquals("x=false", ss.serialize(t));
+ assertEquals("x=$b(false)", sr.serialize(t));
+
+ // Number
+ // Top level
+ t = 123;
+ assertEquals("_value=$n(123)", s.serialize(t));
+ assertEquals("_value=123", ss.serialize(t));
+ assertEquals("_value=$n(123)", sr.serialize(t));
+
+ // 2nd level
+ t = new ObjectMap("{x:123}");
+ assertEquals("x=$n(123)", s.serialize(t));
+ assertEquals("x=123", ss.serialize(t));
+ assertEquals("x=$n(123)", sr.serialize(t));
+
+ // Unencoded chars
+ // Top level
+ t = "x;/?:@-_.!*'";
+ assertEquals("_value=x;/?:@-_.!*'", s.serialize(t));
+ assertEquals("_value=x;/?:@-_.!*'", ss.serialize(t));
+ assertEquals("_value=x;/?:@-_.!*'", sr.serialize(t));
+
+ // 2nd level
+ t = new ObjectMap("{x:'x;/?:@-_.!*\\''}");
+ assertEquals("x=x;/?:@-_.!*'", s.serialize(t));
+ assertEquals("x=x;/?:@-_.!*'", ss.serialize(t));
+ assertEquals("x=x;/?:@-_.!*'", sr.serialize(t));
+
+ // Encoded chars
+ // Top level
+ t = "x{}|\\^[]`<>#%\"&+";
+ assertEquals("_value=x%7B%7D%7C%5C%5E%5B%5D%60%3C%3E%23%25%22%26%2B", s.serialize(t));
+ assertEquals("_value=x%7B%7D%7C%5C%5E%5B%5D%60%3C%3E%23%25%22%26%2B", ss.serialize(t));
+ assertEquals("_value=x%7B%7D%7C%5C%5E%5B%5D%60%3C%3E%23%25%22%26%2B", sr.serialize(t));
+
+ // 2nd level
+ t = new ObjectMap("{'x{}|\\\\^[]`<>#%\"&+':'x{}|\\\\^[]`<>#%\"&+'}");
+ assertEquals("x%7B%7D%7C%5C%5E%5B%5D%60%3C%3E%23%25%22%26%2B=x%7B%7D%7C%5C%5E%5B%5D%60%3C%3E%23%25%22%26%2B", s.serialize(t));
+ assertEquals("x%7B%7D%7C%5C%5E%5B%5D%60%3C%3E%23%25%22%26%2B=x%7B%7D%7C%5C%5E%5B%5D%60%3C%3E%23%25%22%26%2B", ss.serialize(t));
+ assertEquals("x%7B%7D%7C%5C%5E%5B%5D%60%3C%3E%23%25%22%26%2B=x%7B%7D%7C%5C%5E%5B%5D%60%3C%3E%23%25%22%26%2B", sr.serialize(t));
+
+ // Escaped chars
+ // Top level
+ t = "x$,()~";
+ assertEquals("_value=x$,()~", s.serialize(t));
+ assertEquals("_value=x$,()~", ss.serialize(t));
+ assertEquals("_value=x$,()~", sr.serialize(t));
+
+ // 2nd level
+ t = new ObjectMap("{'x$,()~':'x$,()~'}");
+ assertEquals("x$,()~=x$,()~", s.serialize(t));
+ assertEquals("x$,()~=x$,()~", ss.serialize(t));
+ assertEquals("x$,()~=x$,()~", sr.serialize(t));
+
+ // 3rd level
+ t = new ObjectMap("{'x$,()~':{'x$,()~':'x$,()~'}}");
+ assertEquals("x$,()~=$o(x$~,~(~)~~=x$~,~(~)~~)", s.serialize(t));
+ assertEquals("x$,()~=(x$~,~(~)~~=x$~,~(~)~~)", ss.serialize(t));
+ assertEquals("x$,()~=$o(\n\tx$~,~(~)~~=x$~,~(~)~~\n)", sr.serialize(t));
+
+ // Equals sign
+ // Gets encoded at top level, and encoded+escaped at 2nd level.
+ // Top level
+ t = "x=";
+ assertEquals("_value=x=", s.serialize(t));
+ assertEquals("_value=x=", ss.serialize(t));
+ assertEquals("_value=x=", sr.serialize(t));
+
+ // 2nd level
+ t = new ObjectMap("{'x=':'x='}");
+ assertEquals("x%3D=x=", s.serialize(t));
+ assertEquals("x%3D=x=", ss.serialize(t));
+ assertEquals("x%3D=x=", sr.serialize(t));
+
+ // 3rd level
+ t = new ObjectMap("{'x=':{'x=':'x='}}");
+ assertEquals("x%3D=$o(x~==x~=)", s.serialize(t));
+ assertEquals("x%3D=(x~==x~=)", ss.serialize(t));
+ assertEquals("x%3D=$o(\n\tx~==x~=\n)", sr.serialize(t));
+
+ // String starting with parenthesis
+ // Top level
+ t = "()";
+ assertEquals("_value=(~(~))", s.serialize(t));
+ assertEquals("_value=(~(~))", ss.serialize(t));
+ assertEquals("_value=(~(~))", sr.serialize(t));
+
+ // 2nd level
+ t = new ObjectMap("{'()':'()'}");
+ assertEquals("(~(~))=(~(~))", s.serialize(t));
+ assertEquals("(~(~))=(~(~))", ss.serialize(t));
+ assertEquals("(~(~))=(~(~))", sr.serialize(t));
+
+ // String starting with $
+ // Top level
+ t = "$a";
+ assertEquals("_value=($a)", s.serialize(t));
+ assertEquals("_value=($a)", ss.serialize(t));
+ assertEquals("_value=($a)", sr.serialize(t));
+
+ // 2nd level
+ t = new ObjectMap("{$a:'$a'}");
+ assertEquals("($a)=($a)", s.serialize(t));
+ assertEquals("($a)=($a)", ss.serialize(t));
+ assertEquals("($a)=($a)", sr.serialize(t));
+
+ // Blank string
+ // Top level
+ t = "";
+ assertEquals("_value=", s.serialize(t));
+ assertEquals("_value=", ss.serialize(t));
+ assertEquals("_value=", sr.serialize(t));
+
+ // 2nd level
+ t = new ObjectMap("{'':''}");
+ assertEquals("=", s.serialize(t));
+ assertEquals("=", ss.serialize(t));
+ assertEquals("=", sr.serialize(t));
+
+ // 3rd level
+ t = new ObjectMap("{'':{'':''}}");
+ assertEquals("=$o(=)", s.serialize(t));
+ assertEquals("=(=)", ss.serialize(t));
+ assertEquals("=$o(\n\t()=()\n)", sr.serialize(t));
+
+ // Newline character
+ // Top level
+ t = "\n";
+ assertEquals("_value=%0A", s.serialize(t));
+ assertEquals("_value=%0A", ss.serialize(t));
+ assertEquals("_value=(%0A)", sr.serialize(t));
+
+ // 2nd level
+ t = new ObjectMap("{'\n':'\n'}");
+ assertEquals("%0A=%0A", s.serialize(t));
+ assertEquals("%0A=%0A", ss.serialize(t));
+ assertEquals("(%0A)=(%0A)", sr.serialize(t));
+
+ // 3rd level
+ t = new ObjectMap("{'\n':{'\n':'\n'}}");
+ assertEquals("%0A=$o(%0A=%0A)", s.serialize(t));
+ assertEquals("%0A=(%0A=%0A)", ss.serialize(t));
+ assertEquals("(%0A)=$o(\n\t(%0A)=(%0A)\n)", sr.serialize(t));
+ }
+
+ //====================================================================================================
+ // Unicode characters test
+ //====================================================================================================
+ @Test
+ public void testUnicodeChars() throws Exception {
+ Object t;
+
+ // 2-byte UTF-8 character
+ // Top level
+ t = "�";
+ assertEquals("_value=%C2%A2", s.serialize(t));
+ assertEquals("_value=%C2%A2", ss.serialize(t));
+ assertEquals("_value=%C2%A2", sr.serialize(t));
+
+ // 2nd level
+ t = new ObjectMap("{'�':'�'}");
+ assertEquals("%C2%A2=%C2%A2", s.serialize(t));
+ assertEquals("%C2%A2=%C2%A2", ss.serialize(t));
+ assertEquals("%C2%A2=%C2%A2", sr.serialize(t));
+
+ // 3rd level
+ t = new ObjectMap("{'�':{'�':'�'}}");
+ assertEquals("%C2%A2=$o(%C2%A2=%C2%A2)", s.serialize(t));
+ assertEquals("%C2%A2=(%C2%A2=%C2%A2)", ss.serialize(t));
+ assertEquals("%C2%A2=$o(\n\t%C2%A2=%C2%A2\n)", sr.serialize(t));
+
+ // 3-byte UTF-8 character
+ // Top level
+ t = "\u20ac";
+ assertEquals("_value=%E2%82%AC", s.serialize(t));
+ assertEquals("_value=%E2%82%AC", ss.serialize(t));
+ assertEquals("_value=%E2%82%AC", sr.serialize(t));
+
+ // 2nd level
+ t = new ObjectMap("{'\u20ac':'\u20ac'}");
+ assertEquals("%E2%82%AC=%E2%82%AC", s.serialize(t));
+ assertEquals("%E2%82%AC=%E2%82%AC", ss.serialize(t));
+ assertEquals("%E2%82%AC=%E2%82%AC", sr.serialize(t));
+
+ // 3rd level
+ t = new ObjectMap("{'\u20ac':{'\u20ac':'\u20ac'}}");
+ assertEquals("%E2%82%AC=$o(%E2%82%AC=%E2%82%AC)", s.serialize(t));
+ assertEquals("%E2%82%AC=(%E2%82%AC=%E2%82%AC)", ss.serialize(t));
+ assertEquals("%E2%82%AC=$o(\n\t%E2%82%AC=%E2%82%AC\n)", sr.serialize(t));
+
+ // 4-byte UTF-8 character
+ // Top level
+ t = "\U00024b62";
+ assertEquals("_value=%F0%A4%AD%A2", s.serialize(t));
+ assertEquals("_value=%F0%A4%AD%A2", ss.serialize(t));
+ assertEquals("_value=%F0%A4%AD%A2", sr.serialize(t));
+
+ // 2nd level
+ t = new ObjectMap("{'\U00024b62':'\U00024b62'}");
+ assertEquals("%F0%A4%AD%A2=%F0%A4%AD%A2", s.serialize(t));
+ assertEquals("%F0%A4%AD%A2=%F0%A4%AD%A2", ss.serialize(t));
+ assertEquals("%F0%A4%AD%A2=%F0%A4%AD%A2", sr.serialize(t));
+
+ // 3rd level
+ t = new ObjectMap("{'\U00024b62':{'\U00024b62':'\U00024b62'}}");
+ assertEquals("%F0%A4%AD%A2=$o(%F0%A4%AD%A2=%F0%A4%AD%A2)", s.serialize(t));
+ assertEquals("%F0%A4%AD%A2=(%F0%A4%AD%A2=%F0%A4%AD%A2)", ss.serialize(t));
+ assertEquals("%F0%A4%AD%A2=$o(\n\t%F0%A4%AD%A2=%F0%A4%AD%A2\n)", sr.serialize(t));
+ }
+
+ //====================================================================================================
+ // Multi-part parameters on beans via URLENC_expandedParams
+ //====================================================================================================
+ @Test
+ @SuppressWarnings("hiding")
+ public void testMultiPartParametersOnBeansViaProperty() throws Exception {
+ UrlEncodingSerializer s;
+ DTOs.B t = DTOs.B.create();
+ String r;
+
+ s = UrlEncodingSerializer.DEFAULT_SIMPLE;
+ r = s.serialize(t);
+ String e = ""
+ + "f01=(a,b)"
+ + "&f02=(c,d)"
+ + "&f03=(1,2)"
+ + "&f04=(3,4)"
+ + "&f05=((e,f),(g,h))"
+ + "&f06=((i,j),(k,l))"
+ + "&f07=((a=a,b=1,c=true),(a=a,b=1,c=true))"
+ + "&f08=((a=a,b=1,c=true),(a=a,b=1,c=true))"
+ + "&f09=(((a=a,b=1,c=true)),((a=a,b=1,c=true)))"
+ + "&f10=(((a=a,b=1,c=true)),((a=a,b=1,c=true)))"
+ + "&f11=(a,b)"
+ + "&f12=(c,d)"
+ + "&f13=(1,2)"
+ + "&f14=(3,4)"
+ + "&f15=((e,f),(g,h))"
+ + "&f16=((i,j),(k,l))"
+ + "&f17=((a=a,b=1,c=true),(a=a,b=1,c=true))"
+ + "&f18=((a=a,b=1,c=true),(a=a,b=1,c=true))"
+ + "&f19=(((a=a,b=1,c=true)),((a=a,b=1,c=true)))"
+ + "&f20=(((a=a,b=1,c=true)),((a=a,b=1,c=true)))";
+ assertEquals(e, r);
+
+ s = UrlEncodingSerializer.DEFAULT_SIMPLE.clone().setProperty(UrlEncodingContext.URLENC_expandedParams, true);
+ r = s.serialize(t);
+ e = ""
+ + "f01=a&f01=b"
+ + "&f02=c&f02=d"
+ + "&f03=1&f03=2"
+ + "&f04=3&f04=4"
+ + "&f05=(e,f)&f05=(g,h)"
+ + "&f06=(i,j)&f06=(k,l)"
+ + "&f07=(a=a,b=1,c=true)&f07=(a=a,b=1,c=true)"
+ + "&f08=(a=a,b=1,c=true)&f08=(a=a,b=1,c=true)"
+ + "&f09=((a=a,b=1,c=true))&f09=((a=a,b=1,c=true))"
+ + "&f10=((a=a,b=1,c=true))&f10=((a=a,b=1,c=true))"
+ + "&f11=a&f11=b"
+ + "&f12=c&f12=d"
+ + "&f13=1&f13=2"
+ + "&f14=3&f14=4"
+ + "&f15=(e,f)&f15=(g,h)"
+ + "&f16=(i,j)&f16=(k,l)"
+ + "&f17=(a=a,b=1,c=true)&f17=(a=a,b=1,c=true)"
+ + "&f18=(a=a,b=1,c=true)&f18=(a=a,b=1,c=true)"
+ + "&f19=((a=a,b=1,c=true))&f19=((a=a,b=1,c=true))"
+ + "&f20=((a=a,b=1,c=true))&f20=((a=a,b=1,c=true))";
+ assertEquals(e, r);
+ }
+
+
+ //====================================================================================================
+ // Multi-part parameters on beans via @UrlEncoding.expandedParams on class
+ //====================================================================================================
+ @Test
+ @SuppressWarnings("hiding")
+ public void testMultiPartParametersOnBeansViaAnnotationOnClass() throws Exception {
+ UrlEncodingSerializer s;
+ DTOs.C t = DTOs.C.create();
+ String r;
+
+ s = UrlEncodingSerializer.DEFAULT_SIMPLE;
+ r = s.serialize(t);
+ String e = ""
+ + "f01=a&f01=b"
+ + "&f02=c&f02=d"
+ + "&f03=1&f03=2"
+ + "&f04=3&f04=4"
+ + "&f05=(e,f)&f05=(g,h)"
+ + "&f06=(i,j)&f06=(k,l)"
+ + "&f07=(a=a,b=1,c=true)&f07=(a=a,b=1,c=true)"
+ + "&f08=(a=a,b=1,c=true)&f08=(a=a,b=1,c=true)"
+ + "&f09=((a=a,b=1,c=true))&f09=((a=a,b=1,c=true))"
+ + "&f10=((a=a,b=1,c=true))&f10=((a=a,b=1,c=true))"
+ + "&f11=a&f11=b"
+ + "&f12=c&f12=d"
+ + "&f13=1&f13=2"
+ + "&f14=3&f14=4"
+ + "&f15=(e,f)&f15=(g,h)"
+ + "&f16=(i,j)&f16=(k,l)"
+ + "&f17=(a=a,b=1,c=true)&f17=(a=a,b=1,c=true)"
+ + "&f18=(a=a,b=1,c=true)&f18=(a=a,b=1,c=true)"
+ + "&f19=((a=a,b=1,c=true))&f19=((a=a,b=1,c=true))"
+ + "&f20=((a=a,b=1,c=true))&f20=((a=a,b=1,c=true))";
+ assertEquals(e, r);
+
+ s = UrlEncodingSerializer.DEFAULT_SIMPLE.clone().setProperty(UrlEncodingContext.URLENC_expandedParams, true);
+ r = s.serialize(t);
+ e = ""
+ + "f01=a&f01=b"
+ + "&f02=c&f02=d"
+ + "&f03=1&f03=2"
+ + "&f04=3&f04=4"
+ + "&f05=(e,f)&f05=(g,h)"
+ + "&f06=(i,j)&f06=(k,l)"
+ + "&f07=(a=a,b=1,c=true)&f07=(a=a,b=1,c=true)"
+ + "&f08=(a=a,b=1,c=true)&f08=(a=a,b=1,c=true)"
+ + "&f09=((a=a,b=1,c=true))&f09=((a=a,b=1,c=true))"
+ + "&f10=((a=a,b=1,c=true))&f10=((a=a,b=1,c=true))"
+ + "&f11=a&f11=b"
+ + "&f12=c&f12=d"
+ + "&f13=1&f13=2"
+ + "&f14=3&f14=4"
+ + "&f15=(e,f)&f15=(g,h)"
+ + "&f16=(i,j)&f16=(k,l)"
+ + "&f17=(a=a,b=1,c=true)&f17=(a=a,b=1,c=true)"
+ + "&f18=(a=a,b=1,c=true)&f18=(a=a,b=1,c=true)"
+ + "&f19=((a=a,b=1,c=true))&f19=((a=a,b=1,c=true))"
+ + "&f20=((a=a,b=1,c=true))&f20=((a=a,b=1,c=true))";
+ assertEquals(e, r);
+ }
+
+ @Test
+ @SuppressWarnings("hiding")
+ public void testMultiPartParametersOnMapOfStringArrays() throws Exception {
+ UrlEncodingSerializer s;
+ String r;
+
+ Map<String,String[]> t = new LinkedHashMap<String,String[]>();
+ t.put("f1", new String[]{"bar"});
+ t.put("f2", new String[]{"bar","baz"});
+ t.put("f3", new String[]{});
+ s = UrlEncodingSerializer.DEFAULT_SIMPLE_EXPANDED;
+ r = s.serialize(t);
+ String e = "f1=bar&f2=bar&f2=baz";
+ assertEquals(e, r);
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/utils/ArgsTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/utils/ArgsTest.java b/org.apache.juneau/src/test/java/org/apache/juneau/utils/ArgsTest.java
new file mode 100755
index 0000000..f161936
--- /dev/null
+++ b/org.apache.juneau/src/test/java/org/apache/juneau/utils/ArgsTest.java
@@ -0,0 +1,70 @@
+/***************************************************************************************************************************
+ * 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.juneau.utils;
+
+import static org.junit.Assert.*;
+
+import org.junit.*;
+
+public class ArgsTest {
+
+ //====================================================================================================
+ // test - Basic tests
+ //====================================================================================================
+ @Test
+ public void test() throws Exception {
+ Args a;
+
+ // Empty args
+ a = new Args(new String[]{});
+ assertNull(a.getArg(0));
+ assertNull(a.getArg(1));
+ assertNull(a.getArg(-1));
+ assertNull(a.getArg("foo"));
+ assertEquals(0, a.getArgs("foo").size());
+ assertFalse(a.containsKey("foo"));
+
+ a = new Args(new String[]{"foo"});
+ assertEquals("foo", a.getArg(0));
+ assertNull(a.getArg(1));
+ assertNull(a.getArg(-1));
+ assertNull(a.getArg("foo"));
+ assertEquals(0, a.getArgs("foo").size());
+ assertFalse(a.containsKey("foo"));
+
+ a = new Args(new String[]{"foo", "bar bar"});
+ assertEquals("foo", a.getArg(0));
+ assertEquals("bar bar", a.getArg(1));
+ assertNull(a.getArg(-1));
+ assertNull(a.getArg("foo"));
+ assertEquals(0, a.getArgs("foo").size());
+ assertFalse(a.containsKey("foo"));
+
+ a = new Args(new String[]{"foo", "bar bar", "-foo"});
+ assertEquals("foo", a.getArg(0));
+ assertEquals("bar bar", a.getArg(1));
+ assertNull(a.getArg(-1));
+ assertNull(a.getArg("foo"));
+ assertEquals(0, a.getArgs("foo").size());
+ assertTrue(a.containsKey("foo"));
+
+ a = new Args(new String[]{"foo", "bar bar", "-foo", "bar bar"});
+ assertEquals("foo", a.getArg(0));
+ assertEquals("bar bar", a.getArg(1));
+ assertNull(a.getArg(-1));
+ assertEquals("bar bar", a.getArg("foo"));
+ assertEquals(1, a.getArgs("foo").size());
+ assertEquals("bar bar", a.getArgs("foo").get(0));
+ assertTrue(a.containsKey("foo"));
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/utils/ArrayUtilsTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/utils/ArrayUtilsTest.java b/org.apache.juneau/src/test/java/org/apache/juneau/utils/ArrayUtilsTest.java
new file mode 100755
index 0000000..1206d59
--- /dev/null
+++ b/org.apache.juneau/src/test/java/org/apache/juneau/utils/ArrayUtilsTest.java
@@ -0,0 +1,160 @@
+/***************************************************************************************************************************
+ * 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.juneau.utils;
+
+import static org.apache.juneau.TestUtils.*;
+import static org.apache.juneau.internal.ArrayUtils.*;
+import static org.junit.Assert.*;
+
+import java.util.*;
+
+import org.junit.*;
+
+public class ArrayUtilsTest {
+
+ //====================================================================================================
+ // iterator(T[])
+ //====================================================================================================
+ @Test
+ public void testArrayIterator() throws Exception {
+ assertObjectEquals("[1,2,3]", iterator(new Object[]{1,2,3}));
+ assertObjectEquals("[1,2,3]", iterator(new int[]{1,2,3}));
+ assertObjectEquals("[]", iterator(null));
+ }
+
+ //====================================================================================================
+ // append(T[], T...)
+ //====================================================================================================
+ @Test
+ public void testAppendArrayToArray() throws Exception {
+ String[] s = new String[0];
+
+ s = append(s, "a", "b");
+ assertObjectEquals("['a','b']", s);
+
+ s = append(s, "c");
+ assertObjectEquals("['a','b','c']", s);
+
+ s = append(s);
+ assertObjectEquals("['a','b','c']", s);
+
+ Object[] o = append((Object[])null);
+ assertObjectEquals("[]", o);
+
+ s = append((String[])null, "a", "b");
+ assertObjectEquals("['a','b']", s);
+ }
+
+ //====================================================================================================
+ // append(T[], Collection)
+ //====================================================================================================
+ @Test
+ public void testAppendCollectionToArray() throws Exception {
+ String[] s = new String[0];
+
+ s = append(s, Arrays.asList(new String[]{"a","b"}));
+ assertObjectEquals("['a','b']", s);
+
+ s = append(s, Arrays.asList(new String[]{"c"}));
+ assertObjectEquals("['a','b','c']", s);
+
+ s = append(s, Arrays.asList(new String[0]));
+ assertObjectEquals("['a','b','c']", s);
+
+ try {
+ append((Object[])null, Collections.emptyList());
+ fail();
+ } catch (IllegalArgumentException e) {}
+ }
+
+ //====================================================================================================
+ // reverse(T[] array)
+ //====================================================================================================
+ @Test
+ public void testReverse() throws Exception {
+ String[] s = new String[0];
+
+ s = new String[]{"a","b"};
+ assertObjectEquals("['b','a']", reverse(s));
+
+ try {
+ reverse((Object[])null);
+ fail();
+ } catch (IllegalArgumentException e) {}
+ }
+
+ //====================================================================================================
+ // asSet(T[])
+ //====================================================================================================
+ @Test
+ public void testAsSet() throws Exception {
+ String[] s = null;
+
+ try {
+ asSet(s);
+ fail();
+ } catch (IllegalArgumentException e) {}
+
+ s = new String[]{"a"};
+ Iterator<String> i = asSet(s).iterator();
+ assertEquals("a", i.next());
+
+ try {
+ i.remove();
+ fail();
+ } catch (UnsupportedOperationException e) {}
+
+ try {
+ i.next();
+ fail();
+ } catch (NoSuchElementException e) {}
+ }
+
+ //====================================================================================================
+ // iterator(T[])
+ //====================================================================================================
+ @Test
+ public void testIterator() throws Exception {
+ String[] s = null;
+
+ s = new String[]{"a"};
+ Iterator<Object> i = iterator(s);
+ assertEquals("a", i.next());
+
+ try {
+ i.remove();
+ fail();
+ } catch (UnsupportedOperationException e) {}
+
+ try {
+ i.next();
+ fail();
+ } catch (NoSuchElementException e) {}
+ }
+
+ //====================================================================================================
+ // combine(T[]...)
+ //====================================================================================================
+ @Test
+ public void testCombine() throws Exception {
+ String[] s1 = new String[]{"a"}, s2 = new String[]{"b"};
+
+ assertObjectEquals("['a','b']", combine(s1, s2));
+ assertObjectEquals("['a']", combine(s1));
+ assertObjectEquals("['b']", combine(s2));
+ assertObjectEquals("['a']", combine(s1,null));
+ assertObjectEquals("['b']", combine(null,s2));
+ assertNull(combine(null,null));
+ assertNull(combine());
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/utils/ByteArrayCacheTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/utils/ByteArrayCacheTest.java b/org.apache.juneau/src/test/java/org/apache/juneau/utils/ByteArrayCacheTest.java
new file mode 100755
index 0000000..ad4a29c
--- /dev/null
+++ b/org.apache.juneau/src/test/java/org/apache/juneau/utils/ByteArrayCacheTest.java
@@ -0,0 +1,60 @@
+/***************************************************************************************************************************
+ * 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.juneau.utils;
+
+import static org.apache.juneau.TestUtils.*;
+import static org.junit.Assert.*;
+
+import java.io.*;
+
+import org.apache.juneau.internal.*;
+import org.junit.*;
+
+public class ByteArrayCacheTest {
+
+ //====================================================================================================
+ // testBasic
+ //====================================================================================================
+ @Test
+ public void testBasic() throws Exception {
+ ByteArrayCache bac = new ByteArrayCache();
+ byte[] b;
+
+ b = bac.cache(new byte[]{1,2,3});
+ assertObjectEquals("[1,2,3]", b);
+ assertEquals(1, bac.size());
+
+ b = bac.cache(new byte[]{1,2,3});
+ assertObjectEquals("[1,2,3]", b);
+ assertEquals(1, bac.size());
+
+ b = bac.cache(new byte[]{1,2,3,4});
+ assertObjectEquals("[1,2,3,4]", b);
+ b = bac.cache(new byte[]{1,2});
+ assertObjectEquals("[1,2]", b);
+ assertEquals(3, bac.size());
+
+ b = bac.cache(new byte[]{});
+ assertObjectEquals("[]", b);
+
+ b = bac.cache((byte[])null);
+ assertNull(b);
+
+ b = bac.cache((InputStream)null);
+ assertNull(b);
+
+ b = bac.cache(new ByteArrayInputStream(new byte[]{1,2,3}));
+ assertObjectEquals("[1,2,3]", b);
+ assertEquals(4, bac.size());
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/utils/ByteArrayInOutStreamTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/utils/ByteArrayInOutStreamTest.java b/org.apache.juneau/src/test/java/org/apache/juneau/utils/ByteArrayInOutStreamTest.java
new file mode 100755
index 0000000..9b26608
--- /dev/null
+++ b/org.apache.juneau/src/test/java/org/apache/juneau/utils/ByteArrayInOutStreamTest.java
@@ -0,0 +1,34 @@
+/***************************************************************************************************************************
+ * 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.juneau.utils;
+
+import static org.junit.Assert.*;
+
+import java.io.*;
+
+import org.apache.juneau.internal.*;
+import org.junit.*;
+
+public class ByteArrayInOutStreamTest {
+
+ //====================================================================================================
+ // testBasic
+ //====================================================================================================
+ @Test
+ public void testBasic() throws Exception {
+ InputStream is = new ByteArrayInputStream("foobar".getBytes(IOUtils.UTF8));
+ ByteArrayInOutStream baios = new ByteArrayInOutStream();
+ IOPipe.create(is, baios).run();
+ assertEquals("foobar", IOUtils.read(baios.getInputStream()));
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/utils/CT_Args.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/utils/CT_Args.java b/org.apache.juneau/src/test/java/org/apache/juneau/utils/CT_Args.java
deleted file mode 100755
index aeb6a00..0000000
--- a/org.apache.juneau/src/test/java/org/apache/juneau/utils/CT_Args.java
+++ /dev/null
@@ -1,70 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.utils;
-
-import static org.junit.Assert.*;
-
-import org.junit.*;
-
-public class CT_Args {
-
- //====================================================================================================
- // test - Basic tests
- //====================================================================================================
- @Test
- public void test() throws Exception {
- Args a;
-
- // Empty args
- a = new Args(new String[]{});
- assertNull(a.getArg(0));
- assertNull(a.getArg(1));
- assertNull(a.getArg(-1));
- assertNull(a.getArg("foo"));
- assertEquals(0, a.getArgs("foo").size());
- assertFalse(a.containsKey("foo"));
-
- a = new Args(new String[]{"foo"});
- assertEquals("foo", a.getArg(0));
- assertNull(a.getArg(1));
- assertNull(a.getArg(-1));
- assertNull(a.getArg("foo"));
- assertEquals(0, a.getArgs("foo").size());
- assertFalse(a.containsKey("foo"));
-
- a = new Args(new String[]{"foo", "bar bar"});
- assertEquals("foo", a.getArg(0));
- assertEquals("bar bar", a.getArg(1));
- assertNull(a.getArg(-1));
- assertNull(a.getArg("foo"));
- assertEquals(0, a.getArgs("foo").size());
- assertFalse(a.containsKey("foo"));
-
- a = new Args(new String[]{"foo", "bar bar", "-foo"});
- assertEquals("foo", a.getArg(0));
- assertEquals("bar bar", a.getArg(1));
- assertNull(a.getArg(-1));
- assertNull(a.getArg("foo"));
- assertEquals(0, a.getArgs("foo").size());
- assertTrue(a.containsKey("foo"));
-
- a = new Args(new String[]{"foo", "bar bar", "-foo", "bar bar"});
- assertEquals("foo", a.getArg(0));
- assertEquals("bar bar", a.getArg(1));
- assertNull(a.getArg(-1));
- assertEquals("bar bar", a.getArg("foo"));
- assertEquals(1, a.getArgs("foo").size());
- assertEquals("bar bar", a.getArgs("foo").get(0));
- assertTrue(a.containsKey("foo"));
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/utils/CT_ArrayUtils.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/utils/CT_ArrayUtils.java b/org.apache.juneau/src/test/java/org/apache/juneau/utils/CT_ArrayUtils.java
deleted file mode 100755
index c8a84df..0000000
--- a/org.apache.juneau/src/test/java/org/apache/juneau/utils/CT_ArrayUtils.java
+++ /dev/null
@@ -1,160 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.utils;
-
-import static org.apache.juneau.TestUtils.*;
-import static org.apache.juneau.internal.ArrayUtils.*;
-import static org.junit.Assert.*;
-
-import java.util.*;
-
-import org.junit.*;
-
-public class CT_ArrayUtils {
-
- //====================================================================================================
- // iterator(T[])
- //====================================================================================================
- @Test
- public void testArrayIterator() throws Exception {
- assertObjectEquals("[1,2,3]", iterator(new Object[]{1,2,3}));
- assertObjectEquals("[1,2,3]", iterator(new int[]{1,2,3}));
- assertObjectEquals("[]", iterator(null));
- }
-
- //====================================================================================================
- // append(T[], T...)
- //====================================================================================================
- @Test
- public void testAppendArrayToArray() throws Exception {
- String[] s = new String[0];
-
- s = append(s, "a", "b");
- assertObjectEquals("['a','b']", s);
-
- s = append(s, "c");
- assertObjectEquals("['a','b','c']", s);
-
- s = append(s);
- assertObjectEquals("['a','b','c']", s);
-
- Object[] o = append((Object[])null);
- assertObjectEquals("[]", o);
-
- s = append((String[])null, "a", "b");
- assertObjectEquals("['a','b']", s);
- }
-
- //====================================================================================================
- // append(T[], Collection)
- //====================================================================================================
- @Test
- public void testAppendCollectionToArray() throws Exception {
- String[] s = new String[0];
-
- s = append(s, Arrays.asList(new String[]{"a","b"}));
- assertObjectEquals("['a','b']", s);
-
- s = append(s, Arrays.asList(new String[]{"c"}));
- assertObjectEquals("['a','b','c']", s);
-
- s = append(s, Arrays.asList(new String[0]));
- assertObjectEquals("['a','b','c']", s);
-
- try {
- append((Object[])null, Collections.emptyList());
- fail();
- } catch (IllegalArgumentException e) {}
- }
-
- //====================================================================================================
- // reverse(T[] array)
- //====================================================================================================
- @Test
- public void testReverse() throws Exception {
- String[] s = new String[0];
-
- s = new String[]{"a","b"};
- assertObjectEquals("['b','a']", reverse(s));
-
- try {
- reverse((Object[])null);
- fail();
- } catch (IllegalArgumentException e) {}
- }
-
- //====================================================================================================
- // asSet(T[])
- //====================================================================================================
- @Test
- public void testAsSet() throws Exception {
- String[] s = null;
-
- try {
- asSet(s);
- fail();
- } catch (IllegalArgumentException e) {}
-
- s = new String[]{"a"};
- Iterator<String> i = asSet(s).iterator();
- assertEquals("a", i.next());
-
- try {
- i.remove();
- fail();
- } catch (UnsupportedOperationException e) {}
-
- try {
- i.next();
- fail();
- } catch (NoSuchElementException e) {}
- }
-
- //====================================================================================================
- // iterator(T[])
- //====================================================================================================
- @Test
- public void testIterator() throws Exception {
- String[] s = null;
-
- s = new String[]{"a"};
- Iterator<Object> i = iterator(s);
- assertEquals("a", i.next());
-
- try {
- i.remove();
- fail();
- } catch (UnsupportedOperationException e) {}
-
- try {
- i.next();
- fail();
- } catch (NoSuchElementException e) {}
- }
-
- //====================================================================================================
- // combine(T[]...)
- //====================================================================================================
- @Test
- public void testCombine() throws Exception {
- String[] s1 = new String[]{"a"}, s2 = new String[]{"b"};
-
- assertObjectEquals("['a','b']", combine(s1, s2));
- assertObjectEquals("['a']", combine(s1));
- assertObjectEquals("['b']", combine(s2));
- assertObjectEquals("['a']", combine(s1,null));
- assertObjectEquals("['b']", combine(null,s2));
- assertNull(combine(null,null));
- assertNull(combine());
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/utils/CT_ByteArrayCache.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/utils/CT_ByteArrayCache.java b/org.apache.juneau/src/test/java/org/apache/juneau/utils/CT_ByteArrayCache.java
deleted file mode 100755
index 6cdf700..0000000
--- a/org.apache.juneau/src/test/java/org/apache/juneau/utils/CT_ByteArrayCache.java
+++ /dev/null
@@ -1,60 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.utils;
-
-import static org.apache.juneau.TestUtils.*;
-import static org.junit.Assert.*;
-
-import java.io.*;
-
-import org.apache.juneau.internal.*;
-import org.junit.*;
-
-public class CT_ByteArrayCache {
-
- //====================================================================================================
- // testBasic
- //====================================================================================================
- @Test
- public void testBasic() throws Exception {
- ByteArrayCache bac = new ByteArrayCache();
- byte[] b;
-
- b = bac.cache(new byte[]{1,2,3});
- assertObjectEquals("[1,2,3]", b);
- assertEquals(1, bac.size());
-
- b = bac.cache(new byte[]{1,2,3});
- assertObjectEquals("[1,2,3]", b);
- assertEquals(1, bac.size());
-
- b = bac.cache(new byte[]{1,2,3,4});
- assertObjectEquals("[1,2,3,4]", b);
- b = bac.cache(new byte[]{1,2});
- assertObjectEquals("[1,2]", b);
- assertEquals(3, bac.size());
-
- b = bac.cache(new byte[]{});
- assertObjectEquals("[]", b);
-
- b = bac.cache((byte[])null);
- assertNull(b);
-
- b = bac.cache((InputStream)null);
- assertNull(b);
-
- b = bac.cache(new ByteArrayInputStream(new byte[]{1,2,3}));
- assertObjectEquals("[1,2,3]", b);
- assertEquals(4, bac.size());
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/utils/CT_ByteArrayInOutStream.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/utils/CT_ByteArrayInOutStream.java b/org.apache.juneau/src/test/java/org/apache/juneau/utils/CT_ByteArrayInOutStream.java
deleted file mode 100755
index 3133cb8..0000000
--- a/org.apache.juneau/src/test/java/org/apache/juneau/utils/CT_ByteArrayInOutStream.java
+++ /dev/null
@@ -1,34 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.utils;
-
-import static org.junit.Assert.*;
-
-import java.io.*;
-
-import org.apache.juneau.internal.*;
-import org.junit.*;
-
-public class CT_ByteArrayInOutStream {
-
- //====================================================================================================
- // testBasic
- //====================================================================================================
- @Test
- public void testBasic() throws Exception {
- InputStream is = new ByteArrayInputStream("foobar".getBytes(IOUtils.UTF8));
- ByteArrayInOutStream baios = new ByteArrayInOutStream();
- IOPipe.create(is, baios).run();
- assertEquals("foobar", IOUtils.read(baios.getInputStream()));
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/utils/CT_CharSet.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/utils/CT_CharSet.java b/org.apache.juneau/src/test/java/org/apache/juneau/utils/CT_CharSet.java
deleted file mode 100755
index 31af21a..0000000
--- a/org.apache.juneau/src/test/java/org/apache/juneau/utils/CT_CharSet.java
+++ /dev/null
@@ -1,34 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.utils;
-
-import static org.junit.Assert.*;
-
-import org.apache.juneau.internal.*;
-import org.junit.*;
-
-public class CT_CharSet {
-
- //====================================================================================================
- // test - Basic tests
- //====================================================================================================
- @Test
- public void test() throws Exception {
- AsciiSet cs = new AsciiSet("abc\u1234");
- assertTrue(cs.contains('a'));
- assertFalse(cs.contains('d'));
- assertFalse(cs.contains('\u1234'));
- assertFalse(cs.contains((char)-1));
- assertFalse(cs.contains((char)128));
- }
-}
[04/44] incubator-juneau git commit: Rename CT_* testcases.
Posted by ja...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/utils/PojoRestTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/utils/PojoRestTest.java b/org.apache.juneau/src/test/java/org/apache/juneau/utils/PojoRestTest.java
new file mode 100755
index 0000000..ae945b1
--- /dev/null
+++ b/org.apache.juneau/src/test/java/org/apache/juneau/utils/PojoRestTest.java
@@ -0,0 +1,852 @@
+/***************************************************************************************************************************
+ * 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.juneau.utils;
+
+import static org.apache.juneau.serializer.SerializerContext.*;
+import static org.junit.Assert.*;
+
+import java.util.*;
+
+import org.apache.juneau.*;
+import org.apache.juneau.json.*;
+import org.apache.juneau.parser.*;
+import org.junit.*;
+
+@SuppressWarnings({"unchecked","rawtypes","serial"})
+public class PojoRestTest {
+
+ //====================================================================================================
+ // testBasic
+ //====================================================================================================
+ @Test
+ public void testBasic() {
+
+ // TODO: Need to write some exhaustive tests here. Will open work item
+ // to do that later.
+ PojoRest model = new PojoRest(new ObjectMap()); // An empty model.
+
+ // Do a PUT
+ model.put("A", new ObjectMap());
+ model.put("A/B", new ObjectMap());
+ model.put("A/B/C", "A new string");
+ assertEquals("{A:{B:{C:'A new string'}}}", model.toString());
+
+ // Do a POST to a list.
+ model.put("A/B/C", new LinkedList());
+ model.post("A/B/C", "String #1");
+ model.post("A/B/C", "String #2");
+ assertEquals("{A:{B:{C:['String #1\','String #2']}}}", model.toString());
+
+ // Do some GETs
+ String s = (String) model.get("A/B/C/0");
+ assertEquals("String #1", s);
+
+ Map m = (Map) model.get("A/B");
+ assertEquals("{C:['String #1','String #2']}", m.toString());
+ }
+
+ //====================================================================================================
+ // testBeans
+ //====================================================================================================
+ @Test
+ public void testBeans() throws Exception {
+ PojoRest model;
+
+ // Java beans.
+ model = new PojoRest(new ObjectMap());
+ Person p = new Person("some name", 123,
+ new Address("street A", "city A", "state A", 12345, true),
+ new Address("street B", "city B", "state B", 12345, false)
+ );
+ model.put("/person1", p);
+
+ // Make sure it got stored correctly.
+ JsonSerializer serializer = JsonSerializer.DEFAULT_LAX;
+ assertEquals("{person1:{name:'some name',age:123,addresses:[{street:'street A',city:'city A',state:'state A',zip:12345,isCurrent:true},{street:'street B',city:'city B',state:'state B',zip:12345,isCurrent:false}]}}", serializer.serialize(model.getRootObject()));
+
+ // Get the original Person object back.
+ p = (Person)model.get("/person1");
+ assertEquals("city B", p.addresses[1].city);
+
+ // Look for deep information inside beans.
+ Address a3 = (Address)model.get("/person1/addresses/1");
+ assertEquals("city B", a3.city);
+
+ serializer = new JsonSerializer.Simple().setProperty(SERIALIZER_addClassAttrs, true);
+ p = new Person("some name", 123,
+ new Address("street A", "city A", "state A", 12345, true),
+ new Address("street B", "city B", "state B", 12345, false)
+ );
+
+ // Serialize it to JSON.
+ String s = serializer.serialize(p);
+ String expectedValue = "{_class:'org.apache.juneau.utils.PojoRestTest$Person',name:'some name',age:123,addresses:[{street:'street A',city:'city A',state:'state A',zip:12345,isCurrent:true},{street:'street B',city:'city B',state:'state B',zip:12345,isCurrent:false}]}";
+ assertEquals(expectedValue, s);
+
+ // Parse it back to Java objects.
+ p = (Person)JsonParser.DEFAULT.clone().setClassLoader(getClass().getClassLoader()).parse(s, Object.class);
+ expectedValue = "city B";
+ s = p.addresses[1].city;
+ assertEquals(expectedValue, s);
+
+ // Parse it back into JSON again.
+ s = serializer.serialize(p);
+ expectedValue = "{_class:'org.apache.juneau.utils.PojoRestTest$Person',name:'some name',age:123,addresses:[{street:'street A',city:'city A',state:'state A',zip:12345,isCurrent:true},{street:'street B',city:'city B',state:'state B',zip:12345,isCurrent:false}]}";
+ assertEquals(expectedValue, s);
+
+ // Try adding an address
+ model = new PojoRest(p);
+ model.post("addresses", new Address("street C", "city C", "state C", 12345, true));
+ s = ((Address)model.get("addresses/2")).toString();
+ expectedValue = "Address(street=street C,city=city C,state=state C,zip=12345,isCurrent=true)";
+ assertEquals(expectedValue, s);
+
+ // Try replacing addresses
+ model.put("addresses/0", new Address("street D", "city D", "state D", 12345, false));
+ model.put("addresses/1", new Address("street E", "city E", "state E", 12345, false));
+ model.put("addresses/2", new Address("street F", "city F", "state F", 12345, false));
+ serializer = JsonSerializer.DEFAULT_LAX;
+ s = serializer.serialize(p);
+ expectedValue = "{name:'some name',age:123,addresses:[{street:'street D',city:'city D',state:'state D',zip:12345,isCurrent:false},{street:'street E',city:'city E',state:'state E',zip:12345,isCurrent:false},{street:'street F',city:'city F',state:'state F',zip:12345,isCurrent:false}]}";
+ assertEquals(expectedValue, s);
+
+ // Try removing an address
+ model.delete("addresses/1");
+ s = serializer.serialize(p);
+ expectedValue = "{name:'some name',age:123,addresses:[{street:'street D',city:'city D',state:'state D',zip:12345,isCurrent:false},{street:'street F',city:'city F',state:'state F',zip:12345,isCurrent:false}]}";
+ assertEquals(expectedValue, s);
+
+ model.delete("addresses/0");
+ model.delete("addresses/0");
+ s = serializer.serialize(p);
+ expectedValue = "{name:'some name',age:123,addresses:[]}";
+ assertEquals(expectedValue, s);
+
+ // Try adding an out-of-bounds address (should pad it with nulls)
+ model.put("addresses/2", new Address("street A", "city A", "state A", 12345, true));
+ s = serializer.serialize(p);
+ expectedValue = "{name:'some name',age:123,addresses:[null,null,{street:'street A',city:'city A',state:'state A',zip:12345,isCurrent:true}]}";
+ assertEquals(expectedValue, s);
+
+ // Try adding an address as a map (should be automatically converted to an Address)
+ Map m = new HashMap();
+ m.put("street","street D");
+ m.put("city","city D");
+ m.put("state","state D");
+ m.put("zip",new Integer(12345));
+
+ // Try the same for an address in an array.
+ model.put("addresses/1", m);
+ s = ((Address)model.get("addresses/1")).toString();
+ expectedValue = "Address(street=street D,city=city D,state=state D,zip=12345,isCurrent=false)";
+ assertEquals(expectedValue, s);
+
+ // Try setting some fields.
+ model.put("addresses/1/zip", new Integer(99999));
+ s = model.get("addresses/1/zip").toString();
+ expectedValue = "99999";
+ assertEquals(expectedValue, s);
+
+ // Make sure we can get non-existent branches without throwing any exceptions.
+ // get() method should just return null.
+ model = new PojoRest(new ObjectMap());
+ Object o = model.get("xxx");
+ assertEquals("null", (""+o));
+
+ // Make sure blanks and "/" returns the root object.
+ s = model.get("").toString();
+ assertEquals("{}", s);
+ s = model.get("/").toString();
+ assertEquals("{}", s);
+
+ // Make sure doing a PUT against "" or "/" replaces the root object.
+ ObjectMap m2 = new ObjectMap("{x:1}");
+ model.put("", m2);
+ s = model.get("").toString();
+ assertEquals("{x:1}", s);
+ m2 = new ObjectMap("{x:2}");
+ model.put("/", m2);
+ s = model.get("").toString();
+ assertEquals("{x:2}", s);
+
+ // Make sure doing a POST against "" or "/" adds to the root object.
+ model = new PojoRest(new ObjectList());
+ model.post("", new Integer(1));
+ model.post("/", new Integer(2));
+ s = model.get("").toString();
+ assertEquals("[1,2]", s);
+ }
+
+ //====================================================================================================
+ // testAddressBook
+ //====================================================================================================
+ @Test
+ public void testAddressBook() {
+ PojoRest model;
+
+ model = new PojoRest(new AddressBook());
+
+ // Try adding a person to the address book.
+ Person billClinton = new Person("Bill Clinton", 65,
+ new Address("55W. 125th Street", "New York", "NY", 10027, true)
+ );
+
+ model.post("/", billClinton);
+
+ // Make sure we get the original person back.
+ billClinton = (Person)model.get("/0");
+ }
+
+
+ public static class AddressBook extends LinkedList<Person> {
+
+ public AddressBook init() {
+ add(
+ new Person("Bill Clinton", 65,
+ new Address("55W. 125th Street", "New York", "NY", 10027, true)
+ )
+ );
+ return this;
+ }
+ }
+
+ public static class Address {
+ public String street;
+ public String city;
+ public String state;
+ public int zip;
+ public boolean isCurrent;
+
+ public Address() {}
+
+ public Address(String street, String city, String state, int zip, boolean isCurrent) {
+ this.street = street;
+ this.city = city;
+ this.state = state;
+ this.zip = zip;
+ this.isCurrent = isCurrent;
+ }
+ @Override /* Object */
+ public String toString() {
+ return "Address(street="+street+",city="+city+",state="+state+",zip="+zip+",isCurrent="+isCurrent+")";
+ }
+ }
+
+ public static class Person {
+ public String name;
+ public int age;
+ public Address[] addresses;
+
+ public Person() {}
+
+ public Person(String name, int age, Address...addresses) {
+ this.name = name;
+ this.age = age;
+ this.addresses = addresses;
+ }
+
+ @Override /* Object */
+ public String toString() {
+ return "Person(name="+name+",age="+age+")";
+ }
+ }
+
+ //====================================================================================================
+ // PojoRest(Object,ReaderParser)
+ //====================================================================================================
+ @Test
+ public void testConstructors() throws Exception {
+ PojoRest model = new PojoRest(new AddressBook(), JsonParser.DEFAULT);
+
+ // Try adding a person to the address book.
+ Person billClinton = new Person("Bill Clinton", 65,
+ new Address("55W. 125th Street", "New York", "NY", 10027, true)
+ );
+
+ model.post("/", billClinton);
+
+ // Make sure we get the original person back.
+ billClinton = (Person)model.get("/0");
+ }
+
+ //====================================================================================================
+ // setRootLocked()
+ //====================================================================================================
+ @Test
+ public void testRootLocked() throws Exception {
+ PojoRest model = new PojoRest(new AddressBook()).setRootLocked();
+ try {
+ model.put("", new AddressBook());
+ fail();
+ } catch (PojoRestException e) {
+ assertEquals("Cannot overwrite root object", e.getLocalizedMessage());
+ }
+ try {
+ model.put(null, new AddressBook());
+ fail();
+ } catch (PojoRestException e) {
+ assertEquals("Cannot overwrite root object", e.getLocalizedMessage());
+ }
+ try {
+ model.put("/", new AddressBook());
+ fail();
+ } catch (PojoRestException e) {
+ assertEquals("Cannot overwrite root object", e.getLocalizedMessage());
+ }
+ }
+
+ //====================================================================================================
+ // getRootObject()
+ //====================================================================================================
+ @Test
+ public void testGetRootObject() throws Exception {
+ PojoRest model = new PojoRest(new AddressBook());
+ assertTrue(model.getRootObject() instanceof AddressBook);
+ model.put("", "foobar");
+ assertTrue(model.getRootObject() instanceof String);
+ model.put("", null);
+ assertNull(model.getRootObject());
+ }
+
+ //====================================================================================================
+ // get(Class<T> type, String url)
+ // get(Class<T> type, String url, T def)
+ // getString(String url)
+ // getString(String url, String defVal)
+ // getInt(String url)
+ // getInt(String url, Integer defVal)
+ // getLong(String url)
+ // getLong(String url, Long defVal)
+ // getBoolean(String url)
+ // getBoolean(String url, Boolean defVal)
+ // getMap(String url)
+ // getMap(String url, Map<?,?> defVal)
+ // getList(String url)
+ // getList(String url, List<?> defVal)
+ // getObjectMap(String url)
+ // getObjectMap(String url, ObjectMap defVal)
+ // getObjectList(String url)
+ // getObjectList(String url, ObjectList defVal)
+ //====================================================================================================
+ @Test
+ public void testGetMethods() throws Exception {
+ PojoRest model = new PojoRest(new A());
+ ObjectList l = new ObjectList("[{a:'b'}]");
+ ObjectMap m = new ObjectMap("{a:'b'}");
+
+ assertNull(model.get("f1"));
+ assertEquals(0, model.get("f2"));
+ assertEquals(0l, model.get("f3"));
+ assertFalse((Boolean)model.get("f4"));
+ assertNull(model.get("f2a"));
+ assertNull(model.get("f3a"));
+ assertNull(model.get("f4a"));
+ assertNull(model.get("f5"));
+ assertNull(model.get("f6"));
+ assertNull(model.get("f7"));
+ assertNull(model.get("f8"));
+
+ assertEquals("foo", model.get("f1", "foo"));
+ assertEquals(0, model.get("f2", "foo"));
+ assertEquals(0l, model.get("f3", "foo"));
+ assertEquals(false, model.get("f4", "foo"));
+ assertEquals("foo", model.get("f2a", "foo"));
+ assertEquals("foo", model.get("f3a", "foo"));
+ assertEquals("foo", model.get("f4a", "foo"));
+ assertEquals("foo", model.get("f5", "foo"));
+ assertEquals("foo", model.get("f6", "foo"));
+ assertEquals("foo", model.get("f7", "foo"));
+ assertEquals("foo", model.get("f8", "foo"));
+
+ assertNull(model.getString("f1"));
+ assertEquals("0", model.getString("f2"));
+ assertEquals("0", model.getString("f3"));
+ assertEquals("false", model.getString("f4"));
+ assertNull(model.getString("f2a"));
+ assertNull(model.getString("f3a"));
+ assertNull(model.getString("f4a"));
+ assertNull(model.getString("f5"));
+ assertNull(model.getString("f6"));
+ assertNull(model.getString("f7"));
+ assertNull(model.getString("f8"));
+
+ assertEquals("foo", model.getString("f1", "foo"));
+ assertEquals("0", model.getString("f2", "foo"));
+ assertEquals("0", model.getString("f3", "foo"));
+ assertEquals("false", model.getString("f4", "foo"));
+ assertEquals("foo", model.getString("f2a", "foo"));
+ assertEquals("foo", model.getString("f3a", "foo"));
+ assertEquals("foo", model.getString("f4a", "foo"));
+ assertEquals("foo", model.getString("f5", "foo"));
+ assertEquals("foo", model.getString("f6", "foo"));
+ assertEquals("foo", model.getString("f7", "foo"));
+ assertEquals("foo", model.getString("f8", "foo"));
+
+ assertNull(model.getInt("f1"));
+ assertEquals(0, (int)model.getInt("f2"));
+ assertEquals(0, (int)model.getInt("f3"));
+ assertEquals(0, (int)model.getInt("f4"));
+ assertNull(model.getInt("f2a"));
+ assertNull(model.getInt("f3a"));
+ assertNull(model.getInt("f4a"));
+ assertNull(model.getInt("f5"));
+ assertNull(model.getInt("f6"));
+ assertNull(model.getInt("f7"));
+ assertNull(model.getInt("f8"));
+
+ assertEquals(1, (int)model.getInt("f1", 1));
+ assertEquals(0, (int)model.getInt("f2", 1));
+ assertEquals(0, (int)model.getInt("f3", 1));
+ assertEquals(0, (int)model.getInt("f4", 1));
+ assertEquals(1, (int)model.getInt("f2a", 1));
+ assertEquals(1, (int)model.getInt("f3a", 1));
+ assertEquals(1, (int)model.getInt("f4a", 1));
+ assertEquals(1, (int)model.getInt("f5", 1));
+ assertEquals(1, (int)model.getInt("f6", 1));
+ assertEquals(1, (int)model.getInt("f7", 1));
+ assertEquals(1, (int)model.getInt("f8", 1));
+
+ assertNull(model.getLong("f1"));
+ assertEquals(0, (long)model.getLong("f2"));
+ assertEquals(0, (long)model.getLong("f3"));
+ assertEquals(0, (long)model.getLong("f4"));
+ assertNull(model.getLong("f2a"));
+ assertNull(model.getLong("f3a"));
+ assertNull(model.getLong("f4a"));
+ assertNull(model.getLong("f5"));
+ assertNull(model.getLong("f6"));
+ assertNull(model.getLong("f7"));
+ assertNull(model.getLong("f8"));
+
+ assertEquals(1, (long)model.getLong("f1", 1l));
+ assertEquals(0, (long)model.getLong("f2", 1l));
+ assertEquals(0, (long)model.getLong("f3", 1l));
+ assertEquals(0, (long)model.getLong("f4", 1l));
+ assertEquals(1, (long)model.getLong("f2a", 1l));
+ assertEquals(1, (long)model.getLong("f3a", 1l));
+ assertEquals(1, (long)model.getLong("f4a", 1l));
+ assertEquals(1, (long)model.getLong("f5", 1l));
+ assertEquals(1, (long)model.getLong("f6", 1l));
+ assertEquals(1, (long)model.getLong("f7", 1l));
+ assertEquals(1, (long)model.getLong("f8", 1l));
+
+ assertNull(model.getBoolean("f1"));
+ assertEquals(false, model.getBoolean("f2"));
+ assertEquals(false, model.getBoolean("f3"));
+ assertEquals(false, model.getBoolean("f4"));
+ assertNull(model.getBoolean("f2a"));
+ assertNull(model.getBoolean("f3a"));
+ assertNull(model.getBoolean("f4a"));
+ assertNull(model.getBoolean("f5"));
+ assertNull(model.getBoolean("f6"));
+ assertNull(model.getBoolean("f7"));
+ assertNull(model.getBoolean("f8"));
+
+ assertEquals(true, model.getBoolean("f1", true));
+ assertEquals(false, model.getBoolean("f2", true));
+ assertEquals(false, model.getBoolean("f3", true));
+ assertEquals(false, model.getBoolean("f4", true));
+ assertEquals(true, model.getBoolean("f2a", true));
+ assertEquals(true, model.getBoolean("f3a", true));
+ assertEquals(true, model.getBoolean("f4a", true));
+ assertEquals(true, model.getBoolean("f5", true));
+ assertEquals(true, model.getBoolean("f6", true));
+ assertEquals(true, model.getBoolean("f7", true));
+ assertEquals(true, model.getBoolean("f8", true));
+
+ assertNull(model.getMap("f1"));
+ try { model.getMap("f2"); fail(); } catch (InvalidDataConversionException e) {}
+ try { model.getMap("f3"); fail(); } catch (InvalidDataConversionException e) {}
+ try { model.getMap("f4"); fail(); } catch (InvalidDataConversionException e) {}
+ assertNull(model.getMap("f2a"));
+ assertNull(model.getMap("f3a"));
+ assertNull(model.getMap("f4a"));
+ assertNull(model.getMap("f5"));
+ assertNull(model.getMap("f6"));
+ assertNull(model.getMap("f7"));
+ assertNull(model.getMap("f8"));
+
+ assertEquals("{a:'b'}", model.getMap("f1", m).toString());
+ try { model.getMap("f2", m); fail(); } catch (InvalidDataConversionException e) {}
+ try { model.getMap("f3", m); fail(); } catch (InvalidDataConversionException e) {}
+ try { model.getMap("f4", m); fail(); } catch (InvalidDataConversionException e) {}
+ assertEquals("{a:'b'}", model.getMap("f2a", m).toString());
+ assertEquals("{a:'b'}", model.getMap("f3a", m).toString());
+ assertEquals("{a:'b'}", model.getMap("f4a", m).toString());
+ assertEquals("{a:'b'}", model.getMap("f5", m).toString());
+ assertEquals("{a:'b'}", model.getMap("f6", m).toString());
+ assertEquals("{a:'b'}", model.getMap("f7", m).toString());
+ assertEquals("{a:'b'}", model.getMap("f8", m).toString());
+
+ assertNull(model.getMap("f1"));
+ try { model.getObjectMap("f2"); fail(); } catch (InvalidDataConversionException e) {}
+ try { model.getObjectMap("f3"); fail(); } catch (InvalidDataConversionException e) {}
+ try { model.getObjectMap("f4"); fail(); } catch (InvalidDataConversionException e) {}
+ assertNull(model.getObjectMap("f2a"));
+ assertNull(model.getObjectMap("f3a"));
+ assertNull(model.getObjectMap("f4a"));
+ assertNull(model.getObjectMap("f5"));
+ assertNull(model.getObjectMap("f6"));
+ assertNull(model.getObjectMap("f7"));
+ assertNull(model.getObjectMap("f8"));
+
+ assertEquals("{a:'b'}", model.getObjectMap("f1", m).toString());
+ try { model.getObjectMap("f2", m); fail(); } catch (InvalidDataConversionException e) {}
+ try { model.getObjectMap("f3", m); fail(); } catch (InvalidDataConversionException e) {}
+ try { model.getObjectMap("f4", m); fail(); } catch (InvalidDataConversionException e) {}
+ assertEquals("{a:'b'}", model.getObjectMap("f2a", m).toString());
+ assertEquals("{a:'b'}", model.getObjectMap("f3a", m).toString());
+ assertEquals("{a:'b'}", model.getObjectMap("f4a", m).toString());
+ assertEquals("{a:'b'}", model.getObjectMap("f5", m).toString());
+ assertEquals("{a:'b'}", model.getObjectMap("f6", m).toString());
+ assertEquals("{a:'b'}", model.getObjectMap("f7", m).toString());
+ assertEquals("{a:'b'}", model.getObjectMap("f8", m).toString());
+
+ assertNull(model.getList("f1"));
+ try { model.getList("f2"); fail(); } catch (InvalidDataConversionException e) {}
+ try { model.getList("f3"); fail(); } catch (InvalidDataConversionException e) {}
+ try { model.getList("f4"); fail(); } catch (InvalidDataConversionException e) {}
+ assertNull(model.getList("f2a"));
+ assertNull(model.getList("f3a"));
+ assertNull(model.getList("f4a"));
+ assertNull(model.getList("f5"));
+ assertNull(model.getList("f6"));
+ assertNull(model.getList("f7"));
+ assertNull(model.getList("f8"));
+
+ assertEquals("[{a:'b'}]", model.getList("f1", l).toString());
+ try { model.getList("f2", l); fail(); } catch (InvalidDataConversionException e) {}
+ try { model.getList("f3", l); fail(); } catch (InvalidDataConversionException e) {}
+ try { model.getList("f4", l); fail(); } catch (InvalidDataConversionException e) {}
+ assertEquals("[{a:'b'}]", model.getList("f2a", l).toString());
+ assertEquals("[{a:'b'}]", model.getList("f3a", l).toString());
+ assertEquals("[{a:'b'}]", model.getList("f4a", l).toString());
+ assertEquals("[{a:'b'}]", model.getList("f5", l).toString());
+ assertEquals("[{a:'b'}]", model.getList("f6", l).toString());
+ assertEquals("[{a:'b'}]", model.getList("f7", l).toString());
+ assertEquals("[{a:'b'}]", model.getList("f8", l).toString());
+
+ assertNull(model.getObjectList("f1"));
+ try { model.getObjectList("f2"); fail(); } catch (InvalidDataConversionException e) {}
+ try { model.getObjectList("f3"); fail(); } catch (InvalidDataConversionException e) {}
+ try { model.getObjectList("f4"); fail(); } catch (InvalidDataConversionException e) {}
+ assertNull(model.getObjectList("f2a"));
+ assertNull(model.getObjectList("f3a"));
+ assertNull(model.getObjectList("f4a"));
+ assertNull(model.getObjectList("f5"));
+ assertNull(model.getObjectList("f6"));
+ assertNull(model.getObjectList("f7"));
+ assertNull(model.getObjectList("f8"));
+
+ assertEquals("[{a:'b'}]", model.getObjectList("f1", l).toString());
+ try { model.getObjectList("f2", l); fail(); } catch (InvalidDataConversionException e) {}
+ try { model.getObjectList("f3", l); fail(); } catch (InvalidDataConversionException e) {}
+ try { model.getObjectList("f4", l); fail(); } catch (InvalidDataConversionException e) {}
+ assertEquals("[{a:'b'}]", model.getObjectList("f2a", l).toString());
+ assertEquals("[{a:'b'}]", model.getObjectList("f3a", l).toString());
+ assertEquals("[{a:'b'}]", model.getObjectList("f4a", l).toString());
+ assertEquals("[{a:'b'}]", model.getObjectList("f5", l).toString());
+ assertEquals("[{a:'b'}]", model.getObjectList("f6", l).toString());
+ assertEquals("[{a:'b'}]", model.getObjectList("f7", l).toString());
+ assertEquals("[{a:'b'}]", model.getObjectList("f8", l).toString());
+
+ ((A)model.getRootObject()).init();
+
+ assertEquals("1", model.get("f1"));
+ assertEquals("2", model.get("f2").toString());
+ assertEquals("3", model.get("f3").toString());
+ assertEquals("true", model.get("f4").toString());
+ assertEquals("2", model.get("f2a").toString());
+ assertEquals("3", model.get("f3a").toString());
+ assertEquals("true", model.get("f4a").toString());
+ assertEquals("{f5a:'a'}", model.get("f5").toString());
+ assertEquals("[{f6a:'a'}]", model.get("f6").toString());
+ assertEquals("{f5a:'a'}", model.get("f7").toString());
+ assertEquals("[{f6a:'a'}]", model.get("f8").toString());
+
+ assertEquals("1", model.get("f1", "foo"));
+ assertEquals("2", model.get("f2", "foo").toString());
+ assertEquals("3", model.get("f3", "foo").toString());
+ assertEquals("true", model.get("f4", "foo").toString());
+ assertEquals("2", model.get("f2a", "foo").toString());
+ assertEquals("3", model.get("f3a", "foo").toString());
+ assertEquals("true", model.get("f4a", "foo").toString());
+ assertEquals("{f5a:'a'}", model.get("f5", "foo").toString());
+ assertEquals("[{f6a:'a'}]", model.get("f6", "foo").toString());
+ assertEquals("{f5a:'a'}", model.get("f7", "foo").toString());
+ assertEquals("[{f6a:'a'}]", model.get("f8", "foo").toString());
+
+ assertEquals("1", model.getString("f1"));
+ assertEquals("2", model.getString("f2"));
+ assertEquals("3", model.getString("f3"));
+ assertEquals("true", model.getString("f4"));
+ assertEquals("2", model.getString("f2a"));
+ assertEquals("3", model.getString("f3a"));
+ assertEquals("true", model.getString("f4a"));
+ assertEquals("{f5a:'a'}", model.getString("f5"));
+ assertEquals("[{f6a:'a'}]", model.getString("f6"));
+ assertEquals("{f5a:'a'}", model.getString("f7"));
+ assertEquals("[{f6a:'a'}]", model.getString("f8"));
+
+ assertEquals("1", model.getString("f1", "foo"));
+ assertEquals("2", model.getString("f2", "foo"));
+ assertEquals("3", model.getString("f3", "foo"));
+ assertEquals("true", model.getString("f4", "foo"));
+ assertEquals("2", model.getString("f2a", "foo"));
+ assertEquals("3", model.getString("f3a", "foo"));
+ assertEquals("true", model.getString("f4a", "foo"));
+ assertEquals("{f5a:'a'}", model.getString("f5", "foo"));
+ assertEquals("[{f6a:'a'}]", model.getString("f6", "foo"));
+ assertEquals("{f5a:'a'}", model.getString("f7", "foo"));
+ assertEquals("[{f6a:'a'}]", model.getString("f8", "foo"));
+
+ assertEquals(1, (int)model.getInt("f1"));
+ assertEquals(2, (int)model.getInt("f2"));
+ assertEquals(3, (int)model.getInt("f3"));
+ assertEquals(1, (int)model.getInt("f4"));
+ assertEquals(2, (int)model.getInt("f2a"));
+ assertEquals(3, (int)model.getInt("f3a"));
+ assertEquals(1, (int)model.getInt("f4a"));
+ try { model.getInt("f5"); fail(); } catch (InvalidDataConversionException e) {}
+ try { model.getInt("f6"); fail(); } catch (InvalidDataConversionException e) {}
+ try { model.getInt("f7"); fail(); } catch (InvalidDataConversionException e) {}
+ try { model.getInt("f8"); fail(); } catch (InvalidDataConversionException e) {}
+
+ assertEquals(1, (int)model.getInt("f1", 9));
+ assertEquals(2, (int)model.getInt("f2", 9));
+ assertEquals(3, (int)model.getInt("f3", 9));
+ assertEquals(1, (int)model.getInt("f4", 9));
+ assertEquals(2, (int)model.getInt("f2a", 9));
+ assertEquals(3, (int)model.getInt("f3a", 9));
+ assertEquals(1, (int)model.getInt("f4a", 9));
+ try { model.getInt("f5", 9); fail(); } catch (InvalidDataConversionException e) {}
+ try { model.getInt("f6", 9); fail(); } catch (InvalidDataConversionException e) {}
+ try { model.getInt("f7", 9); fail(); } catch (InvalidDataConversionException e) {}
+ try { model.getInt("f8", 9); fail(); } catch (InvalidDataConversionException e) {}
+
+ assertEquals(1, (long)model.getLong("f1"));
+ assertEquals(2, (long)model.getLong("f2"));
+ assertEquals(3, (long)model.getLong("f3"));
+ assertEquals(1, (long)model.getLong("f4"));
+ assertEquals(2, (long)model.getLong("f2a"));
+ assertEquals(3, (long)model.getLong("f3a"));
+ assertEquals(1, (long)model.getLong("f4a"));
+ try { model.getLong("f5"); fail(); } catch (InvalidDataConversionException e) {}
+ try { model.getLong("f6"); fail(); } catch (InvalidDataConversionException e) {}
+ try { model.getLong("f7"); fail(); } catch (InvalidDataConversionException e) {}
+ try { model.getInt("f8"); fail(); } catch (InvalidDataConversionException e) {}
+
+ assertEquals(1, (long)model.getLong("f1", 9l));
+ assertEquals(2, (long)model.getLong("f2", 9l));
+ assertEquals(3, (long)model.getLong("f3", 9l));
+ assertEquals(1, (long)model.getLong("f4", 9l));
+ assertEquals(2, (long)model.getLong("f2a", 9l));
+ assertEquals(3, (long)model.getLong("f3a", 9l));
+ assertEquals(1, (long)model.getLong("f4a", 9l));
+ try { model.getLong("f5", 9l); fail(); } catch (InvalidDataConversionException e) {}
+ try { model.getLong("f6", 9l); fail(); } catch (InvalidDataConversionException e) {}
+ try { model.getLong("f7", 9l); fail(); } catch (InvalidDataConversionException e) {}
+ try { model.getLong("f8", 9l); fail(); } catch (InvalidDataConversionException e) {}
+
+ assertEquals(false, model.getBoolean("f1")); // String "1" equates to false.
+ assertEquals(true, model.getBoolean("f2"));
+ assertEquals(true, model.getBoolean("f3"));
+ assertEquals(true, model.getBoolean("f4"));
+ assertEquals(true, model.getBoolean("f2a"));
+ assertEquals(true, model.getBoolean("f3a"));
+ assertEquals(true, model.getBoolean("f4a"));
+ assertEquals(false, model.getBoolean("f5")); // "{a:'b'}" equates to false.
+ assertEquals(false, model.getBoolean("f6"));
+ assertEquals(false, model.getBoolean("f7"));
+ assertEquals(false, model.getBoolean("f8"));
+
+ assertEquals(false, model.getBoolean("f1", true)); // String "1" equates to false.
+ assertEquals(true, model.getBoolean("f2", true));
+ assertEquals(true, model.getBoolean("f3", true));
+ assertEquals(true, model.getBoolean("f4", true));
+ assertEquals(true, model.getBoolean("f2a", true));
+ assertEquals(true, model.getBoolean("f3a", true));
+ assertEquals(true, model.getBoolean("f4a", true));
+ assertEquals(false, model.getBoolean("f5", true)); // "{a:'b'}" equates to false.
+ assertEquals(false, model.getBoolean("f6", true));
+ assertEquals(false, model.getBoolean("f7", true));
+ assertEquals(false, model.getBoolean("f8", true));
+
+ try { model.getMap("f1"); fail(); } catch (InvalidDataConversionException e) {}
+ try { model.getMap("f2"); fail(); } catch (InvalidDataConversionException e) {}
+ try { model.getMap("f3"); fail(); } catch (InvalidDataConversionException e) {}
+ try { model.getMap("f4"); fail(); } catch (InvalidDataConversionException e) {}
+ try { model.getMap("f2a"); fail(); } catch (InvalidDataConversionException e) {}
+ try { model.getMap("f3a"); fail(); } catch (InvalidDataConversionException e) {}
+ try { model.getMap("f4a"); fail(); } catch (InvalidDataConversionException e) {}
+ assertEquals("{f5a:'a'}", model.getMap("f5").toString());
+ try { model.getMap("f6"); fail(); } catch (InvalidDataConversionException e) {}
+ assertEquals("{f5a:'a'}", model.getMap("f7").toString());
+ try { model.getMap("f8"); fail(); } catch (InvalidDataConversionException e) {}
+
+ try { model.getMap("f1", m); fail(); } catch (InvalidDataConversionException e) {}
+ try { model.getMap("f2", m); fail(); } catch (InvalidDataConversionException e) {}
+ try { model.getMap("f3", m); fail(); } catch (InvalidDataConversionException e) {}
+ try { model.getMap("f4", m); fail(); } catch (InvalidDataConversionException e) {}
+ try { model.getMap("f2a", m); fail(); } catch (InvalidDataConversionException e) {}
+ try { model.getMap("f3a", m); fail(); } catch (InvalidDataConversionException e) {}
+ try { model.getMap("f4a", m); fail(); } catch (InvalidDataConversionException e) {}
+ assertEquals("{f5a:'a'}", model.getMap("f5", m).toString());
+ try { model.getMap("f6", m); fail(); } catch (InvalidDataConversionException e) {}
+ assertEquals("{f5a:'a'}", model.getMap("f7", m).toString());
+ try { model.getMap("f8", m); fail(); } catch (InvalidDataConversionException e) {}
+
+ try { model.getObjectMap("f1"); fail(); } catch (InvalidDataConversionException e) {}
+ try { model.getObjectMap("f2"); fail(); } catch (InvalidDataConversionException e) {}
+ try { model.getObjectMap("f3"); fail(); } catch (InvalidDataConversionException e) {}
+ try { model.getObjectMap("f4"); fail(); } catch (InvalidDataConversionException e) {}
+ try { model.getObjectMap("f2a"); fail(); } catch (InvalidDataConversionException e) {}
+ try { model.getObjectMap("f3a"); fail(); } catch (InvalidDataConversionException e) {}
+ try { model.getObjectMap("f4a"); fail(); } catch (InvalidDataConversionException e) {}
+ assertEquals("{f5a:'a'}", model.getObjectMap("f5").toString());
+ try { model.getObjectMap("f6"); fail(); } catch (InvalidDataConversionException e) {}
+ assertEquals("{f5a:'a'}", model.getObjectMap("f7").toString());
+ try { model.getObjectMap("f8"); fail(); } catch (InvalidDataConversionException e) {}
+
+ try { model.getObjectMap("f1", m); fail(); } catch (InvalidDataConversionException e) {}
+ try { model.getObjectMap("f2", m); fail(); } catch (InvalidDataConversionException e) {}
+ try { model.getObjectMap("f3", m); fail(); } catch (InvalidDataConversionException e) {}
+ try { model.getObjectMap("f4", m); fail(); } catch (InvalidDataConversionException e) {}
+ try { model.getObjectMap("f2a", m); fail(); } catch (InvalidDataConversionException e) {}
+ try { model.getObjectMap("f3a", m); fail(); } catch (InvalidDataConversionException e) {}
+ try { model.getObjectMap("f4a", m); fail(); } catch (InvalidDataConversionException e) {}
+ assertEquals("{f5a:'a'}", model.getObjectMap("f5", m).toString());
+ try { model.getObjectMap("f6", m); fail(); } catch (InvalidDataConversionException e) {}
+ assertEquals("{f5a:'a'}", model.getObjectMap("f7", m).toString());
+ try { model.getObjectMap("f8", m); fail(); } catch (InvalidDataConversionException e) {}
+
+ try { model.getList("f1"); fail(); } catch (InvalidDataConversionException e) {}
+ try { model.getList("f2"); fail(); } catch (InvalidDataConversionException e) {}
+ try { model.getList("f3"); fail(); } catch (InvalidDataConversionException e) {}
+ try { model.getList("f4"); fail(); } catch (InvalidDataConversionException e) {}
+ try { model.getList("f2a"); fail(); } catch (InvalidDataConversionException e) {}
+ try { model.getList("f3a"); fail(); } catch (InvalidDataConversionException e) {}
+ try { model.getList("f4a"); fail(); } catch (InvalidDataConversionException e) {}
+ assertEquals("[{f5a:'a'}]", model.getList("f5").toString());
+ assertEquals("[{f6a:'a'}]", model.getList("f6").toString());
+ assertEquals("[{f5a:'a'}]", model.getList("f7").toString());
+ assertEquals("[{f6a:'a'}]", model.getList("f8").toString());
+
+ try { model.getList("f1", l); fail(); } catch (InvalidDataConversionException e) {}
+ try { model.getList("f2", l); fail(); } catch (InvalidDataConversionException e) {}
+ try { model.getList("f3", l); fail(); } catch (InvalidDataConversionException e) {}
+ try { model.getList("f4", l); fail(); } catch (InvalidDataConversionException e) {}
+ try { model.getList("f2a", l); fail(); } catch (InvalidDataConversionException e) {}
+ try { model.getList("f3a", l); fail(); } catch (InvalidDataConversionException e) {}
+ try { model.getList("f4a", l); fail(); } catch (InvalidDataConversionException e) {}
+ assertEquals("[{f5a:'a'}]", model.getList("f5", l).toString());
+ assertEquals("[{f6a:'a'}]", model.getList("f6", l).toString());
+ assertEquals("[{f5a:'a'}]", model.getList("f7", l).toString());
+ assertEquals("[{f6a:'a'}]", model.getList("f8", l).toString());
+
+ try { model.getObjectList("f1"); fail(); } catch (InvalidDataConversionException e) {}
+ try { model.getObjectList("f2"); fail(); } catch (InvalidDataConversionException e) {}
+ try { model.getObjectList("f3"); fail(); } catch (InvalidDataConversionException e) {}
+ try { model.getObjectList("f4"); fail(); } catch (InvalidDataConversionException e) {}
+ try { model.getObjectList("f2a"); fail(); } catch (InvalidDataConversionException e) {}
+ try { model.getObjectList("f3a"); fail(); } catch (InvalidDataConversionException e) {}
+ try { model.getObjectList("f4a"); fail(); } catch (InvalidDataConversionException e) {}
+ assertEquals("[{f5a:'a'}]", model.getObjectList("f5").toString());
+ assertEquals("[{f6a:'a'}]", model.getObjectList("f6").toString());
+ assertEquals("[{f5a:'a'}]", model.getObjectList("f7").toString());
+ assertEquals("[{f6a:'a'}]", model.getObjectList("f8").toString());
+
+ try { model.getObjectList("f1", l); fail(); } catch (InvalidDataConversionException e) {}
+ try { model.getObjectList("f2", l); fail(); } catch (InvalidDataConversionException e) {}
+ try { model.getObjectList("f3", l); fail(); } catch (InvalidDataConversionException e) {}
+ try { model.getObjectList("f4", l); fail(); } catch (InvalidDataConversionException e) {}
+ try { model.getObjectList("f2a", l); fail(); } catch (InvalidDataConversionException e) {}
+ try { model.getObjectList("f3a", l); fail(); } catch (InvalidDataConversionException e) {}
+ try { model.getObjectList("f4a", l); fail(); } catch (InvalidDataConversionException e) {}
+ assertEquals("[{f5a:'a'}]", model.getObjectList("f5", l).toString());
+ assertEquals("[{f6a:'a'}]", model.getObjectList("f6", l).toString());
+ assertEquals("[{f5a:'a'}]", model.getObjectList("f7", l).toString());
+ assertEquals("[{f6a:'a'}]", model.getObjectList("f8", l).toString());
+ }
+
+ public static class A {
+ public String f1;
+ public int f2;
+ public long f3;
+ public boolean f4;
+ public Integer f2a;
+ public Long f3a;
+ public Boolean f4a;
+ public Map f5;
+ public List f6;
+ public ObjectMap f7;
+ public ObjectList f8;
+
+ public A init() {
+ f1 = "1";
+ f2 = 2;
+ f3 = 3l;
+ f4 = true;
+ f2a = 2;
+ f3a = 3l;
+ f4a = true;
+ try {
+ f5 = new ObjectMap("{f5a:'a'}");
+ f6 = new ObjectList("[{f6a:'a'}]");
+ f7 = new ObjectMap("{f5a:'a'}");
+ f8 = new ObjectList("[{f6a:'a'}]");
+ } catch (ParseException e) {
+ throw new RuntimeException(e);
+ }
+ return this;
+ }
+ }
+
+ //====================================================================================================
+ // invokeMethod(String url, String method, String args)
+ //====================================================================================================
+ @Test
+ public void testInvokeMethod() throws Exception {
+
+ PojoRest model = new PojoRest(new AddressBook().init());
+ assertEquals("Person(name=Bill Clinton,age=65)", model.invokeMethod("0", "toString", ""));
+
+ model = new PojoRest(new AddressBook().init(), JsonParser.DEFAULT);
+ assertEquals("Person(name=Bill Clinton,age=65)", model.invokeMethod("0", "toString", ""));
+ assertEquals("NY", model.invokeMethod("0/addresses/0/state", "toString", ""));
+ assertNull(model.invokeMethod("1", "toString", ""));
+ }
+
+ //====================================================================================================
+ // getPublicMethods(String url)
+ //====================================================================================================
+ @Test
+ public void testGetPublicMethods() throws Exception {
+ PojoRest model = new PojoRest(new AddressBook().init());
+ assertTrue(JsonSerializer.DEFAULT_LAX.toString(model.getPublicMethods("0")).contains("'toString'"));
+ assertTrue(JsonSerializer.DEFAULT_LAX.toString(model.getPublicMethods("0/addresses/0/state")).contains("'toString'"));
+ assertNull(model.getPublicMethods("1"));
+ }
+
+ //====================================================================================================
+ // getClassMeta(String url)
+ //====================================================================================================
+ @Test
+ public void testGetClassMeta() throws Exception {
+ PojoRest model = new PojoRest(new AddressBook().init());
+ assertEquals("Person", model.getClassMeta("0").getInnerClass().getSimpleName());
+ assertEquals("String", model.getClassMeta("0/addresses/0/state").getInnerClass().getSimpleName());
+ assertNull(model.getClassMeta("1"));
+ assertNull(model.getClassMeta("0/addresses/1/state"));
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/utils/SimpleMapTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/utils/SimpleMapTest.java b/org.apache.juneau/src/test/java/org/apache/juneau/utils/SimpleMapTest.java
new file mode 100755
index 0000000..371222c
--- /dev/null
+++ b/org.apache.juneau/src/test/java/org/apache/juneau/utils/SimpleMapTest.java
@@ -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.juneau.utils;
+
+import static org.apache.juneau.TestUtils.*;
+import static org.junit.Assert.*;
+
+import org.apache.juneau.internal.*;
+import org.junit.*;
+
+public class SimpleMapTest {
+
+ @Test
+ public void doTest() throws Exception {
+ String[] keys = {"a","b"};
+ Object[] vals = {"A","B"};
+ SimpleMap m = new SimpleMap(keys, vals);
+ assertEquals(2, m.size());
+ assertEquals("A", m.get("a"));
+ assertEquals("B", m.get("b"));
+ assertObjectEquals("{a:'A',b:'B'}", m);
+ assertObjectEquals("['a','b']", m.keySet());
+ m.put("a", "1");
+ assertObjectEquals("{a:'1',b:'B'}", m);
+ m.entrySet().iterator().next().setValue("2");
+ assertObjectEquals("{a:'2',b:'B'}", m);
+ try { m.put("c", "1"); fail(); } catch (IllegalArgumentException e) {}
+
+ assertNull(m.get("c"));
+
+ try { m = new SimpleMap(null, vals); fail(); } catch (IllegalArgumentException e) {}
+ try { m = new SimpleMap(keys, null); fail(); } catch (IllegalArgumentException e) {}
+ try { m = new SimpleMap(keys, new Object[0]); fail(); } catch (IllegalArgumentException e) {}
+
+ keys[0] = null;
+ try { m = new SimpleMap(keys, vals); fail(); } catch (IllegalArgumentException e) {}
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/utils/StringBuilderWriterTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/utils/StringBuilderWriterTest.java b/org.apache.juneau/src/test/java/org/apache/juneau/utils/StringBuilderWriterTest.java
new file mode 100755
index 0000000..2868fa4
--- /dev/null
+++ b/org.apache.juneau/src/test/java/org/apache/juneau/utils/StringBuilderWriterTest.java
@@ -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.juneau.utils;
+
+import static org.junit.Assert.*;
+
+import org.apache.juneau.internal.*;
+import org.junit.*;
+
+public class StringBuilderWriterTest {
+
+ //====================================================================================================
+ // Basic tests
+ //====================================================================================================
+ @Test
+ public void test() throws Exception {
+ StringBuilderWriter sbw = new StringBuilderWriter();
+ sbw.write("abc");
+ assertEquals("abc", sbw.toString());
+ sbw.append("abc");
+ assertEquals("abcabc", sbw.toString());
+ sbw.write("abc", 1, 1);
+ assertEquals("abcabcb", sbw.toString());
+ sbw.append("abc", 1, 2);
+ assertEquals("abcabcbb", sbw.toString());
+ sbw.write((String)null);
+ assertEquals("abcabcbbnull", sbw.toString());
+ sbw.append((String)null);
+ assertEquals("abcabcbbnullnull", sbw.toString());
+ sbw.append((String)null,0,4);
+ assertEquals("abcabcbbnullnullnull", sbw.toString());
+
+ char[] buff = "abc".toCharArray();
+ sbw = new StringBuilderWriter();
+ sbw.write(buff, 0, buff.length);
+ assertEquals("abc", sbw.toString());
+ sbw.write(buff, 0, 0);
+ assertEquals("abc", sbw.toString());
+
+ try { sbw.write(buff, -1, buff.length); fail(); } catch (IndexOutOfBoundsException e) {}
+ try { sbw.write(buff, buff.length+1, 0); fail(); } catch (IndexOutOfBoundsException e) {}
+ try { sbw.write(buff, buff.length-1, 2); fail(); } catch (IndexOutOfBoundsException e) {}
+ try { sbw.write(buff, 0, buff.length+1); fail(); } catch (IndexOutOfBoundsException e) {}
+ try { sbw.write(buff, 0, -1); fail(); } catch (IndexOutOfBoundsException e) {}
+
+ sbw.flush();
+ sbw.close();
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/utils/StringUtilsTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/utils/StringUtilsTest.java b/org.apache.juneau/src/test/java/org/apache/juneau/utils/StringUtilsTest.java
new file mode 100755
index 0000000..139e575
--- /dev/null
+++ b/org.apache.juneau/src/test/java/org/apache/juneau/utils/StringUtilsTest.java
@@ -0,0 +1,676 @@
+/***************************************************************************************************************************
+ * 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.juneau.utils;
+
+import static org.apache.juneau.TestUtils.*;
+import static org.apache.juneau.internal.StringUtils.*;
+import static org.junit.Assert.*;
+
+import java.io.ObjectInputStream.*;
+import java.math.*;
+import java.util.*;
+import java.util.concurrent.atomic.*;
+
+import org.apache.juneau.*;
+import org.apache.juneau.json.*;
+import org.apache.juneau.parser.*;
+import org.apache.juneau.serializer.*;
+import org.apache.juneau.transforms.*;
+import org.junit.*;
+
+public class StringUtilsTest {
+
+ //====================================================================================================
+ // isNumeric(String,Class)
+ // parseNumber(String,Class)
+ //====================================================================================================
+ @Test
+ public void testParseNumber() throws Exception {
+
+ // Integers
+ assertTrue(isNumeric("123"));
+ assertEquals(123, parseNumber("123", null));
+ assertEquals(123, parseNumber("123", Integer.class));
+ assertEquals((short)123, parseNumber("123", Short.class));
+ assertEquals((long)123, parseNumber("123", Long.class));
+
+ assertTrue(isNumeric("0123"));
+ assertEquals(0123, parseNumber("0123", null));
+
+ assertTrue(isNumeric("-0123"));
+ assertEquals(-0123, parseNumber("-0123", null));
+
+ // Hexadecimal
+ assertTrue(isNumeric("0x123"));
+ assertEquals(0x123, parseNumber("0x123", null));
+
+ assertTrue(isNumeric("-0x123"));
+ assertEquals(-0x123, parseNumber("-0x123", null));
+
+ assertTrue(isNumeric("0X123"));
+ assertEquals(0X123, parseNumber("0X123", null));
+
+ assertTrue(isNumeric("-0X123"));
+ assertEquals(-0X123, parseNumber("-0X123", null));
+
+ assertTrue(isNumeric("#123"));
+ assertEquals(0x123, parseNumber("#123", null));
+
+ assertTrue(isNumeric("-#123"));
+ assertEquals(-0x123, parseNumber("-#123", null));
+
+ assertFalse(isNumeric("x123"));
+ assertFalse(isNumeric("0x123x"));
+
+ // Decimal
+ assertTrue(isNumeric("0.123"));
+ assertEquals(0.123f, parseNumber("0.123", null));
+
+ assertTrue(isNumeric("-0.123"));
+ assertEquals(-0.123f, parseNumber("-0.123", null));
+
+ assertTrue(isNumeric(".123"));
+ assertEquals(.123f, parseNumber(".123", null));
+
+ assertTrue(isNumeric("-.123"));
+ assertEquals(-.123f, parseNumber("-.123", null));
+
+ assertFalse(isNumeric("0.123.4"));
+
+ // Scientific notation
+ assertTrue(isNumeric("1e1"));
+ assertEquals(1e1f, parseNumber("1e1", null));
+
+ assertTrue(isNumeric("1e+1"));
+ assertEquals(1e+1f, parseNumber("1e+1", null));
+
+ assertTrue(isNumeric("1e-1"));
+ assertEquals(1e-1f, parseNumber("1e-1", null));
+
+ assertTrue(isNumeric("1.1e1"));
+ assertEquals(1.1e1f, parseNumber("1.1e1", null));
+
+ assertTrue(isNumeric("1.1e+1"));
+ assertEquals(1.1e+1f, parseNumber("1.1e+1", null));
+
+ assertTrue(isNumeric("1.1e-1"));
+ assertEquals(1.1e-1f, parseNumber("1.1e-1", null));
+
+ assertTrue(isNumeric(".1e1"));
+ assertEquals(.1e1f, parseNumber(".1e1", null));
+
+ assertTrue(isNumeric(".1e+1"));
+ assertEquals(.1e+1f, parseNumber(".1e+1", null));
+
+ assertTrue(isNumeric(".1e-1"));
+ assertEquals(.1e-1f, parseNumber(".1e-1", null));
+
+ // Hexadecimal + scientific
+ assertTrue(isNumeric("0x123e1"));
+ assertEquals(0x123e1, parseNumber("0x123e1", null));
+
+ try {
+ parseNumber("x", Number.class);
+ fail();
+ } catch (ParseException e) {
+ assertTrue(e.getCause() instanceof NumberFormatException);
+ }
+
+ try {
+ parseNumber("x", null);
+ fail();
+ } catch (ParseException e) {
+ assertTrue(e.getCause() instanceof NumberFormatException);
+ }
+
+ try {
+ parseNumber("x", BadNumber.class);
+ fail();
+ } catch (ParseException e) {
+ assertTrue(e.getLocalizedMessage().startsWith("Unsupported Number type"));
+ }
+ }
+
+ @SuppressWarnings("serial")
+ private abstract static class BadNumber extends Number {}
+
+ //====================================================================================================
+ // parseNumber(ParserReader,Class)
+ //====================================================================================================
+ @SuppressWarnings({ "rawtypes", "unchecked" })
+ @Test
+ public void testParseNumberFromReader() throws Exception {
+ ParserReader in;
+ Number n;
+
+ for (Class c : new Class[]{ Integer.class, Double.class, Float.class, Long.class, Short.class, Byte.class, BigInteger.class, BigDecimal.class, Number.class, AtomicInteger.class, AtomicLong.class}) {
+ in = new ParserReader("123'");
+ n = parseNumber(in, c);
+ assertTrue(c.isInstance(n));
+ assertEquals(123, n.intValue());
+ }
+ }
+
+ //====================================================================================================
+ // test - Basic tests
+ //====================================================================================================
+ @Test
+ public void testNumberRanges() throws Exception {
+ String s;
+
+ // An integer range is -2,147,483,648 to 2,147,483,647
+
+ assertFalse(isNumeric(null));
+ assertFalse(isNumeric(""));
+ assertFalse(isNumeric("x"));
+
+ s = "-2147483648";
+ assertTrue(isNumeric(s));
+ assertTrue(parseNumber(s, null) instanceof Integer);
+ assertEquals(-2147483648, parseNumber(s, null));
+
+ s = "2147483647";
+ assertTrue(isNumeric(s));
+ assertTrue(parseNumber(s, null) instanceof Integer);
+ assertEquals(2147483647, parseNumber(s, null));
+
+ s = "-2147483649";
+ assertTrue(isNumeric(s));
+ assertTrue(parseNumber(s, null) instanceof Long);
+ assertEquals(-2147483649L, parseNumber(s, null));
+
+ s = "2147483648";
+ assertTrue(isNumeric(s));
+ assertTrue(parseNumber(s, null) instanceof Long);
+ assertEquals(2147483648L, parseNumber(s, null));
+
+ // An long range is -9,223,372,036,854,775,808 to +9,223,372,036,854,775,807
+
+ s = "-9223372036854775808";
+ assertTrue(isNumeric(s));
+ assertTrue(parseNumber(s, null) instanceof Long);
+ assertEquals(-9223372036854775808L, parseNumber(s, null));
+
+ s = "9223372036854775807";
+ assertTrue(isNumeric(s));
+ assertTrue(parseNumber(s, null) instanceof Long);
+ assertEquals(9223372036854775807L, parseNumber(s, null));
+
+ // Anything that falls outside this range should be a double.
+
+ s = "-9223372036854775809";
+ assertTrue(isNumeric(s));
+ assertTrue(parseNumber(s, null) instanceof Double);
+ assertEquals(-9223372036854775808L, parseNumber(s, null).longValue());
+ assertEquals(-9.223372036854776E18, parseNumber(s, null));
+
+ s = "9223372036854775808";
+ assertTrue(isNumeric(s));
+ assertTrue(parseNumber(s, null) instanceof Double);
+ assertEquals(9223372036854775807L, parseNumber(s, null).longValue());
+ assertEquals(9.223372036854776E18, parseNumber(s, null));
+
+ // Check case where string is longer than 20 characters since it's a different code path.
+
+ s = "-123456789012345678901";
+ assertTrue(isNumeric(s));
+ assertTrue(parseNumber(s, null) instanceof Double);
+ assertEquals(-9223372036854775808L, parseNumber(s, null).longValue());
+ assertEquals(-1.2345678901234568E20, parseNumber(s, null));
+
+ s = "123456789012345678901";
+ assertTrue(isNumeric(s));
+ assertTrue(parseNumber(s, null) instanceof Double);
+ assertEquals(9223372036854775807L, parseNumber(s, null).longValue());
+ assertEquals(1.2345678901234568E20, parseNumber(s, null));
+
+ // Autodetected floating point numbers smaller than Float.MAX_VALUE
+ s = String.valueOf(Float.MAX_VALUE / 2);
+ assertTrue(isNumeric(s));
+ assertTrue(parseNumber(s, null) instanceof Float);
+ assertEquals(1.7014117E38f, parseNumber(s, null));
+
+ s = String.valueOf((-Float.MAX_VALUE) / 2);
+ assertTrue(isNumeric(s));
+ assertTrue(parseNumber(s, null) instanceof Float);
+ assertEquals(-1.7014117E38f, parseNumber(s, null));
+
+ // Autodetected floating point numbers larger than Float.MAX_VALUE
+ s = String.valueOf((double)Float.MAX_VALUE * 2);
+ assertTrue(isNumeric(s));
+ assertTrue(parseNumber(s, null) instanceof Double);
+ assertEquals("6.805646932770577E38", parseNumber(s, null).toString());
+
+ s = String.valueOf((double)Float.MAX_VALUE * -2);
+ assertTrue(isNumeric(s));
+ assertTrue(parseNumber(s, null) instanceof Double);
+ assertEquals("-6.805646932770577E38", parseNumber(s, null).toString());
+
+ s = String.valueOf("214748364x");
+ assertFalse(isNumeric(s));
+ try {
+ parseNumber(s, Number.class);
+ } catch (ParseException e) {}
+
+ s = String.valueOf("2147483640x");
+ assertFalse(isNumeric(s));
+ try {
+ parseNumber(s, Long.class);
+ } catch (ParseException e) {}
+
+
+ }
+
+ //====================================================================================================
+ // testReplaceVars
+ //====================================================================================================
+ @Test
+ public void testReplaceVars() throws Exception {
+ ObjectMap m = new ObjectMap("{a:'A',b:1,c:true,d:'{e}',e:'E{f}E',f:'F',g:'{a}',h:'a',i:null}");
+
+ String s = "xxx";
+ assertEquals("xxx", replaceVars(s, m));
+
+ s = "{a}";
+ assertEquals("A", replaceVars(s, m));
+ s = "{a}{a}";
+ assertEquals("AA", replaceVars(s, m));
+ s = "x{a}x";
+ assertEquals("xAx", replaceVars(s, m));
+ s = "x{a}x{a}x";
+ assertEquals("xAxAx", replaceVars(s, m));
+
+ s = "{b}";
+ assertEquals("1", replaceVars(s, m));
+ s = "{b}{b}";
+ assertEquals("11", replaceVars(s, m));
+ s = "x{b}x";
+ assertEquals("x1x", replaceVars(s, m));
+ s = "x{b}x{b}x";
+ assertEquals("x1x1x", replaceVars(s, m));
+
+ s = "{c}";
+ assertEquals("true", replaceVars(s, m));
+ s = "{c}{c}";
+ assertEquals("truetrue", replaceVars(s, m));
+ s = "x{c}x{c}x";
+ assertEquals("xtruextruex", replaceVars(s, m));
+
+ s = "{d}";
+ assertEquals("EFE", replaceVars(s, m));
+ s = "{d}{d}";
+ assertEquals("EFEEFE", replaceVars(s, m));
+ s = "x{d}x";
+ assertEquals("xEFEx", replaceVars(s, m));
+ s = "x{d}x{d}x";
+ assertEquals("xEFExEFEx", replaceVars(s, m));
+
+ s = "{g}";
+ assertEquals("A", replaceVars(s, m));
+ s = "{g}{g}";
+ assertEquals("AA", replaceVars(s, m));
+ s = "x{g}x";
+ assertEquals("xAx", replaceVars(s, m));
+ s = "x{g}x{g}x";
+ assertEquals("xAxAx", replaceVars(s, m));
+
+ s = "{x}";
+ assertEquals("{x}", replaceVars(s, m));
+ s = "{x}{x}";
+ assertEquals("{x}{x}", replaceVars(s, m));
+ s = "x{x}x{x}x";
+ assertEquals("x{x}x{x}x", replaceVars(s, m));
+
+ s = "{{g}}";
+ assertEquals("{A}", replaceVars(s, m));
+ s = "{{h}}";
+ assertEquals("A", replaceVars(s, m));
+
+ s = "{{i}}";
+ assertEquals("{}", replaceVars(s, m));
+ s = "{}";
+ assertEquals("{}", replaceVars(s, m));
+ }
+
+ //====================================================================================================
+ // isFloat(String)
+ //====================================================================================================
+ @Test
+ public void testisFloat() throws Exception {
+ String[] valid = {
+ "+1.0",
+ "-1.0",
+ ".0",
+ "NaN",
+ "Infinity",
+ "1e1",
+ "-1e-1",
+ "+1e+1",
+ "-1.1e-1",
+ "+1.1e+1",
+ "1.1f",
+ "1.1F",
+ "1.1d",
+ "1.1D",
+ "0x1.fffffffffffffp1023",
+ "0x1.FFFFFFFFFFFFFP1023",
+ };
+ for (String s : valid)
+ assertTrue(isFloat(s));
+
+ String[] invalid = {
+ null,
+ "",
+ "a",
+ "+",
+ "-",
+ ".",
+ "a",
+ "+a",
+ "11a",
+ };
+ for (String s : invalid)
+ assertFalse(isFloat(s));
+ }
+
+ //====================================================================================================
+ // isDecimal(String)
+ //====================================================================================================
+ @Test
+ public void testisDecimal() throws Exception {
+ String[] valid = {
+ "+1",
+ "-1",
+ "0x123",
+ "0X123",
+ "0xdef",
+ "0XDEF",
+ "#def",
+ "#DEF",
+ "0123",
+ };
+ for (String s : valid)
+ assertTrue(isDecimal(s));
+
+ String[] invalid = {
+ null,
+ "",
+ "a",
+ "+",
+ "-",
+ ".",
+ "0xdeg",
+ "0XDEG",
+ "#deg",
+ "#DEG",
+ "0128",
+ "012A",
+ };
+ for (String s : invalid)
+ assertFalse(isDecimal(s));
+ }
+
+ //====================================================================================================
+ // join(Object[],String)
+ // join(int[],String)
+ // join(Collection,String)
+ // join(Object[],char)
+ // join(int[],char)
+ // join(Collection,char)
+ //====================================================================================================
+ @Test
+ public void testJoin() throws Exception {
+ assertNull(join((Object[])null, ","));
+ assertEquals("1", join(new Object[]{1}, ","));
+ assertEquals("1,2", join(new Object[]{1,2}, ","));
+
+ assertNull(join((int[])null, ","));
+ assertEquals("1", join(new int[]{1}, ","));
+ assertEquals("1,2", join(new int[]{1,2}, ","));
+
+ assertNull(join((Collection<?>)null, ","));
+ assertEquals("1", join(Arrays.asList(new Integer[]{1}), ","));
+ assertEquals("1,2", join(Arrays.asList(new Integer[]{1,2}), ","));
+
+ assertNull(join((Object[])null, ','));
+ assertEquals("1", join(new Object[]{1}, ','));
+ assertEquals("1,2", join(new Object[]{1,2}, ','));
+
+ assertNull(join((int[])null, ','));
+ assertEquals("1", join(new int[]{1}, ','));
+ assertEquals("1,2", join(new int[]{1,2}, ','));
+
+ assertNull(join((Collection<?>)null, ','));
+ assertEquals("1", join(Arrays.asList(new Integer[]{1}), ','));
+ assertEquals("1,2", join(Arrays.asList(new Integer[]{1,2}), ','));
+ }
+
+ //====================================================================================================
+ // split(String,char)
+ //====================================================================================================
+ @Test
+ public void testSplit() throws Exception {
+ String[] r;
+
+ assertNull(split(null, ','));
+ assertObjectEquals("[]", split("", ','));
+ assertObjectEquals("['1']", split("1", ','));
+ assertObjectEquals("['1','2']", split("1,2", ','));
+ assertObjectEquals("['1,2']", split("1\\,2", ','));
+
+ r = split("1\\\\,2", ',');
+ assertEquals("1\\", r[0]);
+ assertEquals("2", r[1]);
+
+ r = split("1\\\\\\,2", ',');
+ assertEquals(1, r.length);
+ assertEquals("1\\,2", r[0]);
+
+ r = split("1,2\\", ',');
+ assertEquals("2\\", r[1]);
+
+ r = split("1,2\\\\", ',');
+ assertEquals("2\\", r[1]);
+
+ r = split("1,2\\,", ',');
+ assertEquals("2,", r[1]);
+
+ r = split("1,2\\\\,", ',');
+ assertEquals("2\\", r[1]);
+ assertEquals("", r[2]);
+ }
+
+ //====================================================================================================
+ // nullIfEmpty(String)
+ //====================================================================================================
+ @Test
+ public void testNullIfEmpty() throws Exception {
+ assertNull(nullIfEmpty(null));
+ assertNull(nullIfEmpty(""));
+ assertNotNull(nullIfEmpty("x"));
+ }
+
+ //====================================================================================================
+ // unescapeChars(String,char[],char)
+ //====================================================================================================
+ @Test
+ public void testUnescapeChars() throws Exception {
+ char[] toEscape = {'\\',',','|'};
+ char escape = '\\';
+
+ assertNull(unEscapeChars(null, toEscape, escape));
+ assertEquals("xxx", unEscapeChars("xxx", new char[0], escape));
+ assertEquals("xxx", unEscapeChars("xxx", null, escape));
+ assertEquals("xxx", unEscapeChars("xxx", toEscape, (char)0));
+
+ assertEquals("xxx", unEscapeChars("xxx", toEscape, escape));
+ assertEquals("x,xx", unEscapeChars("x\\,xx", toEscape, escape));
+ assertEquals("x\\xx", unEscapeChars("x\\xx", toEscape, escape));
+ assertEquals("x\\,xx", unEscapeChars("x\\\\,xx", toEscape, escape));
+ assertEquals("x\\,xx", unEscapeChars("x\\\\\\,xx", toEscape, escape));
+ assertEquals("\\", unEscapeChars("\\", toEscape, escape));
+ assertEquals(",", unEscapeChars("\\,", toEscape, escape));
+ assertEquals("|", unEscapeChars("\\|", toEscape, escape));
+
+ toEscape = new char[] {',','|'};
+ assertEquals("x\\\\xx", unEscapeChars("x\\\\xx", toEscape, escape));
+ }
+
+ //====================================================================================================
+ // decodeHex(String)
+ //====================================================================================================
+ @Test
+ public void testDecodeHex() throws Exception {
+ assertNull(decodeHex(null));
+ assertEquals("19azAZ", decodeHex("19azAZ"));
+ assertEquals("[0][1][ffff]", decodeHex("\u0000\u0001\uFFFF"));
+ }
+
+ //====================================================================================================
+ // startsWith(String,char)
+ //====================================================================================================
+ @Test
+ public void testStartsWith() throws Exception {
+ assertFalse(startsWith(null, 'a'));
+ assertFalse(startsWith("", 'a'));
+ assertTrue(startsWith("a", 'a'));
+ assertTrue(startsWith("ab", 'a'));
+ }
+
+ //====================================================================================================
+ // endsWith(String,char)
+ //====================================================================================================
+ @Test
+ public void testEndsWith() throws Exception {
+ assertFalse(endsWith(null, 'a'));
+ assertFalse(endsWith("", 'a'));
+ assertTrue(endsWith("a", 'a'));
+ assertTrue(endsWith("ba", 'a'));
+ }
+
+ //====================================================================================================
+ // base64EncodeToString(String)
+ // base64DecodeToString(String)
+ //====================================================================================================
+ @Test
+ public void testBase64EncodeToString() throws Exception {
+ String s = null;
+
+ assertEquals(s, base64DecodeToString(base64EncodeToString(s)));
+ s = "";
+ assertEquals(s, base64DecodeToString(base64EncodeToString(s)));
+ s = "foobar";
+ assertEquals(s, base64DecodeToString(base64EncodeToString(s)));
+ s = "\u0000\uffff";
+ assertEquals(s, base64DecodeToString(base64EncodeToString(s)));
+
+ try {
+ base64Decode("a");
+ fail();
+ } catch (IllegalArgumentException e) {
+ assertEquals("Invalid BASE64 string length. Must be multiple of 4.", e.getLocalizedMessage());
+ // OK.
+ }
+ try {
+ base64Decode("aaa");
+ fail();
+ } catch (IllegalArgumentException e) {
+ // OK.
+ }
+ }
+
+ //====================================================================================================
+ // generateUUID(String)
+ //====================================================================================================
+ @Test
+ public void testGenerateUUID() throws Exception {
+ for (int i = 0; i < 10; i++) {
+ String s = generateUUID(i);
+ assertEquals(i, s.length());
+ for (char c : s.toCharArray())
+ assertTrue(Character.isLowerCase(c) || Character.isDigit(c));
+ }
+ }
+
+ //====================================================================================================
+ // trim(String)
+ //====================================================================================================
+ @Test
+ public void testTrim() throws Exception {
+ assertNull(trim(null));
+ assertEquals("", trim(""));
+ assertEquals("", trim(" "));
+ }
+
+ //====================================================================================================
+ // parseISO8601Date(String)
+ //====================================================================================================
+ @Test
+ public void testParseISO8601Date() throws Exception {
+ WriterSerializer s = new JsonSerializer.Simple().addTransforms(DateTransform.ISO8601DTPNZ.class);
+
+ assertNull(parseISO8601Date(null));
+ assertNull(parseISO8601Date(""));
+
+ assertEquals("'2000-01-01T00:00:00.000'", s.serialize(parseISO8601Date("2000")));
+ assertEquals("'2000-02-01T00:00:00.000'", s.serialize(parseISO8601Date("2000-02")));
+ assertEquals("'2000-02-03T00:00:00.000'", s.serialize(parseISO8601Date("2000-02-03")));
+ assertEquals("'2000-02-03T04:00:00.000'", s.serialize(parseISO8601Date("2000-02-03T04")));
+ assertEquals("'2000-02-03T04:05:00.000'", s.serialize(parseISO8601Date("2000-02-03T04:05")));
+ assertEquals("'2000-02-03T04:05:06.000'", s.serialize(parseISO8601Date("2000-02-03T04:05:06")));
+ assertEquals("'2000-02-03T04:00:00.000'", s.serialize(parseISO8601Date("2000-02-03 04")));
+ assertEquals("'2000-02-03T04:05:00.000'", s.serialize(parseISO8601Date("2000-02-03 04:05")));
+ assertEquals("'2000-02-03T04:05:06.000'", s.serialize(parseISO8601Date("2000-02-03 04:05:06")));
+
+ // ISO8601 doesn't support milliseconds, so it gets trimmed.
+ assertEquals("'2000-02-03T04:05:06.000'", s.serialize(parseISO8601Date("2000-02-03 04:05:06,789")));
+ }
+
+ //====================================================================================================
+ // pathStartsWith(String, String)
+ //====================================================================================================
+ @Test
+ public void testPathStartsWith() throws Exception {
+ assertTrue(pathStartsWith("foo", "foo"));
+ assertTrue(pathStartsWith("foo/bar", "foo"));
+ assertFalse(pathStartsWith("foo2/bar", "foo"));
+ assertFalse(pathStartsWith("foo2", "foo"));
+ assertFalse(pathStartsWith("foo2", ""));
+ }
+
+ //====================================================================================================
+ // getField(int, String, char)
+ //====================================================================================================
+ @Test
+ public void testGetField() {
+ String in = "0,1,2";
+ assertEquals("0", getField(0, in, ','));
+ assertEquals("1", getField(1, in, ','));
+ assertEquals("2", getField(2, in, ','));
+ assertEquals("", getField(3, in, ','));
+
+ in = ",1,,3,";
+ assertEquals("", getField(0, in, ','));
+ assertEquals("1", getField(1, in, ','));
+ assertEquals("", getField(2, in, ','));
+ assertEquals("3", getField(3, in, ','));
+ assertEquals("", getField(4, in, ','));
+ assertEquals("", getField(5, in, ','));
+
+ in = "";
+ assertEquals("", getField(0, in, ','));
+
+ in = null;
+ assertEquals("", getField(0, in, ','));
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/utils/StringVarResolverTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/utils/StringVarResolverTest.java b/org.apache.juneau/src/test/java/org/apache/juneau/utils/StringVarResolverTest.java
new file mode 100755
index 0000000..4f603bb
--- /dev/null
+++ b/org.apache.juneau/src/test/java/org/apache/juneau/utils/StringVarResolverTest.java
@@ -0,0 +1,332 @@
+/***************************************************************************************************************************
+ * 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.juneau.utils;
+
+import static org.junit.Assert.*;
+
+import org.apache.juneau.internal.*;
+import org.apache.juneau.svl.*;
+import org.junit.*;
+
+public class StringVarResolverTest {
+
+ //====================================================================================================
+ // test - Basic tests
+ //====================================================================================================
+ @Test
+ public void test() throws Exception {
+ VarResolver vr = new VarResolver().addVars(XVar.class);
+ String t;
+
+ t = null;
+ assertEquals("", vr.resolve(t));
+
+ t = "";
+ assertEquals("", vr.resolve(t));
+
+ t = "foo";
+ assertEquals("foo", vr.resolve(t));
+
+ t = "$X{y}";
+ assertEquals("xyx", vr.resolve(t));
+
+ t = "$X{y}x";
+ assertEquals("xyxx", vr.resolve(t));
+
+ t = "x$X{y}";
+ assertEquals("xxyx", vr.resolve(t));
+
+ t = "$X{y}$X{y}";
+ assertEquals("xyxxyx", vr.resolve(t));
+
+ t = "z$X{y}z$X{y}z";
+ assertEquals("zxyxzxyxz", vr.resolve(t));
+
+ t = "$X{$X{y}}";
+ assertEquals("xxyxx", vr.resolve(t));
+
+ t = "$X{z$X{y}z}";
+ assertEquals("xzxyxzx", vr.resolve(t));
+
+ t = "$X.{y}";
+ assertEquals("$X.{y}", vr.resolve(t));
+
+ t = "z$X.{y}z";
+ assertEquals("z$X.{y}z", vr.resolve(t));
+
+ t = "z$X.{$X.{z}}z";
+ assertEquals("z$X.{$X.{z}}z", vr.resolve(t));
+
+ // Non-existent vars
+ t = "$Y{y}";
+ assertEquals("$Y{y}", vr.resolve(t));
+
+ t = "$Y{y}x";
+ assertEquals("$Y{y}x", vr.resolve(t));
+
+ t = "x$Y{y}";
+ assertEquals("x$Y{y}", vr.resolve(t));
+
+ // Incomplete vars
+ // TODO - fix
+// t = "x$Y{y";
+// assertEquals("x$Y{y", vr.resolve(t));
+ }
+
+ public static class XVar extends SimpleVar {
+ public XVar() {
+ super("X");
+ }
+ @Override
+ public String resolve(VarResolverSession session, String arg) {
+ return "x" + arg + "x";
+ }
+ }
+
+ //====================================================================================================
+ // test - No-name variables
+ //====================================================================================================
+ @Test
+ public void test2() throws Exception {
+ VarResolver vr = new VarResolver().addVars(BlankVar.class);
+ String t;
+
+ t = "${y}";
+ assertEquals("xyx", vr.resolve(t));
+
+ t = "${${y}}";
+ assertEquals("xxyxx", vr.resolve(t));
+
+ t = "${${y}${y}}";
+ assertEquals("xxyxxyxx", vr.resolve(t));
+
+ t = "z${z${y}z}z";
+ assertEquals("zxzxyxzxz", vr.resolve(t));
+ }
+
+ public static class BlankVar extends SimpleVar {
+ public BlankVar() {
+ super("");
+ }
+ @Override
+ public String resolve(VarResolverSession session, String arg) {
+ return "x" + arg + "x";
+ }
+ }
+
+ //====================================================================================================
+ // test - No-name variables
+ //====================================================================================================
+ @Test
+ public void testEscaped$() throws Exception {
+ VarResolver vr = new VarResolver().addVars(BlankVar.class);
+ String t;
+
+ t = "${y}";
+ assertEquals("xyx", vr.resolve(t));
+ t = "\\${y}";
+ assertEquals("${y}", vr.resolve(t));
+
+ t = "foo\\${y}foo";
+ assertEquals("foo${y}foo", vr.resolve(t));
+
+ // TODO - This doesn't work.
+ //t = "${\\${y}}";
+ //assertEquals("x${y}x", vr.resolve(t));
+ }
+
+ //====================================================================================================
+ // test - Escape sequences.
+ //====================================================================================================
+ @Test
+ public void testEscapedSequences() throws Exception {
+ VarResolver vr = new VarResolver().addVars(XVar.class);
+ String t;
+ char b = '\\';
+
+ t = "A|A".replace('|',b);
+ assertEquals("A|A".replace('|',b), vr.resolve(t));
+ t = "A||A".replace('|',b);
+ assertEquals("A|A".replace('|',b), vr.resolve(t));
+ t = "A|A$X{B}".replace('|',b);
+ assertEquals("A|AxBx".replace('|',b), vr.resolve(t));
+ t = "A||A$X{B}".replace('|',b);
+ assertEquals("A|AxBx".replace('|',b), vr.resolve(t));
+ t = "A|$X{B}".replace('|',b);
+ assertEquals("A$X{B}".replace('|',b), vr.resolve(t));
+ t = "A||$X{B}".replace('|',b);
+ assertEquals("A|xBx".replace('|',b), vr.resolve(t));
+ t = "A$X|{B}".replace('|',b);
+ assertEquals("A$X{B}".replace('|',b), vr.resolve(t));
+ t = "A$X{B|}".replace('|',b);
+ assertEquals("A$X{B}".replace('|',b), vr.resolve(t));
+ t = "A$X{B}|".replace('|',b);
+ assertEquals("AxBx|".replace('|',b), vr.resolve(t));
+ }
+
+ //====================================================================================================
+ // Test $E variables
+ //====================================================================================================
+ @Test
+ public void test$E() throws Exception {
+ String t;
+
+ t = "$E{PATH}";
+ assertFalse(StringUtils.isEmpty(VarResolver.DEFAULT.resolve(t)));
+ }
+
+ //====================================================================================================
+ // Test that StringResolver(parent) works as expected.
+ //====================================================================================================
+ @Test
+ public void testParent() throws Exception {
+ VarResolver svr = VarResolver.DEFAULT.clone().addVars(XMultipartVar.class);
+ String t;
+ System.setProperty("a", "a1");
+ System.setProperty("b", "b1");
+
+ t = "$X{$S{a},$S{b}}";
+ assertEquals("a1+b1", svr.resolve(t));
+ t = "$X{$S{a}}";
+ assertEquals("a1", svr.resolve(t));
+ }
+
+ public static class XMultipartVar extends MultipartVar {
+ public XMultipartVar() {
+ super("X");
+ }
+ @Override /* MultipartVar */
+ public String resolve(VarResolverSession session, String[] args) {
+ return StringUtils.join(args, '+');
+ }
+ }
+
+ //====================================================================================================
+ // Test false triggers.
+ //====================================================================================================
+ @Test
+ public void testFalseTriggers() throws Exception {
+ VarResolver svr = VarResolver.DEFAULT.clone();
+ String in = null;
+
+ // Should reject names with characters outside A-Za-z
+ for (Class<?> c : new Class[]{InvalidVar1.class, InvalidVar2.class, InvalidVar3.class, InvalidVar4.class, InvalidVar5.class}) {
+ try {
+ svr.addVars(c);
+ fail();
+ } catch (IllegalArgumentException e) {
+ assertEquals("Invalid var name. Must consist of only uppercase and lowercase ASCII letters.", e.getLocalizedMessage());
+ }
+ }
+
+ // These should all be unchanged.
+ in = "$@{foobar}";
+ assertEquals(in, svr.resolve(in));
+ in = "$[{foobar}";
+ assertEquals(in, svr.resolve(in));
+ in = "$`{foobar}";
+ assertEquals(in, svr.resolve(in));
+ in = "$|{foobar}";
+ assertEquals(in, svr.resolve(in));
+ in = "${{foobar}";
+ assertEquals(in, svr.resolve(in));
+ in = "${$foobar}";
+ assertEquals(in, svr.resolve(in));
+
+ System.setProperty("foobar", "baz");
+
+ in = "$";
+ assertEquals(in, svr.resolve(in));
+
+ in = "$S";
+ assertEquals(in, svr.resolve(in));
+
+ in = "$S{";
+ assertEquals(in, svr.resolve(in));
+
+ in = "$S{foobar";
+
+ assertEquals(in, svr.resolve(in));
+ in = "$S{foobar}$";
+ assertEquals("baz$", svr.resolve(in));
+
+ in = "$S{foobar}$S";
+ assertEquals("baz$S", svr.resolve(in));
+
+ in = "$S{foobar}$S{";
+ assertEquals("baz$S{", svr.resolve(in));
+
+ in = "$S{foobar}$S{foobar";
+ assertEquals("baz$S{foobar", svr.resolve(in));
+
+ System.clearProperty("foobar");
+ in = "$S{foobar}";
+
+ // Test nulls returned by StringVar.
+ // Should be converted to blanks.
+ svr.addVars(AlwaysNullVar.class);
+
+ in = "$A{xxx}";
+ assertEquals("", svr.resolve(in));
+ in = "x$A{xxx}";
+ assertEquals("x", svr.resolve(in));
+ in = "$A{xxx}x";
+ assertEquals("x", svr.resolve(in));
+ }
+
+ public static class AlwaysNullVar extends SimpleVar {
+ public AlwaysNullVar() {
+ super("A");
+ }
+ @Override
+ public String resolve(VarResolverSession session, String key) {
+ return null;
+ }
+ }
+
+ public static class InvalidVar extends SimpleVar {
+ public InvalidVar(String c) {
+ super(c);
+ }
+ @Override
+ public String resolve(VarResolverSession session, String key) {
+ return null;
+ }
+ }
+
+ public static class InvalidVar1 extends InvalidVar {
+ public InvalidVar1() {
+ super(null);
+ }
+ }
+ public static class InvalidVar2 extends InvalidVar {
+ public InvalidVar2() {
+ super("@");
+ }
+ }
+ public static class InvalidVar3 extends InvalidVar {
+ public InvalidVar3() {
+ super("[");
+ }
+ }
+ public static class InvalidVar4 extends InvalidVar {
+ public InvalidVar4() {
+ super("`");
+ }
+ }
+ public static class InvalidVar5 extends InvalidVar {
+ public InvalidVar5() {
+ super("|");
+ }
+ }
+}
[14/44] incubator-juneau git commit: Rename CT_* testcases.
Posted by ja...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/json/CT_CommonParser.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/json/CT_CommonParser.java b/org.apache.juneau/src/test/java/org/apache/juneau/json/CT_CommonParser.java
deleted file mode 100755
index c600867..0000000
--- a/org.apache.juneau/src/test/java/org/apache/juneau/json/CT_CommonParser.java
+++ /dev/null
@@ -1,180 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.json;
-
-import static org.apache.juneau.BeanContext.*;
-import static org.apache.juneau.serializer.SerializerContext.*;
-import static org.junit.Assert.*;
-
-import java.util.*;
-
-import org.apache.juneau.*;
-import org.apache.juneau.parser.*;
-import org.junit.*;
-
-@SuppressWarnings({"rawtypes","serial"})
-public class CT_CommonParser {
-
- //====================================================================================================
- // testFromSerializer
- //====================================================================================================
- @Test
- public void testFromSerializer() throws Exception {
- ReaderParser p = JsonParser.DEFAULT.clone().setClassLoader(getClass().getClassLoader());
-
- Map m = null;
- m = (Map)p.parse("{a:1}", Object.class);
- assertEquals(1, m.get("a"));
- m = (Map)p.parse("{a:1,b:\"foo bar\"}", Object.class);
- assertEquals(1, m.get("a"));
- assertEquals("foo bar", m.get("b"));
- m = (Map)p.parse("{a:1,b:\"foo bar\",c:false}", Object.class);
- assertEquals(1, m.get("a"));
- assertEquals(false, m.get("c"));
- m = (Map)p.parse(" { a : 1 , b : 'foo' , c : false } ", Object.class);
- assertEquals(1, m.get("a"));
- assertEquals("foo", m.get("b"));
- assertEquals(false, m.get("c"));
-
- m = (Map)p.parse("{x:\"org.apache.juneau.test.Person\",addresses:[{x:\"org.apache.juneau.test.Address\",city:\"city A\",state:\"state A\",street:\"street A\",zip:12345}]}", Object.class);
- assertEquals("org.apache.juneau.test.Person", m.get("x"));
- List l = (List)m.get("addresses");
- assertNotNull(l);
- m = (Map)l.get(0);
- assertNotNull(m);
- assertEquals("org.apache.juneau.test.Address", m.get("x"));
- assertEquals("city A", m.get("city"));
- assertEquals("state A", m.get("state"));
- assertEquals("street A", m.get("street"));
- assertEquals(12345, m.get("zip"));
-
- ObjectList jl = (ObjectList)p.parse("[{attribute:'value'},{attribute:'value'}]", Object.class);
- assertEquals("value", jl.getObjectMap(0).getString("attribute"));
- assertEquals("value", jl.getObjectMap(1).getString("attribute"));
-
- // Verify that all the following return null.
- assertNull(p.parse((CharSequence)null, Object.class));
- assertNull(p.parse("", Object.class));
- assertNull(p.parse(" ", Object.class));
- assertNull(p.parse(" \t", Object.class));
- assertNull(p.parse(" /*foo*/", Object.class));
- assertNull(p.parse(" /*foo*/ ", Object.class));
- assertNull(p.parse(" //foo ", Object.class));
-
- try {
- jl = (ObjectList)p.parse("[{attribute:'value'},{attribute:'value'}]", Object.class);
- assertEquals("value", jl.getObjectMap(0).getString("attribute"));
- assertEquals("value", jl.getObjectMap(1).getString("attribute"));
- } catch (Exception e) {
- fail(e.getLocalizedMessage());
- }
-
- A1 b = new A1();
- A2 tl = new A2();
- tl.add(new A3("name0","value0"));
- tl.add(new A3("name1","value1"));
- b.list = tl;
- String json = new JsonSerializer().setProperty(SERIALIZER_addClassAttrs, true).serialize(b);
- b = (A1)p.parse(json, Object.class);
- assertEquals("value1", b.list.get(1).value);
-
- json = JsonSerializer.DEFAULT.serialize(b);
- b = p.parse(json, A1.class);
- assertEquals("value1", b.list.get(1).value);
- }
-
- public static class A1 {
- public A2 list;
- }
-
- public static class A2 extends LinkedList<A3> {
- }
-
- public static class A3 {
- public String name, value;
- public A3(){}
- public A3(String name, String value) {
- this.name = name;
- this.value = value;
- }
- }
-
- //====================================================================================================
- // Correct handling of unknown properties.
- //====================================================================================================
- @Test
- public void testCorrectHandlingOfUnknownProperties() throws Exception {
- ReaderParser p = new JsonParser().setProperty(BEAN_ignoreUnknownBeanProperties, true);
- B b;
-
- String in = "{a:1,unknown:3,b:2}";
- b = p.parse(in, B.class);
- assertEquals(b.a, 1);
- assertEquals(b.b, 2);
-
- try {
- p = new JsonParser();
- p.parse(in, B.class);
- fail("Exception expected");
- } catch (ParseException e) {}
- }
-
- public static class B {
- public int a, b;
- }
-
- //====================================================================================================
- // Writing to Collection properties with no setters.
- //====================================================================================================
- @Test
- public void testCollectionPropertiesWithNoSetters() throws Exception {
- JsonParser p = JsonParser.DEFAULT;
- String json = "{ints:[1,2,3],beans:[{a:1,b:2}]}";
- C t = p.parse(json, C.class);
- assertEquals(t.getInts().size(), 3);
- assertEquals(t.getBeans().get(0).b, 2);
- }
-
- public static class C {
- private Collection<Integer> ints = new LinkedList<Integer>();
- private List<B> beans = new LinkedList<B>();
- public Collection<Integer> getInts() {
- return ints;
- }
- public List<B> getBeans() {
- return beans;
- }
- }
-
- //====================================================================================================
- // Parser listeners.
- //====================================================================================================
- @Test
- public void testParserListeners() throws Exception {
- final List<String> events = new LinkedList<String>();
- JsonParser p = new JsonParser().setProperty(BEAN_ignoreUnknownBeanProperties, true);
- p.addListener(
- new ParserListener() {
- @Override /* ParserListener */
- public <T> void onUnknownProperty(String propertyName, Class<T> beanClass, T bean, int line, int col) {
- events.add(propertyName + "," + line + "," + col);
- }
- }
- );
-
- String json = "{a:1,unknownProperty:\"/foo\",b:2}";
- p.parse(json, B.class);
- assertEquals(1, events.size());
- assertEquals("unknownProperty,1,5", events.get(0));
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/json/CT_Json.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/json/CT_Json.java b/org.apache.juneau/src/test/java/org/apache/juneau/json/CT_Json.java
deleted file mode 100755
index 93e3554..0000000
--- a/org.apache.juneau/src/test/java/org/apache/juneau/json/CT_Json.java
+++ /dev/null
@@ -1,308 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.json;
-
-import static org.apache.juneau.TestUtils.*;
-import static org.apache.juneau.json.JsonSerializerContext.*;
-import static org.apache.juneau.serializer.SerializerContext.*;
-import static org.junit.Assert.*;
-
-import java.util.*;
-
-import org.apache.juneau.*;
-import org.apache.juneau.json.annotation.*;
-import org.apache.juneau.serializer.*;
-import org.junit.*;
-
-@SuppressWarnings("serial")
-public class CT_Json {
-
- //====================================================================================================
- // testBasic
- //====================================================================================================
- @Test
- public void testBasic() throws Exception {
- Map<String,Object> m = new LinkedHashMap<String,Object>();
- List<Object> l = new LinkedList<Object>();
-
- WriterSerializer s1 = new JsonSerializer.Simple().setProperty(SERIALIZER_trimNullProperties, false);
- WriterSerializer s2 = new JsonSerializer.Simple().setProperty(SERIALIZER_trimNullProperties, false).setProperty(SERIALIZER_quoteChar, '"');
- String r;
-
- // Null keys and values
- m.clear();
- m.put(null, null);
- m.put("aaa", "bbb");
- assertEquals("A1", "{null:null,aaa:'bbb'}", s1.serialize(m));
-
- // Escapes.
- // String = ["]
- m.clear();
- m.put("x", "[\"]");
- assertEquals("{x:\"[\\\"]\"}", s2.serialize(m));
- // String = [\"]
- // JSON = {x:"\\\""}
- m.clear();
- m.put("x", "[\\\"]");
- assertEquals("{x:\"[\\\\\\\"]\"}", s2.serialize(m));
-
- // String = [\w[\w\-\.]{3,}\w]
- // JSON = {x:"\\w[\\w\\-\\.]{3,}\\w"}
- m.clear();
- r = "\\w[\\w\\-\\.]{3,}\\w";
- m.put("x", r);
- assertEquals("{x:\"\\\\w[\\\\w\\\\-\\\\.]{3,}\\\\w\"}", s2.serialize(m));
- assertEquals(r, new ObjectMap(s2.serialize(m)).getString("x"));
-
- // String = [foo\bar]
- // JSON = {x:"foo\\bar"}
- m.clear();
- m.put("x", "foo\\bar");
- assertEquals("{x:\"foo\\\\bar\"}", s2.serialize(m));
-
- m.clear();
- m.put("null", null);
- m.put("aaa", "bbb");
- assertEquals("A2", "{'null':null,aaa:'bbb'}", s1.serialize(m));
-
- m.clear();
- m.put(null, "null");
- m.put("aaa", "bbb");
- assertEquals("A3", "{null:'null',aaa:'bbb'}", s1.serialize(m));
-
- // Arrays
- m.clear();
- l.clear();
- m.put("J", "f1");
- m.put("B", "b");
- m.put("C", "c");
- l.add("1");
- l.add("2");
- l.add("3");
- Object o = new Object[] { m, l };
- Object o2 = new Object[] { o, "foo", "bar", new Integer(1), new Boolean(false), new Float(1.2), null };
- assertEquals("K1", "[[{J:'f1',B:'b',C:'c'},['1','2','3']],'foo','bar',1,false,1.2,null]", s1.serialize(o2));
- }
-
- @Test
- public void testReservedKeywordAttributes() throws Exception {
- Map<String,Object> m = new LinkedHashMap<String,Object>();
-
- // Keys with reserved names.
- for (String attr : new String[]{"","true","false","null","try","123","1x","-123",".123"}) {
- m.clear();
- m.put(attr,1);
- assertObjectEquals("{'"+attr+"':1}", m);
- }
- }
-
- //====================================================================================================
- // Validate various backslashes in strings.
- //====================================================================================================
- @Test
- public void testBackslashesInStrings() throws Exception {
- JsonSerializer s = new JsonSerializer.Simple().setProperty(SERIALIZER_trimNullProperties, false).setProperty(SERIALIZER_quoteChar, '"');
- String r, r2;
-
- // [\\]
- r = "\\";
- r2 = s.serialize(r);
- assertEquals(r2, "\"\\\\\"");
- assertEquals(JsonParser.DEFAULT.parse(r2, Object.class), r);
-
- // [\b\f\n\t]
- r = "\b\f\n\t";
- r2 = s.serialize(r);
- assertEquals("\"\\b\\f\\n\\t\"", r2);
- assertEquals(r, JsonParser.DEFAULT.parse(r2, Object.class));
-
- // Special JSON case: Forward slashes can OPTIONALLY be escaped.
- // [\/]
- assertEquals(JsonParser.DEFAULT.parse("\"\\/\"", Object.class), "/");
-
- // Unicode
- r = "\u1234\u1ABC\u1abc";
- r2 = s.serialize(r);
- assertEquals("\"\u1234\u1ABC\u1abc\"", r2);
-
- assertEquals("\u1234", JsonParser.DEFAULT.parse("\"\\u1234\"", Object.class));
- }
-
- //====================================================================================================
- // Indentation
- //====================================================================================================
- @Test
- public void testIndentation() throws Exception {
- ObjectMap m = new ObjectMap("{J:{B:['c',{D:'e'},['f',{G:'h'},1,false]]},I:'j'}");
- String e = ""
- + "{"
- + "\n J: {"
- + "\n B: ["
- + "\n 'c', "
- + "\n {"
- + "\n D: 'e'"
- + "\n }, "
- + "\n ["
- + "\n 'f', "
- + "\n {"
- + "\n G: 'h'"
- + "\n }, "
- + "\n 1, "
- + "\n false"
- + "\n ]"
- + "\n ]"
- + "\n }, "
- + "\n I: 'j'"
- + "\n}";
- assertEquals(e, JsonSerializer.DEFAULT_LAX_READABLE.serialize(m));
- }
-
- //====================================================================================================
- // Escaping double quotes
- //====================================================================================================
- @Test
- public void testEscapingDoubleQuotes() throws Exception {
- JsonSerializer s = JsonSerializer.DEFAULT;
- String r = s.serialize(new ObjectMap().append("f1", "x'x\"x"));
- assertEquals("{\"f1\":\"x'x\\\"x\"}", r);
- JsonParser p = JsonParser.DEFAULT;
- assertEquals("x'x\"x", p.parse(r, ObjectMap.class).getString("f1"));
- }
-
- //====================================================================================================
- // Escaping single quotes
- //====================================================================================================
- @Test
- public void testEscapingSingleQuotes() throws Exception {
- JsonSerializer s = JsonSerializer.DEFAULT_LAX;
- String r = s.serialize(new ObjectMap().append("f1", "x'x\"x"));
- assertEquals("{f1:'x\\'x\"x'}", r);
- JsonParser p = JsonParser.DEFAULT;
- assertEquals("x'x\"x", p.parse(r, ObjectMap.class).getString("f1"));
- }
-
- //====================================================================================================
- // testWrapperAttrAnnotationOnBean
- //====================================================================================================
- @Test
- @SuppressWarnings("unchecked")
- public void testWrapperAttrAnnotationOnBean() throws Exception {
- JsonSerializer s = JsonSerializer.DEFAULT_LAX;
- JsonParser p = JsonParser.DEFAULT;
- String r;
-
- A t = A.create();
- r = s.serialize(t);
- assertEquals("{foo:{f1:1}}", r);
- t = p.parse(r, A.class);
- assertEquals(1, t.f1);
-
- Map<String,A> m = new LinkedHashMap<String,A>();
- m.put("bar", A.create());
- r = s.serialize(m);
- assertEquals("{bar:{foo:{f1:1}}}", r);
-
- m = p.parseMap(r, LinkedHashMap.class, String.class, A.class);
- assertEquals(1, m.get("bar").f1);
- }
-
- @Json(wrapperAttr="foo")
- public static class A {
- public int f1;
-
- static A create() {
- A a = new A();
- a.f1 = 1;
- return a;
- }
- }
-
- //====================================================================================================
- // testWrapperAttrAnnotationOnNonBean
- //====================================================================================================
- @Test
- @SuppressWarnings("unchecked")
- public void testWrapperAttrAnnotationOnNonBean() throws Exception {
- JsonSerializer s = JsonSerializer.DEFAULT_LAX;
- JsonParser p = JsonParser.DEFAULT;
- String r;
-
- B t = B.create();
- r = s.serialize(t);
- assertEquals("{foo:'1'}", r);
- t = p.parse(r, B.class);
- assertEquals(1, t.f1);
-
- Map<String,B> m = new LinkedHashMap<String,B>();
- m.put("bar", B.create());
- r = s.serialize(m);
- assertEquals("{bar:{foo:'1'}}", r);
-
- m = p.parseMap(r, LinkedHashMap.class, String.class, B.class);
- assertEquals(1, m.get("bar").f1);
- }
-
- @Json(wrapperAttr="foo")
- public static class B {
- int f1;
-
- static B create() {
- B b = new B();
- b.f1 = 1;
- return b;
- }
-
- @Override /* Object */
- public String toString() {
- return String.valueOf(f1);
- }
-
- public static B valueOf(String s) {
- B b = new B();
- b.f1 = Integer.parseInt(s);
- return b;
- }
- }
-
- //====================================================================================================
- // testAddClassAttrs
- //====================================================================================================
- @Test
- public void testAddClassAttrs() throws Exception {
- JsonSerializer s = new JsonSerializer().setProperty(SERIALIZER_addClassAttrs, true);
- Map<String,Object> o = new HashMap<String,Object>();
- o.put("c", new C());
- assertEquals("{\"c\":{\"_class\":\"org.apache.juneau.json.CT_Json$C\",\"items\":[]}}", s.serialize(o));
- }
-
- public static class C extends LinkedList<String> {
- }
-
- //====================================================================================================
- // testEscapeSolidus
- //====================================================================================================
- @Test
- public void testEscapeSolidus() throws Exception {
- JsonSerializer s = new JsonSerializer().setProperty(JSON_escapeSolidus, false);
- String r = s.serialize("foo/bar");
- assertEquals("\"foo/bar\"", r);
- r = JsonParser.DEFAULT.parse(r, String.class);
- assertEquals("foo/bar", r);
-
- s = new JsonSerializer().setProperty(JSON_escapeSolidus, true);
- r = s.serialize("foo/bar");
- assertEquals("\"foo\\/bar\"", r);
- r = JsonParser.DEFAULT.parse(r, String.class);
- assertEquals("foo/bar", r);
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/json/CT_JsonParser.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/json/CT_JsonParser.java b/org.apache.juneau/src/test/java/org/apache/juneau/json/CT_JsonParser.java
deleted file mode 100755
index e00aa77..0000000
--- a/org.apache.juneau/src/test/java/org/apache/juneau/json/CT_JsonParser.java
+++ /dev/null
@@ -1,331 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.json;
-
-import static org.junit.Assert.*;
-
-import org.apache.juneau.*;
-import org.apache.juneau.parser.*;
-import org.apache.juneau.serializer.*;
-import org.junit.*;
-
-@SuppressWarnings("hiding")
-public class CT_JsonParser {
-
- private static final JsonParser p = JsonParser.DEFAULT;
- private static final JsonParser sp = JsonParser.DEFAULT_STRICT;
-
-
- //====================================================================================================
- // Test invalid input
- //====================================================================================================
- @Test
- public void testInvalidJson() {
- try {
- p.parse("{\na:1,\nb:xxx\n}", Object.class);
- fail("Exception expected.");
- } catch (ParseException e) {}
- }
-
- @Test
- public void testNonExistentAttribute() throws Exception {
- String json = "{foo:,bar:}";
- ObjectMap m = p.parse(json, ObjectMap.class);
- assertEquals("{foo:null,bar:null}", m.toString());
- }
-
- @Test
- public void testNonStringAsString() throws Exception {
- String json = "123";
- String s;
-
- // Strict mode does not allow unquoted values.
- try {
- sp.parse(json, String.class);
- fail("Exception expected");
- } catch (Exception e) {
- assertTrue(e.getMessage().contains("Did not find quote character"));
- }
-
- s = p.parse(json, String.class);
- assertEquals("123", s);
-
- json = " 123 ";
- // Strict mode does not allow unquoted values.
- try {
- sp.parse(json, String.class);
- fail("Exception expected");
- } catch (Exception e) {
- assertTrue(e.getMessage().contains("Did not find quote character"));
- }
-
- s = p.parse(json, String.class);
- assertEquals("123", s);
-
- json = "{\"fa\":123}";
- try {
- sp.parse(json, A.class);
- fail("Exception expected");
- } catch (Exception e) {
- assertTrue(e.getMessage().contains("Did not find quote character"));
- }
-
- A a = p.parse(json, A.class);
- assertEquals("123", a.fa);
-
- json = " { \"fa\" : 123 } ";
- try {
- sp.parse(json, A.class);
- fail("Exception expected");
- } catch (Exception e) {
- assertTrue(e.getMessage().contains("Did not find quote character"));
- }
-
- a = p.parse(json, A.class);
- assertEquals("123", a.fa);
-
- json = "'123'";
- try {
- sp.parse(json, String.class);
- fail("Exception expected");
- } catch (Exception e) {
- assertTrue(e.getMessage().contains("Invalid quote character"));
- }
- }
-
- public static class A {
- public String fa;
- }
-
- @Test
- public void testCognosJson() throws Exception {
- String json = TestUtils.readFile(getClass().getResource("/json/BrokenCognosOutput.txt").getPath());
- p.parse(json, ObjectMap.class);
- }
-
- @Test
- public void testStrictMode() throws Exception {
- JsonParser p = sp;
-
- // Missing attribute values.
- String json = "{\"foo\":,\"bar\":}";
- try {
- p.parse(json, ObjectMap.class);
- fail("Exception expected");
- } catch (ParseException e) {
- assertEquals("Parse exception occurred at {currentClass:'Object',line:1,column:7}. Missing value detected.", e.getRootCause().getMessage());
- }
-
- // Single quoted values.
- json = "{\"foo\":'bar'}";
- try {
- p.parse(json, ObjectMap.class);
- fail("Exception expected");
- } catch (ParseException e) {
- assertEquals("Parse exception occurred at {currentClass:'Object',line:1,column:8}. Invalid quote character \"'\" being used.", e.getRootCause().getMessage());
- }
-
- // Single quoted attribute name.
- json = "{'foo':\"bar\"}";
- try {
- p.parse(json, ObjectMap.class);
- fail("Exception expected");
- } catch (ParseException e) {
- assertEquals("Parse exception occurred at {currentClass:'ObjectMap<String,Object>',line:1,column:2}. Invalid quote character \"'\" being used.", e.getRootCause().getMessage());
- }
-
- // Unquoted attribute name.
- json = "{foo:\"bar\"}";
- try {
- p.parse(json, ObjectMap.class);
- fail("Exception expected");
- } catch (ParseException e) {
- assertEquals("Parse exception occurred at {currentClass:'ObjectMap<String,Object>',line:1,column:1}. Unquoted attribute detected.", e.getRootCause().getMessage());
- }
-
- // Concatenated string
- json = "{\"foo\":\"bar\"+\"baz\"}";
- try {
- p.parse(json, ObjectMap.class);
- fail("Exception expected");
- } catch (ParseException e) {
- assertEquals("Parse exception occurred at {currentClass:'Object',line:1,column:12}. String concatenation detected.", e.getRootCause().getMessage());
- }
-
- // Concatenated string 2
- json = "{\"foo\":\"bar\" + \"baz\"}";
- try {
- p.parse(json, ObjectMap.class);
- fail("Exception expected");
- } catch (ParseException e) {
- assertEquals("Parse exception occurred at {currentClass:'Object',line:1,column:13}. String concatenation detected.", e.getRootCause().getMessage());
- }
-
- json = "{\"foo\":/*comment*/\"bar\"}";
- try {
- p.parse(json, ObjectMap.class);
- fail("Exception expected");
- } catch (ParseException e) {
- assertEquals("Parse exception occurred at {currentClass:'ObjectMap<String,Object>',line:1,column:8}. Javascript comment detected.", e.getRootCause().getMessage());
- }
- }
-
- /**
- * JSON numbers and booleans should be representable as strings and converted accordingly.
- */
- @Test
- public void testPrimitivesAsStrings() throws Exception {
- String json;
- ReaderParser p = JsonParser.DEFAULT;
- WriterSerializer s = JsonSerializer.DEFAULT_LAX;
-
- json = "{f1:'1',f2:'1',f3:'true',f4:'true',f5:'1',f6:'1',f7:'1',f8:'1',f9:'1',f10:'1'}";
- B b = p.parse(json, B.class);
- assertEquals("{f1:1,f2:1,f3:true,f4:true,f5:1.0,f6:1.0,f7:1,f8:1,f9:1,f10:1}", s.toString(b));
-
- json = "{f1:'',f2:'',f3:'',f4:'',f5:'',f6:'',f7:'',f8:'',f9:'',f10:''}";
- b = p.parse(json, B.class);
- assertEquals("{f1:0,f2:0,f3:false,f4:false,f5:0.0,f6:0.0,f7:0,f8:0,f9:0,f10:0}", s.toString(b));
- }
-
- public static class B {
- public int f1;
- public Integer f2;
- public boolean f3;
- public Boolean f4;
- public float f5;
- public Float f6;
- public long f7;
- public Long f8;
- public byte f9;
- public Byte f10;
- }
-
- //====================================================================================================
- // testInvalidJsonNumbers
- // Lax parser allows octal and hexadecimal numbers. Strict parser does not.
- //====================================================================================================
- @Test
- public void testInvalidJsonNumbers() throws Exception {
- JsonParser p1 = JsonParser.DEFAULT;
- JsonParser p2 = JsonParser.DEFAULT_STRICT;
- Number r;
-
- // Lax allows blank strings interpreted as 0, strict does not.
- String s = "\"\"";
- r = p1.parse(s, Number.class);
- assertEquals(0, r.intValue());
- assertTrue(r instanceof Integer);
- try {
- r = p2.parse(s, Number.class);
- fail("Exception expected");
- } catch (ParseException e) {
- assertTrue(e.getMessage().endsWith("Invalid JSON number ''"));
- }
-
- // Either should allow 0 or -0.
- s = "0";
- r = p1.parse(s, Number.class);
- assertEquals(0, r.intValue());
- assertTrue(r instanceof Integer);
- r = p2.parse(s, Number.class);
- assertEquals(0, r.intValue());
- assertTrue(r instanceof Integer);
-
- s = "-0";
- r = p1.parse(s, Number.class);
- assertEquals(0, r.intValue());
- assertTrue(r instanceof Integer);
- r = p2.parse(s, Number.class);
- assertEquals(0, r.intValue());
- assertTrue(r instanceof Integer);
-
- // Lax allows 0123 and -0123, strict does not.
- s = "0123";
- r = p1.parse(s, Number.class);
- assertEquals(0123, r.intValue());
- assertTrue(r instanceof Integer);
- try {
- r = p2.parse(s, Number.class);
- fail("Exception expected");
- } catch (ParseException e) {
- assertTrue(e.getMessage().endsWith("Invalid JSON number '0123'"));
- }
- s = "-0123";
- r = p1.parse(s, Number.class);
- assertEquals(-0123, r.intValue());
- assertTrue(r instanceof Integer);
- try {
- r = p2.parse(s, Number.class);
- fail("Exception expected");
- } catch (ParseException e) {
- assertTrue(e.getMessage().endsWith("Invalid JSON number '-0123'"));
- }
-
- // Lax allows 0x123 and -0x123, strict does not.
- s = "0x123";
- r = p1.parse(s, Number.class);
- assertEquals(0x123, r.intValue());
- assertTrue(r instanceof Integer);
- try {
- r = p2.parse(s, Number.class);
- fail("Exception expected");
- } catch (ParseException e) {
- assertTrue(e.getMessage().endsWith("Invalid JSON number '0x123'"));
- }
- s = "-0x123";
- r = p1.parse(s, Number.class);
- assertEquals(-0x123, r.intValue());
- assertTrue(r instanceof Integer);
- try {
- r = p2.parse(s, Number.class);
- fail("Exception expected");
- } catch (ParseException e) {
- assertTrue(e.getMessage().endsWith("Invalid JSON number '-0x123'"));
- }
- }
-
- //====================================================================================================
- // testUnquotedStrings
- // Lax parser allows unquoted strings if POJO can be converted from a string.
- //====================================================================================================
- @Test
- public void testUnquotedStrings() throws Exception {
- JsonParser p1 = JsonParser.DEFAULT;
- JsonParser p2 = JsonParser.DEFAULT_STRICT;
-
- String s = "foobar";
- C c = p1.parse(s, C.class);
- assertEquals("f=foobar", c.toString());
-
- try {
- p2.parse(s, C.class);
- fail("Exception expected");
- } catch (ParseException e) {
- // OK
- }
- }
-
- public static class C {
- String f;
- public static C valueOf(String s) {
- C c = new C();
- c.f = s;
- return c;
- }
- @Override /* Object */
- public String toString() {
- return "f="+f;
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/json/CT_JsonSchema.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/json/CT_JsonSchema.java b/org.apache.juneau/src/test/java/org/apache/juneau/json/CT_JsonSchema.java
deleted file mode 100755
index a22412c..0000000
--- a/org.apache.juneau/src/test/java/org/apache/juneau/json/CT_JsonSchema.java
+++ /dev/null
@@ -1,44 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.json;
-
-import static org.junit.Assert.*;
-
-import org.junit.*;
-
-public class CT_JsonSchema {
-
- //====================================================================================================
- // Primitive objects
- //====================================================================================================
- @Test
- public void testBasic() throws Exception {
-
- JsonSchemaSerializer s = JsonSerializer.DEFAULT_LAX.getSchemaSerializer();
-
- Object o = new String();
- assertEquals("{type:'string',description:'java.lang.String'}", s.serialize(o));
-
- o = new Integer(123);
- assertEquals("{type:'number',description:'java.lang.Integer'}", s.serialize(o));
-
- o = new Float(123);
- assertEquals("{type:'number',description:'java.lang.Float'}", s.serialize(o));
-
- o = new Double(123);
- assertEquals("{type:'number',description:'java.lang.Double'}", s.serialize(o));
-
- o = Boolean.TRUE;
- assertEquals("{type:'boolean',description:'java.lang.Boolean'}", s.serialize(o));
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/json/CommonParserTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/json/CommonParserTest.java b/org.apache.juneau/src/test/java/org/apache/juneau/json/CommonParserTest.java
new file mode 100755
index 0000000..c809254
--- /dev/null
+++ b/org.apache.juneau/src/test/java/org/apache/juneau/json/CommonParserTest.java
@@ -0,0 +1,180 @@
+/***************************************************************************************************************************
+ * 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.juneau.json;
+
+import static org.apache.juneau.BeanContext.*;
+import static org.apache.juneau.serializer.SerializerContext.*;
+import static org.junit.Assert.*;
+
+import java.util.*;
+
+import org.apache.juneau.*;
+import org.apache.juneau.parser.*;
+import org.junit.*;
+
+@SuppressWarnings({"rawtypes","serial"})
+public class CommonParserTest {
+
+ //====================================================================================================
+ // testFromSerializer
+ //====================================================================================================
+ @Test
+ public void testFromSerializer() throws Exception {
+ ReaderParser p = JsonParser.DEFAULT.clone().setClassLoader(getClass().getClassLoader());
+
+ Map m = null;
+ m = (Map)p.parse("{a:1}", Object.class);
+ assertEquals(1, m.get("a"));
+ m = (Map)p.parse("{a:1,b:\"foo bar\"}", Object.class);
+ assertEquals(1, m.get("a"));
+ assertEquals("foo bar", m.get("b"));
+ m = (Map)p.parse("{a:1,b:\"foo bar\",c:false}", Object.class);
+ assertEquals(1, m.get("a"));
+ assertEquals(false, m.get("c"));
+ m = (Map)p.parse(" { a : 1 , b : 'foo' , c : false } ", Object.class);
+ assertEquals(1, m.get("a"));
+ assertEquals("foo", m.get("b"));
+ assertEquals(false, m.get("c"));
+
+ m = (Map)p.parse("{x:\"org.apache.juneau.test.Person\",addresses:[{x:\"org.apache.juneau.test.Address\",city:\"city A\",state:\"state A\",street:\"street A\",zip:12345}]}", Object.class);
+ assertEquals("org.apache.juneau.test.Person", m.get("x"));
+ List l = (List)m.get("addresses");
+ assertNotNull(l);
+ m = (Map)l.get(0);
+ assertNotNull(m);
+ assertEquals("org.apache.juneau.test.Address", m.get("x"));
+ assertEquals("city A", m.get("city"));
+ assertEquals("state A", m.get("state"));
+ assertEquals("street A", m.get("street"));
+ assertEquals(12345, m.get("zip"));
+
+ ObjectList jl = (ObjectList)p.parse("[{attribute:'value'},{attribute:'value'}]", Object.class);
+ assertEquals("value", jl.getObjectMap(0).getString("attribute"));
+ assertEquals("value", jl.getObjectMap(1).getString("attribute"));
+
+ // Verify that all the following return null.
+ assertNull(p.parse((CharSequence)null, Object.class));
+ assertNull(p.parse("", Object.class));
+ assertNull(p.parse(" ", Object.class));
+ assertNull(p.parse(" \t", Object.class));
+ assertNull(p.parse(" /*foo*/", Object.class));
+ assertNull(p.parse(" /*foo*/ ", Object.class));
+ assertNull(p.parse(" //foo ", Object.class));
+
+ try {
+ jl = (ObjectList)p.parse("[{attribute:'value'},{attribute:'value'}]", Object.class);
+ assertEquals("value", jl.getObjectMap(0).getString("attribute"));
+ assertEquals("value", jl.getObjectMap(1).getString("attribute"));
+ } catch (Exception e) {
+ fail(e.getLocalizedMessage());
+ }
+
+ A1 b = new A1();
+ A2 tl = new A2();
+ tl.add(new A3("name0","value0"));
+ tl.add(new A3("name1","value1"));
+ b.list = tl;
+ String json = new JsonSerializer().setProperty(SERIALIZER_addClassAttrs, true).serialize(b);
+ b = (A1)p.parse(json, Object.class);
+ assertEquals("value1", b.list.get(1).value);
+
+ json = JsonSerializer.DEFAULT.serialize(b);
+ b = p.parse(json, A1.class);
+ assertEquals("value1", b.list.get(1).value);
+ }
+
+ public static class A1 {
+ public A2 list;
+ }
+
+ public static class A2 extends LinkedList<A3> {
+ }
+
+ public static class A3 {
+ public String name, value;
+ public A3(){}
+ public A3(String name, String value) {
+ this.name = name;
+ this.value = value;
+ }
+ }
+
+ //====================================================================================================
+ // Correct handling of unknown properties.
+ //====================================================================================================
+ @Test
+ public void testCorrectHandlingOfUnknownProperties() throws Exception {
+ ReaderParser p = new JsonParser().setProperty(BEAN_ignoreUnknownBeanProperties, true);
+ B b;
+
+ String in = "{a:1,unknown:3,b:2}";
+ b = p.parse(in, B.class);
+ assertEquals(b.a, 1);
+ assertEquals(b.b, 2);
+
+ try {
+ p = new JsonParser();
+ p.parse(in, B.class);
+ fail("Exception expected");
+ } catch (ParseException e) {}
+ }
+
+ public static class B {
+ public int a, b;
+ }
+
+ //====================================================================================================
+ // Writing to Collection properties with no setters.
+ //====================================================================================================
+ @Test
+ public void testCollectionPropertiesWithNoSetters() throws Exception {
+ JsonParser p = JsonParser.DEFAULT;
+ String json = "{ints:[1,2,3],beans:[{a:1,b:2}]}";
+ C t = p.parse(json, C.class);
+ assertEquals(t.getInts().size(), 3);
+ assertEquals(t.getBeans().get(0).b, 2);
+ }
+
+ public static class C {
+ private Collection<Integer> ints = new LinkedList<Integer>();
+ private List<B> beans = new LinkedList<B>();
+ public Collection<Integer> getInts() {
+ return ints;
+ }
+ public List<B> getBeans() {
+ return beans;
+ }
+ }
+
+ //====================================================================================================
+ // Parser listeners.
+ //====================================================================================================
+ @Test
+ public void testParserListeners() throws Exception {
+ final List<String> events = new LinkedList<String>();
+ JsonParser p = new JsonParser().setProperty(BEAN_ignoreUnknownBeanProperties, true);
+ p.addListener(
+ new ParserListener() {
+ @Override /* ParserListener */
+ public <T> void onUnknownProperty(String propertyName, Class<T> beanClass, T bean, int line, int col) {
+ events.add(propertyName + "," + line + "," + col);
+ }
+ }
+ );
+
+ String json = "{a:1,unknownProperty:\"/foo\",b:2}";
+ p.parse(json, B.class);
+ assertEquals(1, events.size());
+ assertEquals("unknownProperty,1,5", events.get(0));
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/json/CommonTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/json/CommonTest.java b/org.apache.juneau/src/test/java/org/apache/juneau/json/CommonTest.java
new file mode 100755
index 0000000..c64fb25
--- /dev/null
+++ b/org.apache.juneau/src/test/java/org/apache/juneau/json/CommonTest.java
@@ -0,0 +1,501 @@
+/***************************************************************************************************************************
+ * 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.juneau.json;
+
+import static org.apache.juneau.BeanContext.*;
+import static org.apache.juneau.TestUtils.*;
+import static org.apache.juneau.serializer.SerializerContext.*;
+import static org.junit.Assert.*;
+
+import java.net.*;
+import java.net.URI;
+import java.util.*;
+
+import org.apache.juneau.*;
+import org.apache.juneau.annotation.*;
+import org.apache.juneau.serializer.*;
+import org.apache.juneau.testbeans.*;
+import org.junit.*;
+
+@SuppressWarnings({"serial"})
+public class CommonTest {
+
+ //====================================================================================================
+ // Trim nulls from beans
+ //====================================================================================================
+ @Test
+ public void testTrimNullsFromBeans() throws Exception {
+ JsonSerializer s = new JsonSerializer.Simple();
+ JsonParser p = JsonParser.DEFAULT;
+ A t1 = A.create(), t2;
+
+ s.setProperty(SERIALIZER_trimNullProperties, false);
+ String r = s.serialize(t1);
+ assertEquals("{s1:null,s2:'s2'}", r);
+ t2 = p.parse(r, A.class);
+ assertEqualObjects(t1, t2);
+
+ s.setProperty(SERIALIZER_trimNullProperties, true);
+ r = s.serialize(t1);
+ assertEquals("{s2:'s2'}", r);
+ t2 = p.parse(r, A.class);
+ assertEqualObjects(t1, t2);
+ }
+
+ public static class A {
+ public String s1, s2;
+
+ public static A create() {
+ A t = new A();
+ t.s2 = "s2";
+ return t;
+ }
+ }
+
+ //====================================================================================================
+ // Trim empty maps
+ //====================================================================================================
+ @Test
+ public void testTrimEmptyMaps() throws Exception {
+ JsonSerializer s = new JsonSerializer.Simple();
+ JsonParser p = JsonParser.DEFAULT;
+ B t1 = B.create(), t2;
+ String r;
+
+ s.setProperty(SERIALIZER_trimEmptyMaps, false);
+ r = s.serialize(t1);
+ assertEquals("{f1:{},f2:{f2a:null,f2b:{s2:'s2'}}}", r);
+ t2 = p.parse(r, B.class);
+ assertEqualObjects(t1, t2);
+
+ s.setProperty(SERIALIZER_trimEmptyMaps, true);
+ r = s.serialize(t1);
+ assertEquals("{f2:{f2a:null,f2b:{s2:'s2'}}}", r);
+ t2 = p.parse(r, B.class);
+ assertNull(t2.f1);
+ }
+
+ public static class B {
+ public TreeMap<String,A> f1, f2;
+
+ public static B create() {
+ B t = new B();
+ t.f1 = new TreeMap<String,A>();
+ t.f2 = new TreeMap<String,A>(){{put("f2a",null);put("f2b",A.create());}};
+ return t;
+ }
+ }
+
+ //====================================================================================================
+ // Trim empty lists
+ //====================================================================================================
+ @Test
+ public void testTrimEmptyLists() throws Exception {
+ JsonSerializer s = new JsonSerializer.Simple();
+ JsonParser p = JsonParser.DEFAULT;
+ C t1 = C.create(), t2;
+ String r;
+
+ s.setProperty(SERIALIZER_trimEmptyLists, false);
+ r = s.serialize(t1);
+ assertEquals("{f1:[],f2:[null,{s2:'s2'}]}", r);
+ t2 = p.parse(r, C.class);
+ assertEqualObjects(t1, t2);
+
+ s.setProperty(SERIALIZER_trimEmptyLists, true);
+ r = s.serialize(t1);
+ assertEquals("{f2:[null,{s2:'s2'}]}", r);
+ t2 = p.parse(r, C.class);
+ assertNull(t2.f1);
+ }
+
+ public static class C {
+ public List<A> f1, f2;
+
+ public static C create() {
+ C t = new C();
+ t.f1 = new LinkedList<A>();
+ t.f2 = new LinkedList<A>(){{add(null);add(A.create());}};
+ return t;
+ }
+ }
+
+ //====================================================================================================
+ // Trim empty arrays
+ //====================================================================================================
+ @Test
+ public void testTrimEmptyArrays() throws Exception {
+ JsonSerializer s = new JsonSerializer.Simple();
+ JsonParser p = JsonParser.DEFAULT;
+ D t1 = D.create(), t2;
+ String r;
+
+ s.setProperty(SERIALIZER_trimEmptyLists, false);
+ r = s.serialize(t1);
+ assertEquals("{f1:[],f2:[null,{s2:'s2'}]}", r);
+ t2 = p.parse(r, D.class);
+ assertEqualObjects(t1, t2);
+
+ s.setProperty(SERIALIZER_trimEmptyLists, true);
+ r = s.serialize(t1);
+ assertEquals("{f2:[null,{s2:'s2'}]}", r);
+ t2 = p.parse(r, D.class);
+ assertNull(t2.f1);
+ }
+
+ public static class D {
+ public A[] f1, f2;
+
+ public static D create() {
+ D t = new D();
+ t.f1 = new A[]{};
+ t.f2 = new A[]{null, A.create()};
+ return t;
+ }
+ }
+
+ //====================================================================================================
+ // @BeanProperty.properties annotation.
+ //====================================================================================================
+ @Test
+ public void testBeanPropertyProperies() throws Exception {
+ JsonSerializer s = JsonSerializer.DEFAULT_LAX;
+ E1 t = new E1();
+ String r;
+
+ r = s.serialize(t);
+ assertEquals("{x1:{f1:1},x2:{f1:1},x3:[{f1:1}],x4:[{f1:1}],x5:[{f1:1}],x6:[{f1:1}]}", r);
+ r = s.getSchemaSerializer().serialize(t);
+ assertTrue(r.indexOf("f2") == -1);
+ }
+
+ public static class E1 {
+ @BeanProperty(properties={"f1"}) public E2 x1 = new E2();
+ @BeanProperty(properties={"f1"}) public Map<String,Integer> x2 = new LinkedHashMap<String,Integer>() {{
+ put("f1",1); put("f2",2);
+ }};
+ @BeanProperty(properties={"f1"}) public E2[] x3 = {new E2()};
+ @BeanProperty(properties={"f1"}) public List<E2> x4 = new LinkedList<E2>() {{
+ add(new E2());
+ }};
+ @BeanProperty(properties={"f1"}) public ObjectMap[] x5 = {new ObjectMap().append("f1",1).append("f2",2)};
+ @BeanProperty(properties={"f1"}) public List<ObjectMap> x6 = new LinkedList<ObjectMap>() {{
+ add(new ObjectMap().append("f1",1).append("f2",2));
+ }};
+ }
+
+ public static class E2 {
+ public int f1 = 1;
+ public int f2 = 2;
+ }
+
+ //====================================================================================================
+ // @BeanProperty.properties annotation on list of beans.
+ //====================================================================================================
+ @Test
+ public void testBeanPropertyProperiesOnListOfBeans() throws Exception {
+ JsonSerializer s = JsonSerializer.DEFAULT_LAX;
+ List<F> l = new LinkedList<F>();
+ F t = new F();
+ t.x1.add(new F());
+ l.add(t);
+ String json = s.serialize(l);
+ assertEquals("[{x1:[{x2:2}],x2:2}]", json);
+ }
+
+ public static class F {
+ @BeanProperty(properties={"x2"}) public List<F> x1 = new LinkedList<F>();
+ public int x2 = 2;
+ }
+
+ //====================================================================================================
+ // Test that URLs and URIs are serialized and parsed correctly.
+ //====================================================================================================
+ @Test
+ public void testURIAttr() throws Exception {
+ JsonSerializer s = JsonSerializer.DEFAULT_LAX;
+ JsonParser p = JsonParser.DEFAULT;
+
+ G t = new G();
+ t.uri = new URI("http://uri");
+ t.f1 = new URI("http://f1");
+ t.f2 = new URL("http://f2");
+
+ String json = s.serialize(t);
+ t = p.parse(json, G.class);
+ assertEquals("http://uri", t.uri.toString());
+ assertEquals("http://f1", t.f1.toString());
+ assertEquals("http://f2", t.f2.toString());
+ }
+
+ public static class G {
+ @BeanProperty(beanUri=true) public URI uri;
+ public URI f1;
+ public URL f2;
+ }
+
+ //====================================================================================================
+ // Test URIs with URI_CONTEXT and URI_AUTHORITY
+ //====================================================================================================
+ @Test
+ public void testUris() throws Exception {
+ WriterSerializer s = new JsonSerializer.Simple();
+ TestURI t = new TestURI();
+ String r;
+ String expected = "";
+
+ s.setProperty(SERIALIZER_relativeUriBase, null);
+ r = s.serialize(t);
+ expected = "{"
+ +"f0:'f0/x0',"
+ +"f1:'f1/x1',"
+ +"f2:'/f2/x2',"
+ +"f3:'http://www.ibm.com/f3/x3',"
+ +"f4:'f4/x4',"
+ +"f5:'/f5/x5',"
+ +"f6:'http://www.ibm.com/f6/x6',"
+ +"f7:'http://www.ibm.com/f7/x7',"
+ +"f8:'f8/x8',"
+ +"f9:'f9/x9',"
+ +"fa:'http://www.ibm.com/fa/xa#MY_LABEL',"
+ +"fb:'http://www.ibm.com/fb/xb?label=MY_LABEL&foo=bar',"
+ +"fc:'http://www.ibm.com/fc/xc?foo=bar&label=MY_LABEL',"
+ +"fd:'http://www.ibm.com/fd/xd?label2=MY_LABEL&foo=bar',"
+ +"fe:'http://www.ibm.com/fe/xe?foo=bar&label2=MY_LABEL'"
+ +"}";
+ assertEquals(expected, r);
+
+ s.setProperty(SERIALIZER_relativeUriBase, ""); // Same as null.
+ r = s.serialize(t);
+ assertEquals(expected, r);
+
+ s.setProperty(SERIALIZER_relativeUriBase, "/cr");
+ r = s.serialize(t);
+ expected = "{"
+ +"f0:'/cr/f0/x0',"
+ +"f1:'/cr/f1/x1',"
+ +"f2:'/f2/x2',"
+ +"f3:'http://www.ibm.com/f3/x3',"
+ +"f4:'/cr/f4/x4',"
+ +"f5:'/f5/x5',"
+ +"f6:'http://www.ibm.com/f6/x6',"
+ +"f7:'http://www.ibm.com/f7/x7',"
+ +"f8:'/cr/f8/x8',"
+ +"f9:'/cr/f9/x9',"
+ +"fa:'http://www.ibm.com/fa/xa#MY_LABEL',"
+ +"fb:'http://www.ibm.com/fb/xb?label=MY_LABEL&foo=bar',"
+ +"fc:'http://www.ibm.com/fc/xc?foo=bar&label=MY_LABEL',"
+ +"fd:'http://www.ibm.com/fd/xd?label2=MY_LABEL&foo=bar',"
+ +"fe:'http://www.ibm.com/fe/xe?foo=bar&label2=MY_LABEL'"
+ +"}";
+ assertEquals(expected, r);
+
+ s.setProperty(SERIALIZER_relativeUriBase, "/cr/"); // Same as above
+ r = s.serialize(t);
+ assertEquals(expected, r);
+
+ s.setProperty(SERIALIZER_relativeUriBase, "/");
+ r = s.serialize(t);
+ expected = "{"
+ +"f0:'/f0/x0',"
+ +"f1:'/f1/x1',"
+ +"f2:'/f2/x2',"
+ +"f3:'http://www.ibm.com/f3/x3',"
+ +"f4:'/f4/x4',"
+ +"f5:'/f5/x5',"
+ +"f6:'http://www.ibm.com/f6/x6',"
+ +"f7:'http://www.ibm.com/f7/x7',"
+ +"f8:'/f8/x8',"
+ +"f9:'/f9/x9',"
+ +"fa:'http://www.ibm.com/fa/xa#MY_LABEL',"
+ +"fb:'http://www.ibm.com/fb/xb?label=MY_LABEL&foo=bar',"
+ +"fc:'http://www.ibm.com/fc/xc?foo=bar&label=MY_LABEL',"
+ +"fd:'http://www.ibm.com/fd/xd?label2=MY_LABEL&foo=bar',"
+ +"fe:'http://www.ibm.com/fe/xe?foo=bar&label2=MY_LABEL'"
+ +"}";
+ assertEquals(expected, r);
+
+ s.setProperty(SERIALIZER_relativeUriBase, null);
+
+ s.setProperty(SERIALIZER_absolutePathUriBase, "http://foo");
+ r = s.serialize(t);
+ expected = "{"
+ +"f0:'f0/x0',"
+ +"f1:'f1/x1',"
+ +"f2:'http://foo/f2/x2',"
+ +"f3:'http://www.ibm.com/f3/x3',"
+ +"f4:'f4/x4',"
+ +"f5:'http://foo/f5/x5',"
+ +"f6:'http://www.ibm.com/f6/x6',"
+ +"f7:'http://www.ibm.com/f7/x7',"
+ +"f8:'f8/x8',"
+ +"f9:'f9/x9',"
+ +"fa:'http://www.ibm.com/fa/xa#MY_LABEL',"
+ +"fb:'http://www.ibm.com/fb/xb?label=MY_LABEL&foo=bar',"
+ +"fc:'http://www.ibm.com/fc/xc?foo=bar&label=MY_LABEL',"
+ +"fd:'http://www.ibm.com/fd/xd?label2=MY_LABEL&foo=bar',"
+ +"fe:'http://www.ibm.com/fe/xe?foo=bar&label2=MY_LABEL'"
+ +"}";
+ assertEquals(expected, r);
+
+ s.setProperty(SERIALIZER_absolutePathUriBase, "http://foo/");
+ r = s.serialize(t);
+ assertEquals(expected, r);
+
+ s.setProperty(SERIALIZER_absolutePathUriBase, ""); // Same as null.
+ r = s.serialize(t);
+ expected = "{"
+ +"f0:'f0/x0',"
+ +"f1:'f1/x1',"
+ +"f2:'/f2/x2',"
+ +"f3:'http://www.ibm.com/f3/x3',"
+ +"f4:'f4/x4',"
+ +"f5:'/f5/x5',"
+ +"f6:'http://www.ibm.com/f6/x6',"
+ +"f7:'http://www.ibm.com/f7/x7',"
+ +"f8:'f8/x8',"
+ +"f9:'f9/x9',"
+ +"fa:'http://www.ibm.com/fa/xa#MY_LABEL',"
+ +"fb:'http://www.ibm.com/fb/xb?label=MY_LABEL&foo=bar',"
+ +"fc:'http://www.ibm.com/fc/xc?foo=bar&label=MY_LABEL',"
+ +"fd:'http://www.ibm.com/fd/xd?label2=MY_LABEL&foo=bar',"
+ +"fe:'http://www.ibm.com/fe/xe?foo=bar&label2=MY_LABEL'"
+ +"}";
+ assertEquals(expected, r);
+ }
+
+ //====================================================================================================
+ // Validate that you cannot update properties on locked serializer.
+ //====================================================================================================
+ @Test
+ public void testLockedSerializer() throws Exception {
+ JsonSerializer s = new JsonSerializer().lock();
+ try {
+ s.setProperty(JsonSerializerContext.JSON_simpleMode, true);
+ fail("Locked exception not thrown");
+ } catch (LockedException e) {}
+ try {
+ s.setProperty(SerializerContext.SERIALIZER_addClassAttrs, true);
+ fail("Locked exception not thrown");
+ } catch (LockedException e) {}
+ try {
+ s.setProperty(BeanContext.BEAN_beanMapPutReturnsOldValue, true);
+ fail("Locked exception not thrown");
+ } catch (LockedException e) {}
+ }
+
+ //====================================================================================================
+ // Recursion
+ //====================================================================================================
+ @Test
+ public void testRecursion() throws Exception {
+ JsonSerializer s = new JsonSerializer.Simple();
+
+ R1 r1 = new R1();
+ R2 r2 = new R2();
+ R3 r3 = new R3();
+ r1.r2 = r2;
+ r2.r3 = r3;
+ r3.r1 = r1;
+
+ // No recursion detection
+ try {
+ s.serialize(r1);
+ fail("Exception expected!");
+ } catch (Exception e) {
+ String msg = e.getLocalizedMessage();
+ assertTrue(msg.contains("It's recommended you use the SerializerContext.SERIALIZER_detectRecursions setting to help locate the loop."));
+ }
+
+ // Recursion detection, no ignore
+ s.setProperty(SERIALIZER_detectRecursions, true);
+ try {
+ s.serialize(r1);
+ fail("Exception expected!");
+ } catch (Exception e) {
+ String msg = e.getLocalizedMessage();
+ assertTrue(msg.contains("[0]root:org.apache.juneau.json.CommonTest$R1"));
+ assertTrue(msg.contains("->[1]r2:org.apache.juneau.json.CommonTest$R2"));
+ assertTrue(msg.contains("->[2]r3:org.apache.juneau.json.CommonTest$R3"));
+ assertTrue(msg.contains("->[3]r1:org.apache.juneau.json.CommonTest$R1"));
+ }
+
+ s.setProperty(SERIALIZER_ignoreRecursions, true);
+ assertEquals("{name:'foo',r2:{name:'bar',r3:{name:'baz'}}}", s.serialize(r1));
+
+ // Make sure this doesn't blow up.
+ s.getSchemaSerializer().serialize(r1);
+ }
+
+ public static class R1 {
+ public String name = "foo";
+ public R2 r2;
+ }
+ public static class R2 {
+ public String name = "bar";
+ public R3 r3;
+ }
+ public static class R3 {
+ public String name = "baz";
+ public R1 r1;
+ }
+
+ //====================================================================================================
+ // Basic bean
+ //====================================================================================================
+ @Test
+ public void testBasicBean() throws Exception {
+ JsonSerializer s = new JsonSerializer.Simple().setProperty(SERIALIZER_trimNullProperties, false).setProperty(BEAN_sortProperties, true);
+
+ J a = new J();
+ a.setF1("J");
+ a.setF2(100);
+ a.setF3(true);
+ assertEquals("C1", "{f1:'J',f2:100,f3:true}", s.serialize(a));
+ }
+
+ public static class J {
+ private String f1 = null;
+ private int f2 = -1;
+ private boolean f3 = false;
+
+ public String getF1() {
+ return this.f1;
+ }
+
+ public void setF1(String f1) {
+ this.f1 = f1;
+ }
+
+ public int getF2() {
+ return this.f2;
+ }
+
+ public void setF2(int f2) {
+ this.f2 = f2;
+ }
+
+ public boolean isF3() {
+ return this.f3;
+ }
+
+ public void setF3(boolean f3) {
+ this.f3 = f3;
+ }
+
+ @Override /* Object */
+ public String toString() {
+ return ("J(f1: " + this.getF1() + ", f2: " + this.getF2() + ")");
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/json/JsonParserTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/json/JsonParserTest.java b/org.apache.juneau/src/test/java/org/apache/juneau/json/JsonParserTest.java
new file mode 100755
index 0000000..1f10dee
--- /dev/null
+++ b/org.apache.juneau/src/test/java/org/apache/juneau/json/JsonParserTest.java
@@ -0,0 +1,331 @@
+/***************************************************************************************************************************
+ * 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.juneau.json;
+
+import static org.junit.Assert.*;
+
+import org.apache.juneau.*;
+import org.apache.juneau.parser.*;
+import org.apache.juneau.serializer.*;
+import org.junit.*;
+
+@SuppressWarnings("hiding")
+public class JsonParserTest {
+
+ private static final JsonParser p = JsonParser.DEFAULT;
+ private static final JsonParser sp = JsonParser.DEFAULT_STRICT;
+
+
+ //====================================================================================================
+ // Test invalid input
+ //====================================================================================================
+ @Test
+ public void testInvalidJson() {
+ try {
+ p.parse("{\na:1,\nb:xxx\n}", Object.class);
+ fail("Exception expected.");
+ } catch (ParseException e) {}
+ }
+
+ @Test
+ public void testNonExistentAttribute() throws Exception {
+ String json = "{foo:,bar:}";
+ ObjectMap m = p.parse(json, ObjectMap.class);
+ assertEquals("{foo:null,bar:null}", m.toString());
+ }
+
+ @Test
+ public void testNonStringAsString() throws Exception {
+ String json = "123";
+ String s;
+
+ // Strict mode does not allow unquoted values.
+ try {
+ sp.parse(json, String.class);
+ fail("Exception expected");
+ } catch (Exception e) {
+ assertTrue(e.getMessage().contains("Did not find quote character"));
+ }
+
+ s = p.parse(json, String.class);
+ assertEquals("123", s);
+
+ json = " 123 ";
+ // Strict mode does not allow unquoted values.
+ try {
+ sp.parse(json, String.class);
+ fail("Exception expected");
+ } catch (Exception e) {
+ assertTrue(e.getMessage().contains("Did not find quote character"));
+ }
+
+ s = p.parse(json, String.class);
+ assertEquals("123", s);
+
+ json = "{\"fa\":123}";
+ try {
+ sp.parse(json, A.class);
+ fail("Exception expected");
+ } catch (Exception e) {
+ assertTrue(e.getMessage().contains("Did not find quote character"));
+ }
+
+ A a = p.parse(json, A.class);
+ assertEquals("123", a.fa);
+
+ json = " { \"fa\" : 123 } ";
+ try {
+ sp.parse(json, A.class);
+ fail("Exception expected");
+ } catch (Exception e) {
+ assertTrue(e.getMessage().contains("Did not find quote character"));
+ }
+
+ a = p.parse(json, A.class);
+ assertEquals("123", a.fa);
+
+ json = "'123'";
+ try {
+ sp.parse(json, String.class);
+ fail("Exception expected");
+ } catch (Exception e) {
+ assertTrue(e.getMessage().contains("Invalid quote character"));
+ }
+ }
+
+ public static class A {
+ public String fa;
+ }
+
+ @Test
+ public void testCognosJson() throws Exception {
+ String json = TestUtils.readFile(getClass().getResource("/json/BrokenCognosOutput.txt").getPath());
+ p.parse(json, ObjectMap.class);
+ }
+
+ @Test
+ public void testStrictMode() throws Exception {
+ JsonParser p = sp;
+
+ // Missing attribute values.
+ String json = "{\"foo\":,\"bar\":}";
+ try {
+ p.parse(json, ObjectMap.class);
+ fail("Exception expected");
+ } catch (ParseException e) {
+ assertEquals("Parse exception occurred at {currentClass:'Object',line:1,column:7}. Missing value detected.", e.getRootCause().getMessage());
+ }
+
+ // Single quoted values.
+ json = "{\"foo\":'bar'}";
+ try {
+ p.parse(json, ObjectMap.class);
+ fail("Exception expected");
+ } catch (ParseException e) {
+ assertEquals("Parse exception occurred at {currentClass:'Object',line:1,column:8}. Invalid quote character \"'\" being used.", e.getRootCause().getMessage());
+ }
+
+ // Single quoted attribute name.
+ json = "{'foo':\"bar\"}";
+ try {
+ p.parse(json, ObjectMap.class);
+ fail("Exception expected");
+ } catch (ParseException e) {
+ assertEquals("Parse exception occurred at {currentClass:'ObjectMap<String,Object>',line:1,column:2}. Invalid quote character \"'\" being used.", e.getRootCause().getMessage());
+ }
+
+ // Unquoted attribute name.
+ json = "{foo:\"bar\"}";
+ try {
+ p.parse(json, ObjectMap.class);
+ fail("Exception expected");
+ } catch (ParseException e) {
+ assertEquals("Parse exception occurred at {currentClass:'ObjectMap<String,Object>',line:1,column:1}. Unquoted attribute detected.", e.getRootCause().getMessage());
+ }
+
+ // Concatenated string
+ json = "{\"foo\":\"bar\"+\"baz\"}";
+ try {
+ p.parse(json, ObjectMap.class);
+ fail("Exception expected");
+ } catch (ParseException e) {
+ assertEquals("Parse exception occurred at {currentClass:'Object',line:1,column:12}. String concatenation detected.", e.getRootCause().getMessage());
+ }
+
+ // Concatenated string 2
+ json = "{\"foo\":\"bar\" + \"baz\"}";
+ try {
+ p.parse(json, ObjectMap.class);
+ fail("Exception expected");
+ } catch (ParseException e) {
+ assertEquals("Parse exception occurred at {currentClass:'Object',line:1,column:13}. String concatenation detected.", e.getRootCause().getMessage());
+ }
+
+ json = "{\"foo\":/*comment*/\"bar\"}";
+ try {
+ p.parse(json, ObjectMap.class);
+ fail("Exception expected");
+ } catch (ParseException e) {
+ assertEquals("Parse exception occurred at {currentClass:'ObjectMap<String,Object>',line:1,column:8}. Javascript comment detected.", e.getRootCause().getMessage());
+ }
+ }
+
+ /**
+ * JSON numbers and booleans should be representable as strings and converted accordingly.
+ */
+ @Test
+ public void testPrimitivesAsStrings() throws Exception {
+ String json;
+ ReaderParser p = JsonParser.DEFAULT;
+ WriterSerializer s = JsonSerializer.DEFAULT_LAX;
+
+ json = "{f1:'1',f2:'1',f3:'true',f4:'true',f5:'1',f6:'1',f7:'1',f8:'1',f9:'1',f10:'1'}";
+ B b = p.parse(json, B.class);
+ assertEquals("{f1:1,f2:1,f3:true,f4:true,f5:1.0,f6:1.0,f7:1,f8:1,f9:1,f10:1}", s.toString(b));
+
+ json = "{f1:'',f2:'',f3:'',f4:'',f5:'',f6:'',f7:'',f8:'',f9:'',f10:''}";
+ b = p.parse(json, B.class);
+ assertEquals("{f1:0,f2:0,f3:false,f4:false,f5:0.0,f6:0.0,f7:0,f8:0,f9:0,f10:0}", s.toString(b));
+ }
+
+ public static class B {
+ public int f1;
+ public Integer f2;
+ public boolean f3;
+ public Boolean f4;
+ public float f5;
+ public Float f6;
+ public long f7;
+ public Long f8;
+ public byte f9;
+ public Byte f10;
+ }
+
+ //====================================================================================================
+ // testInvalidJsonNumbers
+ // Lax parser allows octal and hexadecimal numbers. Strict parser does not.
+ //====================================================================================================
+ @Test
+ public void testInvalidJsonNumbers() throws Exception {
+ JsonParser p1 = JsonParser.DEFAULT;
+ JsonParser p2 = JsonParser.DEFAULT_STRICT;
+ Number r;
+
+ // Lax allows blank strings interpreted as 0, strict does not.
+ String s = "\"\"";
+ r = p1.parse(s, Number.class);
+ assertEquals(0, r.intValue());
+ assertTrue(r instanceof Integer);
+ try {
+ r = p2.parse(s, Number.class);
+ fail("Exception expected");
+ } catch (ParseException e) {
+ assertTrue(e.getMessage().endsWith("Invalid JSON number ''"));
+ }
+
+ // Either should allow 0 or -0.
+ s = "0";
+ r = p1.parse(s, Number.class);
+ assertEquals(0, r.intValue());
+ assertTrue(r instanceof Integer);
+ r = p2.parse(s, Number.class);
+ assertEquals(0, r.intValue());
+ assertTrue(r instanceof Integer);
+
+ s = "-0";
+ r = p1.parse(s, Number.class);
+ assertEquals(0, r.intValue());
+ assertTrue(r instanceof Integer);
+ r = p2.parse(s, Number.class);
+ assertEquals(0, r.intValue());
+ assertTrue(r instanceof Integer);
+
+ // Lax allows 0123 and -0123, strict does not.
+ s = "0123";
+ r = p1.parse(s, Number.class);
+ assertEquals(0123, r.intValue());
+ assertTrue(r instanceof Integer);
+ try {
+ r = p2.parse(s, Number.class);
+ fail("Exception expected");
+ } catch (ParseException e) {
+ assertTrue(e.getMessage().endsWith("Invalid JSON number '0123'"));
+ }
+ s = "-0123";
+ r = p1.parse(s, Number.class);
+ assertEquals(-0123, r.intValue());
+ assertTrue(r instanceof Integer);
+ try {
+ r = p2.parse(s, Number.class);
+ fail("Exception expected");
+ } catch (ParseException e) {
+ assertTrue(e.getMessage().endsWith("Invalid JSON number '-0123'"));
+ }
+
+ // Lax allows 0x123 and -0x123, strict does not.
+ s = "0x123";
+ r = p1.parse(s, Number.class);
+ assertEquals(0x123, r.intValue());
+ assertTrue(r instanceof Integer);
+ try {
+ r = p2.parse(s, Number.class);
+ fail("Exception expected");
+ } catch (ParseException e) {
+ assertTrue(e.getMessage().endsWith("Invalid JSON number '0x123'"));
+ }
+ s = "-0x123";
+ r = p1.parse(s, Number.class);
+ assertEquals(-0x123, r.intValue());
+ assertTrue(r instanceof Integer);
+ try {
+ r = p2.parse(s, Number.class);
+ fail("Exception expected");
+ } catch (ParseException e) {
+ assertTrue(e.getMessage().endsWith("Invalid JSON number '-0x123'"));
+ }
+ }
+
+ //====================================================================================================
+ // testUnquotedStrings
+ // Lax parser allows unquoted strings if POJO can be converted from a string.
+ //====================================================================================================
+ @Test
+ public void testUnquotedStrings() throws Exception {
+ JsonParser p1 = JsonParser.DEFAULT;
+ JsonParser p2 = JsonParser.DEFAULT_STRICT;
+
+ String s = "foobar";
+ C c = p1.parse(s, C.class);
+ assertEquals("f=foobar", c.toString());
+
+ try {
+ p2.parse(s, C.class);
+ fail("Exception expected");
+ } catch (ParseException e) {
+ // OK
+ }
+ }
+
+ public static class C {
+ String f;
+ public static C valueOf(String s) {
+ C c = new C();
+ c.f = s;
+ return c;
+ }
+ @Override /* Object */
+ public String toString() {
+ return "f="+f;
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/json/JsonSchemaTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/json/JsonSchemaTest.java b/org.apache.juneau/src/test/java/org/apache/juneau/json/JsonSchemaTest.java
new file mode 100755
index 0000000..f484a07
--- /dev/null
+++ b/org.apache.juneau/src/test/java/org/apache/juneau/json/JsonSchemaTest.java
@@ -0,0 +1,44 @@
+/***************************************************************************************************************************
+ * 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.juneau.json;
+
+import static org.junit.Assert.*;
+
+import org.junit.*;
+
+public class JsonSchemaTest {
+
+ //====================================================================================================
+ // Primitive objects
+ //====================================================================================================
+ @Test
+ public void testBasic() throws Exception {
+
+ JsonSchemaSerializer s = JsonSerializer.DEFAULT_LAX.getSchemaSerializer();
+
+ Object o = new String();
+ assertEquals("{type:'string',description:'java.lang.String'}", s.serialize(o));
+
+ o = new Integer(123);
+ assertEquals("{type:'number',description:'java.lang.Integer'}", s.serialize(o));
+
+ o = new Float(123);
+ assertEquals("{type:'number',description:'java.lang.Float'}", s.serialize(o));
+
+ o = new Double(123);
+ assertEquals("{type:'number',description:'java.lang.Double'}", s.serialize(o));
+
+ o = Boolean.TRUE;
+ assertEquals("{type:'boolean',description:'java.lang.Boolean'}", s.serialize(o));
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/json/JsonTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/json/JsonTest.java b/org.apache.juneau/src/test/java/org/apache/juneau/json/JsonTest.java
new file mode 100755
index 0000000..6f7fd4f
--- /dev/null
+++ b/org.apache.juneau/src/test/java/org/apache/juneau/json/JsonTest.java
@@ -0,0 +1,308 @@
+/***************************************************************************************************************************
+ * 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.juneau.json;
+
+import static org.apache.juneau.TestUtils.*;
+import static org.apache.juneau.json.JsonSerializerContext.*;
+import static org.apache.juneau.serializer.SerializerContext.*;
+import static org.junit.Assert.*;
+
+import java.util.*;
+
+import org.apache.juneau.*;
+import org.apache.juneau.json.annotation.*;
+import org.apache.juneau.serializer.*;
+import org.junit.*;
+
+@SuppressWarnings("serial")
+public class JsonTest {
+
+ //====================================================================================================
+ // testBasic
+ //====================================================================================================
+ @Test
+ public void testBasic() throws Exception {
+ Map<String,Object> m = new LinkedHashMap<String,Object>();
+ List<Object> l = new LinkedList<Object>();
+
+ WriterSerializer s1 = new JsonSerializer.Simple().setProperty(SERIALIZER_trimNullProperties, false);
+ WriterSerializer s2 = new JsonSerializer.Simple().setProperty(SERIALIZER_trimNullProperties, false).setProperty(SERIALIZER_quoteChar, '"');
+ String r;
+
+ // Null keys and values
+ m.clear();
+ m.put(null, null);
+ m.put("aaa", "bbb");
+ assertEquals("A1", "{null:null,aaa:'bbb'}", s1.serialize(m));
+
+ // Escapes.
+ // String = ["]
+ m.clear();
+ m.put("x", "[\"]");
+ assertEquals("{x:\"[\\\"]\"}", s2.serialize(m));
+ // String = [\"]
+ // JSON = {x:"\\\""}
+ m.clear();
+ m.put("x", "[\\\"]");
+ assertEquals("{x:\"[\\\\\\\"]\"}", s2.serialize(m));
+
+ // String = [\w[\w\-\.]{3,}\w]
+ // JSON = {x:"\\w[\\w\\-\\.]{3,}\\w"}
+ m.clear();
+ r = "\\w[\\w\\-\\.]{3,}\\w";
+ m.put("x", r);
+ assertEquals("{x:\"\\\\w[\\\\w\\\\-\\\\.]{3,}\\\\w\"}", s2.serialize(m));
+ assertEquals(r, new ObjectMap(s2.serialize(m)).getString("x"));
+
+ // String = [foo\bar]
+ // JSON = {x:"foo\\bar"}
+ m.clear();
+ m.put("x", "foo\\bar");
+ assertEquals("{x:\"foo\\\\bar\"}", s2.serialize(m));
+
+ m.clear();
+ m.put("null", null);
+ m.put("aaa", "bbb");
+ assertEquals("A2", "{'null':null,aaa:'bbb'}", s1.serialize(m));
+
+ m.clear();
+ m.put(null, "null");
+ m.put("aaa", "bbb");
+ assertEquals("A3", "{null:'null',aaa:'bbb'}", s1.serialize(m));
+
+ // Arrays
+ m.clear();
+ l.clear();
+ m.put("J", "f1");
+ m.put("B", "b");
+ m.put("C", "c");
+ l.add("1");
+ l.add("2");
+ l.add("3");
+ Object o = new Object[] { m, l };
+ Object o2 = new Object[] { o, "foo", "bar", new Integer(1), new Boolean(false), new Float(1.2), null };
+ assertEquals("K1", "[[{J:'f1',B:'b',C:'c'},['1','2','3']],'foo','bar',1,false,1.2,null]", s1.serialize(o2));
+ }
+
+ @Test
+ public void testReservedKeywordAttributes() throws Exception {
+ Map<String,Object> m = new LinkedHashMap<String,Object>();
+
+ // Keys with reserved names.
+ for (String attr : new String[]{"","true","false","null","try","123","1x","-123",".123"}) {
+ m.clear();
+ m.put(attr,1);
+ assertObjectEquals("{'"+attr+"':1}", m);
+ }
+ }
+
+ //====================================================================================================
+ // Validate various backslashes in strings.
+ //====================================================================================================
+ @Test
+ public void testBackslashesInStrings() throws Exception {
+ JsonSerializer s = new JsonSerializer.Simple().setProperty(SERIALIZER_trimNullProperties, false).setProperty(SERIALIZER_quoteChar, '"');
+ String r, r2;
+
+ // [\\]
+ r = "\\";
+ r2 = s.serialize(r);
+ assertEquals(r2, "\"\\\\\"");
+ assertEquals(JsonParser.DEFAULT.parse(r2, Object.class), r);
+
+ // [\b\f\n\t]
+ r = "\b\f\n\t";
+ r2 = s.serialize(r);
+ assertEquals("\"\\b\\f\\n\\t\"", r2);
+ assertEquals(r, JsonParser.DEFAULT.parse(r2, Object.class));
+
+ // Special JSON case: Forward slashes can OPTIONALLY be escaped.
+ // [\/]
+ assertEquals(JsonParser.DEFAULT.parse("\"\\/\"", Object.class), "/");
+
+ // Unicode
+ r = "\u1234\u1ABC\u1abc";
+ r2 = s.serialize(r);
+ assertEquals("\"\u1234\u1ABC\u1abc\"", r2);
+
+ assertEquals("\u1234", JsonParser.DEFAULT.parse("\"\\u1234\"", Object.class));
+ }
+
+ //====================================================================================================
+ // Indentation
+ //====================================================================================================
+ @Test
+ public void testIndentation() throws Exception {
+ ObjectMap m = new ObjectMap("{J:{B:['c',{D:'e'},['f',{G:'h'},1,false]]},I:'j'}");
+ String e = ""
+ + "{"
+ + "\n J: {"
+ + "\n B: ["
+ + "\n 'c', "
+ + "\n {"
+ + "\n D: 'e'"
+ + "\n }, "
+ + "\n ["
+ + "\n 'f', "
+ + "\n {"
+ + "\n G: 'h'"
+ + "\n }, "
+ + "\n 1, "
+ + "\n false"
+ + "\n ]"
+ + "\n ]"
+ + "\n }, "
+ + "\n I: 'j'"
+ + "\n}";
+ assertEquals(e, JsonSerializer.DEFAULT_LAX_READABLE.serialize(m));
+ }
+
+ //====================================================================================================
+ // Escaping double quotes
+ //====================================================================================================
+ @Test
+ public void testEscapingDoubleQuotes() throws Exception {
+ JsonSerializer s = JsonSerializer.DEFAULT;
+ String r = s.serialize(new ObjectMap().append("f1", "x'x\"x"));
+ assertEquals("{\"f1\":\"x'x\\\"x\"}", r);
+ JsonParser p = JsonParser.DEFAULT;
+ assertEquals("x'x\"x", p.parse(r, ObjectMap.class).getString("f1"));
+ }
+
+ //====================================================================================================
+ // Escaping single quotes
+ //====================================================================================================
+ @Test
+ public void testEscapingSingleQuotes() throws Exception {
+ JsonSerializer s = JsonSerializer.DEFAULT_LAX;
+ String r = s.serialize(new ObjectMap().append("f1", "x'x\"x"));
+ assertEquals("{f1:'x\\'x\"x'}", r);
+ JsonParser p = JsonParser.DEFAULT;
+ assertEquals("x'x\"x", p.parse(r, ObjectMap.class).getString("f1"));
+ }
+
+ //====================================================================================================
+ // testWrapperAttrAnnotationOnBean
+ //====================================================================================================
+ @Test
+ @SuppressWarnings("unchecked")
+ public void testWrapperAttrAnnotationOnBean() throws Exception {
+ JsonSerializer s = JsonSerializer.DEFAULT_LAX;
+ JsonParser p = JsonParser.DEFAULT;
+ String r;
+
+ A t = A.create();
+ r = s.serialize(t);
+ assertEquals("{foo:{f1:1}}", r);
+ t = p.parse(r, A.class);
+ assertEquals(1, t.f1);
+
+ Map<String,A> m = new LinkedHashMap<String,A>();
+ m.put("bar", A.create());
+ r = s.serialize(m);
+ assertEquals("{bar:{foo:{f1:1}}}", r);
+
+ m = p.parseMap(r, LinkedHashMap.class, String.class, A.class);
+ assertEquals(1, m.get("bar").f1);
+ }
+
+ @Json(wrapperAttr="foo")
+ public static class A {
+ public int f1;
+
+ static A create() {
+ A a = new A();
+ a.f1 = 1;
+ return a;
+ }
+ }
+
+ //====================================================================================================
+ // testWrapperAttrAnnotationOnNonBean
+ //====================================================================================================
+ @Test
+ @SuppressWarnings("unchecked")
+ public void testWrapperAttrAnnotationOnNonBean() throws Exception {
+ JsonSerializer s = JsonSerializer.DEFAULT_LAX;
+ JsonParser p = JsonParser.DEFAULT;
+ String r;
+
+ B t = B.create();
+ r = s.serialize(t);
+ assertEquals("{foo:'1'}", r);
+ t = p.parse(r, B.class);
+ assertEquals(1, t.f1);
+
+ Map<String,B> m = new LinkedHashMap<String,B>();
+ m.put("bar", B.create());
+ r = s.serialize(m);
+ assertEquals("{bar:{foo:'1'}}", r);
+
+ m = p.parseMap(r, LinkedHashMap.class, String.class, B.class);
+ assertEquals(1, m.get("bar").f1);
+ }
+
+ @Json(wrapperAttr="foo")
+ public static class B {
+ int f1;
+
+ static B create() {
+ B b = new B();
+ b.f1 = 1;
+ return b;
+ }
+
+ @Override /* Object */
+ public String toString() {
+ return String.valueOf(f1);
+ }
+
+ public static B valueOf(String s) {
+ B b = new B();
+ b.f1 = Integer.parseInt(s);
+ return b;
+ }
+ }
+
+ //====================================================================================================
+ // testAddClassAttrs
+ //====================================================================================================
+ @Test
+ public void testAddClassAttrs() throws Exception {
+ JsonSerializer s = new JsonSerializer().setProperty(SERIALIZER_addClassAttrs, true);
+ Map<String,Object> o = new HashMap<String,Object>();
+ o.put("c", new C());
+ assertEquals("{\"c\":{\"_class\":\"org.apache.juneau.json.JsonTest$C\",\"items\":[]}}", s.serialize(o));
+ }
+
+ public static class C extends LinkedList<String> {
+ }
+
+ //====================================================================================================
+ // testEscapeSolidus
+ //====================================================================================================
+ @Test
+ public void testEscapeSolidus() throws Exception {
+ JsonSerializer s = new JsonSerializer().setProperty(JSON_escapeSolidus, false);
+ String r = s.serialize("foo/bar");
+ assertEquals("\"foo/bar\"", r);
+ r = JsonParser.DEFAULT.parse(r, String.class);
+ assertEquals("foo/bar", r);
+
+ s = new JsonSerializer().setProperty(JSON_escapeSolidus, true);
+ r = s.serialize("foo/bar");
+ assertEquals("\"foo\\/bar\"", r);
+ r = JsonParser.DEFAULT.parse(r, String.class);
+ assertEquals("foo/bar", r);
+ }
+}
\ No newline at end of file
[16/44] incubator-juneau git commit: Rename CT_* testcases.
Posted by ja...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/ini/ConfigMgrTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/ini/ConfigMgrTest.java b/org.apache.juneau/src/test/java/org/apache/juneau/ini/ConfigMgrTest.java
new file mode 100755
index 0000000..a65f80e
--- /dev/null
+++ b/org.apache.juneau/src/test/java/org/apache/juneau/ini/ConfigMgrTest.java
@@ -0,0 +1,204 @@
+/***************************************************************************************************************************
+ * 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.juneau.ini;
+
+import static org.apache.juneau.TestUtils.*;
+import static org.junit.Assert.*;
+
+import java.io.*;
+import java.nio.charset.*;
+
+import org.apache.juneau.internal.*;
+import org.apache.juneau.json.*;
+import org.apache.juneau.svl.*;
+import org.apache.juneau.utils.*;
+import org.junit.*;
+
+public class ConfigMgrTest {
+
+ private static File tempDir;
+
+ @BeforeClass
+ public static void setup() {
+ tempDir = new File(System.getProperty("java.io.tmpdir"), StringUtils.generateUUID(12));
+ FileUtils.mkdirs(tempDir, true);
+ }
+
+ @AfterClass
+ public static void teardown() {
+ FileUtils.delete(tempDir);
+ }
+
+ //====================================================================================================
+ // get(String path)
+ // get(String path, boolean create)
+ //====================================================================================================
+ @Test
+ public void testGet() throws Exception {
+ File f;
+ ConfigMgr cm = new ConfigMgr(false, new XorEncoder(), JsonSerializer.DEFAULT, JsonParser.DEFAULT, Charset.defaultCharset(), new String[]{tempDir.getAbsolutePath()});
+
+ ConfigFile cf = cm.get("TestGet.cfg", true);
+ cf.put("Test/A", "a");
+
+ f = new File(tempDir, "TestGet.cfg");
+ assertTrue(f.exists());
+
+ cf.save();
+ assertTextEquals("[Test]|A = a|", IOUtils.read(f));
+
+ cf = cm.get("TestGet.cfg");
+ assertObjectEquals("{'default':{},Test:{A:'a'}}", cf);
+
+ ConfigFile cf2 = cm.get(tempDir.getAbsolutePath() + "/TestGet.cfg");
+ assertObjectEquals("{'default':{},Test:{A:'a'}}", cf2);
+ assertTrue(cf == cf2); // Relative and absolute paths must resolve to same config file.
+
+ try { cm.get("TestGet2.cfg"); fail(); } catch (FileNotFoundException e) {}
+ try { cm.get(tempDir.getAbsolutePath() + "TestGet2.cfg"); fail(); } catch (FileNotFoundException e) {}
+
+ cm.get(tempDir.getAbsolutePath() + "TestGet2.cfg", true);
+
+ ConfigMgr cm2 = new ConfigMgr(false, new XorEncoder(), JsonSerializer.DEFAULT, JsonParser.DEFAULT, Charset.defaultCharset(), new String[]{tempDir.getAbsolutePath()});
+ cf = cm2.get("TestGet.cfg");
+ assertObjectEquals("{'default':{},Test:{A:'a'}}", cf);
+
+ cm2 = new ConfigMgr(false, new XorEncoder(), JsonSerializer.DEFAULT, JsonParser.DEFAULT, Charset.defaultCharset(), null);
+ try { cf = cm2.get("TestGet.cfg"); fail(); } catch (FileNotFoundException e) {}
+
+ String NL = System.getProperty("line.separator");
+ cf = cm2.create(new StringReader(("[Test]"+NL+"A = a"+NL)));
+ assertObjectEquals("{'default':{},Test:{A:'a'}}", cf);
+
+ ConfigMgr cm3 = new ConfigMgr(false, new XorEncoder(), JsonSerializer.DEFAULT, JsonParser.DEFAULT, IOUtils.UTF8, new String[]{tempDir.getAbsolutePath()});
+ cf = cm3.get("TestGet.cfg");
+ assertObjectEquals("{'default':{},Test:{A:'a'}}", cf);
+
+ cm.deleteAll();
+ cm2.deleteAll();
+ cm3.deleteAll();
+ }
+
+ //====================================================================================================
+ // loadIfModified()
+ //====================================================================================================
+ @Test
+ public void testLoadIfModified() throws Exception {
+ ConfigMgr cm = new ConfigMgr(false, new XorEncoder(), JsonSerializer.DEFAULT, JsonParser.DEFAULT, Charset.defaultCharset(), new String[]{tempDir.getAbsolutePath()});
+ File f;
+ ConfigFile cf = cm.get("TestGet.cfg", true);
+ cf.put("Test/A", "a");
+
+ f = new File(tempDir, "TestGet.cfg");
+ String NL = System.getProperty("line.separator");
+ IOUtils.write(f, new StringReader("[Test]"+NL+"A = b"+NL));
+ FileUtils.modifyTimestamp(f);
+
+ cm.loadIfModified();
+ assertEquals("b", cf.getString("Test/A"));
+ cm.loadIfModified();
+ assertEquals("b", cf.getString("Test/A"));
+
+ // Config file with no backing file.
+ cf = cm.create();
+ cf.put("Test/B", "b");
+ cm.loadIfModified();
+ cf.loadIfModified();
+ assertEquals("b", cf.getString("Test/B"));
+
+ cm.deleteAll();
+ }
+
+ //====================================================================================================
+ // read only
+ //====================================================================================================
+ @Test
+ public void testReadOnly() throws Exception {
+ ConfigMgr cm = new ConfigMgr(true, new XorEncoder(), JsonSerializer.DEFAULT, JsonParser.DEFAULT, Charset.defaultCharset(), new String[]{tempDir.getAbsolutePath()});
+ ConfigFile cf = cm.get("TestGet.cfg", true);
+
+ // All these should fail.
+ try { cf.loadIfModified(); fail(); } catch (UnsupportedOperationException e) {}
+ try { cf.load(); fail(); } catch (UnsupportedOperationException e) {}
+ try { cf.load(new StringReader("")); fail(); } catch (UnsupportedOperationException e) {}
+ try { cf.put("A","b"); fail(); } catch (UnsupportedOperationException e) {}
+ try { cf.put("A","b",true); fail(); } catch (UnsupportedOperationException e) {}
+ try { cf.put("A","b"); fail(); } catch (UnsupportedOperationException e) {}
+ try { cf.put("A","b",true); fail(); } catch (UnsupportedOperationException e) {}
+ try { cf.removeString("A"); fail(); } catch (UnsupportedOperationException e) {}
+ try { cf.addLines("A","b=c"); fail(); } catch (UnsupportedOperationException e) {}
+ try { cf.addHeaderComments("A", "b=c"); fail(); } catch (UnsupportedOperationException e) {}
+ try { cf.clearHeaderComments("A"); fail(); } catch (UnsupportedOperationException e) {}
+ try { cf.addSection("A"); fail(); } catch (UnsupportedOperationException e) {}
+ try { cf.setSection("A",null); fail(); } catch (UnsupportedOperationException e) {}
+ try { cf.removeSection("A"); fail(); } catch (UnsupportedOperationException e) {}
+ try { cf.save(); fail(); } catch (UnsupportedOperationException e) {}
+ try { cf.merge(cf); fail(); } catch (UnsupportedOperationException e) {}
+ try { cf.addListener(new ConfigFileListener(){}); fail(); } catch (UnsupportedOperationException e) {}
+
+ // All these should succeed.
+ cf.getObject(String.class, "A");
+ cf.getObject(String.class, "A", "a");
+ cf.getString("A");
+ cf.getString("A","a");
+ cf.getObject(String.class, "A");
+ cf.getObject(String.class, "A", "a");
+ cf.getObject(String[].class, "A");
+ cf.getStringArray("A");
+ cf.getStringArray("A", null);
+ cf.getInt("A");
+ cf.getInt("A", 0);
+ cf.getBoolean("A");
+ cf.getBoolean("A", true);
+ cf.containsNonEmptyValue("A");
+ cf.getSectionMap("A");
+ cf.serializeTo(new StringWriter());
+ cf.serializeTo(new StringWriter(), ConfigFileFormat.INI);
+ cf.getResolving(VarResolver.DEFAULT);
+ cf.toWritable();
+ }
+
+ //====================================================================================================
+ // main(String[] args)
+ //====================================================================================================
+ @Test
+ public void testMain() throws Exception {
+ System.setProperty("exit.2", "0");
+ ConfigMgr cm = new ConfigMgr(false, new XorEncoder(), JsonSerializer.DEFAULT, JsonParser.DEFAULT, Charset.defaultCharset(), new String[]{tempDir.getAbsolutePath()});
+
+ ConfigFile cf = cm.get("Test.cfg", true)
+ .addLines(null, "# c1", "\t# c2", " c3 ", " ", "x1=1", "x2=true", "x3=null")
+ .addLines("s1", "#c4", "k1=1", "#c5 foo=bar", "k2 = true", "k3 = \tnull");
+ cf.save();
+
+ File configFile = new File(tempDir, "Test.cfg");
+ File envFile = new File(tempDir, "Test.bat");
+
+ ConfigMgr.main(new String[]{"createBatchEnvFile", "-configFile", configFile.getAbsolutePath(), "-envFile", envFile.getAbsolutePath()});
+ String expected = "rem c1|rem c2|rem c3||set x1 = 1|set x2 = true|set x3 = null|rem c4|set s1_k1 = 1|rem c5 foo=bar|set s1_k2 = true|set s1_k3 = null|";
+ String actual = IOUtils.read(envFile);
+ assertTextEquals(expected, actual);
+
+ ConfigMgr.main(new String[]{"createShellEnvFile", "-configFile", configFile.getAbsolutePath(), "-envFile", envFile.getAbsolutePath()});
+ expected = "# c1|# c2|# c3||export x1=\"1\"|export x2=\"true\"|export x3=\"null\"|# c4|export s1_k1=\"1\"|# c5 foo=bar|export s1_k2=\"true\"|export s1_k3=\"null\"|";
+ actual = IOUtils.read(envFile);
+ assertTextEquals(expected, actual);
+
+ ConfigMgr.main(new String[]{"setVals", "-configFile", configFile.getAbsolutePath(), "-vals", "x1=2", "s1/k1=2", "s2/k1=3"});
+ FileUtils.modifyTimestamp(configFile);
+ cf.loadIfModified();
+ assertObjectEquals("{'default':{x1:'2',x2:'true',x3:'null'},s1:{k1:'2',k2:'true',k3:'null'},s2:{k1:'3'}}", cf);
+
+ ConfigMgr.main(new String[]{});
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/internal/CT_VersionRange.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/internal/CT_VersionRange.java b/org.apache.juneau/src/test/java/org/apache/juneau/internal/CT_VersionRange.java
deleted file mode 100755
index db85130..0000000
--- a/org.apache.juneau/src/test/java/org/apache/juneau/internal/CT_VersionRange.java
+++ /dev/null
@@ -1,68 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.internal;
-
-import static org.junit.Assert.*;
-
-import java.util.*;
-
-import org.junit.*;
-import org.junit.runner.*;
-import org.junit.runners.*;
-
-@RunWith(Parameterized.class)
-public class CT_VersionRange {
-
- @Parameterized.Parameters
- public static Collection<Object[]> getPairs() {
- return Arrays.asList(new Object[][] {
- // {range, version, shouldMatch }
- /* 00 */ {"1.1", "1.1.3", true},
- /* 01 */ {"1.1", "1.1", true},
- /* 02 */ {"1.1", "1.1.0", true},
- /* 03 */ {"1.1", "1.0", false},
- /* 04 */ {"1.1", "1.0.9", false},
- /* 05 */ {"[1.0,2.0)", ".9", false},
- /* 06 */ {"[1.0,2.0)", "1", true},
- /* 07 */ {"[1.0,2.0)", "1.0", true},
- /* 08 */ {"[1.0,2.0)", "1.0.0", true},
- /* 09 */ {"[1.0,2.0)", "1.1", true},
- /* 10 */ {"[1.0,2.0)", "2.0", false},
- /* 11 */ {"[1.0,2.0)", "2", false},
- /* 12 */ {"(1.0,2.0]", "2", true},
- /* 13 */ {"(1.0,2.0]", "2.0", true},
- /* 14 */ {"(1.0,2.0]", "2.0.1", true},
- /* 15 */ {"(1.0,2.0]", "2.1", false},
- /* 16 */ {"(.5.0,.6]", ".5", false},
- /* 17 */ {"(.5.0,.6]", ".5.1", true},
- /* 18 */ {"(.5.0,.6]", ".6", true},
- /* 19 */ {"(.5.0,.6]", ".6.1", true},
- /* 20 */ {"(.5.0,.6]", ".7", false},
- });
- }
-
- private VersionRange range;
- private String version;
- private boolean shouldMatch;
-
- public CT_VersionRange(String range, String version, boolean shouldMatch) {
- this.version = version;
- this.range = new VersionRange(range);
- this.shouldMatch = shouldMatch;
- }
-
- @Test
- public void test() throws Exception {
- assertEquals(shouldMatch, range.matches(version));
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/internal/VersionRangeTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/internal/VersionRangeTest.java b/org.apache.juneau/src/test/java/org/apache/juneau/internal/VersionRangeTest.java
new file mode 100755
index 0000000..64b4ed9
--- /dev/null
+++ b/org.apache.juneau/src/test/java/org/apache/juneau/internal/VersionRangeTest.java
@@ -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.juneau.internal;
+
+import static org.junit.Assert.*;
+
+import java.util.*;
+
+import org.junit.*;
+import org.junit.runner.*;
+import org.junit.runners.*;
+
+@RunWith(Parameterized.class)
+public class VersionRangeTest {
+
+ @Parameterized.Parameters
+ public static Collection<Object[]> getPairs() {
+ return Arrays.asList(new Object[][] {
+ // {range, version, shouldMatch }
+ /* 00 */ {"1.1", "1.1.3", true},
+ /* 01 */ {"1.1", "1.1", true},
+ /* 02 */ {"1.1", "1.1.0", true},
+ /* 03 */ {"1.1", "1.0", false},
+ /* 04 */ {"1.1", "1.0.9", false},
+ /* 05 */ {"[1.0,2.0)", ".9", false},
+ /* 06 */ {"[1.0,2.0)", "1", true},
+ /* 07 */ {"[1.0,2.0)", "1.0", true},
+ /* 08 */ {"[1.0,2.0)", "1.0.0", true},
+ /* 09 */ {"[1.0,2.0)", "1.1", true},
+ /* 10 */ {"[1.0,2.0)", "2.0", false},
+ /* 11 */ {"[1.0,2.0)", "2", false},
+ /* 12 */ {"(1.0,2.0]", "2", true},
+ /* 13 */ {"(1.0,2.0]", "2.0", true},
+ /* 14 */ {"(1.0,2.0]", "2.0.1", true},
+ /* 15 */ {"(1.0,2.0]", "2.1", false},
+ /* 16 */ {"(.5.0,.6]", ".5", false},
+ /* 17 */ {"(.5.0,.6]", ".5.1", true},
+ /* 18 */ {"(.5.0,.6]", ".6", true},
+ /* 19 */ {"(.5.0,.6]", ".6.1", true},
+ /* 20 */ {"(.5.0,.6]", ".7", false},
+ });
+ }
+
+ private VersionRange range;
+ private String version;
+ private boolean shouldMatch;
+
+ public VersionRangeTest(String range, String version, boolean shouldMatch) {
+ this.version = version;
+ this.range = new VersionRange(range);
+ this.shouldMatch = shouldMatch;
+ }
+
+ @Test
+ public void test() throws Exception {
+ assertEquals(shouldMatch, range.matches(version));
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/jena/CT_Common.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/jena/CT_Common.java b/org.apache.juneau/src/test/java/org/apache/juneau/jena/CT_Common.java
deleted file mode 100755
index 8ffc9f7..0000000
--- a/org.apache.juneau/src/test/java/org/apache/juneau/jena/CT_Common.java
+++ /dev/null
@@ -1,513 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.jena;
-
-import static org.apache.juneau.TestUtils.*;
-import static org.apache.juneau.jena.RdfCommonContext.*;
-import static org.apache.juneau.serializer.SerializerContext.*;
-import static org.junit.Assert.*;
-
-import java.net.*;
-import java.net.URI;
-import java.util.*;
-
-import org.apache.juneau.*;
-import org.apache.juneau.annotation.*;
-import org.apache.juneau.internal.*;
-import org.apache.juneau.serializer.*;
-import org.apache.juneau.testbeans.*;
-import org.apache.juneau.xml.*;
-import org.junit.*;
-
-@SuppressWarnings({"unchecked","serial"})
-public class CT_Common {
-
- private RdfSerializer getBasicSerializer() {
- return new RdfSerializer()
- .setProperty(SERIALIZER_quoteChar, '\'')
- .setProperty(SERIALIZER_useIndentation, false)
- .setProperty(RDF_rdfxml_allowBadUris, true)
- .setProperty(RDF_rdfxml_showDoctypeDeclaration, false)
- .setProperty(RDF_rdfxml_showXmlDeclaration, false);
- }
-
- private String strip(String s) {
- return s.replaceFirst("<rdf:RDF[^>]+>\\s*", "").replaceAll("</rdf:RDF>$", "").trim().replaceAll("[\\r\\n]", "");
- }
-
- //====================================================================================================
- // Trim nulls from beans
- //====================================================================================================
- @Test
- public void testTrimNullsFromBeans() throws Exception {
- RdfSerializer s = getBasicSerializer();
- RdfParser p = RdfParser.DEFAULT_XML;
- A t1 = A.create(), t2;
-
- s.setProperty(SERIALIZER_trimNullProperties, false);
- String r = s.serialize(t1);
- assertEquals("<rdf:Description><jp:s1 rdf:resource='http://www.w3.org/1999/02/22-rdf-syntax-ns#nil'/><jp:s2>s2</jp:s2></rdf:Description>", strip(r));
- t2 = p.parse(r, A.class);
- assertEqualObjects(t1, t2);
-
- s.setProperty(SERIALIZER_trimNullProperties, true);
- r = s.serialize(t1);
- assertEquals("<rdf:Description><jp:s2>s2</jp:s2></rdf:Description>", strip(r));
- t2 = p.parse(r, A.class);
- assertEqualObjects(t1, t2);
- }
-
- public static class A {
- public String s1, s2;
-
- public static A create() {
- A t = new A();
- t.s2 = "s2";
- return t;
- }
- }
-
- //====================================================================================================
- // Trim empty maps
- //====================================================================================================
- @Test
- public void testTrimEmptyMaps() throws Exception {
- RdfSerializer s = getBasicSerializer();
- RdfParser p = RdfParser.DEFAULT_XML;
- B t1 = B.create(), t2;
- String r;
-
- s.setProperty(SERIALIZER_trimEmptyMaps, false);
- r = s.serialize(t1);
- assertEquals("<rdf:Description><jp:f1 rdf:parseType='Resource'></jp:f1><jp:f2 rdf:parseType='Resource'><jp:f2a rdf:resource='http://www.w3.org/1999/02/22-rdf-syntax-ns#nil'/><jp:f2b rdf:parseType='Resource'><jp:s2>s2</jp:s2></jp:f2b></jp:f2></rdf:Description>", strip(r));
- t2 = p.parse(r, B.class);
- assertEqualObjects(t1, t2);
-
- s.setProperty(SERIALIZER_trimEmptyMaps, true);
- r = s.serialize(t1);
- assertEquals("<rdf:Description><jp:f2 rdf:parseType='Resource'><jp:f2a rdf:resource='http://www.w3.org/1999/02/22-rdf-syntax-ns#nil'/><jp:f2b rdf:parseType='Resource'><jp:s2>s2</jp:s2></jp:f2b></jp:f2></rdf:Description>", strip(r));
- t2 = p.parse(r, B.class);
- assertNull(t2.f1);
- }
-
- public static class B {
- public TreeMap<String,A> f1, f2;
-
- public static B create() {
- B t = new B();
- t.f1 = new TreeMap<String,A>();
- t.f2 = new TreeMap<String,A>(){{put("f2a",null);put("f2b",A.create());}};
- return t;
- }
- }
-
- //====================================================================================================
- // Trim empty lists
- //====================================================================================================
- @Test
- public void testTrimEmptyLists() throws Exception {
- RdfSerializer s = getBasicSerializer();
- RdfParser p = RdfParser.DEFAULT_XML;
- C t1 = C.create(), t2;
- String r;
-
- s.setProperty(SERIALIZER_trimEmptyLists, false);
- r = s.serialize(t1);
- assertEquals("<rdf:Description><jp:f1><rdf:Seq/></jp:f1><jp:f2><rdf:Seq><rdf:li rdf:resource='http://www.w3.org/1999/02/22-rdf-syntax-ns#nil'/><rdf:li rdf:parseType='Resource'><jp:s2>s2</jp:s2></rdf:li></rdf:Seq></jp:f2></rdf:Description>", strip(r));
- t2 = p.parse(r, C.class);
- assertEqualObjects(t1, t2);
-
- s.setProperty(SERIALIZER_trimEmptyLists, true);
- r = s.serialize(t1);
- assertEquals("<rdf:Description><jp:f2><rdf:Seq><rdf:li rdf:resource='http://www.w3.org/1999/02/22-rdf-syntax-ns#nil'/><rdf:li rdf:parseType='Resource'><jp:s2>s2</jp:s2></rdf:li></rdf:Seq></jp:f2></rdf:Description>", strip(r));
- t2 = p.parse(r, C.class);
- assertNull(t2.f1);
- t2 = p.parse(r, C.class);
- }
-
- public static class C {
- public List<A> f1, f2;
-
- public static C create() {
- C t = new C();
- t.f1 = new LinkedList<A>();
- t.f2 = new LinkedList<A>(){{add(null);add(A.create());}};
- return t;
- }
- }
-
- //====================================================================================================
- // Trim empty arrays
- //====================================================================================================
- @Test
- public void testTrimEmptyArrays() throws Exception {
- RdfSerializer s = getBasicSerializer();
- RdfParser p = RdfParser.DEFAULT_XML;
- D t1 = D.create(), t2;
- String r;
-
- s.setProperty(SERIALIZER_trimEmptyLists, false);
- r = s.serialize(t1);
- assertEquals("<rdf:Description><jp:f1><rdf:Seq/></jp:f1><jp:f2><rdf:Seq><rdf:li rdf:resource='http://www.w3.org/1999/02/22-rdf-syntax-ns#nil'/><rdf:li rdf:parseType='Resource'><jp:s2>s2</jp:s2></rdf:li></rdf:Seq></jp:f2></rdf:Description>", strip(r));
- t2 = p.parse(r, D.class);
- assertEqualObjects(t1, t2);
-
- s.setProperty(SERIALIZER_trimEmptyLists, true);
- r = s.serialize(t1);
- assertEquals("<rdf:Description><jp:f2><rdf:Seq><rdf:li rdf:resource='http://www.w3.org/1999/02/22-rdf-syntax-ns#nil'/><rdf:li rdf:parseType='Resource'><jp:s2>s2</jp:s2></rdf:li></rdf:Seq></jp:f2></rdf:Description>", strip(r));
- t2 = p.parse(r, D.class);
- assertNull(t2.f1);
- }
-
- public static class D {
- public A[] f1, f2;
-
- public static D create() {
- D t = new D();
- t.f1 = new A[]{};
- t.f2 = new A[]{null, A.create()};
- return t;
- }
- }
-
- //====================================================================================================
- // @BeanProperty.properties annotation.
- //====================================================================================================
- @Test
- public void testBeanPropertyProperties() throws Exception {
- RdfSerializer s = getBasicSerializer();
- RdfParser p = RdfParser.DEFAULT_XML;
- E1 t1 = E1.create(), t2;
- String r;
-
- r = s.serialize(t1);
- assertEquals("<rdf:Description><jp:x1 rdf:parseType='Resource'><jp:f1>1</jp:f1></jp:x1><jp:x2 rdf:parseType='Resource'><jp:f1>1</jp:f1></jp:x2><jp:x3><rdf:Seq><rdf:li rdf:parseType='Resource'><jp:f1>1</jp:f1></rdf:li></rdf:Seq></jp:x3><jp:x4><rdf:Seq><rdf:li rdf:parseType='Resource'><jp:f1>1</jp:f1></rdf:li></rdf:Seq></jp:x4><jp:x5><rdf:Seq><rdf:li rdf:parseType='Resource'><jp:f1>1</jp:f1></rdf:li></rdf:Seq></jp:x5><jp:x6><rdf:Seq><rdf:li rdf:parseType='Resource'><jp:f1>1</jp:f1></rdf:li></rdf:Seq></jp:x6></rdf:Description>", strip(r));
- t2 = p.parse(r, E1.class);
- assertEqualObjects(t1, t2);
- }
-
- public static class E1 {
- @BeanProperty(properties={"f1"}) public E2 x1;
- @BeanProperty(properties={"f1"}) public Map<String,Integer> x2;
- @BeanProperty(properties={"f1"}) public E2[] x3;
- @BeanProperty(properties={"f1"}) public List<E2> x4;
- @BeanProperty(properties={"f1"}) public ObjectMap[] x5;
- @BeanProperty(properties={"f1"}) public List<ObjectMap> x6;
-
- public static E1 create() {
- E1 t = new E1();
- t.x1 = new E2();
- t.x2 = new LinkedHashMap<String,Integer>() {{ put("f1",1); put("f2",2); }};
- t.x3 = new E2[] {new E2()};
- t.x4 = new LinkedList<E2>() {{ add(new E2()); }};
- t.x5 = new ObjectMap[] {new ObjectMap().append("f1","1").append("f2","2")};
- t.x6 = new LinkedList<ObjectMap>() {{ add(new ObjectMap().append("f1","1").append("f2","2")); }};
- return t;
- }
- }
-
- public static class E2 {
- public int f1 = 1;
- public int f2 = 2;
- }
-
- //====================================================================================================
- // @BeanProperty.properties annotation on list of beans.
- //====================================================================================================
- @Test
- public void testBeanPropertyProperiesOnListOfBeans() throws Exception {
- RdfSerializer s = getBasicSerializer();
- RdfParser p = RdfParser.DEFAULT_XML;
- List<F> l1 = new LinkedList<F>(), l2;
- F t = F.create();
- t.x1.add(F.create());
- l1.add(t);
-
- String r = s.serialize(l1);
- assertEquals("<rdf:Seq><rdf:li rdf:parseType='Resource'><jp:x1><rdf:Seq><rdf:li rdf:parseType='Resource'><jp:x2>2</jp:x2></rdf:li></rdf:Seq></jp:x1><jp:x2>2</jp:x2></rdf:li></rdf:Seq>", strip(r));
- ClassMeta<LinkedList<F>> cm = p.getBeanContext().getCollectionClassMeta(LinkedList.class, F.class);
- l2 = p.parse(r, cm);
- assertEqualObjects(l1, l2);
- }
-
- public static class F {
- @BeanProperty(properties={"x2"}) public List<F> x1;
- public int x2;
-
- public static F create() {
- F t = new F();
- t.x1 = new LinkedList<F>();
- t.x2 = 2;
- return t;
- }
- }
-
- //====================================================================================================
- // Test URIAttr - Test that URLs and URIs are serialized and parsed correctly.
- //====================================================================================================
- @Test
- public void testURIAttr() throws Exception {
- RdfSerializer s = getBasicSerializer();
- RdfParser p = RdfParser.DEFAULT_XML;
-
- G t = new G();
- t.uri = new URI("http://uri");
- t.f1 = new URI("http://f1");
- t.f2 = new URL("http://f2");
-
- String xml = s.serialize(t);
- t = p.parse(xml, G.class);
- assertEquals("http://uri", t.uri.toString());
- assertEquals("http://f1", t.f1.toString());
- assertEquals("http://f2", t.f2.toString());
- }
-
- public static class G {
- @BeanProperty(beanUri=true) public URI uri;
- public URI f1;
- public URL f2;
- }
-
- //====================================================================================================
- // Test URIs with URI_CONTEXT and URI_AUTHORITY
- //====================================================================================================
- @Test
- public void testUris() throws Exception {
- WriterSerializer s = getBasicSerializer();
- TestURI t = new TestURI();
- String r;
- String expected = "";
-
- s.setProperty(SERIALIZER_relativeUriBase, null);
- r = stripAndSort(s.serialize(t));
- expected = ""
- +"</rdf:Description>>"
- +"\n<<rdf:Description rdf:about='f0/x0'>"
- +"\n<jp:f1 rdf:resource='f1/x1'/>"
- +"\n<jp:f2 rdf:resource='/f2/x2'/>"
- +"\n<jp:f3 rdf:resource='http://www.ibm.com/f3/x3'/>"
- +"\n<jp:f4 rdf:resource='f4/x4'/>"
- +"\n<jp:f5 rdf:resource='/f5/x5'/>"
- +"\n<jp:f6 rdf:resource='http://www.ibm.com/f6/x6'/>"
- +"\n<jp:f7 rdf:resource='http://www.ibm.com/f7/x7'/>"
- +"\n<jp:f8 rdf:resource='f8/x8'/>"
- +"\n<jp:f9 rdf:resource='f9/x9'/>"
- +"\n<jp:fa>http://www.ibm.com/fa/xa#MY_LABEL</jp:fa>"
- +"\n<jp:fb>http://www.ibm.com/fb/xb?label=MY_LABEL&foo=bar</jp:fb>"
- +"\n<jp:fc>http://www.ibm.com/fc/xc?foo=bar&label=MY_LABEL</jp:fc>"
- +"\n<jp:fd>http://www.ibm.com/fd/xd?label2=MY_LABEL&foo=bar</jp:fd>"
- +"\n<jp:fe>http://www.ibm.com/fe/xe?foo=bar&label2=MY_LABEL</jp:fe>"
- ;
- assertEquals(expected, r);
-
- s.setProperty(SERIALIZER_relativeUriBase, ""); // Same as null.
- r = stripAndSort(s.serialize(t));
- assertEquals(expected, r);
-
- s.setProperty(SERIALIZER_relativeUriBase, "/cr");
- r = stripAndSort(s.serialize(t));
- expected = ""
- +"</rdf:Description>>"
- +"\n<<rdf:Description rdf:about='/cr/f0/x0'>"
- +"\n<jp:f1 rdf:resource='/cr/f1/x1'/>"
- +"\n<jp:f2 rdf:resource='/f2/x2'/>"
- +"\n<jp:f3 rdf:resource='http://www.ibm.com/f3/x3'/>"
- +"\n<jp:f4 rdf:resource='/cr/f4/x4'/>"
- +"\n<jp:f5 rdf:resource='/f5/x5'/>"
- +"\n<jp:f6 rdf:resource='http://www.ibm.com/f6/x6'/>"
- +"\n<jp:f7 rdf:resource='http://www.ibm.com/f7/x7'/>"
- +"\n<jp:f8 rdf:resource='/cr/f8/x8'/>"
- +"\n<jp:f9 rdf:resource='/cr/f9/x9'/>"
- +"\n<jp:fa>http://www.ibm.com/fa/xa#MY_LABEL</jp:fa>"
- +"\n<jp:fb>http://www.ibm.com/fb/xb?label=MY_LABEL&foo=bar</jp:fb>"
- +"\n<jp:fc>http://www.ibm.com/fc/xc?foo=bar&label=MY_LABEL</jp:fc>"
- +"\n<jp:fd>http://www.ibm.com/fd/xd?label2=MY_LABEL&foo=bar</jp:fd>"
- +"\n<jp:fe>http://www.ibm.com/fe/xe?foo=bar&label2=MY_LABEL</jp:fe>"
- ;
- assertEquals(expected, r);
-
- s.setProperty(SERIALIZER_relativeUriBase, "/cr/"); // Same as above
- r = stripAndSort(s.serialize(t));
- assertEquals(expected, r);
-
- s.setProperty(SERIALIZER_relativeUriBase, "/");
- r = stripAndSort(s.serialize(t));
- expected = ""
- +"</rdf:Description>>"
- +"\n<<rdf:Description rdf:about='/f0/x0'>"
- +"\n<jp:f1 rdf:resource='/f1/x1'/>"
- +"\n<jp:f2 rdf:resource='/f2/x2'/>"
- +"\n<jp:f3 rdf:resource='http://www.ibm.com/f3/x3'/>"
- +"\n<jp:f4 rdf:resource='/f4/x4'/>"
- +"\n<jp:f5 rdf:resource='/f5/x5'/>"
- +"\n<jp:f6 rdf:resource='http://www.ibm.com/f6/x6'/>"
- +"\n<jp:f7 rdf:resource='http://www.ibm.com/f7/x7'/>"
- +"\n<jp:f8 rdf:resource='/f8/x8'/>"
- +"\n<jp:f9 rdf:resource='/f9/x9'/>"
- +"\n<jp:fa>http://www.ibm.com/fa/xa#MY_LABEL</jp:fa>"
- +"\n<jp:fb>http://www.ibm.com/fb/xb?label=MY_LABEL&foo=bar</jp:fb>"
- +"\n<jp:fc>http://www.ibm.com/fc/xc?foo=bar&label=MY_LABEL</jp:fc>"
- +"\n<jp:fd>http://www.ibm.com/fd/xd?label2=MY_LABEL&foo=bar</jp:fd>"
- +"\n<jp:fe>http://www.ibm.com/fe/xe?foo=bar&label2=MY_LABEL</jp:fe>"
- ;
- assertEquals(expected, r);
-
- s.setProperty(SERIALIZER_relativeUriBase, null);
-
- s.setProperty(SERIALIZER_absolutePathUriBase, "http://foo");
- r = stripAndSort(s.serialize(t));
- expected = ""
- +"</rdf:Description>>"
- +"\n<<rdf:Description rdf:about='f0/x0'>"
- +"\n<jp:f1 rdf:resource='f1/x1'/>"
- +"\n<jp:f2 rdf:resource='http://foo/f2/x2'/>"
- +"\n<jp:f3 rdf:resource='http://www.ibm.com/f3/x3'/>"
- +"\n<jp:f4 rdf:resource='f4/x4'/>"
- +"\n<jp:f5 rdf:resource='http://foo/f5/x5'/>"
- +"\n<jp:f6 rdf:resource='http://www.ibm.com/f6/x6'/>"
- +"\n<jp:f7 rdf:resource='http://www.ibm.com/f7/x7'/>"
- +"\n<jp:f8 rdf:resource='f8/x8'/>"
- +"\n<jp:f9 rdf:resource='f9/x9'/>"
- +"\n<jp:fa>http://www.ibm.com/fa/xa#MY_LABEL</jp:fa>"
- +"\n<jp:fb>http://www.ibm.com/fb/xb?label=MY_LABEL&foo=bar</jp:fb>"
- +"\n<jp:fc>http://www.ibm.com/fc/xc?foo=bar&label=MY_LABEL</jp:fc>"
- +"\n<jp:fd>http://www.ibm.com/fd/xd?label2=MY_LABEL&foo=bar</jp:fd>"
- +"\n<jp:fe>http://www.ibm.com/fe/xe?foo=bar&label2=MY_LABEL</jp:fe>"
- ;
- assertEquals(expected, r);
-
- s.setProperty(SERIALIZER_absolutePathUriBase, "http://foo/");
- r = stripAndSort(s.serialize(t));
- assertEquals(expected, r);
-
- s.setProperty(SERIALIZER_absolutePathUriBase, ""); // Same as null.
- r = stripAndSort(s.serialize(t));
- expected = ""
- +"</rdf:Description>>"
- +"\n<<rdf:Description rdf:about='f0/x0'>"
- +"\n<jp:f1 rdf:resource='f1/x1'/>"
- +"\n<jp:f2 rdf:resource='/f2/x2'/>"
- +"\n<jp:f3 rdf:resource='http://www.ibm.com/f3/x3'/>"
- +"\n<jp:f4 rdf:resource='f4/x4'/>"
- +"\n<jp:f5 rdf:resource='/f5/x5'/>"
- +"\n<jp:f6 rdf:resource='http://www.ibm.com/f6/x6'/>"
- +"\n<jp:f7 rdf:resource='http://www.ibm.com/f7/x7'/>"
- +"\n<jp:f8 rdf:resource='f8/x8'/>"
- +"\n<jp:f9 rdf:resource='f9/x9'/>"
- +"\n<jp:fa>http://www.ibm.com/fa/xa#MY_LABEL</jp:fa>"
- +"\n<jp:fb>http://www.ibm.com/fb/xb?label=MY_LABEL&foo=bar</jp:fb>"
- +"\n<jp:fc>http://www.ibm.com/fc/xc?foo=bar&label=MY_LABEL</jp:fc>"
- +"\n<jp:fd>http://www.ibm.com/fd/xd?label2=MY_LABEL&foo=bar</jp:fd>"
- +"\n<jp:fe>http://www.ibm.com/fe/xe?foo=bar&label2=MY_LABEL</jp:fe>"
- ;
- assertEquals(expected, r);
- }
-
- private String stripAndSort(String s) {
- s = strip(s);
- Set<String> set = new TreeSet<String>();
- for (String s2 : s.split("><"))
- set.add('<' + s2 + '>');
- return StringUtils.join(set, "\n");
- }
-
- //====================================================================================================
- // Validate that you cannot update properties on locked serializer.
- //====================================================================================================
- @Test
- public void testLockedSerializer() throws Exception {
- RdfSerializer s = getBasicSerializer().lock();
- try {
- s.setProperty(XmlSerializerContext.XML_enableNamespaces, true);
- fail("Locked exception not thrown");
- } catch (LockedException e) {}
- try {
- s.setProperty(SerializerContext.SERIALIZER_addClassAttrs, true);
- fail("Locked exception not thrown");
- } catch (LockedException e) {}
- try {
- s.setProperty(BeanContext.BEAN_beanMapPutReturnsOldValue, true);
- fail("Locked exception not thrown");
- } catch (LockedException e) {}
- }
-
- //====================================================================================================
- // Recursion
- //====================================================================================================
- @Test
- public void testRecursion() throws Exception {
- WriterSerializer s = new RdfSerializer.XmlAbbrev().setProperty(SERIALIZER_quoteChar, '\'');
-
- R1 r1 = new R1();
- R2 r2 = new R2();
- R3 r3 = new R3();
- r1.r2 = r2;
- r2.r3 = r3;
- r3.r1 = r1;
-
- // No recursion detection
- try {
- s.serialize(r1);
- fail("Exception expected!");
- } catch (Exception e) {
- String msg = e.getLocalizedMessage();
- assertTrue(msg.contains("It's recommended you use the SerializerContext.SERIALIZER_detectRecursions setting to help locate the loop."));
- }
-
- // Recursion detection, no ignore
- s.setProperty(SERIALIZER_detectRecursions, true);
- try {
- s.serialize(r1);
- fail("Exception expected!");
- } catch (Exception e) {
- String msg = e.getLocalizedMessage();
- assertTrue(msg.contains("[0]root:org.apache.juneau.jena.CT_Common$R1"));
- assertTrue(msg.contains("->[1]r2:org.apache.juneau.jena.CT_Common$R2"));
- assertTrue(msg.contains("->[2]r3:org.apache.juneau.jena.CT_Common$R3"));
- assertTrue(msg.contains("->[3]r1:org.apache.juneau.jena.CT_Common$R1"));
- }
-
- s.setProperty(SERIALIZER_ignoreRecursions, true);
- String r = s.serialize(r1).replace("\r", "");
- // Note...the order of the namespaces is not always the same depending on the JVM.
- // The Jena libraries appear to use a hashmap for these.
- assertTrue(r.contains(
- "<rdf:Description>\n"+
- "<jp:name>foo</jp:name>\n"+
- "<jp:r2 rdf:parseType='Resource'>\n"+
- "<jp:name>bar</jp:name>\n"+
- "<jp:r3 rdf:parseType='Resource'>\n"+
- "<jp:name>baz</jp:name>\n"+
- "</jp:r3>\n"+
- "</jp:r2>\n"+
- "</rdf:Description>\n"+
- "</rdf:RDF>\n"
- ));
- assertTrue(r.contains("xmlns:rdf='http://www.w3.org/1999/02/22-rdf-syntax-ns#"));
- assertTrue(r.contains("xmlns:j='http://www.ibm.com/juneau/"));
- assertTrue(r.contains("xmlns:jp='http://www.ibm.com/juneaubp/"));
- }
-
- public static class R1 {
- public String name = "foo";
- public R2 r2;
- }
- public static class R2 {
- public String name = "bar";
- public R3 r3;
- }
- public static class R3 {
- public String name = "baz";
- public R1 r1;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/jena/CT_CommonParser.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/jena/CT_CommonParser.java b/org.apache.juneau/src/test/java/org/apache/juneau/jena/CT_CommonParser.java
deleted file mode 100755
index 9b7638b..0000000
--- a/org.apache.juneau/src/test/java/org/apache/juneau/jena/CT_CommonParser.java
+++ /dev/null
@@ -1,208 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.jena;
-
-import static org.apache.juneau.BeanContext.*;
-import static org.apache.juneau.jena.RdfCommonContext.*;
-import static org.apache.juneau.jena.RdfSerializerContext.*;
-import static org.apache.juneau.serializer.SerializerContext.*;
-import static org.junit.Assert.*;
-
-import java.util.*;
-
-import org.apache.juneau.*;
-import org.apache.juneau.parser.*;
-import org.apache.juneau.serializer.*;
-import org.junit.*;
-
-@SuppressWarnings({"rawtypes","serial"})
-public class CT_CommonParser {
-
- private String wrap(String in) {
- return ""
- + "<rdf:RDF"
- + " xmlns:rdf='http://www.w3.org/1999/02/22-rdf-syntax-ns#'"
- + " xmlns:j='http://www.ibm.com/juneau/'"
- + " xmlns:jp='http://www.ibm.com/juneaubp/'>"
- + in
- + "</rdf:RDF>";
- }
-
- private String strip(String s) {
- return s.replaceFirst("<rdf:RDF[^>]+>\\s*", "").replaceAll("</rdf:RDF>$", "").trim().replaceAll("[\\r\\n]", "");
- }
-
- private RdfSerializer getBasicSerializer() {
- return new RdfSerializer()
- .setProperty(SERIALIZER_quoteChar, '\'')
- .setProperty(RDF_addLiteralTypes, true)
- .setProperty(SERIALIZER_useIndentation, false)
- .setProperty(RDF_rdfxml_allowBadUris, true)
- .setProperty(RDF_rdfxml_showDoctypeDeclaration, false)
- .setProperty(RDF_rdfxml_showXmlDeclaration, false);
- }
-
- //====================================================================================================
- // testBasicFromSerializer
- //====================================================================================================
- @Test
- public void testFromSerializer() throws Exception {
- WriterSerializer s = getBasicSerializer();
- ReaderParser p = new RdfParser.Xml().setProperty(RdfParserContext.RDF_trimWhitespace, true).setClassLoader(getClass().getClassLoader());
- Map m = null;
- String in;
- Integer one = Integer.valueOf(1);
-
- in = wrap("<rdf:Description><jp:a rdf:datatype='http://www.w3.org/2001/XMLSchema#int'>1</jp:a></rdf:Description>");
- m = (Map)p.parse(in, Object.class);
- assertEquals(one, m.get("a"));
-
- in = wrap("<rdf:Description><jp:a rdf:datatype='http://www.w3.org/2001/XMLSchema#int'>1</jp:a><jp:b>foo bar</jp:b><jp:c rdf:datatype='http://www.w3.org/2001/XMLSchema#boolean'>false</jp:c></rdf:Description>");
- m = (Map)p.parse(in, Object.class);
- assertEquals(one, m.get("a"));
- assertEquals("foo bar", m.get("b"));
- in = wrap("<rdf:Description><jp:a rdf:datatype='http://www.w3.org/2001/XMLSchema#int'> 1 </jp:a><jp:b> foo bar </jp:b><jp:c rdf:datatype='http://www.w3.org/2001/XMLSchema#boolean'> false </jp:c></rdf:Description>");
- m = (Map)p.parse(in, Object.class);
- assertEquals(one, m.get("a"));
- assertEquals("foo bar", m.get("b"));
- assertEquals(false, m.get("c"));
-
- in = wrap("<rdf:Description><jp:x>org.apache.juneau.test.Person</jp:x><jp:addresses><rdf:Seq><rdf:li rdf:parseType='Resource'><jp:x>org.apache.juneau.test.Address</jp:x><jp:city>city A</jp:city><jp:state>state A</jp:state><jp:street>street A</jp:street><jp:zip rdf:datatype='http://www.w3.org/2001/XMLSchema#int'>12345</jp:zip></rdf:li></rdf:Seq></jp:addresses></rdf:Description>");
- m = (Map)p.parse(in, Object.class);
- assertEquals("org.apache.juneau.test.Person", m.get("x"));
- List l = (List)m.get("addresses");
- assertNotNull(l);
- m = (Map)l.get(0);
- assertNotNull(m);
- assertEquals("org.apache.juneau.test.Address", m.get("x"));
- assertEquals("city A", m.get("city"));
- assertEquals("state A", m.get("state"));
- assertEquals("street A", m.get("street"));
- assertEquals(12345, m.get("zip"));
-
- in = wrap("<rdf:Seq><rdf:li rdf:parseType='Resource'><jp:attribute>value</jp:attribute></rdf:li><rdf:li rdf:parseType='Resource'><jp:attribute>value</jp:attribute></rdf:li></rdf:Seq>");
- ObjectList jl = (ObjectList)p.parse(in, Object.class);
- assertEquals("value", jl.getObjectMap(0).getString("attribute"));
- assertEquals("value", jl.getObjectMap(1).getString("attribute"));
-
- // Verify that all the following return null.
- assertNull(p.parse((CharSequence)null, Object.class));
- assertNull(p.parse(wrap(""), Object.class));
- assertNull(p.parse(wrap(" "), Object.class));
- assertNull(p.parse(wrap(" \t"), Object.class));
- assertNull(p.parse(wrap(" <!--foo-->"), Object.class));
- assertNull(p.parse(wrap(" <!--foo--> "), Object.class));
- assertNull(p.parse(wrap(" //foo "), Object.class));
-
-
- A1 t1 = new A1();
- A2 t2 = new A2();
- t2.add(new A3("name0","value0"));
- t2.add(new A3("name1","value1"));
- t1.list = t2;
-
- s.setProperty(SERIALIZER_addClassAttrs, true);
- in = strip(s.serialize(t1));
- assertEquals("<rdf:Description><j:class>"+A1.class.getName()+"</j:class><jp:list><rdf:Seq><rdf:li rdf:parseType='Resource'><jp:name>name0</jp:name><jp:value>value0</jp:value></rdf:li><rdf:li rdf:parseType='Resource'><jp:name>name1</jp:name><jp:value>value1</jp:value></rdf:li></rdf:Seq></jp:list></rdf:Description>", in);
- in = wrap(in);
- t1 = (A1)p.parse(in, Object.class);
- assertEquals("value1", t1.list.get(1).value);
- t1 = p.parse(in, A1.class);
- assertEquals("value1", t1.list.get(1).value);
- }
-
- public static class A1 {
- public A2 list;
- }
-
- public static class A2 extends LinkedList<A3> {
- }
-
- public static class A3 {
- public String name, value;
- public A3(){}
- public A3(String name, String value) {
- this.name = name;
- this.value = value;
- }
- }
-
- //====================================================================================================
- // Correct handling of unknown properties.
- //====================================================================================================
- @Test
- public void testCorrectHandlingOfUnknownProperties() throws Exception {
- ReaderParser p = new RdfParser.Xml().setProperty(BEAN_ignoreUnknownBeanProperties, true);
- B t;
-
- String in = wrap("<rdf:Description><jp:a rdf:datatype='http://www.w3.org/2001/XMLSchema#int'>1</jp:a><jp:unknownProperty>foo</jp:unknownProperty><jp:b rdf:datatype='http://www.w3.org/2001/XMLSchema#int'>2</jp:b></rdf:Description>");
- t = p.parse(in, B.class);
- assertEquals(t.a, 1);
- assertEquals(t.b, 2);
-
- try {
- p = new RdfParser.Xml();
- p.parse(in, B.class);
- fail("Exception expected");
- } catch (ParseException e) {}
- }
-
- public static class B {
- public int a, b;
- }
-
- //====================================================================================================
- // Writing to Collection properties with no setters.
- //====================================================================================================
- @Test
- public void testCollectionPropertiesWithNoSetters() throws Exception {
- RdfParser p = new RdfParser.Xml();
- String in = wrap("<rdf:Description><jp:ints><rdf:Seq><rdf:li>1</rdf:li><rdf:li>2</rdf:li></rdf:Seq></jp:ints><jp:beans><rdf:Seq><rdf:li rdf:parseType='Resource'><jp:a>1</jp:a><jp:b>2</jp:b></rdf:li></rdf:Seq></jp:beans></rdf:Description>");
- C t = p.parse(in, C.class);
- assertEquals(t.getInts().size(), 2);
- assertEquals(t.getBeans().get(0).b, 2);
- }
-
- public static class C {
- private Collection<Integer> ints = new LinkedList<Integer>();
- private List<B> beans = new LinkedList<B>();
- public Collection<Integer> getInts() {
- return ints;
- }
- public List<B> getBeans() {
- return beans;
- }
- }
-
- //====================================================================================================
- // Parser listeners.
- //====================================================================================================
- @Test
- public void testParserListeners() throws Exception {
- final List<String> events = new LinkedList<String>();
- RdfParser p = new RdfParser.Xml().setProperty(BEAN_ignoreUnknownBeanProperties, true);
- p.addListener(
- new ParserListener() {
- @Override /* ParserListener */
- public <T> void onUnknownProperty(String propertyName, Class<T> beanClass, T bean, int line, int col) {
- events.add(propertyName + "," + line + "," + col);
- }
- }
- );
-
- String in = wrap("<rdf:Description><jp:a rdf:datatype='http://www.w3.org/2001/XMLSchema#int'>1</jp:a><jp:unknownProperty>foo</jp:unknownProperty><jp:b rdf:datatype='http://www.w3.org/2001/XMLSchema#int'>2</jp:b></rdf:Description>");
- p.parse(in, B.class);
- assertEquals(1, events.size());
- assertEquals("unknownProperty,-1,-1", events.get(0));
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/jena/CT_CommonXml.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/jena/CT_CommonXml.java b/org.apache.juneau/src/test/java/org/apache/juneau/jena/CT_CommonXml.java
deleted file mode 100755
index 40c0f4f..0000000
--- a/org.apache.juneau/src/test/java/org/apache/juneau/jena/CT_CommonXml.java
+++ /dev/null
@@ -1,95 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.jena;
-
-import static org.apache.juneau.TestUtils.*;
-import static org.apache.juneau.jena.RdfCommonContext.*;
-import static org.apache.juneau.serializer.SerializerContext.*;
-import static org.junit.Assert.*;
-
-import java.net.*;
-
-import org.apache.juneau.annotation.*;
-import org.junit.*;
-
-public class CT_CommonXml {
-
- private RdfSerializer getBasicSerializer() {
- return new RdfSerializer()
- .setProperty(SERIALIZER_quoteChar, '\'')
- .setProperty(SERIALIZER_useIndentation, false)
- .setProperty(RDF_rdfxml_allowBadUris, true)
- .setProperty(RDF_rdfxml_showDoctypeDeclaration, false)
- .setProperty(RDF_rdfxml_showXmlDeclaration, false);
- }
-
- private String strip(String s) {
- return s.replaceFirst("<rdf:RDF[^>]+>\\s*", "").replaceAll("</rdf:RDF>$", "").trim().replaceAll("[\\r\\n]", "");
- }
-
- //====================================================================================================
- // Bean.uri annotation
- //====================================================================================================
- @Test
- public void testBeanUriAnnotation() throws Exception {
- RdfSerializer s = getBasicSerializer();
- RdfParser p = RdfParser.DEFAULT_XML;
- A t1 = A.create(), t2;
- String r;
-
- r = s.serialize(t1);
- assertEquals("<rdf:Description rdf:about='http://foo'><jp:name>bar</jp:name></rdf:Description>", strip(r));
- t2 = p.parse(r, A.class);
- assertEqualObjects(t1, t2);
- }
-
- public static class A {
- @BeanProperty(beanUri=true) public URL url;
- public String name;
-
- public static A create() throws Exception {
- A t = new A();
- t.url = new URL("http://foo");
- t.name = "bar";
- return t;
- }
- }
-
- //====================================================================================================
- // Bean.uri annotation, only uri property
- //====================================================================================================
- @Test
- public void testBeanUriAnnotationOnlyUriProperty() throws Exception {
- RdfSerializer s = getBasicSerializer();
- RdfParser p = RdfParser.DEFAULT_XML;
- B t1 = B.create(), t2;
- String r;
-
- r = s.serialize(t1);
- assertEquals("<rdf:Description rdf:about='http://foo'><jp:url2 rdf:resource='http://foo/2'/></rdf:Description>", strip(r));
- t2 = p.parse(r, B.class);
- assertEqualObjects(t1, t2);
- }
-
- public static class B {
- @BeanProperty(beanUri=true) public URL url;
- public URL url2;
-
- public static B create() throws Exception {
- B t = new B();
- t.url = new URL("http://foo");
- t.url2 = new URL("http://foo/2");
- return t;
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/jena/CT_Rdf.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/jena/CT_Rdf.java b/org.apache.juneau/src/test/java/org/apache/juneau/jena/CT_Rdf.java
deleted file mode 100755
index d04cb10..0000000
--- a/org.apache.juneau/src/test/java/org/apache/juneau/jena/CT_Rdf.java
+++ /dev/null
@@ -1,597 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.jena;
-
-import static org.apache.juneau.TestUtils.*;
-import static org.apache.juneau.jena.RdfCommonContext.*;
-import static org.apache.juneau.jena.RdfSerializerContext.*;
-import static org.apache.juneau.serializer.SerializerContext.*;
-
-import java.net.URI;
-import java.util.*;
-
-import org.apache.juneau.annotation.*;
-import org.apache.juneau.jena.annotation.*;
-import org.apache.juneau.parser.*;
-import org.apache.juneau.serializer.*;
-import org.junit.*;
-
-@SuppressWarnings("serial")
-public class CT_Rdf {
-
- @Test
- public void testCollectionFormatProperties() throws Exception {
- A a = new A().init(), a2;
- String rdfXml;
- String expected;
-
- RdfSerializer s = new RdfSerializer.XmlAbbrev()
- .setProperty(RDF_rdfxml_tab, 3)
- .setProperty(SERIALIZER_quoteChar, '\'')
- .setProperty(RDF_addRootProperty, true);
- RdfParser p = RdfParser.DEFAULT_XML.clone();
-
- //--------------------------------------------------------------------------------
- // Normal format - Sequence
- //--------------------------------------------------------------------------------
- expected =
- "<rdf:RDF a='http://ns/' j='http://www.ibm.com/juneau/' jp='http://www.ibm.com/juneaubp/' rdf='http://www.w3.org/1999/02/22-rdf-syntax-ns#'>"
- + "\n <rdf:Description about='http://test/a'>"
- + "\n <a:f2>"
- + "\n <rdf:Seq>"
- + "\n <rdf:li>f2a</rdf:li>"
- + "\n <rdf:li>f2b</rdf:li>"
- + "\n </rdf:Seq>"
- + "\n </a:f2>"
- + "\n <a:f3>"
- + "\n <rdf:Seq>"
- + "\n <rdf:li>1</rdf:li>"
- + "\n <rdf:li>2</rdf:li>"
- + "\n </rdf:Seq>"
- + "\n </a:f3>"
- + "\n <j:root>true</j:root>"
- + "\n </rdf:Description>"
- + "\n</rdf:RDF>";
- rdfXml = s.serialize(a);
- assertXmlEquals(expected, rdfXml);
-
- a2 = p.parse(rdfXml, A.class);
- assertEqualObjects(a, a2);
-
- //--------------------------------------------------------------------------------
- // Explicit sequence
- //--------------------------------------------------------------------------------
- s.setProperty(RDF_collectionFormat, RdfCollectionFormat.SEQ);
- expected =
- "<rdf:RDF a='http://ns/' j='http://www.ibm.com/juneau/' jp='http://www.ibm.com/juneaubp/' rdf='http://www.w3.org/1999/02/22-rdf-syntax-ns#'>"
- + "\n <rdf:Description about='http://test/a'>"
- + "\n <a:f2>"
- + "\n <rdf:Seq>"
- + "\n <rdf:li>f2a</rdf:li>"
- + "\n <rdf:li>f2b</rdf:li>"
- + "\n </rdf:Seq>"
- + "\n </a:f2>"
- + "\n <a:f3>"
- + "\n <rdf:Seq>"
- + "\n <rdf:li>1</rdf:li>"
- + "\n <rdf:li>2</rdf:li>"
- + "\n </rdf:Seq>"
- + "\n </a:f3>"
- + "\n <j:root>true</j:root>"
- + "\n </rdf:Description>"
- + "\n</rdf:RDF>";
- rdfXml = s.serialize(a);
- assertXmlEquals(expected, rdfXml);
-
- a2 = p.parse(rdfXml, A.class);
- assertEqualObjects(a, a2);
-
- //--------------------------------------------------------------------------------
- // Bag
- //--------------------------------------------------------------------------------
- s.setProperty(RDF_collectionFormat, RdfCollectionFormat.BAG);
- expected =
- "<rdf:RDF a='http://ns/' j='http://www.ibm.com/juneau/' jp='http://www.ibm.com/juneaubp/' rdf='http://www.w3.org/1999/02/22-rdf-syntax-ns#'>"
- + "\n <rdf:Description about='http://test/a'>"
- + "\n <a:f2>"
- + "\n <rdf:Bag>"
- + "\n <rdf:li>f2a</rdf:li>"
- + "\n <rdf:li>f2b</rdf:li>"
- + "\n </rdf:Bag>"
- + "\n </a:f2>"
- + "\n <a:f3>"
- + "\n <rdf:Bag>"
- + "\n <rdf:li>1</rdf:li>"
- + "\n <rdf:li>2</rdf:li>"
- + "\n </rdf:Bag>"
- + "\n </a:f3>"
- + "\n <j:root>true</j:root>"
- + "\n </rdf:Description>"
- + "\n</rdf:RDF>";
- rdfXml = s.serialize(a);
- assertXmlEquals(expected, rdfXml);
-
- a2 = p.parse(rdfXml, A.class);
- assertEqualObjects(a, a2);
-
- //--------------------------------------------------------------------------------
- // List
- //--------------------------------------------------------------------------------
- s.setProperty(RDF_collectionFormat, RdfCollectionFormat.LIST);
- expected =
- "<rdf:RDF a='http://ns/' j='http://www.ibm.com/juneau/' jp='http://www.ibm.com/juneaubp/' rdf='http://www.w3.org/1999/02/22-rdf-syntax-ns#'>"
- + "\n <rdf:Description about='http://test/a'>"
- + "\n <a:f2 parseType='Resource'>"
- + "\n <rdf:first>f2a</rdf:first>"
- + "\n <rdf:rest parseType='Resource'>"
- + "\n <rdf:first>f2b</rdf:first>"
- + "\n <rdf:rest resource='http://www.w3.org/1999/02/22-rdf-syntax-ns#nil'/>"
- + "\n </rdf:rest>"
- + "\n </a:f2>"
- + "\n <a:f3 parseType='Resource'>"
- + "\n <rdf:first>1</rdf:first>"
- + "\n <rdf:rest parseType='Resource'>"
- + "\n <rdf:first>2</rdf:first>"
- + "\n <rdf:rest resource='http://www.w3.org/1999/02/22-rdf-syntax-ns#nil'/>"
- + "\n </rdf:rest>"
- + "\n </a:f3>"
- + "\n <j:root>true</j:root>"
- + "\n </rdf:Description>"
- + "\n</rdf:RDF>";
- rdfXml = s.serialize(a);
- assertXmlEquals(expected, rdfXml);
-
- a2 = p.parse(rdfXml, A.class);
- assertEqualObjects(a, a2);
-
- //--------------------------------------------------------------------------------
- // Multi-properties
- //--------------------------------------------------------------------------------
- s.setProperty(RDF_collectionFormat, RdfCollectionFormat.MULTI_VALUED);
- expected =
- "<rdf:RDF a='http://ns/' j='http://www.ibm.com/juneau/' jp='http://www.ibm.com/juneaubp/' rdf='http://www.w3.org/1999/02/22-rdf-syntax-ns#'>"
- + "\n <rdf:Description about='http://test/a'>"
- + "\n <a:f2>f2a</a:f2>"
- + "\n <a:f2>f2b</a:f2>"
- + "\n <a:f3>1</a:f3>"
- + "\n <a:f3>2</a:f3>"
- + "\n <j:root>true</j:root>"
- + "\n </rdf:Description>"
- + "\n</rdf:RDF>";
- rdfXml = s.serialize(a);
- assertXmlEquals(expected, rdfXml);
-
- // Note - Must specify collection format on parser for it to be able to understand this layout.
- p.setProperty(RDF_collectionFormat, RdfCollectionFormat.MULTI_VALUED);
- a2 = p.parse(rdfXml, A.class);
- assertEqualObjects(a, a2);
- }
-
- @Rdf(prefix="a", namespace="http://ns/")
- public static class A {
- @BeanProperty(beanUri=true) public URI f1;
- public String[] f2;
- public List<Integer> f3;
-
- public A init() throws Exception {
- f1 = new URI("http://test/a");
- f2 = new String[]{"f2a","f2b"};
- f3 = Arrays.asList(new Integer[]{1,2});
- return this;
- }
- }
-
- @Test
- public void testCollectionFormatAnnotations() throws Exception {
- B b = new B().init(), b2;
- String rdfXml, expected;
- RdfSerializer s = new RdfSerializer.XmlAbbrev()
- .setProperty(RDF_rdfxml_tab, 3)
- .setProperty(SERIALIZER_quoteChar, '\'')
- .setProperty(RDF_addRootProperty, true);
- RdfParser p = RdfParser.DEFAULT_XML.clone();
-
- //--------------------------------------------------------------------------------
- // Normal format - Sequence
- //--------------------------------------------------------------------------------
-
- expected =
- "<rdf:RDF b='http://ns/' j='http://www.ibm.com/juneau/' jp='http://www.ibm.com/juneaubp/' rdf='http://www.w3.org/1999/02/22-rdf-syntax-ns#'>"
- + "\n <rdf:Description about='http://test/b'>"
- + "\n <b:f2>"
- + "\n <rdf:Seq>"
- + "\n <rdf:li>f2a</rdf:li>"
- + "\n <rdf:li>f2b</rdf:li>"
- + "\n </rdf:Seq>"
- + "\n </b:f2>"
- + "\n <b:f3>"
- + "\n <rdf:Bag>"
- + "\n <rdf:li>f3a</rdf:li>"
- + "\n <rdf:li>f3b</rdf:li>"
- + "\n </rdf:Bag>"
- + "\n </b:f3>"
- + "\n <b:f4 parseType='Resource'>"
- + "\n <rdf:first>f4a</rdf:first>"
- + "\n <rdf:rest parseType='Resource'>"
- + "\n <rdf:first>f4b</rdf:first>"
- + "\n <rdf:rest resource='http://www.w3.org/1999/02/22-rdf-syntax-ns#nil'/>"
- + "\n </rdf:rest>"
- + "\n </b:f4>"
- + "\n <b:f5>f5a</b:f5>"
- + "\n <b:f5>f5b</b:f5>"
- + "\n <b:f6>"
- + "\n <rdf:Seq>"
- + "\n <rdf:li>f6a</rdf:li>"
- + "\n <rdf:li>f6b</rdf:li>"
- + "\n </rdf:Seq>"
- + "\n </b:f6>"
- + "\n <b:f7>"
- + "\n <rdf:Seq>"
- + "\n <rdf:li>f7a</rdf:li>"
- + "\n <rdf:li>f7b</rdf:li>"
- + "\n </rdf:Seq>"
- + "\n </b:f7>"
- + "\n <b:f8>"
- + "\n <rdf:Bag>"
- + "\n <rdf:li>f8a</rdf:li>"
- + "\n <rdf:li>f8b</rdf:li>"
- + "\n </rdf:Bag>"
- + "\n </b:f8>"
- + "\n <b:f9 parseType='Resource'>"
- + "\n <rdf:first>f9a</rdf:first>"
- + "\n <rdf:rest parseType='Resource'>"
- + "\n <rdf:first>f9b</rdf:first>"
- + "\n <rdf:rest resource='http://www.w3.org/1999/02/22-rdf-syntax-ns#nil'/>"
- + "\n </rdf:rest>"
- + "\n </b:f9>"
- + "\n <b:fa>faa</b:fa>"
- + "\n <b:fa>fab</b:fa>"
- + "\n <b:fb>"
- + "\n <rdf:Seq>"
- + "\n <rdf:li>fba</rdf:li>"
- + "\n <rdf:li>fbb</rdf:li>"
- + "\n </rdf:Seq>"
- + "\n </b:fb>"
- + "\n <j:root>true</j:root>"
- + "\n </rdf:Description>"
- + "\n</rdf:RDF>";
- rdfXml = s.serialize(b);
- assertXmlEquals(expected, rdfXml);
-
- b2 = p.parse(rdfXml, B.class);
- assertEqualObjects(b, b2, true);
-
- //--------------------------------------------------------------------------------
- // Default is Bag - Should only affect DEFAULT properties.
- //--------------------------------------------------------------------------------
- s.setProperty(RDF_collectionFormat, RdfCollectionFormat.BAG);
- expected =
- "<rdf:RDF b='http://ns/' j='http://www.ibm.com/juneau/' jp='http://www.ibm.com/juneaubp/' rdf='http://www.w3.org/1999/02/22-rdf-syntax-ns#'>"
- + "\n <rdf:Description about='http://test/b'>"
- + "\n <b:f2>"
- + "\n <rdf:Seq>"
- + "\n <rdf:li>f2a</rdf:li>"
- + "\n <rdf:li>f2b</rdf:li>"
- + "\n </rdf:Seq>"
- + "\n </b:f2>"
- + "\n <b:f3>"
- + "\n <rdf:Bag>"
- + "\n <rdf:li>f3a</rdf:li>"
- + "\n <rdf:li>f3b</rdf:li>"
- + "\n </rdf:Bag>"
- + "\n </b:f3>"
- + "\n <b:f4 parseType='Resource'>"
- + "\n <rdf:first>f4a</rdf:first>"
- + "\n <rdf:rest parseType='Resource'>"
- + "\n <rdf:first>f4b</rdf:first>"
- + "\n <rdf:rest resource='http://www.w3.org/1999/02/22-rdf-syntax-ns#nil'/>"
- + "\n </rdf:rest>"
- + "\n </b:f4>"
- + "\n <b:f5>f5a</b:f5>"
- + "\n <b:f5>f5b</b:f5>"
- + "\n <b:f6>"
- + "\n <rdf:Bag>"
- + "\n <rdf:li>f6a</rdf:li>"
- + "\n <rdf:li>f6b</rdf:li>"
- + "\n </rdf:Bag>"
- + "\n </b:f6>"
- + "\n <b:f7>"
- + "\n <rdf:Seq>"
- + "\n <rdf:li>f7a</rdf:li>"
- + "\n <rdf:li>f7b</rdf:li>"
- + "\n </rdf:Seq>"
- + "\n </b:f7>"
- + "\n <b:f8>"
- + "\n <rdf:Bag>"
- + "\n <rdf:li>f8a</rdf:li>"
- + "\n <rdf:li>f8b</rdf:li>"
- + "\n </rdf:Bag>"
- + "\n </b:f8>"
- + "\n <b:f9 parseType='Resource'>"
- + "\n <rdf:first>f9a</rdf:first>"
- + "\n <rdf:rest parseType='Resource'>"
- + "\n <rdf:first>f9b</rdf:first>"
- + "\n <rdf:rest resource='http://www.w3.org/1999/02/22-rdf-syntax-ns#nil'/>"
- + "\n </rdf:rest>"
- + "\n </b:f9>"
- + "\n <b:fa>faa</b:fa>"
- + "\n <b:fa>fab</b:fa>"
- + "\n <b:fb>"
- + "\n <rdf:Bag>"
- + "\n <rdf:li>fba</rdf:li>"
- + "\n <rdf:li>fbb</rdf:li>"
- + "\n </rdf:Bag>"
- + "\n </b:fb>"
- + "\n <j:root>true</j:root>"
- + "\n </rdf:Description>"
- + "\n</rdf:RDF>";
-
- rdfXml = s.serialize(b);
- assertXmlEquals(expected, rdfXml);
-
- b2 = p.parse(rdfXml, B.class);
- assertEqualObjects(b, b2, true);
- }
-
- @Rdf(prefix="b", namespace="http://ns/")
- public static class B {
- @BeanProperty(beanUri=true) public URI f1;
-
- @Rdf(collectionFormat=RdfCollectionFormat.SEQ)
- public String[] f2;
-
- @Rdf(collectionFormat=RdfCollectionFormat.BAG)
- public String[] f3;
-
- @Rdf(collectionFormat=RdfCollectionFormat.LIST)
- public String[] f4;
-
- @Rdf(collectionFormat=RdfCollectionFormat.MULTI_VALUED)
- public String[] f5;
-
- @Rdf(collectionFormat=RdfCollectionFormat.DEFAULT)
- public String[] f6;
-
- public BA f7;
- public BB f8;
- public BC f9;
- public BD fa;
- public BE fb;
-
- public B init() throws Exception {
- f1 = new URI("http://test/b");
- f2 = new String[]{"f2a","f2b"};
- f3 = new String[]{"f3a","f3b"};
- f4 = new String[]{"f4a","f4b"};
- f5 = new String[]{"f5a","f5b"};
- f6 = new String[]{"f6a","f6b"};
- f7 = new BA().append("f7a","f7b");
- f8 = new BB().append("f8a","f8b");
- f9 = new BC().append("f9a","f9b");
- fa = new BD().append("faa","fab");
- fb = new BE().append("fba","fbb");
- return this;
- }
- }
-
- @Rdf(prefix="ba", namespace="http://ns/", collectionFormat=RdfCollectionFormat.SEQ)
- public static class BA extends ArrayList<String> {
- public BA append(String...s) {
- this.addAll(Arrays.asList(s));
- return this;
- }
- }
-
- @Rdf(prefix="bb", namespace="http://ns/", collectionFormat=RdfCollectionFormat.BAG)
- public static class BB extends ArrayList<String> {
- public BB append(String...s) {
- this.addAll(Arrays.asList(s));
- return this;
- }
- }
-
- @Rdf(prefix="bc", namespace="http://ns/", collectionFormat=RdfCollectionFormat.LIST)
- public static class BC extends ArrayList<String> {
- public BC append(String...s) {
- this.addAll(Arrays.asList(s));
- return this;
- }
- }
-
- @Rdf(prefix="bd", namespace="http://ns/", collectionFormat=RdfCollectionFormat.MULTI_VALUED)
- public static class BD extends ArrayList<String> {
- public BD append(String...s) {
- this.addAll(Arrays.asList(s));
- return this;
- }
- }
-
- @Rdf(prefix="bd", namespace="http://ns/", collectionFormat=RdfCollectionFormat.DEFAULT)
- public static class BE extends ArrayList<String> {
- public BE append(String...s) {
- this.addAll(Arrays.asList(s));
- return this;
- }
- }
-
- @Test
- public void testCollectionFormatAnnotationOnClass() throws Exception {
- C c = new C().init(), c2;
- String rdfXml, expected;
- RdfSerializer s = new RdfSerializer.XmlAbbrev()
- .setProperty(RDF_rdfxml_tab, 3)
- .setProperty(SERIALIZER_quoteChar, '\'')
- .setProperty(RDF_addRootProperty, true);
- RdfParser p = RdfParser.DEFAULT_XML.clone();
-
- //--------------------------------------------------------------------------------
- // Default on class is Bag - Should only affect DEFAULT properties.
- //--------------------------------------------------------------------------------
- s.setProperty(RDF_collectionFormat, RdfCollectionFormat.BAG);
- expected =
- "<rdf:RDF b='http://ns/' j='http://www.ibm.com/juneau/' jp='http://www.ibm.com/juneaubp/' rdf='http://www.w3.org/1999/02/22-rdf-syntax-ns#'>"
- + "\n <rdf:Description about='http://test/b'>"
- + "\n <b:f2>"
- + "\n <rdf:Seq>"
- + "\n <rdf:li>f2a</rdf:li>"
- + "\n <rdf:li>f2b</rdf:li>"
- + "\n </rdf:Seq>"
- + "\n </b:f2>"
- + "\n <b:f3>"
- + "\n <rdf:Bag>"
- + "\n <rdf:li>f3a</rdf:li>"
- + "\n <rdf:li>f3b</rdf:li>"
- + "\n </rdf:Bag>"
- + "\n </b:f3>"
- + "\n <b:f4 parseType='Resource'>"
- + "\n <rdf:first>f4a</rdf:first>"
- + "\n <rdf:rest parseType='Resource'>"
- + "\n <rdf:first>f4b</rdf:first>"
- + "\n <rdf:rest resource='http://www.w3.org/1999/02/22-rdf-syntax-ns#nil'/>"
- + "\n </rdf:rest>"
- + "\n </b:f4>"
- + "\n <b:f5>f5a</b:f5>"
- + "\n <b:f5>f5b</b:f5>"
- + "\n <b:f6>"
- + "\n <rdf:Bag>"
- + "\n <rdf:li>f6a</rdf:li>"
- + "\n <rdf:li>f6b</rdf:li>"
- + "\n </rdf:Bag>"
- + "\n </b:f6>"
- + "\n <b:f7>"
- + "\n <rdf:Seq>"
- + "\n <rdf:li>f7a</rdf:li>"
- + "\n <rdf:li>f7b</rdf:li>"
- + "\n </rdf:Seq>"
- + "\n </b:f7>"
- + "\n <b:f8>"
- + "\n <rdf:Bag>"
- + "\n <rdf:li>f8a</rdf:li>"
- + "\n <rdf:li>f8b</rdf:li>"
- + "\n </rdf:Bag>"
- + "\n </b:f8>"
- + "\n <b:f9 parseType='Resource'>"
- + "\n <rdf:first>f9a</rdf:first>"
- + "\n <rdf:rest parseType='Resource'>"
- + "\n <rdf:first>f9b</rdf:first>"
- + "\n <rdf:rest resource='http://www.w3.org/1999/02/22-rdf-syntax-ns#nil'/>"
- + "\n </rdf:rest>"
- + "\n </b:f9>"
- + "\n <b:fa>faa</b:fa>"
- + "\n <b:fa>fab</b:fa>"
- + "\n <b:fb>"
- + "\n <rdf:Bag>"
- + "\n <rdf:li>fba</rdf:li>"
- + "\n <rdf:li>fbb</rdf:li>"
- + "\n </rdf:Bag>"
- + "\n </b:fb>"
- + "\n <j:root>true</j:root>"
- + "\n </rdf:Description>"
- + "\n</rdf:RDF>";
-
- rdfXml = s.serialize(c);
- assertXmlEquals(expected, rdfXml);
-
- c2 = p.parse(rdfXml, C.class);
- assertEqualObjects(c, c2, true);
- }
-
- @Rdf(collectionFormat=RdfCollectionFormat.BAG)
- public static class C extends B {
- @Override /* B */
- public C init() throws Exception {
- f1 = new URI("http://test/b");
- f2 = new String[]{"f2a","f2b"};
- f3 = new String[]{"f3a","f3b"};
- f4 = new String[]{"f4a","f4b"};
- f5 = new String[]{"f5a","f5b"};
- f6 = new String[]{"f6a","f6b"};
- f7 = new BA().append("f7a","f7b");
- f8 = new BB().append("f8a","f8b");
- f9 = new BC().append("f9a","f9b");
- fa = new BD().append("faa","fab");
- fb = new BE().append("fba","fbb");
- return this;
- }
- }
-
- @Test
- @SuppressWarnings("unchecked")
- public void testLooseCollectionsOfBeans() throws Exception {
- WriterSerializer s = new RdfSerializer.XmlAbbrev().setProperty(RDF_looseCollection, true);
- ReaderParser p = new RdfParser.Xml().setProperty(RDF_looseCollection, true);
- String rdfXml, expected;
-
- List<D> l = new LinkedList<D>();
- l.add(new D().init(1));
- l.add(new D().init(2));
-
- rdfXml = s.serialize(l);
- expected =
- "<rdf:RDF j='http://www.ibm.com/juneau/' jp='http://www.ibm.com/juneaubp/' rdf='http://www.w3.org/1999/02/22-rdf-syntax-ns#'>"
- + "\n <rdf:Description about='http://localhost/f1/2'>"
- + "\n <jp:f2>f2</jp:f2>"
- + "\n <jp:f3 resource='http://localhost/f3/2'/>"
- + "\n </rdf:Description>"
- + "\n <rdf:Description about='http://localhost/f1/1'>"
- + "\n <jp:f2>f2</jp:f2>"
- + "\n <jp:f3 resource='http://localhost/f3/1'/>"
- + "\n </rdf:Description>"
- + "\n</rdf:RDF>";
- assertXmlEquals(expected, rdfXml);
-
- l = p.parseCollection(rdfXml, LinkedList.class, D.class);
- D[] da = l.toArray(new D[l.size()]);
- rdfXml = s.serialize(da);
- expected =
- "<rdf:RDF j='http://www.ibm.com/juneau/' jp='http://www.ibm.com/juneaubp/' rdf='http://www.w3.org/1999/02/22-rdf-syntax-ns#'>"
- + "\n <rdf:Description about='http://localhost/f1/2'>"
- + "\n <jp:f2>f2</jp:f2>"
- + "\n <jp:f3 resource='http://localhost/f3/2'/>"
- + "\n </rdf:Description>"
- + "\n <rdf:Description about='http://localhost/f1/1'>"
- + "\n <jp:f2>f2</jp:f2>"
- + "\n <jp:f3 resource='http://localhost/f3/1'/>"
- + "\n </rdf:Description>"
- + "\n</rdf:RDF>";
- assertXmlEquals(expected, rdfXml);
-
- da = p.parse(rdfXml, D[].class);
- rdfXml = s.serialize(da);
- expected =
- "<rdf:RDF j='http://www.ibm.com/juneau/' jp='http://www.ibm.com/juneaubp/' rdf='http://www.w3.org/1999/02/22-rdf-syntax-ns#'>"
- + "\n <rdf:Description about='http://localhost/f1/2'>"
- + "\n <jp:f2>f2</jp:f2>"
- + "\n <jp:f3 resource='http://localhost/f3/2'/>"
- + "\n </rdf:Description>"
- + "\n <rdf:Description about='http://localhost/f1/1'>"
- + "\n <jp:f2>f2</jp:f2>"
- + "\n <jp:f3 resource='http://localhost/f3/1'/>"
- + "\n </rdf:Description>"
- + "\n</rdf:RDF>";
- assertXmlEquals(expected, rdfXml);
- }
-
- public static class D {
- @BeanProperty(beanUri=true) public URI f1;
- public String f2;
- public URI f3;
-
- public D init(int num) throws Exception {
- f1 = new URI("http://localhost/f1/" + num);
- f2 = "f2";
- f3 = new URI("http://localhost/f3/" + num);
- return this;
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/jena/CT_RdfParser.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/jena/CT_RdfParser.java b/org.apache.juneau/src/test/java/org/apache/juneau/jena/CT_RdfParser.java
deleted file mode 100755
index 06640d0..0000000
--- a/org.apache.juneau/src/test/java/org/apache/juneau/jena/CT_RdfParser.java
+++ /dev/null
@@ -1,149 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.jena;
-
-import static org.apache.juneau.TestUtils.*;
-import static org.apache.juneau.jena.RdfCommonContext.*;
-import static org.apache.juneau.jena.RdfSerializerContext.*;
-import static org.apache.juneau.serializer.SerializerContext.*;
-import static org.junit.Assert.*;
-
-import java.net.URI;
-import java.text.*;
-import java.util.*;
-
-import org.apache.juneau.*;
-import org.apache.juneau.annotation.*;
-import org.apache.juneau.jena.annotation.*;
-import org.apache.juneau.json.*;
-import org.apache.juneau.transforms.*;
-import org.junit.*;
-
-public class CT_RdfParser {
-
- @Test
- public void testParseIntoGenericPojos() throws Exception {
- A a = new A().init();
-
- // Create a new serializer with readable output.
- RdfSerializer s = new RdfSerializer.XmlAbbrev()
- .setProperty(RDF_rdfxml_tab, 3)
- .setProperty(SERIALIZER_quoteChar, '\'')
- .setProperty(RDF_addRootProperty, true);
-
- String expected =
- "<rdf:RDF a='http://ns/' a1='http://ns2/' j='http://www.ibm.com/juneau/' jp='http://www.ibm.com/juneaubp/' rdf='http://www.w3.org/1999/02/22-rdf-syntax-ns#'>"
- + "\n <rdf:Description about='http://test/a'>"
- + "\n <a:f1>1</a:f1>"
- + "\n <a:f2>f2</a:f2>"
- + "\n <a:f4a rdf:resource='http://test/a'/>"
- + "\n <a:f4b rdf:resource='http://test/external'/>"
- + "\n <a:f5>1999-01-01T00:00:00Z</a:f5>"
- + "\n <a:f6>"
- + "\n <rdf:Seq>"
- + "\n <rdf:li>"
- + "\n <rdf:Description about='http://test/a/a1'>"
- + "\n <a1:f1>1</a1:f1>"
- + "\n <a1:f2>f2</a1:f2>"
- + "\n <a1:f4a rdf:resource='http://test/a'/>"
- + "\n <a1:f4b rdf:resource='http://test/external'/>"
- + "\n <a1:f5>1999-01-01T00:00:00Z</a1:f5>"
- + "\n </rdf:Description>"
- + "\n </rdf:li>"
- + "\n </rdf:Seq>"
- + "\n </a:f6>"
- + "\n <j:root>true</j:root>"
- + "\n </rdf:Description>"
- + "\n</rdf:RDF>";
-
- String rdfXml = s.serialize(a);
- assertXmlEquals(expected, rdfXml);
-
- A a2 = RdfParser.DEFAULT_XML.parse(rdfXml, A.class);
-
- assertEqualObjects(a, a2);
-
- ObjectMap m = RdfParser.DEFAULT_XML.parse(rdfXml, ObjectMap.class);
- String json = JsonSerializer.DEFAULT_LAX_READABLE.serialize(m);
-
- String e = ""
- + "{\n"
- + " uri: 'http://test/a', \n"
- + " f6: [\n"
- + " {\n"
- + " uri: 'http://test/a/a1', \n"
- + " f5: '1999-01-01T00:00:00Z', \n"
- + " f4b: 'http://test/external', \n"
- + " f4a: 'http://test/a', \n"
- + " f2: 'f2', \n"
- + " f1: '1'\n"
- + " }\n"
- + " ], \n"
- + " f5: '1999-01-01T00:00:00Z', \n"
- + " f4b: 'http://test/external', \n"
- + " f4a: 'http://test/a', \n"
- + " f2: 'f2', \n"
- + " f1: '1', \n"
- + " root: 'true'\n"
- + "}";
- assertEquals(e, json.replace("\r", ""));
-
- }
-
- @Rdf(prefix="a", namespace="http://ns/")
- public static class A {
- public int f1;
- public String f2;
- @BeanProperty(beanUri=true) public URI f3;
- public URI f4a, f4b;
- @BeanProperty(transform=CalendarTransform.ISO8601DTZ.class) public Calendar f5;
- public LinkedList<A1> f6 = new LinkedList<A1>();
-
- public A init() throws Exception {
- f1 = 1;
- f2 = "f2";
- f3 = new URI("http://test/a"); // Bean URI.
- f4a = new URI("http://test/a"); // Points to itself.
- f4b = new URI("http://test/external");
- f5 = new GregorianCalendar();
- DateFormat df = DateFormat.getDateInstance(DateFormat.MEDIUM);
- df.setTimeZone(TimeZone.getTimeZone("GMT"));
- f5.setTime(df.parse("Jan 1, 1999"));
- f6 = new LinkedList<A1>();
- f6.add(new A1().init());
- return this;
- }
- }
-
- @Rdf(prefix="a1", namespace="http://ns2/")
- public static class A1 {
- public int f1;
- public String f2;
- @BeanProperty(beanUri=true) public URI f3;
- public URI f4a, f4b;
- @BeanProperty(transform=CalendarTransform.ISO8601DTZ.class) public Calendar f5;
-
- public A1 init() throws Exception {
- f1 = 1;
- f2 = "f2";
- f3 = new URI("http://test/a/a1");
- f4a = new URI("http://test/a");
- f4b = new URI("http://test/external");
- f5 = new GregorianCalendar();
- DateFormat df = DateFormat.getDateInstance(DateFormat.MEDIUM);
- df.setTimeZone(TimeZone.getTimeZone("GMT"));
- f5.setTime(df.parse("Jan 1, 1999"));
- return this;
- }
- }
-}
[22/44] incubator-juneau git commit: Rename CT_* testcases.
Posted by ja...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/RoundTripPrimitivesBeansTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/RoundTripPrimitivesBeansTest.java b/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/RoundTripPrimitivesBeansTest.java
new file mode 100755
index 0000000..c028554
--- /dev/null
+++ b/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/RoundTripPrimitivesBeansTest.java
@@ -0,0 +1,367 @@
+/***************************************************************************************************************************
+ * 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.juneau.a.rttests;
+
+import static org.junit.Assert.*;
+
+import java.util.*;
+
+import org.apache.juneau.parser.*;
+import org.apache.juneau.serializer.*;
+import org.junit.*;
+
+/**
+ * Tests designed to serialize and parse objects to make sure we end up
+ * with the same objects for all serializers and parsers.
+ */
+@SuppressWarnings({"unchecked","serial"})
+public class RoundTripPrimitivesBeansTest extends RoundTripTest {
+
+ public RoundTripPrimitivesBeansTest(String label, Serializer s, Parser p, int flags) throws Exception {
+ super(label, s, p, flags);
+ }
+
+ //====================================================================================================
+ // testPrimitivesBean
+ //====================================================================================================
+ @Test
+ public void testPrimitivesBean() throws Exception {
+ PrimitivesBean t = new PrimitivesBean().init();
+ t = roundTrip(t, PrimitivesBean.class);
+
+ // primitives
+ assertEquals(true, t.pBoolean);
+ assertEquals(1, t.pByte);
+ assertEquals('a', t.pChar);
+ assertEquals(2, t.pShort);
+ assertEquals(3, t.pInt);
+ assertEquals(4l, t.pLong);
+ assertEquals(5f, t.pFloat, 0.1f);
+ assertEquals(6d, t.pDouble, 0.1f);
+
+ // uninitialized primitives
+ assertEquals(false, t.puBoolean);
+ assertEquals(0, t.puByte);
+ assertEquals((char)0, t.puChar);
+ assertEquals(0, t.puShort);
+ assertEquals(0, t.puInt);
+ assertEquals(0l, t.puLong);
+ assertEquals(0f, t.puFloat, 0.1f);
+ assertEquals(0d, t.puDouble, 0.1f);
+
+ // primitive arrays
+ assertEquals(false, t.paBoolean[1][0]);
+ assertEquals(2, t.paByte[1][0]);
+ assertEquals('b', t.paChar[1][0]);
+ assertEquals(2, t.paShort[1][0]);
+ assertEquals(2, t.paInt[1][0]);
+ assertEquals(2l, t.paLong[1][0]);
+ assertEquals(2f, t.paFloat[1][0], 0.1f);
+ assertEquals(2d, t.paDouble[1][0], 0.1f);
+ assertNull(t.paBoolean[2]);
+ assertNull(t.paByte[2]);
+ assertNull(t.paChar[2]);
+ assertNull(t.paShort[2]);
+ assertNull(t.paInt[2]);
+ assertNull(t.paLong[2]);
+ assertNull(t.paFloat[2]);
+ assertNull(t.paDouble[2]);
+
+ // uninitialized primitive arrays
+ assertNull(t.pauBoolean);
+ assertNull(t.pauByte);
+ assertNull(t.pauChar);
+ assertNull(t.pauShort);
+ assertNull(t.pauInt);
+ assertNull(t.pauLong);
+ assertNull(t.pauFloat);
+ assertNull(t.pauDouble);
+
+ // anonymous list of primitive arrays
+ assertEquals(true, t.palBoolean.get(0)[0]);
+ assertEquals(1, t.palByte.get(0)[0]);
+ assertEquals('a', t.palChar.get(0)[0]);
+ assertEquals(1, t.palShort.get(0)[0]);
+ assertEquals(1, t.palInt.get(0)[0]);
+ assertEquals(1l, t.palLong.get(0)[0]);
+ assertEquals(1f, t.palFloat.get(0)[0], 0.1f);
+ assertEquals(1d, t.palDouble.get(0)[0], 0.1f);
+ assertNull(t.palBoolean.get(1));
+ assertNull(t.palByte.get(1));
+ assertNull(t.palChar.get(1));
+ assertNull(t.palShort.get(1));
+ assertNull(t.palInt.get(1));
+ assertNull(t.palLong.get(1));
+ assertNull(t.palFloat.get(1));
+ assertNull(t.palDouble.get(1));
+
+ // regular list of primitive arrays
+ assertEquals(true, t.plBoolean.get(0)[0]);
+ assertEquals(1, t.plByte.get(0)[0]);
+ assertEquals('a', t.plChar.get(0)[0]);
+ assertEquals(1, t.plShort.get(0)[0]);
+ assertEquals(1, t.plInt.get(0)[0]);
+ assertEquals(1l, t.plLong.get(0)[0]);
+ assertEquals(1f, t.plFloat.get(0)[0], 0.1f);
+ assertEquals(1d, t.plDouble.get(0)[0], 0.1f);
+ assertNull(t.plBoolean.get(1));
+ assertNull(t.plByte.get(1));
+ assertNull(t.plChar.get(1));
+ assertNull(t.plShort.get(1));
+ assertNull(t.plInt.get(1));
+ assertNull(t.plLong.get(1));
+ assertNull(t.plFloat.get(1));
+ assertNull(t.plDouble.get(1));
+ }
+
+ public static class PrimitivesBean {
+
+ // primitives
+ public boolean pBoolean;
+ public byte pByte;
+ public char pChar;
+ public short pShort;
+ public int pInt;
+ public long pLong;
+ public float pFloat;
+ public double pDouble;
+
+ // uninitialized primitives
+ public boolean puBoolean;
+ public byte puByte;
+ public char puChar;
+ public short puShort;
+ public int puInt;
+ public long puLong;
+ public float puFloat;
+ public double puDouble;
+
+ // primitive arrays
+ public boolean[][] paBoolean;
+ public byte[][] paByte;
+ public char[][] paChar;
+ public short[][] paShort;
+ public int[][] paInt;
+ public long[][] paLong;
+ public float[][] paFloat;
+ public double[][] paDouble;
+
+ // uninitialized primitive arrays
+ public boolean[][] pauBoolean;
+ public byte[][] pauByte;
+ public char[][] pauChar;
+ public short[][] pauShort;
+ public int[][] pauInt;
+ public long[][] pauLong;
+ public float[][] pauFloat;
+ public double[][] pauDouble;
+
+ // Regular lists of primitives
+ public List<boolean[]> plBoolean;
+ public List<byte[]> plByte;
+ public List<char[]> plChar;
+ public List<short[]> plShort;
+ public List<int[]> plInt;
+ public List<long[]> plLong;
+ public List<float[]> plFloat;
+ public List<double[]> plDouble;
+
+ // Anonymous list of primitives
+ public List<boolean[]> palBoolean;
+ public List<byte[]> palByte;
+ public List<char[]> palChar;
+ public List<short[]> palShort;
+ public List<int[]> palInt;
+ public List<long[]> palLong;
+ public List<float[]> palFloat;
+ public List<double[]> palDouble;
+
+ public PrimitivesBean init() {
+ // primitives
+ pBoolean = true;
+ pByte = 1;
+ pChar = 'a';
+ pShort = 2;
+ pInt = 3;
+ pLong = 4l;
+ pFloat = 5f;
+ pDouble = 6d;
+
+ // primitive arrays
+ paBoolean = new boolean[][]{{true},{false},null};
+ paByte = new byte[][]{{1},{2},null};
+ paChar = new char[][]{{'a'},{'b'},null};
+ paShort = new short[][]{{1},{2},null};
+ paInt = new int[][]{{1},{2},null};
+ paLong = new long[][]{{1},{2},null};
+ paFloat = new float[][]{{1},{2},null};
+ paDouble = new double[][]{{1},{2},null};
+
+ // Regular lists of primitives
+ plBoolean = new ArrayList<boolean[]>() {{
+ add(new boolean[]{true}); add(null);
+ }};
+ plByte = new ArrayList<byte[]>() {{
+ add(new byte[]{1}); add(null);
+ }};
+ plChar = new ArrayList<char[]>() {{
+ add(new char[]{'a'}); add(null);
+ }};
+ plShort = new ArrayList<short[]>() {{
+ add(new short[]{1}); add(null);
+ }};
+ plInt = new ArrayList<int[]>() {{
+ add(new int[]{1}); add(null);
+ }};
+ plLong = new ArrayList<long[]>() {{
+ add(new long[]{1}); add(null);
+ }};
+ plFloat = new ArrayList<float[]>() {{
+ add(new float[]{1}); add(null);
+ }};
+ plDouble = new ArrayList<double[]>() {{
+ add(new double[]{1}); add(null);
+ }};
+
+ // Anonymous list of primitives
+ palBoolean = new ArrayList<boolean[]>();
+ palBoolean.add(new boolean[]{true});
+ palBoolean.add(null);
+ palByte = new ArrayList<byte[]>();
+ palByte.add(new byte[]{1});
+ palByte.add(null);
+ palChar = new ArrayList<char[]>();
+ palChar.add(new char[]{'a'});
+ palChar.add(null);
+ palShort = new ArrayList<short[]>();
+ palShort.add(new short[]{1});
+ palShort.add(null);
+ palInt = new ArrayList<int[]>();
+ palInt.add(new int[]{1});
+ palInt.add(null);
+ palLong = new ArrayList<long[]>();
+ palLong.add(new long[]{1});
+ palLong.add(null);
+ palFloat = new ArrayList<float[]>();
+ palFloat.add(new float[]{1});
+ palFloat.add(null);
+ palDouble = new ArrayList<double[]>();
+ palDouble.add(new double[]{1});
+ palDouble.add(null);
+ return this;
+ }
+ }
+
+ //====================================================================================================
+ // List of PrimitivesBean
+ //====================================================================================================
+ @Test
+ public void testPrimitivesBeanList() throws Exception {
+ List<PrimitivesBean> t = new ArrayList<PrimitivesBean>() {{
+ add(new PrimitivesBean().init());
+ add(null);
+ add(new PrimitivesBean().init());
+ }};
+ if (p == null)
+ return;
+ t = roundTrip(t, p.getBeanContext().getCollectionClassMeta(List.class, PrimitivesBean.class));
+
+ PrimitivesBean t2 = t.get(2);
+
+ // primitives
+ assertEquals(true, t2.pBoolean);
+ assertEquals(1, t2.pByte);
+ assertEquals('a', t2.pChar);
+ assertEquals(2, t2.pShort);
+ assertEquals(3, t2.pInt);
+ assertEquals(4l, t2.pLong);
+ assertEquals(5f, t2.pFloat, 0.1f);
+ assertEquals(6d, t2.pDouble, 0.1f);
+
+ // uninitialized primitives
+ assertEquals(false, t2.puBoolean);
+ assertEquals(0, t2.puByte);
+ assertEquals((char)0, t2.puChar);
+ assertEquals(0, t2.puShort);
+ assertEquals(0, t2.puInt);
+ assertEquals(0l, t2.puLong);
+ assertEquals(0f, t2.puFloat, 0.1f);
+ assertEquals(0d, t2.puDouble, 0.1f);
+
+ // primitive arrays
+ assertEquals(false, t2.paBoolean[1][0]);
+ assertEquals(2, t2.paByte[1][0]);
+ assertEquals('b', t2.paChar[1][0]);
+ assertEquals(2, t2.paShort[1][0]);
+ assertEquals(2, t2.paInt[1][0]);
+ assertEquals(2l, t2.paLong[1][0]);
+ assertEquals(2f, t2.paFloat[1][0], 0.1f);
+ assertEquals(2d, t2.paDouble[1][0], 0.1f);
+ assertNull(t2.paBoolean[2]);
+ assertNull(t2.paByte[2]);
+ assertNull(t2.paChar[2]);
+ assertNull(t2.paShort[2]);
+ assertNull(t2.paInt[2]);
+ assertNull(t2.paLong[2]);
+ assertNull(t2.paFloat[2]);
+ assertNull(t2.paDouble[2]);
+
+ // uninitialized primitive arrays
+ assertNull(t2.pauBoolean);
+ assertNull(t2.pauByte);
+ assertNull(t2.pauChar);
+ assertNull(t2.pauShort);
+ assertNull(t2.pauInt);
+ assertNull(t2.pauLong);
+ assertNull(t2.pauFloat);
+ assertNull(t2.pauDouble);
+
+ // anonymous list of primitive arrays
+ assertEquals(true, t2.palBoolean.get(0)[0]);
+ assertEquals(1, t2.palByte.get(0)[0]);
+ assertEquals('a', t2.palChar.get(0)[0]);
+ assertEquals(1, t2.palShort.get(0)[0]);
+ assertEquals(1, t2.palInt.get(0)[0]);
+ assertEquals(1l, t2.palLong.get(0)[0]);
+ assertEquals(1f, t2.palFloat.get(0)[0], 0.1f);
+ assertEquals(1d, t2.palDouble.get(0)[0], 0.1f);
+ assertNull(t2.palBoolean.get(1));
+ assertNull(t2.palByte.get(1));
+ assertNull(t2.palChar.get(1));
+ assertNull(t2.palShort.get(1));
+ assertNull(t2.palInt.get(1));
+ assertNull(t2.palLong.get(1));
+ assertNull(t2.palFloat.get(1));
+ assertNull(t2.palDouble.get(1));
+
+ // regular list of primitive arrays
+ assertEquals(true, t2.plBoolean.get(0)[0]);
+ assertEquals(1, t2.plByte.get(0)[0]);
+ assertEquals('a', t2.plChar.get(0)[0]);
+ assertEquals(1, t2.plShort.get(0)[0]);
+ assertEquals(1, t2.plInt.get(0)[0]);
+ assertEquals(1l, t2.plLong.get(0)[0]);
+ assertEquals(1f, t2.plFloat.get(0)[0], 0.1f);
+ assertEquals(1d, t2.plDouble.get(0)[0], 0.1f);
+ assertNull(t2.plBoolean.get(1));
+ assertNull(t2.plByte.get(1));
+ assertNull(t2.plChar.get(1));
+ assertNull(t2.plShort.get(1));
+ assertNull(t2.plInt.get(1));
+ assertNull(t2.plLong.get(1));
+ assertNull(t2.plFloat.get(1));
+ assertNull(t2.plDouble.get(1));
+
+ assertNull(t.get(1));
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/RoundTripReadOnlyBeansTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/RoundTripReadOnlyBeansTest.java b/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/RoundTripReadOnlyBeansTest.java
new file mode 100755
index 0000000..bf6214c
--- /dev/null
+++ b/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/RoundTripReadOnlyBeansTest.java
@@ -0,0 +1,100 @@
+/***************************************************************************************************************************
+ * 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.juneau.a.rttests;
+
+import static org.junit.Assert.*;
+
+import org.apache.juneau.annotation.*;
+import org.apache.juneau.parser.*;
+import org.apache.juneau.serializer.*;
+import org.junit.*;
+
+/**
+ * Tests designed to serialize and parse objects to make sure we end up
+ * with the same objects for all serializers and parsers.
+ */
+public class RoundTripReadOnlyBeansTest extends RoundTripTest {
+
+ public RoundTripReadOnlyBeansTest(String label, Serializer s, Parser p, int flags) throws Exception {
+ super(label, s, p, flags);
+ }
+
+ //====================================================================================================
+ // test
+ //====================================================================================================
+ @Test
+ public void test() throws Exception {
+ B t1 = new B(1, "a"), t2 = new B(2, "b");
+ A t3 = new A(t1, t2);
+
+ t3 = roundTrip(t3, A.class);
+ assertEquals(1, t3.getF1().getF1());
+ assertEquals("a", t3.getF1().getF2());
+ assertEquals(2, t3.getF2().getF1());
+ assertEquals("b", t3.getF2().getF2());
+ }
+
+ public static class A {
+ private B f1;
+ private final B f2;
+
+ @BeanConstructor(properties={"f2"})
+ public A(B f2) {
+ this.f2 = f2;
+ }
+
+ public A(B f1, B f2) {
+ this.f1 = f1;
+ this.f2 = f2;
+ }
+
+ public B getF1() {
+ return f1;
+ }
+
+ public void setF1(B f1) {
+ this.f1 = f1;
+ }
+
+ public B getF2() {
+ return f2;
+ }
+ }
+
+ public static class B {
+ private int f1;
+ private final String f2;
+
+ @BeanConstructor(properties={"f2"})
+ public B(String sField) {
+ this.f2 = sField;
+ }
+
+ public B(int iField, String sField) {
+ this.f1 = iField;
+ this.f2 = sField;
+ }
+
+ public int getF1() {
+ return f1;
+ }
+
+ public void setF1(int f1) {
+ this.f1 = f1;
+ }
+
+ public String getF2() {
+ return f2;
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/RoundTripSimpleObjectsTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/RoundTripSimpleObjectsTest.java b/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/RoundTripSimpleObjectsTest.java
new file mode 100755
index 0000000..91b7d81
--- /dev/null
+++ b/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/RoundTripSimpleObjectsTest.java
@@ -0,0 +1,750 @@
+/***************************************************************************************************************************
+ * 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.juneau.a.rttests;
+
+import static org.junit.Assert.*;
+
+import java.util.*;
+
+import org.apache.juneau.*;
+import org.apache.juneau.parser.*;
+import org.apache.juneau.serializer.*;
+import org.junit.*;
+
+/**
+ * Tests designed to serialize and parse objects to make sure we end up
+ * with the same objects for all serializers and parsers.
+ */
+@SuppressWarnings({ "unchecked", "rawtypes" })
+public class RoundTripSimpleObjectsTest extends RoundTripTest {
+
+ public RoundTripSimpleObjectsTest(String label, Serializer s, Parser p, int flags) throws Exception {
+ super(label, s, p, flags);
+ }
+
+ //====================================================================================================
+ // testNull
+ //====================================================================================================
+ @Test
+ public void testNull() throws Exception {
+ String t = null;
+ t = roundTrip(t);
+ assertNull(t);
+ }
+
+ //====================================================================================================
+ // testString
+ //====================================================================================================
+ @Test
+ public void testString() throws Exception {
+ String t = "foobar";
+ t = roundTrip(t);
+ assertEquals("foobar", t);
+ t = "";
+ t = roundTrip(t);
+ assertEquals("", t);
+ }
+
+ //====================================================================================================
+ // testStringArray
+ //====================================================================================================
+ @Test
+ public void testStringArray() throws Exception {
+ String[] t = {"foo", null, "null", ""};
+ t = roundTrip(t, String[].class);
+ assertEquals("foo", t[0]);
+ assertNull(t[1]);
+ assertEquals("null", t[2]);
+ assertEquals("", t[3]);
+ }
+
+ //====================================================================================================
+ // testString2dArray
+ //====================================================================================================
+ @Test
+ public void testString2dArray() throws Exception {
+ String[][] t = {{"foo", null, "null", ""},null};
+ t = roundTrip(t, String[][].class);
+ assertEquals("foo", t[0][0]);
+ assertNull(t[0][1]);
+ assertEquals("null", t[0][2]);
+ assertEquals("", t[0][3]);
+ assertNull(t[1]);
+ }
+
+ //====================================================================================================
+ // testInt
+ //====================================================================================================
+ @Test
+ public void testInt() throws Exception {
+ int t = 123;
+ t = roundTrip(t);
+ assertEquals(123, t);
+ }
+
+ //====================================================================================================
+ // testIntArray
+ //====================================================================================================
+ @Test
+ public void testIntArray() throws Exception {
+ int[] t = roundTrip(new int[]{1,2,3}, int[].class);
+ assertEquals(1, t[0]);
+ assertEquals(2, t[1]);
+ assertEquals(3, t[2]);
+ }
+
+ //====================================================================================================
+ // testInt2dArray
+ //====================================================================================================
+ @Test
+ public void testInt2dArray() throws Exception {
+ int[][] t = {{1,2,3},null};
+ t = roundTrip(t, int[][].class);
+ assertEquals(1, t[0][0]);
+ assertEquals(2, t[0][1]);
+ assertEquals(3, t[0][2]);
+ assertNull(t[1]);
+ }
+
+ //====================================================================================================
+ // testInt3dArray
+ //====================================================================================================
+ @Test
+ public void testInt3dArray() throws Exception {
+ int[][][] t = {{{1,2,3},{4,5,6},null},null};
+ t = roundTrip(t, int[][][].class);
+ assertEquals(1, t[0][0][0]);
+ assertEquals(2, t[0][0][1]);
+ assertEquals(3, t[0][0][2]);
+ assertEquals(4, t[0][1][0]);
+ assertEquals(5, t[0][1][1]);
+ assertEquals(6, t[0][1][2]);
+ assertNull(t[0][2]);
+ assertNull(t[1]);
+ }
+
+ //====================================================================================================
+ // testBoolean
+ //====================================================================================================
+ @Test
+ public void testBoolean() throws Exception {
+ boolean t = true;
+ t = roundTrip(t);
+ assertTrue(t);
+ t = false;
+ t = roundTrip(t);
+ assertFalse(t);
+ }
+
+ //====================================================================================================
+ // testBooleanArray
+ //====================================================================================================
+ @Test
+ public void testBooleanArray() throws Exception {
+ boolean[] t = {true,false};
+ t = roundTrip(t, boolean[].class);
+ assertTrue(t[0]);
+ assertFalse(t[1]);
+ }
+
+ //====================================================================================================
+ // testBoolean2dArray
+ //====================================================================================================
+ @Test
+ public void testBoolean2dArray() throws Exception {
+ boolean[][] t = {{true,false},null};
+ t = roundTrip(t, boolean[][].class);
+ assertTrue(t[0][0]);
+ assertFalse(t[0][1]);
+ assertNull(t[1]);
+ }
+
+ //====================================================================================================
+ // testChar
+ //====================================================================================================
+ @Test
+ public void testChar() throws Exception {
+ char t = 'a';
+ t = roundTrip(t, char.class);
+ assertEquals('a', t);
+ }
+
+ //====================================================================================================
+ // testCharArray
+ //====================================================================================================
+ @Test
+ public void testCharArray() throws Exception {
+ char[] t = {'a',0};
+ t = roundTrip(t, char[].class);
+ assertEquals('a', t[0]);
+ assertEquals(0, t[1]);
+ }
+
+ //====================================================================================================
+ // testChar2dArray
+ //====================================================================================================
+ @Test
+ public void testChar2dArray() throws Exception {
+ char[][] t = {{'a',0},null};
+ t = roundTrip(t, char[][].class);
+ assertEquals('a', t[0][0]);
+ assertEquals(0, t[0][1]);
+ assertNull(t[1]);
+ }
+
+ //====================================================================================================
+ // testFloat
+ //====================================================================================================
+ @Test
+ public void testFloat() throws Exception {
+ float t = 1f;
+ t = roundTrip(t, float.class);
+ assertEquals(1f, t, 0.1f);
+ }
+
+ //====================================================================================================
+ // testFloatArray
+ //====================================================================================================
+ @Test
+ public void testFloatArray() throws Exception {
+ float[] t = {1f};
+ t = roundTrip(t, float[].class);
+ assertEquals(1f, t[0], 0.1f);
+ }
+
+ //====================================================================================================
+ // testFloat2dArray
+ //====================================================================================================
+ @Test
+ public void testFloat2dArray() throws Exception {
+ float[][] t = {{1f},null};
+ t = roundTrip(t, float[][].class);
+ assertEquals(1f, t[0][0], 0.1f);
+ assertNull(t[1]);
+ }
+
+ //====================================================================================================
+ // testDouble
+ //====================================================================================================
+ @Test
+ public void testDouble() throws Exception {
+ double t = 1d;
+ t = roundTrip(t, double.class);
+ assertEquals(1d, t, 0.1f);
+ }
+
+ //====================================================================================================
+ // testDoubleArray
+ //====================================================================================================
+ @Test
+ public void testDoubleArray() throws Exception {
+ double[] t = {1d};
+ t = roundTrip(t, double[].class);
+ assertEquals(1d, t[0], 0.1f);
+ }
+
+ //====================================================================================================
+ // testDouble2dArray
+ //====================================================================================================
+ @Test
+ public void testDouble2dArray() throws Exception {
+ double[][] t = {{1d},null};
+ t = roundTrip(t, double[][].class);
+ assertEquals(1d, t[0][0], 0.1f);
+ assertNull(t[1]);
+ }
+
+ //====================================================================================================
+ // testLong
+ //====================================================================================================
+ @Test
+ public void testLong() throws Exception {
+ long t = 1l;
+ t = roundTrip(t, long.class);
+ assertEquals(1l, t);
+ }
+
+ //====================================================================================================
+ // testLongArray
+ //====================================================================================================
+ @Test
+ public void testLongArray() throws Exception {
+ long[] t = {1l};
+ t = roundTrip(t, long[].class);
+ assertEquals(1l, t[0]);
+ }
+
+ //====================================================================================================
+ // testLong2dArray
+ //====================================================================================================
+ @Test
+ public void testLong2dArray() throws Exception {
+ long[][] t = {{1l},null};
+ t = roundTrip(t, long[][].class);
+ assertEquals(1l, t[0][0]);
+ assertNull(t[1]);
+ }
+
+ //====================================================================================================
+ // testShort
+ //====================================================================================================
+ @Test
+ public void testShort() throws Exception {
+ short t = (short)1;
+ t = roundTrip(t, short.class);
+ assertEquals(1l, t);
+ }
+
+ //====================================================================================================
+ // testShortArray
+ //====================================================================================================
+ @Test
+ public void testShortArray() throws Exception {
+ short[] t = {(short)1};
+ t = roundTrip(t, short[].class);
+ assertEquals(1l, t[0]);
+ }
+
+ //====================================================================================================
+ // testShort2dArray
+ //====================================================================================================
+ @Test
+ public void testShort2dArray() throws Exception {
+ short[][] t = {{(short)1},null};
+ t = roundTrip(t, short[][].class);
+ assertEquals((short)1, t[0][0]);
+ assertNull(t[1]);
+ }
+
+ //====================================================================================================
+ // testInteger
+ //====================================================================================================
+ @Test
+ public void testInteger() throws Exception {
+ Integer t = 123;
+ t = roundTrip(t, Integer.class);
+ assertEquals(new Integer(123), t);
+ }
+
+ //====================================================================================================
+ // testIntegerArray
+ //====================================================================================================
+ @Test
+ public void testIntegerArray() throws Exception {
+ Integer[] t = {123, null};
+ t = roundTrip(t, Integer[].class);
+ assertEquals(new Integer(123), t[0]);
+ assertNull(t[1]);
+ }
+
+ //====================================================================================================
+ // testInteger2dArray
+ //====================================================================================================
+ @Test
+ public void testInteger2dArray() throws Exception {
+ Integer[][] t = {{123,null},null};
+ t = roundTrip(t, Integer[][].class);
+ assertEquals(new Integer(123), t[0][0]);
+ assertNull(t[0][1]);
+ assertNull(t[1]);
+ }
+
+ //====================================================================================================
+ // testInteger3dArray
+ //====================================================================================================
+ @Test
+ public void testInteger3dArray() throws Exception {
+ Integer[][][] t = {{{123,null},null},null};
+ t = roundTrip(t, Integer[][][].class);
+ assertEquals(new Integer(123), t[0][0][0]);
+ assertNull(t[0][0][1]);
+ assertNull(t[0][1]);
+ assertNull(t[1]);
+ }
+
+ //====================================================================================================
+ // testBooleanObject
+ //====================================================================================================
+ @Test
+ public void testBooleanObject() throws Exception {
+ Boolean t = Boolean.TRUE;
+ t = roundTrip(t, Boolean.class);
+ assertTrue(t);
+ t = Boolean.FALSE;
+ t = roundTrip(t, Boolean.class);
+ assertFalse(t);
+ }
+
+ //====================================================================================================
+ // testBooleanObjectArray
+ //====================================================================================================
+ @Test
+ public void testBooleanObjectArray() throws Exception {
+ Boolean[] t = {true,false,null};
+ t = roundTrip(t, Boolean[].class);
+ assertTrue(t[0]);
+ assertFalse(t[1]);
+ assertNull(t[2]);
+ }
+
+ //====================================================================================================
+ // testBooleanObject2dArray
+ //====================================================================================================
+ @Test
+ public void testBooleanObject2dArray() throws Exception {
+ Boolean[][] t = {{true,false,null},null};
+ t = roundTrip(t, Boolean[][].class);
+ assertTrue(t[0][0]);
+ assertFalse(t[0][1]);
+ assertNull(t[0][2]);
+ assertNull(t[1]);
+ }
+
+ //====================================================================================================
+ // testCharacter
+ //====================================================================================================
+ @Test
+ public void testCharacter() throws Exception {
+ Character t = 'a';
+ t = roundTrip(t, Character.class);
+ assertEquals(new Character('a'), t);
+ }
+
+ //====================================================================================================
+ // testCharacterArray
+ //====================================================================================================
+ @Test
+ public void testCharacterArray() throws Exception {
+ Character[] t = {'a',null};
+ t = roundTrip(t, Character[].class);
+ assertEquals(new Character('a'), t[0]);
+ assertNull(t[1]);
+ }
+
+ //====================================================================================================
+ // testCharacter2dArray
+ //====================================================================================================
+ @Test
+ public void testCharacter2dArray() throws Exception {
+ Character[][] t = {{'a',null},null};
+ t = roundTrip(t, Character[][].class);
+ assertEquals(new Character('a'), t[0][0]);
+ assertNull(t[0][1]);
+ assertNull(t[1]);
+ }
+
+ //====================================================================================================
+ // testFloatObject
+ //====================================================================================================
+ @Test
+ public void testFloatObject() throws Exception {
+ Float t = 1f;
+ t = roundTrip(t, Float.class);
+ assertEquals(new Float(1f), t);
+ }
+
+ //====================================================================================================
+ // testFloatObjectArray
+ //====================================================================================================
+ @Test
+ public void testFloatObjectArray() throws Exception {
+ Float[] t = {1f, null};
+ t = roundTrip(t, Float[].class);
+ assertEquals(new Float(1f), t[0]);
+ assertNull(t[1]);
+ }
+
+ //====================================================================================================
+ // testFloatObject2dArray
+ //====================================================================================================
+ @Test
+ public void testFloatObject2dArray() throws Exception {
+ Float[][] t = {{1f,null},null};
+ t = roundTrip(t, Float[][].class);
+ assertEquals(new Float(1f), t[0][0]);
+ assertNull(t[0][1]);
+ assertNull(t[1]);
+ }
+
+ //====================================================================================================
+ // testDoubleObject
+ //====================================================================================================
+ @Test
+ public void testDoubleObject() throws Exception {
+ Double t = 1d;
+ t = roundTrip(t, Double.class);
+ assertEquals(new Double(1d), t);
+ }
+
+ //====================================================================================================
+ // testDoubleObjectArray
+ //====================================================================================================
+ @Test
+ public void testDoubleObjectArray() throws Exception {
+ Double[] t = {1d,null};
+ t = roundTrip(t, Double[].class);
+ assertEquals(new Double(1d), t[0]);
+ assertNull(t[1]);
+ }
+
+ //====================================================================================================
+ // testDoubleObject2dArray
+ //====================================================================================================
+ @Test
+ public void testDoubleObject2dArray() throws Exception {
+ Double[][] t = {{1d,null},null};
+ t = roundTrip(t, Double[][].class);
+ assertEquals(new Double(1d), t[0][0]);
+ assertNull(t[0][1]);
+ assertNull(t[1]);
+ }
+
+ //====================================================================================================
+ // testLongObject
+ //====================================================================================================
+ @Test
+ public void testLongObject() throws Exception {
+ Long t = 1l;
+ t = roundTrip(t, Long.class);
+ assertEquals(new Long(1l), t);
+ }
+
+ //====================================================================================================
+ // testLongObjectArray
+ //====================================================================================================
+ @Test
+ public void testLongObjectArray() throws Exception {
+ Long[] t = {1l, null};
+ t = roundTrip(t, Long[].class);
+ assertEquals(new Long(1l), t[0]);
+ assertNull(t[1]);
+ }
+
+ //====================================================================================================
+ // testLongObject2dArray
+ //====================================================================================================
+ @Test
+ public void testLongObject2dArray() throws Exception {
+ Long[][] t = {{1l,null},null};
+ t = roundTrip(t, Long[][].class);
+ assertEquals(new Long(1l), t[0][0]);
+ assertNull(t[0][1]);
+ assertNull(t[1]);
+ }
+
+ //====================================================================================================
+ // testShortObject
+ //====================================================================================================
+ @Test
+ public void testShortObject() throws Exception {
+ Short t = (short)1;
+ t = roundTrip(t, Short.class);
+ assertEquals(new Short((short)1), t);
+ }
+
+ //====================================================================================================
+ // testShortObjectArray
+ //====================================================================================================
+ @Test
+ public void testShortObjectArray() throws Exception {
+ Short[] t = {(short)1,null};
+ t = roundTrip(t, Short[].class);
+ assertEquals(new Short((short)1), t[0]);
+ assertNull(t[1]);
+ }
+
+ //====================================================================================================
+ // testShortObject2dArray
+ //====================================================================================================
+ @Test
+ public void testShortObject2dArray() throws Exception {
+ Short[][] t = {{(short)1,null},null};
+ t = roundTrip(t, Short[][].class);
+ assertEquals(new Short((short)1), t[0][0]);
+ assertNull(t[0][1]);
+ assertNull(t[1]);
+ }
+
+ //====================================================================================================
+ // testObjectMap
+ //====================================================================================================
+ @Test
+ public void testObjectMap() throws Exception {
+ ObjectMap t = new ObjectMap("{a:'b',c:123,d:false,e:null,f:[123,'abc',true,false,null]}");
+ t = roundTrip(t);
+ assertEquals("b", t.get("a"));
+ assertEquals(123, t.get("c"));
+ assertEquals(false, t.get("d"));
+ assertNull(t.get("e"));
+ List l = (List)t.get("f");
+ assertEquals(123, l.get(0));
+ assertEquals("abc", l.get(1));
+ assertEquals(true, l.get(2));
+ assertEquals(false, l.get(3));
+ assertNull(l.get(4));
+ }
+
+ //====================================================================================================
+ // testObjectList
+ //====================================================================================================
+ @Test
+ public void testObjectList() throws Exception {
+ ObjectList t = new ObjectList("['abc',123,true,false,null,{a:'b'}]");
+ t = roundTrip(t);
+ assertEquals("abc", t.get(0));
+ assertEquals(123, t.get(1));
+ assertEquals(true, t.get(2));
+ assertEquals(false, t.get(3));
+ assertNull(t.get(4));
+ Map m = (Map)t.get(5);
+ assertEquals("b", m.get("a"));
+ }
+
+ //====================================================================================================
+ // testTreeMap
+ //====================================================================================================
+ @Test
+ public void testTreeMap() throws Exception {
+ TreeMap t = new TreeMap();
+ t.put("a", 1);
+ t.put("b", 2);
+ t.put("c", 3);
+ t = roundTrip(t, TreeMap.class);
+ assertEquals(1, t.get("a"));
+ assertEquals(2, t.get("b"));
+ assertEquals(3, t.get("c"));
+
+ t = new TreeMap();
+ t.put("a", true);
+ t.put("b", false);
+ t.put("c", null);
+ t.put("d", "foo");
+ t.put("null", "baz");
+ t.put("a\"a", "a\"a");
+ t.put("b'b", "b'b");
+ t.put("\"cc\"", "\"cc\"");
+ t.put("'dd'", "'dd'");
+ t = roundTrip(t, TreeMap.class);
+ assertEquals(true, t.get("a"));
+ assertEquals(false, t.get("b"));
+ assertNull(t.get("c"));
+ assertEquals("foo", t.get("d"));
+ assertEquals("baz", t.get("null"));
+ assertEquals("a\"a", t.get("a\"a"));
+ assertEquals("b'b", t.get("b'b"));
+ assertEquals("\"cc\"", t.get("\"cc\""));
+ assertEquals("'dd'", t.get("'dd'"));
+ }
+
+ //====================================================================================================
+ // testLinkedHashMap
+ //====================================================================================================
+ @Test
+ public void testLinkedHashMap() throws Exception {
+ LinkedHashMap t = new LinkedHashMap();
+ t.put("a", true);
+ t.put("b", false);
+ t.put("c", null);
+ t.put("d", "foo");
+ t.put(null, "bar");
+ t.put("null", "null");
+ t.put("true", "true");
+ t.put("false", "false");
+ t.put("a\"a", "a\"a");
+ t.put("b'b", "b'b");
+ t.put("\"cc\"", "\"cc\"");
+ t.put("'dd'", "'dd'");
+ t.put("<ee>", "<ee>");
+ t.put("<ff/>", "<ff/>");
+ t.put("</gg>", "</gg>");
+ t.put("<>", "<>");
+ t.put("{}", "{}");
+ t.put("[]", "[]");
+ t.put("&", "&");
+ t.put("?", "?");
+ t.put("/", "/");
+ t.put("\b", "\b");
+ t.put("\\b", "\\b");
+ t.put("\n", "\n");
+ t.put("\\n", "\\n");
+ t.put("\t", "\t");
+ t.put("\\t", "\\t");
+ t.put("\f", "\f");
+ t.put("\\f", "\\f");
+ t.put("\\", "\\");
+ t.put("\\\\", "\\\\");
+ t.put("\u2345", "\u2345");
+ t.put("\\u2345", "\\u2345");
+ t.put("\\\u2345", "\\\u2345");
+ t.put("<>{}[]&?/\b\n\t\f\\\\\u2345", "<>{}[]&?/\b\n\t\f\\\\\u2345");
+ t = roundTrip(t, LinkedHashMap.class);
+ assertEquals(true, t.get("a"));
+ assertEquals(false, t.get("b"));
+ assertNull(t.get("c"));
+ assertEquals("foo", t.get("d"));
+ assertEquals("bar", t.get(null));
+ assertEquals("null", t.get("null"));
+ assertEquals("true", t.get("true"));
+ assertEquals("false", t.get("false"));
+ assertEquals("a\"a", t.get("a\"a"));
+ assertEquals("b'b", t.get("b'b"));
+ assertEquals("\"cc\"", t.get("\"cc\""));
+ assertEquals("'dd'", t.get("'dd'"));
+ assertEquals("<ee>", t.get("<ee>"));
+ assertEquals("<ff/>", t.get("<ff/>"));
+ assertEquals("</gg>", t.get("</gg>"));
+ assertEquals("<>", t.get("<>"));
+ assertEquals("{}", t.get("{}"));
+ assertEquals("[]", t.get("[]"));
+ assertEquals("&", t.get("&"));
+ assertEquals("?", t.get("?"));
+ assertEquals("/", t.get("/"));
+ assertEquals("\b", t.get("\b"));
+ assertEquals("\\b", t.get("\\b"));
+ assertEquals("\n", t.get("\n"));
+ assertEquals("\\n", t.get("\\n"));
+ assertEquals("\t", t.get("\t"));
+ assertEquals("\\t", t.get("\\t"));
+ assertEquals("\f", t.get("\f"));
+ assertEquals("\\f", t.get("\\f"));
+ assertEquals("\\", t.get("\\"));
+ assertEquals("\\\\", t.get("\\\\"));
+ assertEquals("\u2345", t.get("\u2345"));
+ assertEquals("\\u2345", t.get("\\u2345"));
+ assertEquals("\\\u2345", t.get("\\\u2345"));
+ assertEquals("<>{}[]&?/\b\n\t\f\\\\\u2345", t.get("<>{}[]&?/\b\n\t\f\\\\\u2345"));
+ }
+
+ //====================================================================================================
+ // testVector
+ //====================================================================================================
+ @Test
+ public void testVector() throws Exception {
+ Vector<Integer> t = new Vector<Integer>();
+ t.add(1);
+ t.add(2);
+ t.add(3);
+ t = roundTripCollection(t, Vector.class, Integer.class);
+ }
+
+ //====================================================================================================
+ // testNull
+ //====================================================================================================
+ @Test
+ public void testExtendedUnicode() throws Exception {
+ // Test 4-byte UTF-8 character
+ String t = "\U00024b62\U00024b62";
+ t = roundTrip(t);
+ assertEquals("\U00024b62\U00024b62", t);
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/RoundTripToObjectMapsTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/RoundTripToObjectMapsTest.java b/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/RoundTripToObjectMapsTest.java
new file mode 100755
index 0000000..9c7a276
--- /dev/null
+++ b/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/RoundTripToObjectMapsTest.java
@@ -0,0 +1,78 @@
+/***************************************************************************************************************************
+ * 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.juneau.a.rttests;
+
+import static org.junit.Assert.*;
+
+import java.util.*;
+
+import org.apache.juneau.*;
+import org.apache.juneau.parser.*;
+import org.apache.juneau.serializer.*;
+import org.junit.*;
+
+
+
+/**
+ * Tests designed to serialize and parse objects to make sure we end up
+ * with the same objects for all serializers and parsers.
+ */
+public class RoundTripToObjectMapsTest extends RoundTripTest {
+
+ public RoundTripToObjectMapsTest(String label, Serializer s, Parser p, int flags) throws Exception {
+ super(label, s, p, flags);
+ }
+
+ //====================================================================================================
+ // Class with X(ObjectMap) constructor and toObjectMap() method.
+ //====================================================================================================
+ @SuppressWarnings({ "serial", "unchecked" })
+ @Test
+ public void test() throws Exception {
+ A a = new A(new ObjectMap("{f1:'a',f2:2}"));
+ a = roundTrip(a, A.class);
+ assertEquals("a", a.f1);
+ assertEquals(2, a.f2);
+
+ A[] aa = new A[]{a};
+ aa = roundTrip(aa, A[].class);
+ assertEquals(1, aa.length);
+ assertEquals("a", aa[0].f1);
+ assertEquals(2, aa[0].f2);
+
+ List<A> a2 = new ArrayList<A>(){{add(new A(new ObjectMap("{f1:'a',f2:2}")));}};
+ a2 = roundTrip(a2, BeanContext.DEFAULT.getCollectionClassMeta(List.class, A.class));
+ assertEquals(1, a2.size());
+ assertEquals("a", a2.get(0).f1);
+ assertEquals(2, a2.get(0).f2);
+
+ Map<String,A> a3 = new LinkedHashMap<String,A>(){{put("a", new A(new ObjectMap("{f1:'a',f2:2}")));}};
+ a3 = roundTrip(a3, BeanContext.DEFAULT.getMapClassMeta(Map.class, String.class, A.class));
+ assertEquals(1, a3.size());
+ assertEquals("a", a3.get("a").f1);
+ assertEquals(2, a3.get("a").f2);
+ }
+
+ public static class A {
+ private String f1;
+ private int f2;
+ public A(ObjectMap m) {
+ this.f1 = m.getString("f1");
+ this.f2 = m.getInt("f2");
+ }
+ public ObjectMap toObjectMap() {
+ return new ObjectMap().append("f1",f1).append("f2",f2);
+ }
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/RoundTripTransformBeansTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/RoundTripTransformBeansTest.java b/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/RoundTripTransformBeansTest.java
new file mode 100755
index 0000000..0e882eb
--- /dev/null
+++ b/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/RoundTripTransformBeansTest.java
@@ -0,0 +1,382 @@
+/***************************************************************************************************************************
+ * 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.juneau.a.rttests;
+
+import static org.junit.Assert.*;
+
+import java.io.*;
+import java.util.*;
+
+import javax.xml.datatype.*;
+
+import org.apache.juneau.*;
+import org.apache.juneau.annotation.*;
+import org.apache.juneau.annotation.Transform;
+import org.apache.juneau.json.*;
+import org.apache.juneau.parser.*;
+import org.apache.juneau.serializer.*;
+import org.apache.juneau.transform.*;
+import org.apache.juneau.transforms.*;
+import org.junit.*;
+
+/**
+ * Tests designed to serialize and parse objects to make sure we end up
+ * with the same objects for all serializers and parsers.
+ */
+@SuppressWarnings({"unchecked","rawtypes","hiding","serial"})
+public class RoundTripTransformBeansTest extends RoundTripTest {
+
+ public RoundTripTransformBeansTest(String label, Serializer s, Parser p, int flags) throws Exception {
+ super(label, s, p, flags);
+ }
+
+ //====================================================================================================
+ // testTransformBeans1
+ //====================================================================================================
+ @Test
+ public void testTransformBeans1() throws Exception {
+ Class<?>[] f = {
+ ByteArrayBase64Transform.class,
+ CalendarTransform.ISO8601DTZ.class,
+ DateTransform.ISO8601DTZ.class
+ };
+ s.addTransforms(f);
+ if (p != null)
+ p.addTransforms(f);
+ A t = new A().init();
+ t = roundTrip(t, A.class);
+
+ // ByteArrayBase64Transform
+ assertEquals(3, t.fByte[3]);
+ assertNull(t.fnByte);
+ assertEquals(5, t.faByte[2][1]);
+ assertEquals(6, t.flByte.get(1)[2]);
+ assertNull(t.flByte.get(2));
+ assertEquals(6, t.fmByte.get("bar")[2]);
+ assertNull(t.fmByte.get("baz"));
+
+ // CalendarTransform
+ t.fCalendar.setTimeZone(TimeZone.getTimeZone("GMT"));
+ assertEquals(2001, t.fCalendar.get(Calendar.YEAR));
+ assertEquals(01, t.fCalendar.get(Calendar.MONTH));
+ assertEquals(02, t.fCalendar.get(Calendar.DATE));
+ assertEquals(03, t.fCalendar.get(Calendar.HOUR));
+ assertEquals(04, t.fCalendar.get(Calendar.MINUTE));
+ assertEquals(05, t.fCalendar.get(Calendar.SECOND));
+
+ t.faCalendar[0].setTimeZone(TimeZone.getTimeZone("GMT"));
+ assertEquals(2001, t.faCalendar[0].get(Calendar.YEAR));
+ assertEquals(01, t.faCalendar[0].get(Calendar.MONTH));
+ assertEquals(02, t.faCalendar[0].get(Calendar.DATE));
+ assertEquals(03, t.faCalendar[0].get(Calendar.HOUR));
+ assertEquals(04, t.faCalendar[0].get(Calendar.MINUTE));
+ assertEquals(05, t.faCalendar[0].get(Calendar.SECOND));
+ assertNull(t.fnCalendar);
+ assertNull(t.fn2Calendar);
+
+ // DateTransform
+ assertEquals(1000, t.fDate.getTime());
+ assertNull(t.fnDate);
+ assertEquals(3000, t.faDate[2].getTime());
+ assertEquals(4000, t.flDate.get(0).getTime());
+ assertNull(t.flDate.get(1));
+ assertEquals(5000, t.fmDate.get("foo").getTime());
+ assertNull(t.fmDate.get("bar"));
+ }
+
+ public static class A {
+
+ // Test ByteArrayBase64Transform
+ public byte[] fByte;
+ public byte[] fnByte;
+ public byte[][] faByte;
+ public List<byte[]> flByte;
+ public Map<String,byte[]> fmByte;
+
+ public GregorianCalendar fCalendar;
+ public GregorianCalendar fnCalendar;
+ public Calendar fn2Calendar;
+ public GregorianCalendar[] faCalendar;
+
+ public Date fDate;
+ public Date fnDate;
+ public Date[] faDate;
+ public List<Date> flDate;
+ public Map<String,Date> fmDate;
+
+ public A init() {
+ fByte = new byte[]{0,1,2,3};
+ fnByte = null;
+ faByte = new byte[][]{{0,1},{2,3},{4,5}};
+ flByte = new ArrayList<byte[]>() {{
+ add(new byte[]{1,2,3});
+ add(new byte[]{4,5,6});
+ add(null);
+ }};
+ fmByte = new LinkedHashMap<String,byte[]>() {{
+ put("foo", new byte[]{1,2,3});
+ put("bar", new byte[]{4,5,6});
+ put("baz", null);
+ }};
+
+ fCalendar = new GregorianCalendar() {{
+ set(2001, 01, 02, 03, 04, 05);
+ setTimeZone(TimeZone.getTimeZone("GMT"));
+ }};
+ fnCalendar = null;
+ fn2Calendar = null;
+ faCalendar = new GregorianCalendar[]{
+ new GregorianCalendar() {{
+ set(2001, 01, 02, 03, 04, 05);
+ setTimeZone(TimeZone.getTimeZone("GMT"));
+ }}
+ };
+
+ fDate = new Date(1000);
+ fnDate = null;
+ faDate = new Date[]{
+ new Date(1000), new Date(2000), new Date(3000)
+ };
+ flDate = new ArrayList<Date>() {{
+ add(new Date(4000));
+ add(null);
+ }};
+ fmDate = new LinkedHashMap<String,Date>() {{
+ put("foo", new Date(5000));
+ put("bar", null);
+ }};
+ return this;
+ }
+ }
+
+
+ //====================================================================================================
+ // testTransformBeans2
+ //====================================================================================================
+ @Test
+ public void testTransformBeans2() throws Exception {
+ Class<?>[] f = {
+ ByteArrayBase64Transform.class,
+ CalendarTransform.Medium.class,
+ DateTransform.RFC2822DT.class,
+ };
+ s.addTransforms(f);
+ if (p != null)
+ p.addTransforms(f);
+ A t = new A().init();
+ t = roundTrip(t, A.class);
+
+ // ByteArrayBase64Transform
+ assertEquals(3, t.fByte[3]);
+ assertNull(t.fnByte);
+ assertEquals(5, t.faByte[2][1]);
+ assertEquals(6, t.flByte.get(1)[2]);
+ assertNull(t.flByte.get(2));
+ assertEquals(6, t.fmByte.get("bar")[2]);
+ assertNull(t.fmByte.get("baz"));
+
+ // CalendarTransform
+ t.fCalendar.setTimeZone(TimeZone.getTimeZone("GMT"));
+ assertEquals(2001, t.fCalendar.get(Calendar.YEAR));
+ assertEquals(01, t.fCalendar.get(Calendar.MONTH));
+ // Note: We lose precision on the following because of the transform type.
+ //assertEquals(02, b.fCalendar.get(Calendar.DATE));
+ //assertEquals(03, b.fCalendar.get(Calendar.HOUR));
+ //assertEquals(04, b.fCalendar.get(Calendar.MINUTE));
+ //assertEquals(05, b.fCalendar.get(Calendar.SECOND));
+
+ t.faCalendar[0].setTimeZone(TimeZone.getTimeZone("GMT"));
+ assertEquals(2001, t.faCalendar[0].get(Calendar.YEAR));
+ assertEquals(01, t.faCalendar[0].get(Calendar.MONTH));
+ // Note: We lose precision on the following because of the transform type.
+ //assertEquals(02, b.faCalendar[0].get(Calendar.DATE));
+ //assertEquals(03, b.faCalendar[0].get(Calendar.HOUR));
+ //assertEquals(04, b.faCalendar[0].get(Calendar.MINUTE));
+ //assertEquals(05, b.faCalendar[0].get(Calendar.SECOND));
+ assertNull(t.fnCalendar);
+ assertNull(t.fn2Calendar);
+
+ // DateTransform
+ assertEquals(1000, t.fDate.getTime());
+ assertNull(t.fnDate);
+ assertEquals(3000, t.faDate[2].getTime());
+ assertEquals(4000, t.flDate.get(0).getTime());
+ assertNull(t.flDate.get(1));
+ assertEquals(5000, t.fmDate.get("foo").getTime());
+ assertNull(t.fmDate.get("bar"));
+ }
+
+ //====================================================================================================
+ // testTransform - Bean.transform annotation
+ //====================================================================================================
+ @Test
+ public void testTransform() throws Exception {
+ B t = new B();
+ t.f1 = "bar";
+ t = roundTrip(t, B.class);
+
+ assertEquals("bar", t.f1);
+ }
+
+ @Transform(BTransform.class)
+ public static class B {
+ public String f1;
+ }
+
+ public static class BTransform extends PojoTransform<B,String> {
+ @Override /* PojoTransform */
+ public String transform(B o) throws SerializeException {
+ return o.f1;
+ }
+ @Override /* PojoTransform */
+ public B normalize(String f, ClassMeta<?> hint) throws ParseException {
+ B b1 = new B();
+ b1.f1 = f;
+ return b1;
+ }
+ }
+
+ //====================================================================================================
+ // testXMLGregorianCalendar - Test XMLGregorianCalendarTransform class.
+ //====================================================================================================
+ @Test
+ public void testXMLGregorianCalendar() throws Exception {
+
+ if (isValidationOnly())
+ return;
+
+ GregorianCalendar gc = new GregorianCalendar();
+ XMLGregorianCalendar c = DatatypeFactory.newInstance().newXMLGregorianCalendar(gc);
+
+ Serializer s = getSerializer().clone().addTransforms(XMLGregorianCalendarTransform.class);
+ Parser p = getParser().clone().addTransforms(XMLGregorianCalendarTransform.class);
+
+ Object r = s.serialize(c);
+ XMLGregorianCalendar c2 = p.parse(r, XMLGregorianCalendar.class);
+ assertEquals(c, c2);
+ }
+
+ //====================================================================================================
+ // testSubTypeWithGenerics
+ //====================================================================================================
+ @Test
+ public void testSubTypeWithGenerics() throws Exception {
+ JsonSerializer s = JsonSerializer.DEFAULT;
+
+ C1 c1 = C3.create();
+ String r = s.serialize(c1);
+ assertEquals("{\"type\":\"C3\",\"f1\":{\"f2\":\"f2\",\"f3\":3}}", r);
+ }
+
+
+ @Bean(
+ subTypeProperty="type",
+ subTypes={
+ @BeanSubType(id="C3", type=C3.class)
+ }
+ )
+ public static interface C1<T> extends Serializable {
+ void setF1(T f1);
+ T getF1();
+ }
+
+ public abstract static class C2<T> implements C1<T> {
+ protected T f1;
+
+ @Override /* C1 */
+ public void setF1(T f1) {
+ this.f1 = f1;
+ }
+
+ @Override /* C1 */
+ public T getF1() {
+ return f1;
+ }
+ }
+
+ public static class C3<T> extends C2<T> {
+
+ public static C3 create() {
+ C3 c3 = new C3<Object>();
+ CDTO cdto = new CDTO();
+ cdto.f2 = "f2";
+ cdto.f3 = 3;
+ c3.f1 = cdto;
+ return c3;
+ }
+
+ @Override /* C1 */
+ public void setF1(T f1) {
+ this.f1 = f1;
+ }
+
+ @Override /* C1 */
+ public T getF1() {
+ return f1;
+ }
+ }
+
+ public static class CDTO {
+ public String f2;
+ public int f3;
+ }
+
+
+ //====================================================================================================
+ // Surrogate transforms
+ //====================================================================================================
+ @Test
+ public void testSurrogateTransform() throws Exception {
+ addTransforms(D2.class);
+
+ JsonSerializer s = new JsonSerializer.Simple().addTransforms(D2.class);
+ JsonParser p = new JsonParser().addTransforms(D2.class);
+ Object r;
+ D1 d1 = D1.create();
+
+ r = s.serialize(d1);
+ assertEquals("{f2:'f1'}", r);
+
+ d1 = p.parse(r, D1.class);
+ assertEquals("f1", d1.f1);
+
+ r = getSerializer().serialize(d1);
+ assertTrue(TestUtils.toString(r).contains("f2"));
+
+ d1 = roundTrip(d1, D1.class);
+ }
+
+ public static class D1 {
+ public String f1;
+
+ public static D1 create() {
+ D1 d1 = new D1();
+ d1.f1 = "f1";
+ return d1;
+ }
+ }
+
+ public static class D2 {
+ public String f2;
+ public D2(D1 d1) {
+ f2 = d1.f1;
+ }
+ public D2() {
+ }
+ public static D1 valueOf(D2 d2) {
+ D1 d1 = new D1();
+ d1.f1 = d2.f2;
+ return d1;
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/RoundTripTrimStringsTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/RoundTripTrimStringsTest.java b/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/RoundTripTrimStringsTest.java
new file mode 100755
index 0000000..83b9e67
--- /dev/null
+++ b/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/RoundTripTrimStringsTest.java
@@ -0,0 +1,98 @@
+/***************************************************************************************************************************
+ * 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.juneau.a.rttests;
+
+import static org.apache.juneau.TestUtils.*;
+
+import org.apache.juneau.*;
+import org.apache.juneau.parser.*;
+import org.apache.juneau.serializer.*;
+import org.junit.*;
+
+
+/**
+ * Tests for the {@link SerializerContext#SERIALIZER_trimStrings} and {@link ParserContext#PARSER_trimStrings}.
+ */
+public class RoundTripTrimStringsTest extends RoundTripTest {
+
+ public RoundTripTrimStringsTest(String label, Serializer s, Parser p, int flags) throws Exception {
+ super(label, s, p, flags);
+ }
+
+ //====================================================================================================
+ // test
+ //====================================================================================================
+ @SuppressWarnings("hiding")
+ @Test
+ public void test() throws Exception {
+ if (isValidationOnly())
+ return;
+ Serializer s = getSerializer();
+ Parser p = getParser();
+ Object in, a, e;
+
+ Serializer s2 = s.clone().setProperty(SerializerContext.SERIALIZER_trimStrings, true);
+ Parser p2 = p.clone().setProperty(ParserContext.PARSER_trimStrings, true);
+
+ in = " foo bar ";
+ e = "foo bar";
+ a = p.parse(s2.serialize(in), String.class);
+ assertEqualObjects(e, a);
+ a = p2.parse(s.serialize(in), String.class);
+ assertEqualObjects(e, a);
+
+ in = new ObjectMap("{' foo ': ' bar '}");
+ e = new ObjectMap("{foo:'bar'}");
+ a = p.parse(s2.serialize(in), ObjectMap.class);
+ assertEqualObjects(e, a);
+ a = p2.parse(s.serialize(in), ObjectMap.class);
+ assertEqualObjects(e, a);
+
+ in = new ObjectList("[' foo ', {' foo ': ' bar '}]");
+ e = new ObjectList("['foo',{foo:'bar'}]");
+ a = p.parse(s2.serialize(in), ObjectList.class);
+ assertEqualObjects(e, a);
+ a = p2.parse(s.serialize(in), ObjectList.class);
+ assertEqualObjects(e, a);
+
+ in = new A().init1();
+ e = new A().init2();
+ a = p.parse(s2.serialize(in), A.class);
+ assertEqualObjects(e, a);
+ a = p2.parse(s.serialize(in), A.class);
+ assertEqualObjects(e, a);
+ }
+
+ public static class A {
+ public String f1;
+ public String[] f2;
+ public ObjectList f3;
+ public ObjectMap f4;
+
+ public A init1() throws Exception {
+ f1 = " f1 ";
+ f2 = new String[]{" f2a ", " f2b "};
+ f3 = new ObjectList("[' f3a ',' f3b ']");
+ f4 = new ObjectMap("{' foo ':' bar '}");
+ return this;
+ }
+
+ public A init2() throws Exception {
+ f1 = "f1";
+ f2 = new String[]{"f2a", "f2b"};
+ f3 = new ObjectList("['f3a','f3b']");
+ f4 = new ObjectMap("{'foo':'bar'}");
+ return this;
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/csv/CT_Csv.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/csv/CT_Csv.java b/org.apache.juneau/src/test/java/org/apache/juneau/csv/CT_Csv.java
deleted file mode 100755
index 5ef83ee..0000000
--- a/org.apache.juneau/src/test/java/org/apache/juneau/csv/CT_Csv.java
+++ /dev/null
@@ -1,50 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.csv;
-
-import static org.junit.Assert.*;
-
-import java.util.*;
-
-import org.apache.juneau.serializer.*;
-import org.junit.*;
-
-public class CT_Csv {
-
- //====================================================================================================
- // testBasic
- //====================================================================================================
- @Test
- public void testBasic() throws Exception {
- List<A> l = new LinkedList<A>();
- l.add(new A("b1",1));
- l.add(new A("b2",2));
-
- WriterSerializer s = new CsvSerializer();
- String r;
-
- r = s.serialize(l);
-
- assertEquals("b,c\nb1,1\nb2,2\n", r);
- }
-
- public static class A {
- public String b;
- public int c;
-
- public A(String b, int c) {
- this.b = b;
- this.c = c;
- }
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/csv/CsvTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/csv/CsvTest.java b/org.apache.juneau/src/test/java/org/apache/juneau/csv/CsvTest.java
new file mode 100755
index 0000000..09453df
--- /dev/null
+++ b/org.apache.juneau/src/test/java/org/apache/juneau/csv/CsvTest.java
@@ -0,0 +1,50 @@
+/***************************************************************************************************************************
+ * 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.juneau.csv;
+
+import static org.junit.Assert.*;
+
+import java.util.*;
+
+import org.apache.juneau.serializer.*;
+import org.junit.*;
+
+public class CsvTest {
+
+ //====================================================================================================
+ // testBasic
+ //====================================================================================================
+ @Test
+ public void testBasic() throws Exception {
+ List<A> l = new LinkedList<A>();
+ l.add(new A("b1",1));
+ l.add(new A("b2",2));
+
+ WriterSerializer s = new CsvSerializer();
+ String r;
+
+ r = s.serialize(l);
+
+ assertEquals("b,c\nb1,1\nb2,2\n", r);
+ }
+
+ public static class A {
+ public String b;
+ public int c;
+
+ public A(String b, int c) {
+ this.b = b;
+ this.c = c;
+ }
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/dto/atom/AtomTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/dto/atom/AtomTest.java b/org.apache.juneau/src/test/java/org/apache/juneau/dto/atom/AtomTest.java
new file mode 100755
index 0000000..5e78d27
--- /dev/null
+++ b/org.apache.juneau/src/test/java/org/apache/juneau/dto/atom/AtomTest.java
@@ -0,0 +1,102 @@
+/***************************************************************************************************************************
+ * 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.juneau.dto.atom;
+
+import static javax.xml.bind.DatatypeConverter.*;
+import static org.apache.juneau.BeanContext.*;
+import static org.apache.juneau.TestUtils.*;
+import static org.apache.juneau.xml.XmlSerializerContext.*;
+import static org.junit.Assert.*;
+
+import java.net.*;
+
+import org.apache.juneau.xml.*;
+import org.junit.*;
+
+
+public class AtomTest {
+
+ @Test
+ public void testBasic() throws Exception {
+ XmlSerializer s;
+ XmlParser p = XmlParser.DEFAULT;
+ String expected, r;
+ Feed f2;
+
+ Feed f = new Feed()
+ .setTitle(new Text("text", "dive into mark"))
+ .setSubTitle(new Text("html", "A <em>lot</em> of effort went into making this effortless"))
+ .setUpdated(parseDateTime("2005-07-31T12:29:29Z"))
+ .setId(new Id("tag:example.org,2003:3"))
+ .addLinks(
+ new Link("alternate", "text/html", "http://example.org/").setHreflang("en"),
+ new Link("self", "application/atom+xml", "http://example.org/feed.atom")
+ )
+ .setRights(new Text("Copyright (c) 2003, Mark Pilgrim"))
+ .setGenerator(new Generator("Example Toolkit").setUri(new URI("http://www.example.com/")).setVersion("1.0"))
+ .addEntries(
+ new Entry()
+ .setTitle(new Text("Atom draft-07 snapshot"))
+ .addLinks(
+ new Link("alternate", "text/html", "http://example.org/2005/04/02/atom"),
+ new Link("enclosure", "audio/mpeg", "http://example.org/audio/ph34r_my_podcast.mp3").setLength(1337)
+ )
+ .setId(new Id("tag:example.org,2003:3.2397"))
+ .setUpdated(parseDateTime("2005-07-31T12:29:29Z"))
+ .setPublished(parseDateTime("2003-12-13T08:29:29-04:00"))
+ .addAuthors(new Person("Mark Pilgrim").setUri(new URI("http://example.org/")).setEmail("f8dy@example.com"))
+ .addContributors(
+ new Person("Sam Ruby"),
+ new Person("Joe Gregorio")
+ )
+ .setContent(
+ new Content()
+ .setLang("en")
+ .setBase(new URI("http://diveintomark.org/"))
+ .setType("xhtml")
+ .setText("<div xmlns=\"http://www.w3.org/1999/xhtml\"><p><i>[Update: The Atom draft is finished.]</i></p></div>")
+ )
+ )
+ ;
+
+ //--------------------------------------------------------------------------------
+ // Test without namespaces
+ //--------------------------------------------------------------------------------
+ s = new XmlSerializer.SqReadable().setProperty(XML_enableNamespaces, false).setProperty(BEAN_sortProperties, true);
+ expected = readFile(getClass().getResource("/dto/atom/test1.xml").getPath());
+ r = s.serialize(f);
+ assertEquals(expected, r);
+ f2 = p.parse(r, Feed.class);
+ assertEqualObjects(f, f2);
+
+ //--------------------------------------------------------------------------------
+ // Test with namespaces
+ //--------------------------------------------------------------------------------
+ s = new XmlSerializer.SqReadable().setProperty(BEAN_sortProperties, true);
+ expected = readFile(getClass().getResource("/dto/atom/test2.xml").getPath());
+ r = s.serialize(f);
+ assertEquals(expected, r);
+ f2 = p.parse(r, Feed.class);
+ assertEqualObjects(f, f2);
+
+ //--------------------------------------------------------------------------------
+ // Test with namespaces but with atom as the default namespace
+ //--------------------------------------------------------------------------------
+ s = new XmlSerializer.SqReadable().setProperty(XML_defaultNamespaceUri, "atom").setProperty(BEAN_sortProperties, true);
+ expected = readFile(getClass().getResource("/dto/atom/test3.xml").getPath());
+ r = s.serialize(f);
+ assertEquals(expected, r);
+ f2 = p.parse(r, Feed.class);
+ assertEqualObjects(f, f2);
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/dto/atom/CT_Atom.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/dto/atom/CT_Atom.java b/org.apache.juneau/src/test/java/org/apache/juneau/dto/atom/CT_Atom.java
deleted file mode 100755
index 09dc6f6..0000000
--- a/org.apache.juneau/src/test/java/org/apache/juneau/dto/atom/CT_Atom.java
+++ /dev/null
@@ -1,102 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.dto.atom;
-
-import static javax.xml.bind.DatatypeConverter.*;
-import static org.apache.juneau.BeanContext.*;
-import static org.apache.juneau.TestUtils.*;
-import static org.apache.juneau.xml.XmlSerializerContext.*;
-import static org.junit.Assert.*;
-
-import java.net.*;
-
-import org.apache.juneau.xml.*;
-import org.junit.*;
-
-
-public class CT_Atom {
-
- @Test
- public void testBasic() throws Exception {
- XmlSerializer s;
- XmlParser p = XmlParser.DEFAULT;
- String expected, r;
- Feed f2;
-
- Feed f = new Feed()
- .setTitle(new Text("text", "dive into mark"))
- .setSubTitle(new Text("html", "A <em>lot</em> of effort went into making this effortless"))
- .setUpdated(parseDateTime("2005-07-31T12:29:29Z"))
- .setId(new Id("tag:example.org,2003:3"))
- .addLinks(
- new Link("alternate", "text/html", "http://example.org/").setHreflang("en"),
- new Link("self", "application/atom+xml", "http://example.org/feed.atom")
- )
- .setRights(new Text("Copyright (c) 2003, Mark Pilgrim"))
- .setGenerator(new Generator("Example Toolkit").setUri(new URI("http://www.example.com/")).setVersion("1.0"))
- .addEntries(
- new Entry()
- .setTitle(new Text("Atom draft-07 snapshot"))
- .addLinks(
- new Link("alternate", "text/html", "http://example.org/2005/04/02/atom"),
- new Link("enclosure", "audio/mpeg", "http://example.org/audio/ph34r_my_podcast.mp3").setLength(1337)
- )
- .setId(new Id("tag:example.org,2003:3.2397"))
- .setUpdated(parseDateTime("2005-07-31T12:29:29Z"))
- .setPublished(parseDateTime("2003-12-13T08:29:29-04:00"))
- .addAuthors(new Person("Mark Pilgrim").setUri(new URI("http://example.org/")).setEmail("f8dy@example.com"))
- .addContributors(
- new Person("Sam Ruby"),
- new Person("Joe Gregorio")
- )
- .setContent(
- new Content()
- .setLang("en")
- .setBase(new URI("http://diveintomark.org/"))
- .setType("xhtml")
- .setText("<div xmlns=\"http://www.w3.org/1999/xhtml\"><p><i>[Update: The Atom draft is finished.]</i></p></div>")
- )
- )
- ;
-
- //--------------------------------------------------------------------------------
- // Test without namespaces
- //--------------------------------------------------------------------------------
- s = new XmlSerializer.SqReadable().setProperty(XML_enableNamespaces, false).setProperty(BEAN_sortProperties, true);
- expected = readFile(getClass().getResource("/dto/atom/test1.xml").getPath());
- r = s.serialize(f);
- assertEquals(expected, r);
- f2 = p.parse(r, Feed.class);
- assertEqualObjects(f, f2);
-
- //--------------------------------------------------------------------------------
- // Test with namespaces
- //--------------------------------------------------------------------------------
- s = new XmlSerializer.SqReadable().setProperty(BEAN_sortProperties, true);
- expected = readFile(getClass().getResource("/dto/atom/test2.xml").getPath());
- r = s.serialize(f);
- assertEquals(expected, r);
- f2 = p.parse(r, Feed.class);
- assertEqualObjects(f, f2);
-
- //--------------------------------------------------------------------------------
- // Test with namespaces but with atom as the default namespace
- //--------------------------------------------------------------------------------
- s = new XmlSerializer.SqReadable().setProperty(XML_defaultNamespaceUri, "atom").setProperty(BEAN_sortProperties, true);
- expected = readFile(getClass().getResource("/dto/atom/test3.xml").getPath());
- r = s.serialize(f);
- assertEquals(expected, r);
- f2 = p.parse(r, Feed.class);
- assertEqualObjects(f, f2);
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/dto/cognos/CT_CognosXml.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/dto/cognos/CT_CognosXml.java b/org.apache.juneau/src/test/java/org/apache/juneau/dto/cognos/CT_CognosXml.java
deleted file mode 100755
index 9613ed5..0000000
--- a/org.apache.juneau/src/test/java/org/apache/juneau/dto/cognos/CT_CognosXml.java
+++ /dev/null
@@ -1,106 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.dto.cognos;
-
-import static org.apache.juneau.TestUtils.*;
-import static org.apache.juneau.serializer.SerializerContext.*;
-import static org.apache.juneau.xml.XmlSerializerContext.*;
-import static org.junit.Assert.*;
-
-import java.util.*;
-
-import org.apache.juneau.*;
-import org.apache.juneau.xml.*;
-import org.junit.*;
-
-public class CT_CognosXml {
-
- //====================================================================================================
- // test
- //====================================================================================================
- @Test
- public void test() throws Exception {
- String expected = ""
- + "<dataset xmlns='http://developer.cognos.com/schemas/xmldata/1/' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'>\n"
- + " <metadata>\n"
- + " <item name='asOfDate' type='xs:string' length='12'/>\n"
- + " <item name='rateOfReturn' type='xs:double'/>\n"
- + " <item name='famAcctIndex' type='xs:string' length='3'/>\n"
- + " <item name='rowID' type='xs:string' length='1'/>\n"
- + " <item name='brM' type='xs:string' length='1'/>\n"
- + " <item name='productLineCode' type='xs:int'/>\n"
- + " </metadata>\n"
- + " <data>\n"
- + " <row>\n"
- + " <value>Apr 26, 2002</value>\n"
- + " <value>0.21006642</value>\n"
- + " <value>JA1</value>\n"
- + " <value>F</value>\n"
- + " <value>B</value>\n"
- + " <value>1</value>\n"
- + " </row>\n"
- + " <row>\n"
- + " <value>Apr 27, 2002</value>\n"
- + " <value>0.1111111</value>\n"
- + " <value>BBB</value>\n"
- + " <value>G</value>\n"
- + " <value>B</value>\n"
- + " <value>2</value>\n"
- + " </row>\n"
- + " </data>\n"
- + "</dataset>\n";
-
- List<Object> rows = new LinkedList<Object>();
- rows.add(new ObjectMap("{asOfDate:'Apr 26, 2002',rateOfReturn:0.210066429,famAcctIndex:'JA1',rowID:'F',brM:'B',productLineCode:1}"));
- rows.add(new Item("Apr 27, 2002", 0.1111111, "BBB", "G", "B", 2));
-
- Column[] c = {
- new Column("asOfDate", "xs:string", 12),
- new Column("rateOfReturn", "xs:double"),
- new Column("famAcctIndex", "xs:string", 3),
- new Column("rowID", "xs:string", 1),
- new Column("brM", "xs:string", 1),
- new Column("productLineCode", "xs:int")
- };
-
- XmlSerializer s = new XmlSerializer().setProperty(SERIALIZER_useIndentation, true).setProperty(SERIALIZER_quoteChar, '\'').setProperty(XML_defaultNamespaceUri, "cognos");
-
- DataSet ds = new DataSet(c, rows, BeanContext.DEFAULT);
-
- String out = s.serialize(ds);
-
- assertEquals(expected, out);
-
- // Make sure we can parse it back into a POJO.
- DataSet ds2 = XmlParser.DEFAULT.parse(out, DataSet.class);
- assertEqualObjects(ds, ds2);
- }
-
- public static class Item {
- public String asOfDate;
- public double rateOfReturn;
- public String famAcctIndex;
- public String rowID;
- public String brM;
- public int productLineCode;
-
- public Item(String asOfDate, double rateOfReturn, String famAcctIndex, String rowID, String brM, int productLineCode) {
- this.asOfDate = asOfDate;
- this.rateOfReturn = rateOfReturn;
- this.famAcctIndex = famAcctIndex;
- this.rowID = rowID;
- this.brM = brM;
- this.productLineCode = productLineCode;
- }
- }
-}
\ No newline at end of file
[17/44] incubator-juneau git commit: Rename CT_* testcases.
Posted by ja...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/ini/ConfigFileTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/ini/ConfigFileTest.java b/org.apache.juneau/src/test/java/org/apache/juneau/ini/ConfigFileTest.java
new file mode 100755
index 0000000..0cc2f8b
--- /dev/null
+++ b/org.apache.juneau/src/test/java/org/apache/juneau/ini/ConfigFileTest.java
@@ -0,0 +1,2154 @@
+/***************************************************************************************************************************
+ * 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.juneau.ini;
+
+import static org.apache.juneau.TestUtils.*;
+import static org.junit.Assert.*;
+
+import java.io.*;
+import java.net.*;
+import java.util.*;
+import java.util.concurrent.*;
+
+import org.apache.juneau.*;
+import org.apache.juneau.annotation.*;
+import org.apache.juneau.internal.*;
+import org.apache.juneau.json.*;
+import org.apache.juneau.parser.*;
+import org.apache.juneau.svl.*;
+import org.apache.juneau.utils.*;
+import org.junit.*;
+
+public class ConfigFileTest {
+
+ private File getFreshFile() {
+ String tempDir = System.getProperty("java.io.tmpdir");
+ File f = new File(tempDir, "Test.cfg");
+ if (f.exists())
+ f.delete();
+ f.deleteOnExit();
+ return f;
+ }
+
+ //====================================================================================================
+ // testCommentsOnly
+ //====================================================================================================
+ @Test
+ public void testCommentsOnly() throws Exception {
+
+ File f = getFreshFile();
+
+ ConfigFile cf = ConfigMgr.DEFAULT.create(f)
+ .addLines(null, "# c1", "\t# c2", " c3 ");
+ ConfigFile cfw = cf.getResolving(VarResolver.DEFAULT);
+
+ String expected = "# c1|\t# c2| c3 |";
+ assertTextEquals(expected, cf);
+ assertTextEquals(expected, cfw);
+
+ cf.save();
+ cf = ConfigMgr.DEFAULT.create(f);
+ expected = "# c1|\t# c2| c3 |";
+ assertTextEquals(expected, cf);
+ assertTextEquals(expected, cfw);
+
+ }
+
+ //====================================================================================================
+ // testBasics
+ //====================================================================================================
+ @Test
+ public void testBasics() throws Exception {
+
+ File f = getFreshFile();
+
+ ConfigFile cf = ConfigMgr.DEFAULT.create(f)
+ .addLines(null, "# c1", "\t# c2", " c3 ", "x1=1", "x2=true", "x3=null")
+ .addLines("s1", "#c4", "k1=1", "#c5 foo=bar", "k2 = true", "k3 = \tnull");
+ ConfigFile cfw = cf.getResolving().getResolving();
+
+ String expected = "# c1|\t# c2| c3 |x1 = 1|x2 = true|x3 = null|[s1]|#c4|k1 = 1|#c5 foo=bar|k2 = true|k3 = null|";
+ assertTextEquals(expected, cf);
+ assertTextEquals(expected, cfw);
+
+ cf.save();
+ cf = ConfigMgr.DEFAULT.create(f);
+ cfw = cf.getResolving(VarResolver.DEFAULT);
+ assertEquals(1, cf.getInt("x1"));
+ assertEquals(true, cf.getBoolean("x2"));
+ assertEquals("null", cf.getString("x3"));
+ assertEquals(1, cf.getInt("s1/k1"));
+ assertEquals(true, cf.getBoolean("s1/k2"));
+ assertEquals("null", cf.getString("s1/k3"));
+
+ assertEquals(-1, cf.getInt("X1/k1", -1));
+ assertEquals(true, cf.getBoolean("X1/k2", true));
+ assertEquals("null", cf.getString("X1/k3", "null"));
+
+ assertEquals(1, cfw.getInt("x1"));
+ assertEquals(true, cfw.getBoolean("x2"));
+ assertEquals("null", cfw.getString("x3"));
+ assertEquals(1, cfw.getInt("s1/k1"));
+ assertEquals(true, cfw.getBoolean("s1/k2"));
+ assertEquals("null", cfw.getString("s1/k3"));
+
+ assertEquals(-1, cfw.getInt("X1/k1", -1));
+ assertEquals(true, cfw.getBoolean("X1/k2", true));
+ assertEquals("null", cfw.getString("X1/k3", "null"));
+
+ cf.put("x1", 2);
+ cf.put("x2", false);
+ cf.put("x3", "foo");
+ cf.put("s1/k1", 2);
+ cf.put("s1/k2", false);
+ cf.put("s1/k3", "bar");
+
+ expected = "# c1|\t# c2| c3 |x1 = 2|x2 = false|x3 = foo|[s1]|#c4|k1 = 2|#c5 foo=bar|k2 = false|k3 = bar|";
+ assertTextEquals(expected, cf);
+ assertTextEquals(expected, cfw);
+
+ cfw.put("x1", 3);
+ cfw.put("x2", true);
+ cfw.put("x3", "bar");
+ cfw.put("s1/k1", 4);
+ cfw.put("s1/k2", true);
+ cfw.put("s1/k3", "baz");
+
+ expected = "# c1|\t# c2| c3 |x1 = 3|x2 = true|x3 = bar|[s1]|#c4|k1 = 4|#c5 foo=bar|k2 = true|k3 = baz|";
+ assertTextEquals(expected, cf);
+ assertTextEquals(expected, cfw);
+
+ // Null strings.
+ cf.put("x1", (String)null);
+ expected = "# c1|\t# c2| c3 |x1 = |x2 = true|x3 = bar|[s1]|#c4|k1 = 4|#c5 foo=bar|k2 = true|k3 = baz|";
+ assertTextEquals(expected, cf);
+ }
+
+ @Test
+ public void testSerialization() throws Exception {
+
+ ConfigFile cf = ConfigMgr.DEFAULT.create();
+ cf.put("x1", 1);
+
+ String expected = "{'default':{x1:'1'}}";
+ assertObjectEquals(expected, cf);
+ cf = cf.getResolving(VarResolver.DEFAULT);
+ assertObjectEquals(expected, cf);
+ }
+
+ //====================================================================================================
+ // testHeaderComments
+ //====================================================================================================
+ @Test
+ public void testHeaderComments() throws Exception {
+ ConfigFile[] cff = {
+ ConfigMgr.DEFAULT.create(getFreshFile()).addLines(null, "x").addLines("s1", "#c3", "#c4").addHeaderComments("s1", "#c1", "#c2"),
+ ConfigMgr.DEFAULT.create(getFreshFile()).addLines(null, "x").addLines("s1", "#c3", "#c4").addHeaderComments("s1", "#c1", "#c2").getResolving()
+ };
+
+ for (ConfigFile cf : cff) {
+
+ String expected = "x|#c1|#c2|[s1]|#c3|#c4|";
+ assertTextEquals(expected, cf);
+
+ cf.save();
+ cf.load();
+
+ cf.clearHeaderComments("s1");
+ expected = "x|[s1]|#c3|#c4|";
+ assertTextEquals(expected, cf);
+
+ cf.clearHeaderComments("x1");
+
+ cf.addHeaderComments("s1", "#c5", "c6");
+ expected = "x|#c5|#c6|[s1]|#c3|#c4|";
+ assertTextEquals(expected, cf);
+ }
+ }
+
+ //====================================================================================================
+ // testRemoveEntries
+ //====================================================================================================
+ @Test
+ public void testRemoveEntries() throws Exception {
+
+ File f = getFreshFile();
+
+ ConfigFile cf = ConfigMgr.DEFAULT.create(f)
+ .addLines(null, "x1=1")
+ .addLines("s1", "x2=2");
+ ConfigFile cfw = cf.getResolving(VarResolver.DEFAULT);
+
+ String expected = "x1 = 1|[s1]|x2 = 2|";
+ assertTextEquals(expected, cf);
+ assertTextEquals(expected, cfw);
+
+ cf.save();
+ cf.load();
+
+ cf.removeString("x1");
+ expected = "[s1]|x2 = 2|";
+ assertTextEquals(expected, cf);
+ assertTextEquals(expected, cfw);
+
+ cfw.save();
+ cfw.load();
+
+ cf.removeString("s1/x2");
+ expected = "[s1]|";
+ assertTextEquals(expected, cf);
+ assertTextEquals(expected, cfw);
+
+ cf.removeSection("s1");
+ assertEquals("", cf.toString());
+ assertEquals("", cfw.toString());
+ }
+
+ //====================================================================================================
+ // testPut
+ //====================================================================================================
+ @Test
+ public void testPut() throws Exception {
+
+ ConfigFile cf = ConfigMgr.DEFAULT.create();
+ ConfigFile cfw = cf.getResolving(VarResolver.DEFAULT);
+
+ cf.addSection(null);
+ cf.put("x1", "1");
+ cf.addHeaderComments(null, "#h1");
+ cf.addLines(null, "#c1", "c2");
+ cf.addSection("s1");
+ cf.put("s1/x2", "1");
+ cf.addHeaderComments("s1","#h2");
+ cf.addLines("s1", "#c3", "c4");
+
+ String expected = "#h1|x1 = 1|#c1|c2|#h2|[s1]|x2 = 1|#c3|c4|";
+ assertTextEquals(expected, cf);
+ assertTextEquals(expected, cfw);
+
+ cfw.addSection(null);
+ cfw.put("x2", "2");
+ cfw.addHeaderComments(null, "#h2");
+ cfw.addLines(null, "#c2", "c3");
+ cfw.addSection("s2");
+ cfw.put("s2/x3", "2");
+ cfw.addHeaderComments("s2","#h3");
+ cfw.addLines("s2", "#c4", "c5");
+
+ expected = "#h1|#h2|x1 = 1|#c1|c2|x2 = 2|#c2|c3|#h2|[s1]|x2 = 1|#c3|c4|#h3|[s2]|x3 = 2|#c4|c5|";
+ assertTextEquals(expected, cf);
+ assertTextEquals(expected, cfw);
+ }
+
+ //====================================================================================================
+ // testExampleInConfigFile - Example in ConfigFile
+ //====================================================================================================
+ @Test
+ public void testExampleInConfigFile() throws Exception {
+
+ ConfigFile cf = ConfigMgr.DEFAULT.create()
+ .addLines(null, "# Default section", "key1 = 1", "key2 = true", "key3 = 1,2,3", "key4 = 'http://foo'", "")
+ .addHeaderComments("section1", "# Section 1")
+ .addLines("section1", "key1 = 2", "key2 = false", "key3 = 4,5,6", "key4 = 'http://bar'");
+ ConfigFile cfw = cf.getResolving(VarResolver.DEFAULT);
+
+ assertEquals(1, cf.getInt("key1"));
+ assertEquals(true, cf.getBoolean("key2"));
+ assertEquals(3, cf.getObject(int[].class, "key3")[2]);
+ assertEquals(6, cf.getObject(int[].class, "xkey3", new int[]{4,5,6})[2]);
+ assertEquals(6, cf.getObject(int[].class, "X/key3", new int[]{4,5,6})[2]);
+ assertEquals(new URL("http://foo").toString(), cf.getObject(URL.class, "key4").toString());
+
+ assertEquals(1, cfw.getInt("key1"));
+ assertEquals(true, cfw.getBoolean("key2"));
+ assertEquals(3, cfw.getObject(int[].class, "key3")[2]);
+ assertEquals(6, cfw.getObject(int[].class, "xkey3", new int[]{4,5,6})[2]);
+ assertEquals(6, cfw.getObject(int[].class, "X/key3", new int[]{4,5,6})[2]);
+ assertEquals(new URL("http://foo").toString(), cfw.getObject(URL.class, "key4").toString());
+
+ assertEquals(2, cf.getInt("section1/key1"));
+ assertEquals(false, cf.getBoolean("section1/key2"));
+ assertEquals(6, cf.getObject(int[].class, "section1/key3")[2]);
+ assertEquals(new URL("http://bar").toString(), cf.getObject(URL.class, "section1/key4").toString());
+
+ assertEquals(2, cfw.getInt("section1/key1"));
+ assertEquals(false, cfw.getBoolean("section1/key2"));
+ assertEquals(6, cfw.getObject(int[].class, "section1/key3")[2]);
+ assertEquals(new URL("http://bar").toString(), cfw.getObject(URL.class, "section1/key4").toString());
+
+ cf = ConfigMgr.DEFAULT.create(getFreshFile())
+ .addLines(null, "# Default section")
+ .addHeaderComments("section1", "# Section 1");
+ cfw = cf.getResolving(VarResolver.DEFAULT);
+
+ cf.put("key1", 1);
+ cf.put("key2", true);
+ cf.put("key3", new int[]{1,2,3});
+ cf.put("key4", new URL("http://foo"));
+ cf.put("section1/key1", 2);
+ cf.put("section1/key2", false);
+ cf.put("section1/key3", new int[]{4,5,6});
+ cf.put("section1/key4", new URL("http://bar"));
+
+ cf.save();
+ cf.load();
+
+ assertEquals(1, cf.getInt("key1"));
+ assertEquals(true, cf.getBoolean("key2"));
+ assertEquals(3, cf.getObject(int[].class, "key3")[2]);
+ assertEquals(new URL("http://foo").toString(), cf.getObject(URL.class, "key4").toString());
+
+ assertEquals(1, cfw.getInt("key1"));
+ assertEquals(true, cfw.getBoolean("key2"));
+ assertEquals(3, cfw.getObject(int[].class, "key3")[2]);
+ assertEquals(new URL("http://foo").toString(), cfw.getObject(URL.class, "key4").toString());
+
+ assertEquals(2, cf.getInt("section1/key1"));
+ assertEquals(false, cf.getBoolean("section1/key2"));
+ assertEquals(6, cf.getObject(int[].class, "section1/key3")[2]);
+ assertEquals(new URL("http://bar").toString(), cf.getObject(URL.class, "section1/key4").toString());
+
+ assertEquals(2, cfw.getInt("section1/key1"));
+ assertEquals(false, cfw.getBoolean("section1/key2"));
+ assertEquals(6, cfw.getObject(int[].class, "section1/key3")[2]);
+ assertEquals(new URL("http://bar").toString(), cfw.getObject(URL.class, "section1/key4").toString());
+
+ cfw.put("key1", 2);
+ cfw.put("key2", false);
+ cfw.put("key3", new int[]{4,5,6});
+ cfw.put("key4", new URL("http://bar"));
+ cfw.put("section1/key1", 3);
+ cfw.put("section1/key2", true);
+ cfw.put("section1/key3", new int[]{7,8,9});
+ cfw.put("section1/key4", new URL("http://baz"));
+
+ cfw.save();
+ cfw.load();
+
+ assertEquals(2, cf.getInt("key1"));
+ assertEquals(false, cf.getBoolean("key2"));
+ assertEquals(6, cf.getObject(int[].class, "key3")[2]);
+ assertEquals(new URL("http://bar").toString(), cf.getObject(URL.class, "key4").toString());
+
+ assertEquals(2, cfw.getInt("key1"));
+ assertEquals(false, cfw.getBoolean("key2"));
+ assertEquals(6, cfw.getObject(int[].class, "key3")[2]);
+ assertEquals(new URL("http://bar").toString(), cfw.getObject(URL.class, "key4").toString());
+
+ assertEquals(3, cf.getInt("section1/key1"));
+ assertEquals(true, cf.getBoolean("section1/key2"));
+ assertEquals(9, cf.getObject(int[].class, "section1/key3")[2]);
+ assertEquals(new URL("http://baz").toString(), cf.getObject(URL.class, "section1/key4").toString());
+
+ assertEquals(3, cfw.getInt("section1/key1"));
+ assertEquals(true, cfw.getBoolean("section1/key2"));
+ assertEquals(9, cfw.getObject(int[].class, "section1/key3")[2]);
+ assertEquals(new URL("http://baz").toString(), cfw.getObject(URL.class, "section1/key4").toString());
+ }
+
+ //====================================================================================================
+ // testEnum
+ //====================================================================================================
+ @Test
+ public void testEnum() throws Exception {
+ ConfigFile cf = ConfigMgr.DEFAULT.create(getFreshFile())
+ .addLines(null, "key1 = 'MINUTES'");
+ ConfigFile cfw = cf.getResolving(VarResolver.DEFAULT);
+
+ assertEquals(TimeUnit.MINUTES, cf.getObject(TimeUnit.class, "key1"));
+ assertEquals(TimeUnit.MINUTES, cfw.getObject(TimeUnit.class, "key1"));
+
+ cf.save();
+ cf.load();
+
+ assertEquals(TimeUnit.MINUTES, cf.getObject(TimeUnit.class, "key1"));
+ assertEquals(TimeUnit.MINUTES, cfw.getObject(TimeUnit.class, "key1"));
+ }
+
+ //====================================================================================================
+ // testBatchFileGeneration
+ //====================================================================================================
+ @Test
+ public void testBatchFileGeneration() throws Exception {
+ ConfigFile cf = ConfigMgr.DEFAULT.create()
+ .addLines(null, "# c1", "\t# c2", " c3 ", "", " ", "x1=1", "x2=true", "x3=null")
+ .addHeaderComments(null, "header null", "", null)
+ .addLines("s1", "#c4", "k1=1", "#c5 foo=bar", "k2 = true", "k3 = \tnull")
+ .addHeaderComments("s1", "header s1", "", null);
+ ConfigFile cfw = cf.getResolving(VarResolver.DEFAULT);
+
+ String expected = "rem header null|||rem c1|rem c2|rem c3|||set x1 = 1|set x2 = true|set x3 = null|rem header s1|||rem c4|set s1_k1 = 1|rem c5 foo=bar|set s1_k2 = true|set s1_k3 = null|";
+
+ StringWriter sw = new StringWriter();
+ cf.serializeTo(new PrintWriter(sw), ConfigFileFormat.BATCH);
+ assertTextEquals(expected, sw);
+
+ sw = new StringWriter();
+ cfw.serializeTo(new PrintWriter(sw), ConfigFileFormat.BATCH);
+ assertTextEquals(expected, sw);
+ }
+
+ //====================================================================================================
+ // testShellScriptGeneration
+ //====================================================================================================
+ @Test
+ public void testShellScriptGeneration() throws Exception {
+ ConfigFile cf = ConfigMgr.DEFAULT.create()
+ .addLines(null, "# c1", "\t# c2", " c3 ", "", " ", "x1=1", "x2=true", "x3=null")
+ .addHeaderComments(null, "header null", "", null)
+ .addLines("s1", "#c4", "k1=1", "#c5 foo=bar", "k2 = true", "k3 = \tnull")
+ .addHeaderComments("s1", "header s1", "", null);
+ ConfigFile cfw = cf.getResolving(VarResolver.DEFAULT);
+
+ String expected = "# header null|||# c1|# c2|# c3|||export x1=\"1\"|export x2=\"true\"|export x3=\"null\"|# header s1|||# c4|export s1_k1=\"1\"|# c5 foo=bar|export s1_k2=\"true\"|export s1_k3=\"null\"|";
+
+ StringWriter sw = new StringWriter();
+ cf.serializeTo(new PrintWriter(sw), ConfigFileFormat.SHELL);
+ assertTextEquals(expected, sw);
+
+ sw = new StringWriter();
+ cfw.serializeTo(new PrintWriter(sw), ConfigFileFormat.SHELL);
+ assertTextEquals(expected, sw);
+ }
+
+ //====================================================================================================
+ // testEncodedValues
+ //====================================================================================================
+ @Test
+ public void testEncodedValues() throws Exception {
+ File f = getFreshFile();
+
+ ConfigFile cf = ConfigMgr.DEFAULT.create(f)
+ .addLines("s1", "", "foo* = mypassword")
+ .getResolving(VarResolver.DEFAULT);
+ ConfigFile cfw = cf.getResolving(VarResolver.DEFAULT);
+
+ assertEquals("mypassword", cf.getString("s1/foo"));
+ assertEquals("mypassword", cfw.getString("s1/foo"));
+ assertTrue(cf.isEncoded("s1/foo"));
+ assertTrue(cfw.isEncoded("s1/foo"));
+ cf.save();
+ String expected = "[s1]||foo* = {AwwJVhwUQFZEMg==}|";
+ String actual = IOUtils.read(new FileReader(f));
+ assertTextEquals(expected, actual);
+ cf.load();
+ assertEquals("mypassword", cf.getString("s1/foo"));
+ assertEquals("mypassword", cfw.getString("s1/foo"));
+
+ IOUtils.write(f, new StringReader("[s1]\nfoo* = mypassword2\n"));
+ FileUtils.modifyTimestamp(f);
+ cf.loadIfModified();
+ assertTrue(cf.isEncoded("s1/foo"));
+ assertEquals("mypassword2", cf.getString("s1/foo"));
+ cf.put("s1/foo", "mypassword");
+ assertTrue(cf.isEncoded("s1/foo"));
+
+ // INI output should be encoded
+ StringWriter sw = new StringWriter();
+ cf.serializeTo(new PrintWriter(sw), ConfigFileFormat.INI);
+ expected = "[s1]|foo* = {AwwJVhwUQFZEMg==}|";
+ assertTextEquals(expected, sw);
+
+ // BATCH output should not be encoded
+ sw = new StringWriter();
+ cf.serializeTo(new PrintWriter(sw), ConfigFileFormat.BATCH);
+ expected = "set s1_foo = mypassword|";
+ assertTextEquals(expected, sw);
+
+ // SHELL output should not be encoded
+ sw = new StringWriter();
+ cf.serializeTo(new PrintWriter(sw), ConfigFileFormat.SHELL);
+ expected = "export s1_foo=\"mypassword\"|";
+ assertTextEquals(expected, sw);
+ }
+
+ //====================================================================================================
+ // testVariables
+ //====================================================================================================
+ @Test
+ public void testVariables() throws Exception {
+
+ ConfigFile cf = ConfigMgr.DEFAULT.create()
+ .addLines("s1",
+ "f1 = $S{foo}",
+ "f2 = $S{foo,bar}",
+ "f3 = $S{$S{baz,bing},bar}"
+ );
+ ConfigFile cfw = cf.getResolving(VarResolver.DEFAULT);
+
+ System.getProperties().remove("foo");
+ System.getProperties().remove("bar");
+ System.getProperties().remove("baz");
+ System.getProperties().remove("bing");
+
+ assertEquals("$S{foo}", cf.getString("s1/f1"));
+ assertEquals("$S{foo,bar}", cf.getString("s1/f2"));
+ assertEquals("$S{$S{baz,bing},bar}", cf.getString("s1/f3"));
+ assertEquals("", cfw.getString("s1/f1"));
+ assertEquals("bar", cfw.getString("s1/f2"));
+ assertEquals("bar", cfw.getString("s1/f3"));
+
+ System.setProperty("foo", "123");
+ assertEquals("$S{foo}", cf.getString("s1/f1"));
+ assertEquals("$S{foo,bar}", cf.getString("s1/f2"));
+ assertEquals("$S{$S{baz,bing},bar}", cf.getString("s1/f3"));
+ assertEquals("123", cfw.getString("s1/f1"));
+ assertEquals("123", cfw.getString("s1/f2"));
+ assertEquals("bar", cfw.getString("s1/f3"));
+
+ System.setProperty("foo", "$S{bar}");
+ System.setProperty("bar", "baz");
+ assertEquals("$S{foo}", cf.getString("s1/f1"));
+ assertEquals("$S{foo,bar}", cf.getString("s1/f2"));
+ assertEquals("$S{$S{baz,bing},bar}", cf.getString("s1/f3"));
+ assertEquals("baz", cfw.getString("s1/f1"));
+ assertEquals("baz", cfw.getString("s1/f2"));
+ assertEquals("bar", cfw.getString("s1/f3"));
+
+ System.setProperty("bing", "$S{foo}");
+ assertEquals("$S{$S{baz,bing},bar}", cf.getString("s1/f3"));
+ assertEquals("baz", cfw.getString("s1/f3"));
+
+ System.setProperty("baz", "foo");
+ System.setProperty("foo", "123");
+ assertEquals("$S{$S{baz,bing},bar}", cf.getString("s1/f3"));
+ assertEquals("123", cfw.getString("s1/f3"));
+ }
+
+ //====================================================================================================
+ // testXorEncoder
+ //====================================================================================================
+ @Test
+ public void testXorEncoder() throws Exception {
+ testXor("foo");
+ testXor("");
+ testXor("123");
+ testXor("\u20ac"); // 3-byte UTF-8 character
+ testXor("\U00024b62"); // 4-byte UTF-8 character
+ }
+
+ private void testXor(String in) {
+ XorEncoder e = new XorEncoder();
+ String s = e.encode("", in);
+ String s2 = e.decode("", s);
+ assertEquals(in, s2);
+ }
+
+ //====================================================================================================
+ // testMultiLines
+ //====================================================================================================
+ @Test
+ public void testMultiLines() throws Exception {
+ ConfigFile cf = ConfigMgr.DEFAULT.create()
+ .addLines("s1",
+ "f1 = x \ny \n z"
+ );
+ ConfigFile cfw = cf.getResolving(VarResolver.DEFAULT);
+
+ assertEquals("x \ny \n z", cf.getString("s1/f1"));
+ assertEquals("x \ny \n z", cfw.getString("s1/f1"));
+
+ StringWriter sw = new StringWriter();
+ cf.serializeTo(sw);
+ String expected = "[s1]|f1 = x |\ty |\t z|";
+ assertTextEquals(expected, sw);
+
+ sw = new StringWriter();
+ cfw.serializeTo(sw);
+ assertTextEquals(expected, sw);
+ }
+
+ //====================================================================================================
+ // testNumberShortcuts
+ //====================================================================================================
+ @Test
+ public void testNumberShortcuts() throws Exception {
+ ConfigFile cf = ConfigMgr.DEFAULT.create()
+ .addLines("s1",
+ "f1 = 1M",
+ "f2 = 1K",
+ "f3 = 1 M",
+ "f4 = 1 K"
+ );
+ ConfigFile cfw = cf.getResolving(VarResolver.DEFAULT);
+
+ assertEquals(1048576, cf.getInt("s1/f1"));
+ assertEquals(1024, cf.getInt("s1/f2"));
+ assertEquals(1048576, cf.getInt("s1/f3"));
+ assertEquals(1024, cf.getInt("s1/f4"));
+
+ assertEquals(1048576, cfw.getInt("s1/f1"));
+ assertEquals(1024, cfw.getInt("s1/f2"));
+ assertEquals(1048576, cfw.getInt("s1/f3"));
+ assertEquals(1024, cfw.getInt("s1/f4"));
+ }
+
+ //====================================================================================================
+ // testListeners
+ //====================================================================================================
+ @SuppressWarnings("serial")
+ @Test
+ public void testListeners() throws Exception {
+ ConfigFile[] cff = {
+ ConfigMgr.DEFAULT.create(FileUtils.createTempFile("ConfigFileTest.cfg")).addLines(null, "a1=1").addLines("B", "b1=1"),
+ ConfigMgr.DEFAULT.create(FileUtils.createTempFile("ConfigFileTest.cfg")).addLines(null, "a1=1").addLines("B", "b1=1").getResolving(VarResolver.DEFAULT)
+ };
+
+ for (ConfigFile cf : cff) {
+ final Set<String> changes = new TreeSet<String>(String.CASE_INSENSITIVE_ORDER);
+ final int[] count = new int[]{0};
+
+ cf.addListener(
+ new ConfigFileListener() {
+ @Override /* ConfigFileListener */
+ public void onLoad(ConfigFile f) {
+ super.onLoad(f);
+ changes.add("<load>");
+ count[0]++;
+ }
+ @Override /* ConfigFileListener */
+ public void onSave(ConfigFile f) {
+ super.onSave(f);
+ changes.add("<save>");
+ count[0]++;
+ }
+ @Override /* ConfigFileListener */
+ public void onChange(ConfigFile f, Set<String> ss) {
+ super.onChange(f, ss);
+ for (String sss : ss)
+ changes.add(sss + '=' + f.getString(sss));
+ count[0]++;
+ }
+ }
+ );
+
+ // ConfigFile.addLines(section,lines)
+ changes.clear();
+ count[0] = 0;
+ cf.addLines(null, "a1=3", "a3=3").addLines("B", "b1=3","b3=3");
+ assertObjectEquals("['a1=3','a3=3','B/b1=3','B/b3=3']", changes);
+ assertEquals(2, count[0]);
+
+ // ConfigFile.put(key,value,encoded)
+ changes.clear();
+ count[0] = 0;
+ cf.put("a1", "2");
+ cf.put("B/b1", "2");
+ cf.put("a2", "2");
+ cf.put("B/b2", "2");
+ cf.put("C/c1", "2");
+ cf.put("C/c2", "2");
+ assertObjectEquals("['a1=2','a2=2','B/b1=2','B/b2=2','C/c1=2','C/c2=2']", changes);
+ assertEquals(6, count[0]);
+
+ // put(key,value,encoded)
+ changes.clear();
+ count[0] = 0;
+ cf.put("a4", "4", true);
+ cf.put("B/b4", "4", true);
+ assertObjectEquals("['a4=4','B/b4=4']", changes);
+ assertEquals(2, count[0]);
+
+ // put(key,value)
+ changes.clear();
+ count[0] = 0;
+ cf.put("a5", "5");
+ cf.put("B/b5", "5");
+ assertObjectEquals("['a5=5','B/b5=5']", changes);
+ assertEquals(2, count[0]);
+
+ // put(key,value,encoded)
+ changes.clear();
+ count[0] = 0;
+ cf.put("a6", "6", true);
+ cf.put("B/b6", "6", true);
+ assertObjectEquals("['a6=6','B/b6=6']", changes);
+ assertEquals(2, count[0]);
+
+ // removeString(key)
+ changes.clear();
+ count[0] = 0;
+ cf.removeString("a6");
+ cf.removeString("B/b6");
+ cf.removeString("B/bx");
+ cf.removeString("X/bx");
+ assertObjectEquals("['a6=null','B/b6=null']", changes);
+ assertEquals(2, count[0]);
+
+ // addSection(name)
+ changes.clear();
+ count[0] = 0;
+ cf.addSection("D");
+ assertObjectEquals("[]", changes);
+ assertEquals(0, count[0]);
+
+ // setSection(name,contents)
+ changes.clear();
+ count[0] = 0;
+ cf.setSection("E", new LinkedHashMap<String,String>(){{put("e1", "1");put("e2", "2");}});
+ assertObjectEquals("['E/e1=1','E/e2=2']", changes);
+ assertEquals(1, count[0]);
+ cf.removeSection("E");
+
+ // removeSection(name)
+ changes.clear();
+ count[0] = 0;
+ cf.removeSection("B");
+ assertObjectEquals("['B/b1=null','B/b2=null','B/b3=null','B/b4=null','B/b5=null']", changes);
+ assertEquals(1, count[0]);
+
+ // removeSection(name)
+ changes.clear();
+ count[0] = 0;
+ cf.removeSection("B");
+ assertObjectEquals("[]", changes);
+ assertEquals(0, count[0]);
+
+ // put(key) {
+ changes.clear();
+ count[0] = 0;
+ Section c = cf.get("C");
+ cf.put("B", c);
+ assertObjectEquals("['C/c1=2','C/c2=2']", changes);
+ assertEquals(1, count[0]);
+
+ // remove(key)
+ cf.remove("B");
+ cf.addLines("B", "b1=1","b2=2");
+ changes.clear();
+ count[0] = 0;
+ cf.remove("B");
+ assertObjectEquals("['B/b1=null','B/b2=null']", changes);
+ assertEquals(1, count[0]);
+
+ // putAll(map)
+ ConfigFile cf2 = ConfigMgr.DEFAULT.create();
+ cf2.addLines("D", "d1=1","d2=1").addLines("E", "e1=1","e2=2");
+ changes.clear();
+ count[0] = 0;
+ cf.putAll(cf2);
+ assertObjectEquals("['a1=null','a2=null','a3=null','a4=null','a5=null','D/d1=1','D/d2=1','E/e1=1','E/e2=2']", changes);
+ assertEquals(1, count[0]);
+
+ // clear()
+ cf.clear();
+ cf.addLines(null, "a1=1", "a2=1").addLines("B", "b1=1", "b2=1");
+ changes.clear();
+ count[0] = 0;
+ cf.clear();
+ assertObjectEquals("['a1=null','a2=null','B/b1=null','B/b2=null']", changes);
+ assertEquals(1, count[0]);
+
+ // entrySet()
+ cf.addLines(null, "a1=1", "a2=1").addLines("B", "b1=1", "b2=1");
+ changes.clear();
+ count[0] = 0;
+ for (Iterator<Map.Entry<String,Section>> i = cf.entrySet().iterator(); i.hasNext();) {
+ i.next();
+ i.remove();
+ }
+ assertObjectEquals("['a1=null','a2=null','B/b1=null','B/b2=null']", changes);
+ assertEquals(2, count[0]);
+
+ // keySet()
+ cf.addLines(null, "a1=1", "a2=1").addLines("B", "b1=1", "b2=1");
+ changes.clear();
+ count[0] = 0;
+ for (Iterator<String> i = cf.keySet().iterator(); i.hasNext();) {
+ i.next();
+ i.remove();
+ }
+ assertObjectEquals("['a1=null','a2=null','B/b1=null','B/b2=null']", changes);
+ assertEquals(2, count[0]);
+
+ // values()
+ cf.addLines(null, "a1=1", "a2=1").addLines("B", "b1=1", "b2=1");
+ changes.clear();
+ count[0] = 0;
+ for (Iterator<Section> i = cf.values().iterator(); i.hasNext();) {
+ i.next();
+ i.remove();
+ }
+ assertObjectEquals("['a1=null','a2=null','B/b1=null','B/b2=null']", changes);
+ assertEquals(2, count[0]);
+
+ // ConfigFile.merge()
+ cf.clear();
+ cf.addLines(null, "a1=1", "a2=1", "a3=1").addLines("B", "b1=1", "b2=1", "b3=1").addLines("C", "c1=1", "c2=1", "c3=1");
+ cf2.clear();
+ cf2.addLines(null, "a2=1", "a3=2", "a4=2").addLines("B", "b2=1", "b3=2", "b4=2").addLines("D", "d2=1", "d3=2", "d4=2");
+ changes.clear();
+ count[0] = 0;
+ cf.merge(cf2);
+ assertObjectEquals("['a1=null','a3=2','a4=2','B/b1=null','B/b3=2','B/b4=2','C/c1=null','C/c2=null','C/c3=null','D/d2=1','D/d3=2','D/d4=2']", changes);
+ assertEquals(1, count[0]);
+
+ // ConfigFile.save()
+ // ConfigFile.load()
+ changes.clear();
+ count[0] = 0;
+ cf.save();
+ cf.load();
+ assertObjectEquals("['<load>','<save>']", changes);
+ assertEquals(2, count[0]);
+
+ // Section.clear()
+ cf.clear();
+ cf.addLines(null, "a1=1", "a2=1").addLines("B", "b1=1", "b2=1");
+ changes.clear();
+ count[0] = 0;
+ cf.get("default").clear();
+ cf.get("B").clear();
+ assertObjectEquals("['a1=null','a2=null','B/b1=null','B/b2=null']", changes);
+ assertEquals(2, count[0]);
+
+ // Section.put(key,value)
+ cf.clear();
+ cf.addLines(null, "a1=1", "a2=1").addLines("B", "b1=1", "b2=1");
+ changes.clear();
+ count[0] = 0;
+ cf.get("default").put("a1", "2");
+ cf.get("default").put("a3", "2");
+ cf.get("B").put("b1", "2");
+ cf.get("B").put("b3", "2");
+ assertObjectEquals("['a1=2','a3=2','B/b1=2','B/b3=2']", changes);
+ assertEquals(4, count[0]);
+
+ // Section put(key,value,encoded)
+ cf.clear();
+ cf.addLines(null, "a1=1", "a2=1").addLines("B", "b1=1", "b2=1");
+ changes.clear();
+ count[0] = 0;
+ cf.get("default").put("a1", "2", true);
+ cf.get("default").put("a3", "2", true);
+ cf.get("B").put("b1", "2", true);
+ cf.get("B").put("b3", "2", true);
+ assertObjectEquals("['a1=2','a3=2','B/b1=2','B/b3=2']", changes);
+ assertEquals(4, count[0]);
+
+ // Section.putAll(map)
+ cf.clear();
+ cf.addLines(null, "a1=1", "a2=1").addLines("B", "b1=1", "b2=1");
+ changes.clear();
+ count[0] = 0;
+ cf.get("default").putAll(new HashMap<String,String>(){{put("a1","1");put("a2","2");put("a3","2");}});
+ cf.get("B").putAll(new HashMap<String,String>(){{put("b1","1");put("b2","2");put("b3","2");}});
+ assertObjectEquals("['a2=2','a3=2','B/b2=2','B/b3=2']", changes);
+ assertEquals(2, count[0]);
+
+ // Section.remove(key)
+ cf.clear();
+ cf.addLines(null, "a1=1", "a2=1").addLines("B", "b1=1", "b2=1");
+ changes.clear();
+ count[0] = 0;
+ cf.get("default").remove("a1");
+ cf.get("default").remove("ax");
+ cf.get("B").remove("b1");
+ cf.get("B").remove("bx");
+ assertObjectEquals("['a1=null','B/b1=null']", changes);
+ assertEquals(2, count[0]);
+
+ // Section.entrySet()
+ cf.clear();
+ cf.addLines(null, "a1=1", "a2=1").addLines("B", "b1=1", "b2=1");
+ changes.clear();
+ count[0] = 0;
+ Section n = cf.get("default");
+ for (Iterator<Map.Entry<String,String>> i = n.entrySet().iterator(); i.hasNext();) {
+ i.next();
+ i.remove();
+ }
+ n = cf.get("B");
+ for (Iterator<Map.Entry<String,String>> i = n.entrySet().iterator(); i.hasNext();) {
+ i.next();
+ i.remove();
+ }
+ assertObjectEquals("['a1=null','a2=null','B/b1=null','B/b2=null']", changes);
+ assertEquals(4, count[0]);
+
+ // Section.keySet()
+ cf.clear();
+ cf.addLines("default", "a1=1", "a2=1").addLines("B", "b1=1", "b2=1");
+ changes.clear();
+ count[0] = 0;
+ for (Iterator<String> i = cf.get("default").keySet().iterator(); i.hasNext();) {
+ i.next();
+ i.remove();
+ }
+ for (Iterator<String> i = cf.get("B").keySet().iterator(); i.hasNext();) {
+ i.next();
+ i.remove();
+ }
+ assertObjectEquals("['a1=null','a2=null','B/b1=null','B/b2=null']", changes);
+ assertEquals(4, count[0]);
+
+ // Section.values()
+ cf.clear();
+ cf.addLines(null, "a1=1", "a2=1").addLines("B", "b1=1", "b2=1");
+ try {
+ Iterator<String> i = cf.get("default").values().iterator();
+ i.next();
+ i.remove();
+ fail("Exception expected");
+ } catch (UnsupportedOperationException e) {}
+ try {
+ Iterator<String> i = cf.get("B").values().iterator();
+ i.next();
+ i.remove();
+ fail("Exception expected");
+ } catch (UnsupportedOperationException e) {}
+ }
+ }
+
+ //====================================================================================================
+ // testEntryListener
+ //====================================================================================================
+ @Test
+ public void testEntryListener() throws Exception {
+ ConfigFile[] cff = {
+ ConfigMgr.DEFAULT.create().addLines(null, "a1=1").addLines("B", "b1=1"),
+ ConfigMgr.DEFAULT.create().addLines(null, "a1=1").addLines("B", "b1=1").getResolving(VarResolver.DEFAULT)
+ };
+
+ for (ConfigFile cf : cff) {
+ final Set<String> changes = new TreeSet<String>(String.CASE_INSENSITIVE_ORDER);
+ final int[] count = new int[]{0};
+
+ cf.addListener(
+ new EntryListener("a1") {
+ @Override /* EntryListener */
+ public void onChange(ConfigFile f) {
+ super.onChange(f);
+ changes.add("a1=" + f.getString("a1"));
+ count[0]++;
+ }
+ }
+ );
+
+ cf.addListener(
+ new EntryListener("B/b1") {
+ @Override /* EntryListener */
+ public void onChange(ConfigFile f) {
+ changes.add("B/b1=" + f.getString("B/b1"));
+ count[0]++;
+ }
+ }
+ );
+
+ cf.put("a1", "2");
+ cf.put("a2", "2");
+ cf.put("B/b1", "2");
+ cf.put("B/b2", "2");
+ assertObjectEquals("['a1=2','B/b1=2']", changes);
+ assertEquals(2, count[0]);
+ }
+ }
+
+ //====================================================================================================
+ // testSectionListener
+ //====================================================================================================
+ @Test
+ public void testSectionListener() throws Exception {
+ ConfigFile[] cff = {
+ ConfigMgr.DEFAULT.create().addLines(null, "a1=1").addLines("B", "b1=1"),
+ ConfigMgr.DEFAULT.create().addLines(null, "a1=1").addLines("B", "b1=1").getResolving(VarResolver.DEFAULT)
+ };
+
+ for (ConfigFile cf : cff) {
+
+ final Set<String> changes = new TreeSet<String>(String.CASE_INSENSITIVE_ORDER);
+ final int[] count = new int[]{0};
+
+ cf.addListener(
+ new SectionListener(null) {
+ @Override /* SectionListener */
+ public void onChange(ConfigFile f) {
+ super.onChange(f);
+ changes.add("x=" + f.getString("a1"));
+ count[0]++;
+ }
+ }
+ );
+
+ cf.addListener(
+ new SectionListener("") {
+ @Override /* SectionListener */
+ public void onChange(ConfigFile f) {
+ changes.add("y=" + f.getString("a1"));
+ count[0]++;
+ }
+ }
+ );
+
+ cf.addListener(
+ new SectionListener("B") {
+ @Override /* SectionListener */
+ public void onChange(ConfigFile f) {
+ changes.add("z=" + f.getString("B/b1"));
+ count[0]++;
+ }
+ }
+ );
+
+ cf.put("a1", "2");
+ cf.put("a2", "2");
+ cf.put("B/b1", "2");
+ cf.put("B/b2", "2");
+ assertObjectEquals("['x=2','y=2','z=2']", changes);
+ assertEquals(6, count[0]);
+ }
+ }
+
+ //====================================================================================================
+ // testMerge
+ //====================================================================================================
+ @Test
+ public void testMerge() throws Exception {
+ ConfigFile cf1 = ConfigMgr.DEFAULT.create()
+ .addLines(null, "# comment a1", "a1=1")
+ .addLines("B", "# comment b1", "b1=1").addHeaderComments("B", "# comment B1")
+ .addLines("C", "# comment c1", "bc=1").addHeaderComments("C", "# comment C1");
+ ConfigFile cf2 = ConfigMgr.DEFAULT.create()
+ .addLines(null, "# comment a2", "a2=2")
+ .addLines("B", "# comment b2", "b2=2").addHeaderComments("B", "# comment B2")
+ .addLines("D", "# comment d2", "d2=2").addHeaderComments("D", "# comment D2");
+ cf1.merge(cf2);
+
+ String expected = "# comment a2|a2 = 2|# comment B2|[B]|# comment b2|b2 = 2|# comment D2|[D]|# comment d2|d2 = 2|";
+ assertTextEquals(expected, cf1);
+
+ cf1 = ConfigMgr.DEFAULT.create()
+ .addLines(null, "# comment a1", "a1=1")
+ .addLines("B", "# comment b1", "b1=1").addHeaderComments("B", "# comment B1")
+ .addLines("C", "# comment c1", "bc=1").addHeaderComments("C", "# comment C1").getResolving(VarResolver.DEFAULT);
+ cf2 = ConfigMgr.DEFAULT.create()
+ .addLines(null, "# comment a2", "a2=2")
+ .addLines("B", "# comment b2", "b2=2").addHeaderComments("B", "# comment B2")
+ .addLines("D", "# comment d2", "d2=2").addHeaderComments("D", "# comment D2").getResolving(VarResolver.DEFAULT);
+
+ cf1.merge(cf2);
+ assertTextEquals(expected, cf1);
+ }
+
+ //====================================================================================================
+ // testDefaultSection
+ // Default section should be keyed by either null, "", or "default"
+ //====================================================================================================
+ @Test
+ public void testDefaultSection() throws Exception {
+ ConfigFile[] cff = {
+ ConfigMgr.DEFAULT.create().addLines(null, "a1=1").addLines("", "a2=2").addLines("default", "a3=3"),
+ ConfigMgr.DEFAULT.create().addLines(null, "a1=1").addLines("", "a2=2").addLines("default", "a3=3").getResolving(VarResolver.DEFAULT)
+ };
+
+ for (ConfigFile cf : cff) {
+ assertObjectEquals("{'default':{a1:'1',a2:'2',a3:'3'}}", cf);
+ assertTextEquals("a1 = 1|a2 = 2|a3 = 3|", cf);
+
+ assertObjectEquals("{a1:'1',a2:'2',a3:'3'}", cf.get(null));
+ assertObjectEquals("{a1:'1',a2:'2',a3:'3'}", cf.get(""));
+ assertObjectEquals("{a1:'1',a2:'2',a3:'3'}", cf.get("default"));
+
+ assertEquals("1", cf.getString("a1"));
+ assertEquals("1", cf.getString("default/a1"));
+
+ assertObjectEquals("{a1:'1',a2:'2',a3:'3'}", cf.getSectionMap(null));
+ assertObjectEquals("{a1:'1',a2:'2',a3:'3'}", cf.getSectionMap(""));
+ assertObjectEquals("{a1:'1',a2:'2',a3:'3'}", cf.getSectionMap("default"));
+
+ cf.put(null, cf.get(null));
+ assertObjectEquals("{a1:'1',a2:'2',a3:'3'}", cf.get(null));
+ cf.put("", cf.get(null));
+ assertObjectEquals("{a1:'1',a2:'2',a3:'3'}", cf.get(null));
+ cf.put("default", cf.get(null));
+ assertObjectEquals("{a1:'1',a2:'2',a3:'3'}", cf.get(null));
+ }
+ }
+
+ //====================================================================================================
+ // ConfigFileImpl(File)
+ // ConfigFileImpl()
+ //====================================================================================================
+ @Test
+ public void testAlternateConstructors() throws Exception {
+ ConfigFile cf = new ConfigFileImpl();
+ cf.put("A", "a");
+ try { cf.save(); fail(); } catch (UnsupportedOperationException e) {}
+ cf.loadIfModified();
+ assertEquals("a", cf.getString("A"));
+ }
+
+ //====================================================================================================
+ // containsKey(Object)
+ // containsValue(Object)
+ // size()
+ //====================================================================================================
+ @Test
+ public void testContains() throws Exception {
+ ConfigFile cf = ConfigMgr.DEFAULT.create().addLines(null, "a1=1").addLines("", "a2=2").addLines("default", "a3=3").addLines("A", "a4=4");
+ ConfigFile cfw = cf.getResolving();
+
+ assertTrue(cf.containsKey(null));
+ assertTrue(cf.containsKey(""));
+ assertTrue(cf.containsKey("default"));
+ assertTrue(cf.containsKey("A"));
+ assertFalse(cf.containsKey("x"));
+
+ assertTrue(cfw.containsKey(null));
+ assertTrue(cfw.containsKey(""));
+ assertTrue(cfw.containsKey("default"));
+ assertTrue(cfw.containsKey("A"));
+ assertFalse(cfw.containsKey("x"));
+
+ Section s = cf.get(null);
+ assertTrue(cf.containsValue(s));
+ assertTrue(cfw.containsValue(s));
+ s = cf.get("A");
+ assertTrue(cf.containsValue(s));
+ assertTrue(cfw.containsValue(s));
+
+ assertFalse(cf.isEmpty());
+ assertFalse(cfw.isEmpty());
+
+ cf.clear();
+ assertTrue(cf.isEmpty());
+ assertTrue(cfw.isEmpty());
+ assertFalse(cf.containsKey(null));
+ assertFalse(cfw.containsKey(null));
+ assertEquals(0, cf.size());
+ assertEquals(0, cfw.size());
+ assertEquals(0, cf.keySet().size());
+ assertEquals(0, cfw.keySet().size());
+ assertEquals(0, cf.entrySet().size());
+ assertEquals(0, cfw.entrySet().size());
+ assertEquals(0, cf.values().size());
+ assertEquals(0, cfw.values().size());
+ }
+
+ //====================================================================================================
+ // getObjectArray(Class c, String key)
+ // getObjectArray(Class c, String key, T[] def)
+ //====================================================================================================
+ @Test
+ public void testGetObjectArray() throws Exception {
+ ConfigFile cf = ConfigMgr.DEFAULT.create().addLines("A", "a1=1,2,3");
+ ConfigFile cfw = cf.getResolving();
+ assertObjectEquals("[1,2,3]", cf.getObject(Integer[].class, "A/a1"));
+ assertObjectEquals("[1,2,3]", cfw.getObject(Integer[].class, "A/a1"));
+ assertObjectEquals("[4,5,6]", cf.getObject(Integer[].class, "A/a2", new Integer[]{4,5,6}));
+ assertObjectEquals("[4,5,6]", cfw.getObject(Integer[].class, "A/a2", new Integer[]{4,5,6}));
+ assertObjectEquals("[7,8,9]", cf.getObject(Integer[].class, "B/a1", new Integer[]{7,8,9}));
+ assertObjectEquals("[7,8,9]", cfw.getObject(Integer[].class, "B/a1", new Integer[]{7,8,9}));
+ assertObjectEquals("[]", cf.getObject(Integer[].class, "B/a1"));
+ assertObjectEquals("[]", cfw.getObject(Integer[].class, "B/a1"));
+
+ cf = ConfigMgr.DEFAULT.create().addLines("A", "a1 = 1 ,\n\t2 ,\n\t3 ");
+ assertObjectEquals("[1,2,3]", cf.getObject(Integer[].class, "A/a1"));
+ assertObjectEquals("[1,2,3]", cfw.getObject(Integer[].class, "A/a1"));
+
+ // We cannot cast primitive arrays to Object[], so the following throws exceptions.
+ assertObjectEquals("[1,2,3]", cf.getObject(int[].class, "A/a1"));
+ assertEquals("int", cf.getObject(int[].class, "A/a1").getClass().getComponentType().getSimpleName());
+ assertObjectEquals("[]", cf.getObject(int[].class, "B/a1"));
+ assertEquals("int", cf.getObject(int[].class, "B/a1").getClass().getComponentType().getSimpleName());
+ assertObjectEquals("[]", cf.getObject(int[].class, "A/a2"));
+ assertEquals("int", cf.getObject(int[].class, "A/a2").getClass().getComponentType().getSimpleName());
+
+ assertObjectEquals("[1,2,3]", cf.getObject(int[].class, "A/a1", new int[]{4}));
+ assertEquals("int", cf.getObject(int[].class, "A/a1", new int[]{4}).getClass().getComponentType().getSimpleName());
+ assertObjectEquals("[4]", cf.getObject(int[].class, "B/a1", new int[]{4}));
+ assertEquals("int", cf.getObject(int[].class, "B/a1", new int[]{4}).getClass().getComponentType().getSimpleName());
+ assertObjectEquals("[4]", cf.getObject(int[].class, "A/a2", new int[]{4}));
+ assertEquals("int", cf.getObject(int[].class, "A/a2", new int[]{4}).getClass().getComponentType().getSimpleName());
+
+ System.setProperty("X", "4,5,6");
+ cf = ConfigMgr.DEFAULT.create().addLines(null, "x1=$C{A/a1}", "x2=$S{X}", "x3=$S{Y}").addLines("A", "a1=1,2,3").getResolving();
+ assertObjectEquals("[1,2,3]", cf.getObject(int[].class, "x1", new int[]{9}));
+ assertObjectEquals("[4,5,6]", cf.getObject(int[].class, "x2", new int[]{9}));
+ assertObjectEquals("[9]", cf.getObject(int[].class, "x3", new int[]{9}));
+ System.clearProperty("X");
+ }
+
+ //====================================================================================================
+ // getStringArray(String key)
+ // getStringArray(String key, String[] def)
+ //====================================================================================================
+ @Test
+ public void testGetStringArray() throws Exception {
+ ConfigFile cf = ConfigMgr.DEFAULT.create().addLines("A", "a1=1,2,3");
+ ConfigFile cfw = cf.getResolving();
+ assertObjectEquals("['1','2','3']", cf.getStringArray("A/a1"));
+ assertObjectEquals("['1','2','3']", cfw.getStringArray("A/a1"));
+ assertObjectEquals("['4','5','6']", cf.getStringArray("A/a2", new String[]{"4","5","6"}));
+ assertObjectEquals("['4','5','6']", cfw.getStringArray("A/a2", new String[]{"4","5","6"}));
+ assertObjectEquals("['7','8','9']", cf.getStringArray("B/a1", new String[]{"7","8","9"}));
+ assertObjectEquals("['7','8','9']", cfw.getStringArray("B/a1", new String[]{"7","8","9"}));
+ assertObjectEquals("[]", cf.getStringArray("B/a1"));
+ assertObjectEquals("[]", cfw.getStringArray("B/a1"));
+
+ cf = ConfigMgr.DEFAULT.create().addLines("A", "a1 = 1 ,\n\t2 ,\n\t3 ");
+ assertObjectEquals("['1','2','3']", cf.getStringArray("A/a1"));
+ assertObjectEquals("['1','2','3']", cfw.getStringArray("A/a1"));
+
+ System.setProperty("X", "4,5,6");
+ cf = ConfigMgr.DEFAULT.create().addLines(null, "x1=$C{A/a1}", "x2=$S{X}", "x3=$S{Y}", "x4=$S{Y,$S{X}}").addLines("A", "a1=1,2,3").getResolving();
+ assertObjectEquals("['1','2','3']", cf.getStringArray("x1", new String[]{"9"}));
+ assertObjectEquals("['4','5','6']", cf.getStringArray("x2", new String[]{"9"}));
+ assertObjectEquals("['9']", cf.getStringArray("x3", new String[]{"9"}));
+
+ // TODO - Doesn't work yet.
+ // assertObjectEquals("['4','5','6']", cf.getStringArray("x4", new String[]{"9"}));
+ System.clearProperty("X");
+ }
+
+ //====================================================================================================
+ // getSectionMap(String name)
+ //====================================================================================================
+ @Test
+ public void testGetSectionMap() throws Exception {
+ ConfigFile cf = ConfigMgr.DEFAULT.create().addLines("A", "a1=1", "").addLines("D", "d1=$C{A/a1}","d2=$S{X}");
+
+ assertObjectEquals("{a1:'1'}", cf.getSectionMap("A"));
+ assertNull(cf.getSectionMap("B"));
+ assertObjectEquals("null", cf.getSectionMap("C"));
+
+ ObjectMap m = cf.getSectionMap("A");
+ assertObjectEquals("{a1:'1'}", m);
+
+ m = cf.getSectionMap("D");
+ assertObjectEquals("{d1:'$C{A/a1}',d2:'$S{X}'}", m);
+
+ cf = cf.getResolving();
+
+ System.setProperty("X", "x");
+ m = cf.getSectionMap("D");
+ assertObjectEquals("{d1:'1',d2:'x'}", m);
+ System.clearProperty("X");
+ }
+
+ //====================================================================================================
+ // load(Reader)
+ //====================================================================================================
+ @Test
+ public void testLoadFromReader() throws Exception {
+ ConfigFile[] cff = {
+ ConfigMgr.DEFAULT.create().addLines(null, "a1=1"),
+ ConfigMgr.DEFAULT.create().addLines(null, "a1=1").getResolving(VarResolver.DEFAULT)
+ };
+
+ for (ConfigFile cf : cff) {
+ cf.load(new StringReader("[B]\nb1=1"));
+ assertObjectEquals("{'default':{},B:{b1:'1'}}", cf);
+ }
+ }
+
+
+ //====================================================================================================
+ // toWritable()
+ //====================================================================================================
+ @Test
+ public void testToWritable() throws Exception {
+ ConfigFile cf = ConfigMgr.DEFAULT.create()
+ .addLines(null, "a=b");
+ ConfigFile cfw = cf.getResolving();
+
+ StringWriter sw = new StringWriter();
+ cf.toWritable().writeTo(sw);
+ assertTextEquals("a = b|", sw);
+
+ sw = new StringWriter();
+ cfw.toWritable().writeTo(sw);
+ assertTextEquals("a = b|", sw);
+
+ assertEquals("text/plain", cf.toWritable().getMediaType());
+ assertEquals("text/plain", cfw.toWritable().getMediaType());
+ }
+
+ //====================================================================================================
+ // containsNonEmptyKey()
+ //====================================================================================================
+ @Test
+ public void testContainsNonEmptyKey() throws Exception {
+ ConfigFile cf = ConfigMgr.DEFAULT.create()
+ .addLines(null, "a=b","c=");
+ ConfigFile cfw = cf.getResolving();
+
+ assertTrue(cf.containsNonEmptyValue("a"));
+ assertFalse(cf.containsNonEmptyValue("c"));
+ assertFalse(cf.containsNonEmptyValue("d"));
+
+ assertTrue(cfw.containsNonEmptyValue("a"));
+ assertFalse(cfw.containsNonEmptyValue("c"));
+ assertFalse(cfw.containsNonEmptyValue("d"));
+
+ cf.addLines("A", "a1=$S{X}", "a2=$S{Y,$S{X}}");
+ assertFalse(cfw.containsNonEmptyValue("A/a1"));
+ assertFalse(cfw.containsNonEmptyValue("A/a2"));
+
+ System.setProperty("X", "x");
+ assertTrue(cfw.containsNonEmptyValue("A/a1"));
+ assertTrue(cfw.containsNonEmptyValue("A/a2"));
+ System.clearProperty("X");
+ }
+
+ //====================================================================================================
+ // getSectionKeys(String sectionName)
+ //====================================================================================================
+ @Test
+ public void testGetSectionKeys() throws Exception {
+ ConfigFile cf = ConfigMgr.DEFAULT.create()
+ .addLines(null, "x1=1", "x2=")
+ .addLines("A", "a1=1", "a2=");
+
+ assertObjectEquals("['x1','x2']", cf.getSectionKeys(null));
+ assertObjectEquals("['x1','x2']", cf.getSectionKeys(""));
+ assertObjectEquals("['x1','x2']", cf.getSectionKeys("default"));
+ assertObjectEquals("['a1','a2']", cf.getSectionKeys("A"));
+ assertNull(cf.getSectionKeys("B"));
+
+ cf = cf.getResolving();
+
+ assertObjectEquals("['x1','x2']", cf.getSectionKeys(null));
+ assertObjectEquals("['x1','x2']", cf.getSectionKeys(""));
+ assertObjectEquals("['x1','x2']", cf.getSectionKeys("default"));
+ assertObjectEquals("['a1','a2']", cf.getSectionKeys("A"));
+ assertNull(cf.getSectionKeys("B"));
+ }
+
+ //====================================================================================================
+ // addLines(String section, String...lines)
+ //====================================================================================================
+ @Test
+ public void testAddLines() throws Exception {
+ ConfigFile cf = ConfigMgr.DEFAULT.create()
+ .addLines(null, "x1=1")
+ .addLines("A", "a1=1");
+
+ cf.addLines(null, "# comment1", "x1=2", "x2=1", "foobar");
+ cf.addLines("A", "# comment2", "a1=2", "a2=1", "foobar");
+ cf.addLines("B", "# comment3", "b1=2", "b2=1", "foobar");
+ cf.addLines("C", (String[])null); // Should be OK.
+ cf.addLines("C", (String)null); // Should be OK.
+ assertObjectEquals("{'default':{x1:'2',x2:'1'},A:{a1:'2',a2:'1'},B:{b1:'2',b2:'1'},C:{}}", cf);
+ assertTextEquals("# comment1|x1 = 2|x2 = 1|foobar|[A]|# comment2|a1 = 2|a2 = 1|foobar|[B]|# comment3|b1 = 2|b2 = 1|foobar|[C]||", cf);
+
+ cf = ConfigMgr.DEFAULT.create()
+ .addLines(null, "x1=1")
+ .addLines("A", "a1=1")
+ .getResolving();
+
+ cf.addLines(null, "# comment1", "x1=2", "x2=1", "foobar");
+ cf.addLines("A", "# comment2", "a1=2", "a2=1", "foobar");
+ cf.addLines("B", "# comment3", "b1=2", "b2=1", "foobar");
+ cf.addLines("C", (String[])null); // Should be OK.
+ cf.addLines("C", (String)null); // Should be OK.
+ assertObjectEquals("{'default':{x1:'2',x2:'1'},A:{a1:'2',a2:'1'},B:{b1:'2',b2:'1'},C:{}}", cf);
+ assertTextEquals("# comment1|x1 = 2|x2 = 1|foobar|[A]|# comment2|a1 = 2|a2 = 1|foobar|[B]|# comment3|b1 = 2|b2 = 1|foobar|[C]||", cf);
+
+ cf = ConfigMgr.DEFAULT.create()
+ .addLines(null, "x1=$C{A/a2}")
+ .addLines("A", "a1=1")
+ .getResolving();
+ assertObjectEquals("{'default':{x1:'$C{A/a2}'},A:{a1:'1'}}", cf);
+ assertTextEquals("x1 = $C{A/a2}|[A]|a1 = 1|", cf);
+
+ assertEquals("", cf.getString("x1"));
+
+ cf.addLines("A", "a2=2");
+
+ assertEquals("2", cf.getString("x1"));
+ }
+
+
+ //====================================================================================================
+ // addHeaderComments(String section, String...headerComments)
+ // clearHeaderComments(String section)
+ //====================================================================================================
+ @Test
+ public void testAddHeaderComments() throws Exception {
+ ConfigFile cf = ConfigMgr.DEFAULT.create()
+ .addLines(null, "x1=1")
+ .addLines("A", "a1=1");
+
+ cf.addHeaderComments(null, "# h1");
+ cf.addHeaderComments("", "# h2");
+ cf.addHeaderComments("default", "# h3");
+ cf.addHeaderComments("A", "# h4");
+ cf.addHeaderComments("B", "# h5");
+ cf.addHeaderComments("C", (String[])null);
+ cf.addHeaderComments("C", (String)null);
+
+ assertTextEquals("# h1|# h2|# h3|x1 = 1|# h4|[A]|a1 = 1|# h5|[B]|#|[C]|", cf);
+
+ cf = ConfigMgr.DEFAULT.create()
+ .addLines(null, "x1=1")
+ .addLines("A", "a1=1");
+
+ cf.addHeaderComments(null, "h1");
+ cf.addHeaderComments("", "h2");
+ cf.addHeaderComments("default", "h3");
+ cf.addHeaderComments("A", "h4");
+ cf.addHeaderComments("B", "h5");
+ cf.addHeaderComments("C", (String[])null);
+ cf.addHeaderComments("C", (String)null);
+
+ assertTextEquals("#h1|#h2|#h3|x1 = 1|#h4|[A]|a1 = 1|#h5|[B]|#|[C]|", cf);
+
+ cf.clearHeaderComments(null).clearHeaderComments("A").clearHeaderComments("B").clearHeaderComments("C");
+ assertTextEquals("x1 = 1|[A]|a1 = 1|[B]|[C]|", cf);
+
+ cf = ConfigMgr.DEFAULT.create()
+ .addLines(null, "x1=1")
+ .addLines("A", "a1=1")
+ .getResolving();
+
+ cf.addHeaderComments(null, "h1");
+ cf.addHeaderComments("", "h2");
+ cf.addHeaderComments("default", "h3");
+ cf.addHeaderComments("A", "h4");
+ cf.addHeaderComments("B", "h5");
+ cf.addHeaderComments("C", (String[])null);
+ cf.addHeaderComments("C", (String)null);
+
+ assertTextEquals("#h1|#h2|#h3|x1 = 1|#h4|[A]|a1 = 1|#h5|[B]|#|[C]|", cf);
+
+ cf.clearHeaderComments(null).clearHeaderComments("A").clearHeaderComments("B").clearHeaderComments("C");
+ assertTextEquals("x1 = 1|[A]|a1 = 1|[B]|[C]|", cf);
+ }
+
+ //====================================================================================================
+ // getString(String key)
+ // getString(String key, String def)
+ //====================================================================================================
+ @Test
+ public void testGetString() throws Exception {
+ System.setProperty("S1", "1");
+ ConfigFile cf = ConfigMgr.DEFAULT.create()
+ .addLines(null, "x1=1", "x2=$C{A/a2}", "x3=$S{S1,2}", "x4=$S{S2,3}")
+ .addLines("A", "a1=1", "a2=$C{A/a1}", "a3=$S{S1,2}", "a4=$S{S2,3}");
+
+ assertEquals("1", cf.getString("x1"));
+ assertEquals("1", cf.getString("x1", "x"));
+ assertEquals("$C{A/a2}", cf.getString("x2"));
+ assertEquals("$C{A/a2}", cf.getString("x2", "x"));
+ assertEquals("$S{S1,2}", cf.getString("x3"));
+ assertEquals("$S{S1,2}", cf.getString("x3", "x"));
+ assertEquals("$S{S2,3}", cf.getString("x4"));
+ assertEquals("$S{S2,3}", cf.getString("x4", "x"));
+ assertNull(cf.getString("x5"));
+ assertEquals("x", cf.getString("x5", "x"));
+
+ assertEquals("1", cf.getString("A/a1"));
+ assertEquals("1", cf.getString("A/a1", "x"));
+ assertEquals("$C{A/a1}", cf.getString("A/a2"));
+ assertEquals("$C{A/a1}", cf.getString("A/a2", "x"));
+ assertEquals("$S{S1,2}", cf.getString("A/a3"));
+ assertEquals("$S{S1,2}", cf.getString("A/a3", "x"));
+ assertEquals("$S{S2,3}", cf.getString("A/a4"));
+ assertEquals("$S{S2,3}", cf.getString("A/a4", "x"));
+ assertNull(cf.getString("A/a5"));
+ assertEquals("x", cf.getString("A/a5", "x"));
+
+ assertNull(cf.getString("B/b1"));
+ assertEquals("x", cf.getString("B/b1", "x"));
+
+ cf = cf.getResolving();
+
+ assertEquals("1", cf.getString("x1"));
+ assertEquals("1", cf.getString("x1", "x"));
+ assertEquals("1", cf.getString("x2"));
+ assertEquals("1", cf.getString("x2", "x"));
+ assertEquals("1", cf.getString("x3"));
+ assertEquals("1", cf.getString("x3", "x"));
+ assertEquals("3", cf.getString("x4"));
+ assertEquals("3", cf.getString("x4", "x"));
+ assertNull(cf.getString("x5"));
+ assertEquals("x", cf.getString("x5", "x"));
+
+ assertEquals("1", cf.getString("A/a1"));
+ assertEquals("1", cf.getString("A/a1", "x"));
+ assertEquals("1", cf.getString("A/a2"));
+ assertEquals("1", cf.getString("A/a2", "x"));
+ assertEquals("1", cf.getString("A/a3"));
+ assertEquals("1", cf.getString("A/a3", "x"));
+ assertEquals("3", cf.getString("A/a4"));
+ assertEquals("3", cf.getString("A/a4", "x"));
+ assertNull(cf.getString("A/a5"));
+ assertEquals("x", cf.getString("A/a5", "x"));
+
+ assertNull(cf.getString("B/b1"));
+ assertEquals("x", cf.getString("B/b1", "x"));
+
+ System.clearProperty("S1");
+ }
+
+ //====================================================================================================
+ // put(String key, Object value)
+ //====================================================================================================
+ @Test
+ public void testPutString() throws Exception {
+ ConfigFile cf = ConfigMgr.DEFAULT.create()
+ .addLines(null, "x1=1")
+ .addLines("A", "a1=1");
+
+ cf.put("x1", 2);
+ cf.put("x2", 3);
+ cf.put("A/a1", 2);
+ cf.put("A/a2", 3);
+ cf.put("B/b1", 2);
+
+ assertObjectEquals("{'default':{x1:'2',x2:'3'},A:{a1:'2',a2:'3'},B:{b1:'2'}}", cf);
+ assertTextEquals("x1 = 2|x2 = 3|[A]|a1 = 2|a2 = 3|[B]|b1 = 2|", cf);
+
+ cf = ConfigMgr.DEFAULT.create()
+ .addLines(null, "x1=1")
+ .addLines("A", "a1=1")
+ .getResolving();
+
+ cf.put("x1", 2);
+ cf.put("x2", 3);
+ cf.put("A/a1", 2);
+ cf.put("A/a2", 3);
+ cf.put("B/b1", 2);
+
+ assertObjectEquals("{'default':{x1:'2',x2:'3'},A:{a1:'2',a2:'3'},B:{b1:'2'}}", cf);
+ assertTextEquals("x1 = 2|x2 = 3|[A]|a1 = 2|a2 = 3|[B]|b1 = 2|", cf);
+
+ cf.put("x1", 9);
+ cf.put("x2", "$C{x1}");
+ cf.put("A/a1", "$C{x1}");
+ cf.put("A/a2", "$C{x1}");
+ cf.put("B/b1", "$C{x1}");
+
+ assertObjectEquals("{'default':{x1:'9',x2:'$C{x1}'},A:{a1:'$C{x1}',a2:'$C{x1}'},B:{b1:'$C{x1}'}}", cf);
+ assertTextEquals("x1 = 9|x2 = $C{x1}|[A]|a1 = $C{x1}|a2 = $C{x1}|[B]|b1 = $C{x1}|", cf);
+
+ assertEquals("9", cf.getString("x1"));
+ assertEquals("9", cf.getString("x2"));
+ assertEquals("9", cf.getString("A/a1"));
+ assertEquals("9", cf.getString("A/a2"));
+ assertEquals("9", cf.getString("B/b1"));
+ }
+
+ //====================================================================================================
+ // put(String key, Object value, boolean encoded)
+ //====================================================================================================
+ @Test
+ public void testPutStringEncoded() throws Exception {
+ ConfigFile cf = ConfigMgr.DEFAULT.create()
+ .addLines(null, "x1=1")
+ .addLines("A", "a1=1");
+
+ cf.put("x1", 2, true);
+ cf.put("x2", 3, true);
+ cf.put("A/a1", 2, true);
+ cf.put("A/a2", 3, true);
+ cf.put("B/b1", 2, true);
+
+ assertObjectEquals("{'default':{x1:'2',x2:'3'},A:{a1:'2',a2:'3'},B:{b1:'2'}}", cf);
+ assertTextEquals("x1* = {XA==}|x2* = {XQ==}|[A]|a1* = {XA==}|a2* = {XQ==}|[B]|b1* = {XA==}|", cf);
+
+ cf = ConfigMgr.DEFAULT.create()
+ .addLines(null, "x1=1")
+ .addLines("A", "a1=1")
+ .getResolving();
+
+ cf.put("x1", 2, true);
+ cf.put("x2", 3, true);
+ cf.put("A/a1", 2, true);
+ cf.put("A/a2", 3, true);
+ cf.put("B/b1", 2, true);
+
+ assertObjectEquals("{'default':{x1:'2',x2:'3'},A:{a1:'2',a2:'3'},B:{b1:'2'}}", cf);
+ assertTextEquals("x1* = {XA==}|x2* = {XQ==}|[A]|a1* = {XA==}|a2* = {XQ==}|[B]|b1* = {XA==}|", cf);
+
+ cf.put("x1", 9, true);
+ cf.put("x2", "$C{x1}", true);
+ cf.put("A/a1", "$C{x1}", true);
+ cf.put("A/a2", "$C{x1}", true);
+ cf.put("B/b1", "$C{x1}", true);
+
+ assertObjectEquals("{'default':{x1:'9',x2:'$C{x1}'},A:{a1:'$C{x1}',a2:'$C{x1}'},B:{b1:'$C{x1}'}}", cf);
+ assertTextEquals("x1* = {Vw==}|x2* = {SjYCT14a}|[A]|a1* = {SjYCT14a}|a2* = {SjYCT14a}|[B]|b1* = {SjYCT14a}|", cf);
+
+ assertEquals("9", cf.getString("x1"));
+ assertEquals("9", cf.getString("x2"));
+ assertEquals("9", cf.getString("A/a1"));
+ assertEquals("9", cf.getString("A/a2"));
+ assertEquals("9", cf.getString("B/b1"));
+ }
+
+ //====================================================================================================
+ // removeString(String key)
+ //====================================================================================================
+ @Test
+ public void testRemoveString() throws Exception {
+ ConfigFile cf = ConfigMgr.DEFAULT.create()
+ .addLines(null, "x1=1")
+ .addLines("A", "a1=1");
+
+ cf.removeString("x1");
+ cf.removeString("x2");
+ cf.removeString("A/a1");
+ cf.removeString("A/a2");
+
+ assertObjectEquals("{'default':{},A:{}}", cf);
+ assertTextEquals("[A]|", cf);
+
+ cf = ConfigMgr.DEFAULT.create()
+ .addLines(null, "x1=1")
+ .addLines("A", "a1=1")
+ .getResolving();
+
+ cf.removeString("x1");
+ cf.removeString("x2");
+ cf.removeString("A/a1");
+ cf.removeString("A/a2");
+
+ assertObjectEquals("{'default':{},A:{}}", cf);
+ assertTextEquals("[A]|", cf);
+ }
+
+ //====================================================================================================
+ // getObject(Class c, String key)
+ // getObject(Class c, String key, T def)
+ //====================================================================================================
+ @Test
+ public void testGetObject() throws Exception {
+ ConfigFile cf = ConfigMgr.DEFAULT.create().addLines("A", "a1=1,2,3", "a2=1", "a3=true", "a4=1.2", "a5=1.2,3.4");
+ ConfigFile cfw = cf.getResolving();
+
+ assertObjectEquals("['1','2','3']", cf.getObject(String[].class, "A/a1"));
+ assertObjectEquals("'1,2,3'", cf.getObject(String.class, "A/a1"));
+ assertObjectEquals("'foobar'", cf.getObject(String.class, "X/a1", "foobar"));
+ assertObjectEquals("1", cf.getObject(int.class, "A/a2"));
+ assertObjectEquals("1", cf.getObject(Integer.class, "A/a2"));
+ assertObjectEquals("true", cf.getObject(boolean.class, "A/a3"));
+ assertObjectEquals("true", cf.getObject(Boolean.class, "A/a3"));
+ assertObjectEquals("1.2", cf.getObject(Float.class, "A/a4"));
+ assertObjectEquals("[1.2,3.4]", cf.getObject(Float[].class, "A/a5"));
+ assertObjectEquals("1.2", cf.getObject(float.class, "A/a4"));
+ assertObjectEquals("[1.2,3.4]", cf.getObject(float[].class, "A/a5"));
+ assertNull(cf.getObject(String.class, "B/a4"));
+
+ assertObjectEquals("['1','2','3']", cfw.getObject(String[].class, "A/a1"));
+ assertObjectEquals("'1,2,3'", cfw.getObject(String.class, "A/a1"));
+ assertObjectEquals("'foobar'", cfw.getObject(String.class, "X/a1", "foobar"));
+ assertObjectEquals("1", cfw.getObject(int.class, "A/a2"));
+ assertObjectEquals("1", cfw.getObject(Integer.class, "A/a2"));
+ assertObjectEquals("true", cfw.getObject(boolean.class, "A/a3"));
+ assertObjectEquals("true", cfw.getObject(Boolean.class, "A/a3"));
+ assertObjectEquals("1.2", cfw.getObject(Float.class, "A/a4"));
+ assertObjectEquals("[1.2,3.4]", cfw.getObject(Float[].class, "A/a5"));
+ assertObjectEquals("1.2", cfw.getObject(float.class, "A/a4"));
+ assertObjectEquals("[1.2,3.4]", cfw.getObject(float[].class, "A/a5"));
+ assertNull(cfw.getObject(String.class, "B/a4"));
+ }
+
+ //====================================================================================================
+ // getInt(String key)
+ // getInt(String key, int def)
+ //====================================================================================================
+ @Test
+ public void testGetInt() throws Exception {
+ System.setProperty("X", "1");
+ ConfigFile cf = ConfigMgr.DEFAULT.create().addLines(null, "x1=$C{A/a1}", "x2=$S{X}", "x3=$S{Y}", "x4=$S{Y,2}").addLines("A", "a1=1");
+
+ try {
+ cf.getInt("x1");
+ fail();
+ } catch (NumberFormatException e) {}
+ try {
+ cf.getInt("x2");
+ fail();
+ } catch (NumberFormatException e) {}
+ try {
+ cf.getInt("x3");
+ fail();
+ } catch (NumberFormatException e) {}
+ try {
+ cf.getInt("x4");
+ fail();
+ } catch (NumberFormatException e) {}
+ assertEquals(1, cf.getInt("A/a1"));
+
+ cf = cf.getResolving();
+
+ assertEquals(1, cf.getInt("x1"));
+ assertEquals(1, cf.getInt("x2"));
+ assertEquals(0, cf.getInt("x3"));
+ assertEquals(9, cf.getInt("x3", 9));
+ assertEquals(2, cf.getInt("x4"));
+ assertEquals(9, cf.getInt("x5", 9));
+ assertEquals(1, cf.getInt("A/a1"));
+ assertEquals(9, cf.getInt("A/a2", 9));
+ assertEquals(9, cf.getInt("B/b1", 9));
+
+ System.clearProperty("X");
+ }
+
+ //====================================================================================================
+ // getBoolean(String key)
+ // getBoolean(String key, boolean def)
+ //====================================================================================================
+ @Test
+ public void testGetBoolean() throws Exception {
+ System.setProperty("X", "true");
+ ConfigFile cf = ConfigMgr.DEFAULT.create().addLines(null, "x1=$C{A/a1}", "x2=$S{X}", "x3=$S{Y}", "x4=$S{Y,true}").addLines("A", "a1=true");
+
+ assertFalse(cf.getBoolean("x1"));
+ assertFalse(cf.getBoolean("x2"));
+ assertFalse(cf.getBoolean("x3"));
+ assertFalse(cf.getBoolean("x4"));
+ assertTrue(cf.getBoolean("A/a1"));
+
+ cf = cf.getResolving();
+
+ assertTrue(cf.getBoolean("x1"));
+ assertTrue(cf.getBoolean("x2"));
+ assertFalse(cf.getBoolean("x3"));
+ assertTrue(cf.getBoolean("x3", true));
+ assertTrue(cf.getBoolean("x4"));
+ assertTrue(cf.getBoolean("x5", true));
+ assertTrue(cf.getBoolean("A/a1"));
+ assertTrue(cf.getBoolean("A/a2", true));
+ assertTrue(cf.getBoolean("B/b1", true));
+
+ System.clearProperty("X");
+ }
+
+ //====================================================================================================
+ // getSectionAsBean(String,Class)
+ //====================================================================================================
+ @Test
+ public void testGetSectionAsBean() throws Exception {
+ ConfigFile cf = ConfigMgr.DEFAULT.create();
+ cf.put("A/a", "1");
+ cf.put("A/b", "2");
+
+ A a = cf.getSectionAsBean("A", A.class);
+ assertObjectEquals("{a:1,b:2}", a);
+
+ cf.put("A/c", "3");
+ try { cf.getSectionAsBean("A",A.class);} catch (ParseException e) {}
+ a = cf.getSectionAsBean("A", A.class, true);
+ assertObjectEquals("{a:1,b:2}", a);
+
+ System.setProperty("X", "3");
+ cf.put("A/a", "$S{X}");
+ cf.put("A/b", "$S{Y,$S{X}}");
+ cf = cf.getResolving();
+ a = cf.getSectionAsBean("A", A.class, true);
+ assertObjectEquals("{a:3,b:3}", a);
+ System.clearProperty("X");
+ }
+
+ public static class A {
+ public int a;
+ private int b;
+ public int getB() {
+ return b;
+ }
+ public void setB(int b) {
+ this.b = b;
+ }
+ }
+
+ //====================================================================================================
+ // writeProperties(...)
+ //====================================================================================================
+ @Test
+ public void testWriteProperties() throws Exception {
+ ConfigFile cf = ConfigMgr.DEFAULT.create();
+ cf.put("B/a", "1");
+
+ B b = new B();
+ cf.writeProperties("B", b, false);
+ assertObjectEquals("{a:1}", b);
+
+ cf.put("B/b", "2");
+ try { cf.writeProperties("B", b, false);} catch (ParseException e) {}
+ cf.writeProperties("B", b, true);
+ assertObjectEquals("{a:1}", b);
+ cf.removeString("B/b");
+
+ cf.put("B/c", "2");
+ try { cf.writeProperties("B", b, false);} catch (ParseException e) {}
+ cf.writeProperties("B", b, true);
+ assertObjectEquals("{a:1}", b);
+ cf.removeString("B/c");
+
+ cf.put("B/c2", "2");
+ try { cf.writeProperties("B", b, false);} catch (ParseException e) {}
+ cf.writeProperties("B", b, true);
+ assertObjectEquals("{a:1}", b);
+ cf.removeString("B/c2");
+
+ cf.put("B/d", "2");
+ try { cf.writeProperties("B", b, false);} catch (ParseException e) {}
+ cf.writeProperties("B", b, true);
+ assertObjectEquals("{a:1}", b);
+ cf.removeString("B/d");
+
+ cf.put("B/e", "2");
+ cf.writeProperties("B", b, false);
+ assertObjectEquals("{a:1,e:2}", b);
+
+ cf.put("B/f", "foobar");
+ try {
+ cf.writeProperties("B", b, false, int.class, Integer.class);
+ } catch (ParseException e) {
+ assertTrue(e.getLocalizedMessage().startsWith("Invalid"));
+ }
+ assertObjectEquals("{a:1,e:2}", b);
+
+ cf.removeString("B/f");
+ System.setProperty("X", "3");
+ cf.put("B/a", "$S{X}");
+ cf.put("B/e", "$S{Y,$S{X}}");
+ cf = cf.getResolving();
+ cf.writeProperties("B", b, true);
+ assertObjectEquals("{a:3,e:3}", b);
+
+ System.clearProperty("X");
+ }
+
+ @SuppressWarnings("unused")
+ @Bean(sort=true)
+ public static class B {
+ private int a;
+ private Integer e;
+ public int getA() {
+ return a;
+ }
+ public void setA(int a) {
+ this.a = a;
+ }
+ public static void setB(String b) {
+ throw new RuntimeException("Should not be called.");
+ }
+ protected void setC(String c) {
+ throw new RuntimeException("Should not be called.");
+ }
+ protected static void setC2(String c2) {
+ throw new RuntimeException("Should not be called.");
+ }
+ public void setD(String d, String x) {
+ throw new RuntimeException("Should not be called.");
+ }
+ public Integer getE() {
+ return e;
+ }
+ public void setE(Integer e) {
+ this.e = e;
+ }
+ public String getF() {
+ return null;
+ }
+ public void setF(String f) {
+ throw new RuntimeException("Should not be called.");
+ }
+ }
+
+ //====================================================================================================
+ // Bad input
+ //====================================================================================================
+ @Test
+ public void testBadInput() throws Exception {
+ ConfigFile[] cff = {
+ ConfigMgr.DEFAULT.create().addLines("A", "a1=1", ""),
+ ConfigMgr.DEFAULT.create().addLines("A", "a1=1", "").getResolving()
+ };
+
+ for (ConfigFile cf : cff) {
+ try {
+ cf.load(null);
+ fail();
+ } catch (IllegalArgumentException e) {
+ assertEquals("Field 'r' cannot be null.", e.getLocalizedMessage());
+ }
+ try {
+ cf.getString(null);
+ fail();
+ } catch (IllegalArgumentException e) {
+ assertEquals("Field 'key' cannot be null.", e.getLocalizedMessage());
+ }
+ try {
+ cf.getString(null, null);
+ fail();
+ } catch (IllegalArgumentException e) {
+ assertEquals("Field 'key' cannot be null.", e.getLocalizedMessage());
+ }
+ try {
+ cf.put(null, (Object)null);
+ fail();
+ } catch (IllegalArgumentException e) {
+ assertEquals("Field 'key' cannot be null.", e.getLocalizedMessage());
+ }
+ try {
+ cf.put(null, null, true);
+ fail();
+ } catch (IllegalArgumentException e) {
+ assertEquals("Field 'key' cannot be null.", e.getLocalizedMessage());
+ }
+ try {
+ cf.removeString(null);
+ fail();
+ } catch (IllegalArgumentException e) {
+ assertEquals("Field 'key' cannot be null.", e.getLocalizedMessage());
+ }
+ try {
+ cf.getObject(Object.class, null);
+ fail();
+ } catch (IllegalArgumentException e) {
+ assertEquals("Field 'key' cannot be null.", e.getLocalizedMessage());
+ }
+ try {
+ cf.getObject(null, "");
+ fail();
+ } catch (IllegalArgumentException e) {
+ assertEquals("Field 'c' cannot be null.", e.getLocalizedMessage());
+ }
+ try {
+ cf.getStringArray(null);
+ fail();
+ } catch (IllegalArgumentException e) {
+ assertEquals("Field 'key' cannot be null.", e.getLocalizedMessage());
+ }
+ try {
+ cf.getStringArray(null, null);
+ fail();
+ } catch (IllegalArgumentException e) {
+ assertEquals("Field 'key' cannot be null.", e.getLocalizedMessage());
+ }
+ try {
+ cf.getInt(null);
+ fail();
+ } catch (IllegalArgumentException e) {
+ assertEquals("Field 'key' cannot be null.", e.getLocalizedMessage());
+ }
+ try {
+ cf.getInt(null, -1);
+ fail();
+ } catch (IllegalArgumentException e) {
+ assertEquals("Field 'key' cannot be null.", e.getLocalizedMessage());
+ }
+ try {
+ cf.getBoolean(null);
+ fail();
+ } catch (IllegalArgumentException e) {
+ assertEquals("Field 'key' cannot be null.", e.getLocalizedMessage());
+ }
+ try {
+ cf.getBoolean(null, true);
+ fail();
+ } catch (IllegalArgumentException e) {
+ assertEquals("Field 'key' cannot be null.", e.getLocalizedMessage());
+ }
+ try {
+ cf.put(null, (String)null);
+ fail();
+ } catch (IllegalArgumentException e) {
+ assertEquals("Field 'key' cannot be null.", e.getLocalizedMessage());
+ }
+ try {
+ cf.put(null, null, true);
+ fail();
+ } catch (IllegalArgumentException e) {
+ assertEquals("Field 'key' cannot be null.", e.getLocalizedMessage());
+ }
+ try {
+ cf.writeProperties(null, null, true);
+ fail();
+ } catch (IllegalArgumentException e) {
+ assertEquals("Field 'bean' cannot be null.", e.getLocalizedMessage());
+ }
+ try {
+ cf.getSectionAsBean(null, null);
+ fail();
+ } catch (IllegalArgumentException e) {
+ assertEquals("Field 'c' cannot be null.", e.getLocalizedMessage());
+ }
+ try {
+ cf.getSectionAsBean(null, null, true);
+ fail();
+ } catch (IllegalArgumentException e) {
+ assertEquals("Field 'c' cannot be null.", e.getLocalizedMessage());
+ }
+ try {
+ cf.containsNonEmptyValue(null);
+ fail();
+ } catch (IllegalArgumentException e) {
+ assertEquals("Field 'key' cannot be null.", e.getLocalizedMessage());
+ }
+ try {
+ cf.isEncoded(null);
+ fail();
+ } catch (IllegalArgumentException e) {
+ assertEquals("Field 'key' cannot be null.", e.getLocalizedMessage());
+ }
+ try {
+ cf.addListener(null);
+ fail();
+ } catch (IllegalArgumentException e) {
+ assertEquals("Field 'listener' cannot be null.", e.getLocalizedMessage());
+ }
+ try {
+ cf.merge(null);
+ fail();
+ } catch (IllegalArgumentException e) {
+ assertEquals("Field 'cf' cannot be null.", e.getLocalizedMessage());
+ }
+ try {
+ cf.getResolving((VarResolver)null);
+ fail();
+ } catch (IllegalArgumentException e) {
+ assertEquals("Field 'vr' cannot be null.", e.getLocalizedMessage());
+ }
+ }
+ }
+
+ //====================================================================================================
+ // Config to and from JSON
+ //====================================================================================================
+ @Test
+ public void testSerializedAsJson() throws Exception {
+ ConfigFile cf = ConfigMgr.DEFAULT.create();
+ cf.put("a", "1");
+ cf.put("B/a", "2");
+
+ String json = JsonSerializer.DEFAULT_LAX.toString(cf);
+ assertEquals("{'default':{a:'1'},B:{a:'2'}}", json);
+
+ cf = JsonParser.DEFAULT.parse(json, ConfigFileImpl.class);
+ assertObjectEquals("{'default':{a:'1'},B:{a:'2'}}", cf);
+
+ }
+
+ //====================================================================================================
+ // Test resolving with override
+ //====================================================================================================
+ @Test
+ public void testResolvingWithOverride() throws Exception {
+ ConfigFile cf = ConfigMgr.DEFAULT.create();
+ cf.put("a", "$A{X}");
+ cf.put("b", "$B{X}");
+ cf.put("c", "$A{$B{X}}");
+ cf.put("d", "$B{$A{X}}");
+ cf.put("e", "$D{X}");
+
+ VarResolver vr = new VarResolver().addVars(ALVar.class, BLVar.class);
+
+ cf = cf.getResolving(vr);
+
+ assertEquals("aXa", cf.getString("a"));
+ assertEquals("bXb", cf.getString("b"));
+ assertEquals("abXba", cf.getString("c"));
+ assertEquals("baXab", cf.getString("d"));
+ assertEquals("$D{X}", cf.getString("e"));
+
+ // Create new resolver that addx $C and overrides $A
+ VarResolver vr2 = vr.clone().addVars(AUVar.class, DUVar.class);
+
+ // true == augment by adding existing as parent to the new resolver
+ cf = cf.getResolving(vr2);
+ assertEquals("AXA", cf.getString("a"));
+ assertEquals("bXb", cf.getString("b"));
+ assertEquals("AbXbA", cf.getString("c"));
+ assertEquals("bAXAb", cf.getString("d"));
+ assertEquals("DXD", cf.getString("e"));
+ }
+
+ public static class ALVar extends SimpleVar {
+ public ALVar() {
+ super("A");
+ }
+ @Override
+ public String resolve(VarResolverSession session, String key) {
+ return 'a' + key + 'a';
+ }
+ }
+
+ public static class AUVar extends SimpleVar {
+ public AUVar() {
+ super("A");
+ }
+ @Override
+ public String resolve(VarResolverSession session, String key) {
+ return 'A' + key + 'A';
+ }
+ }
+
+ public static class BLVar extends SimpleVar {
+ public BLVar() {
+ super("B");
+ }
+ @Override
+ public String resolve(VarResolverSession session, String key) {
+ return 'b' + key + 'b';
+ }
+ }
+
+ public static class DUVar extends SimpleVar {
+ public DUVar() {
+ super("D");
+ }
+ @Override
+ public String resolve(VarResolverSession session, String key) {
+ return 'D' + key + 'D';
+ }
+ }
+
+ //====================================================================================================
+ // Test multiline values.
+ //====================================================================================================
+ @Test
+ public void testMultilineValues() throws Exception {
+ File f = getFreshFile();
+
+ ConfigFile cf = ConfigMgr.DEFAULT.create(f);
+ cf.put("a", "a,\nb,\nc");
+ cf.put("A/a", "a,\nb,\nc");
+
+ assertTextEquals("a = a,|\tb,|\tc|[A]|a = a,|\tb,|\tc|", cf);
+ cf.save();
+ assertTextEquals("a = a,|\tb,|\tc|[A]|a = a,|\tb,|\tc|", IOUtils.read(f));
+
+ cf.load();
+ assertEquals("a,\nb,\nc", cf.getString("a"));
+ assertEquals("a,\nb,\nc", cf.getString("A/a"));
+
+ assertObjectEquals("['a','b','c']", cf.getStringArray("a", null));
+ assertObjectEquals("['a','b','c']", cf.getStringArray("A/a", null));
+ }
+
+ //====================================================================================================
+ // Test special character encoding.
+ //====================================================================================================
+ @Test
+ public void testSpecialCharacterEncoding() throws Exception {
+ File f = getFreshFile();
+
+ ConfigFile cf = ConfigMgr.DEFAULT.create(f);
+ cf.put("a", "a,#b,=c");
+ cf.put("A/a", "a,#b,=c");
+
+ assertTextEquals("a = a,\\u0023b,\\u003Dc|[A]|a = a,\\u0023b,\\u003Dc|", cf);
+ cf.save();
+ assertTextEquals("a = a,\\u0023b,\\u003Dc|[A]|a = a,\\u0023b,\\u003Dc|", IOUtils.read(f));
+
+ cf.load();
+ assertEquals("a,#b,=c", cf.getString("a"));
+ assertEquals("a,#b,=c", cf.getString("A/a"));
+ }
+}
\ No newline at end of file
[21/44] incubator-juneau git commit: Rename CT_* testcases.
Posted by ja...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/dto/cognos/CognosXmlTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/dto/cognos/CognosXmlTest.java b/org.apache.juneau/src/test/java/org/apache/juneau/dto/cognos/CognosXmlTest.java
new file mode 100755
index 0000000..55ad7aa
--- /dev/null
+++ b/org.apache.juneau/src/test/java/org/apache/juneau/dto/cognos/CognosXmlTest.java
@@ -0,0 +1,106 @@
+/***************************************************************************************************************************
+ * 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.juneau.dto.cognos;
+
+import static org.apache.juneau.TestUtils.*;
+import static org.apache.juneau.serializer.SerializerContext.*;
+import static org.apache.juneau.xml.XmlSerializerContext.*;
+import static org.junit.Assert.*;
+
+import java.util.*;
+
+import org.apache.juneau.*;
+import org.apache.juneau.xml.*;
+import org.junit.*;
+
+public class CognosXmlTest {
+
+ //====================================================================================================
+ // test
+ //====================================================================================================
+ @Test
+ public void test() throws Exception {
+ String expected = ""
+ + "<dataset xmlns='http://developer.cognos.com/schemas/xmldata/1/' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'>\n"
+ + " <metadata>\n"
+ + " <item name='asOfDate' type='xs:string' length='12'/>\n"
+ + " <item name='rateOfReturn' type='xs:double'/>\n"
+ + " <item name='famAcctIndex' type='xs:string' length='3'/>\n"
+ + " <item name='rowID' type='xs:string' length='1'/>\n"
+ + " <item name='brM' type='xs:string' length='1'/>\n"
+ + " <item name='productLineCode' type='xs:int'/>\n"
+ + " </metadata>\n"
+ + " <data>\n"
+ + " <row>\n"
+ + " <value>Apr 26, 2002</value>\n"
+ + " <value>0.21006642</value>\n"
+ + " <value>JA1</value>\n"
+ + " <value>F</value>\n"
+ + " <value>B</value>\n"
+ + " <value>1</value>\n"
+ + " </row>\n"
+ + " <row>\n"
+ + " <value>Apr 27, 2002</value>\n"
+ + " <value>0.1111111</value>\n"
+ + " <value>BBB</value>\n"
+ + " <value>G</value>\n"
+ + " <value>B</value>\n"
+ + " <value>2</value>\n"
+ + " </row>\n"
+ + " </data>\n"
+ + "</dataset>\n";
+
+ List<Object> rows = new LinkedList<Object>();
+ rows.add(new ObjectMap("{asOfDate:'Apr 26, 2002',rateOfReturn:0.210066429,famAcctIndex:'JA1',rowID:'F',brM:'B',productLineCode:1}"));
+ rows.add(new Item("Apr 27, 2002", 0.1111111, "BBB", "G", "B", 2));
+
+ Column[] c = {
+ new Column("asOfDate", "xs:string", 12),
+ new Column("rateOfReturn", "xs:double"),
+ new Column("famAcctIndex", "xs:string", 3),
+ new Column("rowID", "xs:string", 1),
+ new Column("brM", "xs:string", 1),
+ new Column("productLineCode", "xs:int")
+ };
+
+ XmlSerializer s = new XmlSerializer().setProperty(SERIALIZER_useIndentation, true).setProperty(SERIALIZER_quoteChar, '\'').setProperty(XML_defaultNamespaceUri, "cognos");
+
+ DataSet ds = new DataSet(c, rows, BeanContext.DEFAULT);
+
+ String out = s.serialize(ds);
+
+ assertEquals(expected, out);
+
+ // Make sure we can parse it back into a POJO.
+ DataSet ds2 = XmlParser.DEFAULT.parse(out, DataSet.class);
+ assertEqualObjects(ds, ds2);
+ }
+
+ public static class Item {
+ public String asOfDate;
+ public double rateOfReturn;
+ public String famAcctIndex;
+ public String rowID;
+ public String brM;
+ public int productLineCode;
+
+ public Item(String asOfDate, double rateOfReturn, String famAcctIndex, String rowID, String brM, int productLineCode) {
+ this.asOfDate = asOfDate;
+ this.rateOfReturn = rateOfReturn;
+ this.famAcctIndex = famAcctIndex;
+ this.rowID = rowID;
+ this.brM = brM;
+ this.productLineCode = productLineCode;
+ }
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/dto/jsonschema/CT_JsonSchema.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/dto/jsonschema/CT_JsonSchema.java b/org.apache.juneau/src/test/java/org/apache/juneau/dto/jsonschema/CT_JsonSchema.java
deleted file mode 100755
index 8145c53..0000000
--- a/org.apache.juneau/src/test/java/org/apache/juneau/dto/jsonschema/CT_JsonSchema.java
+++ /dev/null
@@ -1,103 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.dto.jsonschema;
-
-import static org.apache.juneau.TestUtils.*;
-import static org.junit.Assert.*;
-
-import java.net.*;
-
-import org.apache.juneau.json.*;
-import org.junit.*;
-
-
-public class CT_JsonSchema {
-
- @Test
- public void testSchema1() throws Exception {
- JsonSerializer s = JsonSerializer.DEFAULT_LAX_READABLE;
- JsonParser p = JsonParser.DEFAULT;
- String r;
- Schema t, t2;
-
- t = getTest1();
- r = s.serialize(t);
- String expected = readFile(getClass().getResource("/dto/jsonschema/test1.json").getPath());
- assertEquals(expected, r);
- t2 = p.parse(r, Schema.class);
- assertEqualObjects(t, t2);
- }
-
- @Test
- public void testSchema2() throws Exception {
- JsonSerializer s = JsonSerializer.DEFAULT_LAX_READABLE;
- JsonParser p = JsonParser.DEFAULT;
- String r;
- Schema t, t2;
-
- t = getTest2();
- r = s.serialize(t);
- String expected = readFile(getClass().getResource("/dto/jsonschema/test2.json").getPath());
- assertEquals(expected, r);
- t2 = p.parse(r, Schema.class);
- assertEqualObjects(t, t2);
- }
-
- /** Bean with simple values for each property */
- public static Schema getTest1() {
- return new Schema()
- .setId("http://id")
- .setSchemaVersionUri("http://schemaVersionUri")
- .setTitle("title")
- .setDescription("description")
- .setType(JsonType.NUMBER)
- .addDefinition("definition", new SchemaRef("http://definition"))
- .addProperties(new SchemaProperty("property", JsonType.NUMBER))
- .addPatternProperties(new SchemaProperty("/pattern/", JsonType.NUMBER))
- .addDependency("dependency", new SchemaRef("http://dependency"))
- .addItems(new Schema().setType(JsonType.NUMBER))
- .setMultipleOf(1)
- .setMaximum(2)
- .setExclusiveMaximum(true)
- .setMinimum(3)
- .setExclusiveMinimum(true)
- .setMaxLength(4)
- .setMinLength(5)
- .setPattern("/pattern/")
- .addAdditionalItems(new SchemaProperty("additionalItem", JsonType.NUMBER))
- .setMaxItems(6)
- .setMinItems(7)
- .setUniqueItems(true)
- .setMaxProperties(8)
- .setMinProperties(9)
- .addRequired("required")
- .setAdditionalProperties(new SchemaRef("http://additionalProperty"))
- .addEnum("enum")
- .addAllOf(new SchemaRef("http://allOf"))
- .addAnyOf(new SchemaRef("http://anyOf"))
- .addOneOf(new SchemaRef("http://oneOf"))
- .setNot(new SchemaRef("http://not"));
- }
-
- /** Bean with other possible property value types not covered in test1 */
- public static Schema getTest2() {
- return new Schema()
- .setId(URI.create("http://id"))
- .setSchemaVersionUri(URI.create("http://schemaVersionUri"))
- .setType(new JsonTypeArray(JsonType.STRING, JsonType.NUMBER))
- .addDefinition("definition", new Schema().setId("http://definition"))
- .setItems(new SchemaArray(new SchemaRef("http://items")))
- .setAdditionalItems(Boolean.TRUE)
- .setAdditionalProperties(Boolean.TRUE);
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/dto/jsonschema/JsonSchemaTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/dto/jsonschema/JsonSchemaTest.java b/org.apache.juneau/src/test/java/org/apache/juneau/dto/jsonschema/JsonSchemaTest.java
new file mode 100755
index 0000000..c889af3
--- /dev/null
+++ b/org.apache.juneau/src/test/java/org/apache/juneau/dto/jsonschema/JsonSchemaTest.java
@@ -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.juneau.dto.jsonschema;
+
+import static org.apache.juneau.TestUtils.*;
+import static org.junit.Assert.*;
+
+import java.net.*;
+
+import org.apache.juneau.json.*;
+import org.junit.*;
+
+
+public class JsonSchemaTest {
+
+ @Test
+ public void testSchema1() throws Exception {
+ JsonSerializer s = JsonSerializer.DEFAULT_LAX_READABLE;
+ JsonParser p = JsonParser.DEFAULT;
+ String r;
+ Schema t, t2;
+
+ t = getTest1();
+ r = s.serialize(t);
+ String expected = readFile(getClass().getResource("/dto/jsonschema/test1.json").getPath());
+ assertEquals(expected, r);
+ t2 = p.parse(r, Schema.class);
+ assertEqualObjects(t, t2);
+ }
+
+ @Test
+ public void testSchema2() throws Exception {
+ JsonSerializer s = JsonSerializer.DEFAULT_LAX_READABLE;
+ JsonParser p = JsonParser.DEFAULT;
+ String r;
+ Schema t, t2;
+
+ t = getTest2();
+ r = s.serialize(t);
+ String expected = readFile(getClass().getResource("/dto/jsonschema/test2.json").getPath());
+ assertEquals(expected, r);
+ t2 = p.parse(r, Schema.class);
+ assertEqualObjects(t, t2);
+ }
+
+ /** Bean with simple values for each property */
+ public static Schema getTest1() {
+ return new Schema()
+ .setId("http://id")
+ .setSchemaVersionUri("http://schemaVersionUri")
+ .setTitle("title")
+ .setDescription("description")
+ .setType(JsonType.NUMBER)
+ .addDefinition("definition", new SchemaRef("http://definition"))
+ .addProperties(new SchemaProperty("property", JsonType.NUMBER))
+ .addPatternProperties(new SchemaProperty("/pattern/", JsonType.NUMBER))
+ .addDependency("dependency", new SchemaRef("http://dependency"))
+ .addItems(new Schema().setType(JsonType.NUMBER))
+ .setMultipleOf(1)
+ .setMaximum(2)
+ .setExclusiveMaximum(true)
+ .setMinimum(3)
+ .setExclusiveMinimum(true)
+ .setMaxLength(4)
+ .setMinLength(5)
+ .setPattern("/pattern/")
+ .addAdditionalItems(new SchemaProperty("additionalItem", JsonType.NUMBER))
+ .setMaxItems(6)
+ .setMinItems(7)
+ .setUniqueItems(true)
+ .setMaxProperties(8)
+ .setMinProperties(9)
+ .addRequired("required")
+ .setAdditionalProperties(new SchemaRef("http://additionalProperty"))
+ .addEnum("enum")
+ .addAllOf(new SchemaRef("http://allOf"))
+ .addAnyOf(new SchemaRef("http://anyOf"))
+ .addOneOf(new SchemaRef("http://oneOf"))
+ .setNot(new SchemaRef("http://not"));
+ }
+
+ /** Bean with other possible property value types not covered in test1 */
+ public static Schema getTest2() {
+ return new Schema()
+ .setId(URI.create("http://id"))
+ .setSchemaVersionUri(URI.create("http://schemaVersionUri"))
+ .setType(new JsonTypeArray(JsonType.STRING, JsonType.NUMBER))
+ .addDefinition("definition", new Schema().setId("http://definition"))
+ .setItems(new SchemaArray(new SchemaRef("http://items")))
+ .setAdditionalItems(Boolean.TRUE)
+ .setAdditionalProperties(Boolean.TRUE);
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/html/CT_Common.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/html/CT_Common.java b/org.apache.juneau/src/test/java/org/apache/juneau/html/CT_Common.java
deleted file mode 100755
index d6d9197..0000000
--- a/org.apache.juneau/src/test/java/org/apache/juneau/html/CT_Common.java
+++ /dev/null
@@ -1,564 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.html;
-
-import static org.apache.juneau.BeanContext.*;
-import static org.apache.juneau.TestUtils.*;
-import static org.apache.juneau.html.HtmlSerializerContext.*;
-import static org.apache.juneau.serializer.SerializerContext.*;
-import static org.junit.Assert.*;
-
-import java.net.*;
-import java.net.URI;
-import java.util.*;
-
-import org.apache.juneau.*;
-import org.apache.juneau.annotation.*;
-import org.apache.juneau.serializer.*;
-import org.apache.juneau.testbeans.*;
-import org.apache.juneau.xml.*;
-import org.junit.*;
-
-@SuppressWarnings("serial")
-public class CT_Common {
-
- //====================================================================================================
- // Trim nulls from beans
- //====================================================================================================
- @Test
- public void testTrimNullsFromBeans() throws Exception {
- HtmlSerializer s = new HtmlSerializer.Sq();
- HtmlParser p = HtmlParser.DEFAULT;
- A t1 = A.create(), t2;
-
- s.setProperty(SERIALIZER_trimNullProperties, false);
- String r = s.serialize(t1);
- assertEquals("<table type='object'><tr><th><string>key</string></th><th><string>value</string></th></tr><tr><td><string>s1</string></td><td><null/></td></tr><tr><td><string>s2</string></td><td><string>s2</string></td></tr></table>", r);
- t2 = p.parse(r, A.class);
- assertEqualObjects(t1, t2);
-
- s.setProperty(SERIALIZER_trimNullProperties, true);
- r = s.serialize(t1);
- assertEquals("<table type='object'><tr><th><string>key</string></th><th><string>value</string></th></tr><tr><td><string>s2</string></td><td><string>s2</string></td></tr></table>", r);
- t2 = p.parse(r, A.class);
- assertEqualObjects(t1, t2);
- }
-
- public static class A {
- public String s1, s2;
-
- public static A create() {
- A t = new A();
- t.s2 = "s2";
- return t;
- }
- }
-
- //====================================================================================================
- // Trim empty maps
- //====================================================================================================
- @Test
- public void testTrimEmptyMaps() throws Exception {
- HtmlSerializer s = new HtmlSerializer.Sq();
- HtmlParser p = HtmlParser.DEFAULT;
- B t1 = B.create(), t2;
- String r;
-
- s.setProperty(SERIALIZER_trimEmptyMaps, false);
- r = s.serialize(t1);
- assertEquals("<table type='object'><tr><th><string>key</string></th><th><string>value</string></th></tr><tr><td><string>f1</string></td><td><table type='object'><tr><th><string>key</string></th><th><string>value</string></th></tr></table></td></tr><tr><td><string>f2</string></td><td><table type='object'><tr><th><string>key</string></th><th><string>value</string></th></tr><tr><td><string>f2a</string></td><td><null/></td></tr><tr><td><string>f2b</string></td><td><table type='object'><tr><th><string>key</string></th><th><string>value</string></th></tr><tr><td><string>s2</string></td><td><string>s2</string></td></tr></table></td></tr></table></td></tr></table>", r);
- t2 = p.parse(r, B.class);
- assertEqualObjects(t1, t2);
-
- s.setProperty(SERIALIZER_trimEmptyMaps, true);
- r = s.serialize(t1);
- assertEquals("<table type='object'><tr><th><string>key</string></th><th><string>value</string></th></tr><tr><td><string>f2</string></td><td><table type='object'><tr><th><string>key</string></th><th><string>value</string></th></tr><tr><td><string>f2a</string></td><td><null/></td></tr><tr><td><string>f2b</string></td><td><table type='object'><tr><th><string>key</string></th><th><string>value</string></th></tr><tr><td><string>s2</string></td><td><string>s2</string></td></tr></table></td></tr></table></td></tr></table>", r);
- t2 = p.parse(r, B.class);
- assertNull(t2.f1);
- }
-
- public static class B {
- public TreeMap<String,A> f1, f2;
-
- public static B create() {
- B t = new B();
- t.f1 = new TreeMap<String,A>();
- t.f2 = new TreeMap<String,A>(){{put("f2a",null);put("f2b",A.create());}};
- return t;
- }
- }
-
- //====================================================================================================
- // Trim empty lists
- //====================================================================================================
- @Test
- public void testTrimEmptyLists() throws Exception {
- HtmlSerializer s = new HtmlSerializer.Sq();
- HtmlParser p = HtmlParser.DEFAULT;
- C t1 = C.create(), t2;
- String r;
-
- s.setProperty(SERIALIZER_trimEmptyLists, false);
- r = s.serialize(t1);
- assertEquals("<table type='object'><tr><th><string>key</string></th><th><string>value</string></th></tr><tr><td><string>f1</string></td><td><ul></ul></td></tr><tr><td><string>f2</string></td><td><table type='array'><tr><th>s1</th><th>s2</th></tr><tr><null/></tr><tr><td><null/></td><td><string>s2</string></td></tr></table></td></tr></table>", r);
- t2 = p.parse(r, C.class);
- assertEqualObjects(t1, t2);
-
- s.setProperty(SERIALIZER_trimEmptyLists, true);
- r = s.serialize(t1);
- assertEquals("<table type='object'><tr><th><string>key</string></th><th><string>value</string></th></tr><tr><td><string>f2</string></td><td><table type='array'><tr><th>s1</th><th>s2</th></tr><tr><null/></tr><tr><td><null/></td><td><string>s2</string></td></tr></table></td></tr></table>", r);
- t2 = p.parse(r, C.class);
- assertNull(t2.f1);
- }
-
- public static class C {
- public List<A> f1, f2;
-
- public static C create() {
- C t = new C();
- t.f1 = new LinkedList<A>();
- t.f2 = new LinkedList<A>(){{add(null);add(A.create());}};
- return t;
- }
- }
-
- //====================================================================================================
- // Trim empty arrays
- //====================================================================================================
- @Test
- public void testTrimEmptyArrays() throws Exception {
- HtmlSerializer s = new HtmlSerializer.Sq();
- HtmlParser p = HtmlParser.DEFAULT;
- D t1 = D.create(), t2;
- String r;
-
- s.setProperty(SERIALIZER_trimEmptyLists, false);
- r = s.serialize(t1);
- assertEquals("<table type='object'><tr><th><string>key</string></th><th><string>value</string></th></tr><tr><td><string>f1</string></td><td><ul></ul></td></tr><tr><td><string>f2</string></td><td><table type='array'><tr><th>s1</th><th>s2</th></tr><tr><null/></tr><tr><td><null/></td><td><string>s2</string></td></tr></table></td></tr></table>", r);
- t2 = p.parse(r, D.class);
- assertEqualObjects(t1, t2);
-
- s.setProperty(SERIALIZER_trimEmptyLists, true);
- r = s.serialize(t1);
- assertEquals("<table type='object'><tr><th><string>key</string></th><th><string>value</string></th></tr><tr><td><string>f2</string></td><td><table type='array'><tr><th>s1</th><th>s2</th></tr><tr><null/></tr><tr><td><null/></td><td><string>s2</string></td></tr></table></td></tr></table>", r);
- t2 = p.parse(r, D.class);
- assertNull(t2.f1);
- }
-
- public static class D {
- public A[] f1, f2;
-
- public static D create() {
- D t = new D();
- t.f1 = new A[]{};
- t.f2 = new A[]{null, A.create()};
- return t;
- }
- }
-
- //====================================================================================================
- // @BeanProperty.properties annotation.
- //====================================================================================================
- @Test
- public void testBeanPropertyProperties() throws Exception {
- HtmlSerializer s = HtmlSerializer.DEFAULT_SQ;
- E1 t = new E1();
- String r;
-
- r = s.serialize(t);
- assertEquals("<table type='object'><tr><th><string>key</string></th><th><string>value</string></th></tr><tr><td><string>x1</string></td><td><table type='object'><tr><th><string>key</string></th><th><string>value</string></th></tr><tr><td><string>f1</string></td><td><number>1</number></td></tr></table></td></tr><tr><td><string>x2</string></td><td><table type='object'><tr><th><string>key</string></th><th><string>value</string></th></tr><tr><td><string>f1</string></td><td><number>1</number></td></tr></table></td></tr><tr><td><string>x3</string></td><td><table type='array'><tr><th>f1</th></tr><tr><td><number>1</number></td></tr></table></td></tr><tr><td><string>x4</string></td><td><table type='array'><tr><th>f1</th></tr><tr><td><number>1</number></td></tr></table></td></tr><tr><td><string>x5</string></td><td><table type='array'><tr><th>f1</th></tr><tr><td><number>1</number></td></tr></table></td></tr><tr><td><string>x6</string></td><td><table type='array'><tr><th>f1</th></tr><tr><td><
number>1</number></td></tr></table></td></tr></table>", r);
- r = s.getSchemaSerializer().serialize(new E1());
- assertTrue(r.indexOf("f2") == -1);
- }
-
- public static class E1 {
- @BeanProperty(properties={"f1"}) public E2 x1 = new E2();
- @BeanProperty(properties={"f1"}) public Map<String,Integer> x2 = new LinkedHashMap<String,Integer>() {{
- put("f1",1); put("f2",2);
- }};
- @BeanProperty(properties={"f1"}) public E2[] x3 = {new E2()};
- @BeanProperty(properties={"f1"}) public List<E2> x4 = new LinkedList<E2>() {{
- add(new E2());
- }};
- @BeanProperty(properties={"f1"}) public ObjectMap[] x5 = {new ObjectMap().append("f1",1).append("f2",2)};
- @BeanProperty(properties={"f1"}) public List<ObjectMap> x6 = new LinkedList<ObjectMap>() {{
- add(new ObjectMap().append("f1",1).append("f2",2));
- }};
- }
-
- public static class E2 {
- public int f1 = 1;
- public int f2 = 2;
- }
-
- //====================================================================================================
- // @BeanProperty.properties annotation on list of beans.
- //====================================================================================================
- @Test
- public void testBeanPropertyPropertiesOnListOfBeans() throws Exception {
- HtmlSerializer s = HtmlSerializer.DEFAULT_SQ;
- List<F> l = new LinkedList<F>();
- F t = new F();
- t.x1.add(new F());
- l.add(t);
- String html = s.serialize(l);
- assertEquals("<table type='array'><tr><th>x1</th><th>x2</th></tr><tr><td><table type='array'><tr><th>x2</th></tr><tr><td><number>2</number></td></tr></table></td><td><number>2</number></td></tr></table>", html);
- }
-
- public static class F {
- @BeanProperty(properties={"x2"}) public List<F> x1 = new LinkedList<F>();
- public int x2 = 2;
- }
-
- //====================================================================================================
- // Test that URLs and URIs are serialized and parsed correctly.
- //====================================================================================================
- @Test
- public void testURIAttr() throws Exception {
- HtmlSerializer s = HtmlSerializer.DEFAULT_SQ;
- HtmlParser p = HtmlParser.DEFAULT;
-
- G t = new G();
- t.uri = new URI("http://uri");
- t.f1 = new URI("http://f1");
- t.f2 = new URL("http://f2");
-
- String html = s.serialize(t);
- t = p.parse(html, G.class);
- assertEquals("http://uri", t.uri.toString());
- assertEquals("http://f1", t.f1.toString());
- assertEquals("http://f2", t.f2.toString());
- }
-
- public static class G {
- @BeanProperty(beanUri=true) public URI uri;
- public URI f1;
- public URL f2;
- }
-
- //====================================================================================================
- // Test URIs with URI_CONTEXT and URI_AUTHORITY
- //====================================================================================================
- @Test
- public void testUris() throws Exception {
- HtmlSerializer s = new HtmlSerializer.Sq().setProperty(HTML_uriAnchorText, PROPERTY_NAME).setProperty(SERIALIZER_useIndentation, false);
- TestURI t = new TestURI();
- String r;
- String expected;
-
- s.setProperty(SERIALIZER_relativeUriBase, null);
- r = strip(s.serialize(t));
- expected = ""
- +"\n[f0]=<a href='f0/x0'>f0</a>"
- +"\n[f1]=<a href='f1/x1'>f1</a>"
- +"\n[f2]=<a href='/f2/x2'>f2</a>"
- +"\n[f3]=<a href='http://www.ibm.com/f3/x3'>f3</a>"
- +"\n[f4]=<a href='f4/x4'>f4</a>"
- +"\n[f5]=<a href='/f5/x5'>f5</a>"
- +"\n[f6]=<a href='http://www.ibm.com/f6/x6'>f6</a>"
- +"\n[f7]=<a href='http://www.ibm.com/f7/x7'>f7</a>"
- +"\n[f8]=<a href='f8/x8'>f8</a>"
- +"\n[f9]=<a href='f9/x9'>f9</a>"
- +"\n[fa]=<a href='http://www.ibm.com/fa/xa#MY_LABEL'>fa</a>"
- +"\n[fb]=<a href='http://www.ibm.com/fb/xb?label=MY_LABEL&foo=bar'>MY_LABEL</a>"
- +"\n[fc]=<a href='http://www.ibm.com/fc/xc?foo=bar&label=MY_LABEL'>MY_LABEL</a>"
- +"\n[fd]=<a href='http://www.ibm.com/fd/xd?label2=MY_LABEL&foo=bar'>fd</a>"
- +"\n[fe]=<a href='http://www.ibm.com/fe/xe?foo=bar&label2=MY_LABEL'>fe</a>"
- ;
- assertEquals(expected, r);
-
- s.setProperty(SERIALIZER_relativeUriBase, ""); // Same as null.
- r = strip(s.serialize(t));
- expected = ""
- +"\n[f0]=<a href='f0/x0'>f0</a>"
- +"\n[f1]=<a href='f1/x1'>f1</a>"
- +"\n[f2]=<a href='/f2/x2'>f2</a>"
- +"\n[f3]=<a href='http://www.ibm.com/f3/x3'>f3</a>"
- +"\n[f4]=<a href='f4/x4'>f4</a>"
- +"\n[f5]=<a href='/f5/x5'>f5</a>"
- +"\n[f6]=<a href='http://www.ibm.com/f6/x6'>f6</a>"
- +"\n[f7]=<a href='http://www.ibm.com/f7/x7'>f7</a>"
- +"\n[f8]=<a href='f8/x8'>f8</a>"
- +"\n[f9]=<a href='f9/x9'>f9</a>"
- +"\n[fa]=<a href='http://www.ibm.com/fa/xa#MY_LABEL'>fa</a>"
- +"\n[fb]=<a href='http://www.ibm.com/fb/xb?label=MY_LABEL&foo=bar'>MY_LABEL</a>"
- +"\n[fc]=<a href='http://www.ibm.com/fc/xc?foo=bar&label=MY_LABEL'>MY_LABEL</a>"
- +"\n[fd]=<a href='http://www.ibm.com/fd/xd?label2=MY_LABEL&foo=bar'>fd</a>"
- +"\n[fe]=<a href='http://www.ibm.com/fe/xe?foo=bar&label2=MY_LABEL'>fe</a>"
- ;
- assertEquals(expected, r);
-
- s.setProperty(SERIALIZER_relativeUriBase, "/cr");
- r = strip(s.serialize(t));
- expected = ""
- +"\n[f0]=<a href='/cr/f0/x0'>f0</a>"
- +"\n[f1]=<a href='/cr/f1/x1'>f1</a>"
- +"\n[f2]=<a href='/f2/x2'>f2</a>"
- +"\n[f3]=<a href='http://www.ibm.com/f3/x3'>f3</a>"
- +"\n[f4]=<a href='/cr/f4/x4'>f4</a>"
- +"\n[f5]=<a href='/f5/x5'>f5</a>"
- +"\n[f6]=<a href='http://www.ibm.com/f6/x6'>f6</a>"
- +"\n[f7]=<a href='http://www.ibm.com/f7/x7'>f7</a>"
- +"\n[f8]=<a href='/cr/f8/x8'>f8</a>"
- +"\n[f9]=<a href='/cr/f9/x9'>f9</a>"
- +"\n[fa]=<a href='http://www.ibm.com/fa/xa#MY_LABEL'>fa</a>"
- +"\n[fb]=<a href='http://www.ibm.com/fb/xb?label=MY_LABEL&foo=bar'>MY_LABEL</a>"
- +"\n[fc]=<a href='http://www.ibm.com/fc/xc?foo=bar&label=MY_LABEL'>MY_LABEL</a>"
- +"\n[fd]=<a href='http://www.ibm.com/fd/xd?label2=MY_LABEL&foo=bar'>fd</a>"
- +"\n[fe]=<a href='http://www.ibm.com/fe/xe?foo=bar&label2=MY_LABEL'>fe</a>"
- ;
- assertEquals(expected, r);
-
- s.setProperty(SERIALIZER_relativeUriBase, "/cr/"); // Same as above
- r = strip(s.serialize(t));
- expected = ""
- +"\n[f0]=<a href='/cr/f0/x0'>f0</a>"
- +"\n[f1]=<a href='/cr/f1/x1'>f1</a>"
- +"\n[f2]=<a href='/f2/x2'>f2</a>"
- +"\n[f3]=<a href='http://www.ibm.com/f3/x3'>f3</a>"
- +"\n[f4]=<a href='/cr/f4/x4'>f4</a>"
- +"\n[f5]=<a href='/f5/x5'>f5</a>"
- +"\n[f6]=<a href='http://www.ibm.com/f6/x6'>f6</a>"
- +"\n[f7]=<a href='http://www.ibm.com/f7/x7'>f7</a>"
- +"\n[f8]=<a href='/cr/f8/x8'>f8</a>"
- +"\n[f9]=<a href='/cr/f9/x9'>f9</a>"
- +"\n[fa]=<a href='http://www.ibm.com/fa/xa#MY_LABEL'>fa</a>"
- +"\n[fb]=<a href='http://www.ibm.com/fb/xb?label=MY_LABEL&foo=bar'>MY_LABEL</a>"
- +"\n[fc]=<a href='http://www.ibm.com/fc/xc?foo=bar&label=MY_LABEL'>MY_LABEL</a>"
- +"\n[fd]=<a href='http://www.ibm.com/fd/xd?label2=MY_LABEL&foo=bar'>fd</a>"
- +"\n[fe]=<a href='http://www.ibm.com/fe/xe?foo=bar&label2=MY_LABEL'>fe</a>"
- ;
- assertEquals(expected, r);
-
- s.setProperty(SERIALIZER_relativeUriBase, "/");
- r = strip(s.serialize(t));
- expected = ""
- +"\n[f0]=<a href='/f0/x0'>f0</a>"
- +"\n[f1]=<a href='/f1/x1'>f1</a>"
- +"\n[f2]=<a href='/f2/x2'>f2</a>"
- +"\n[f3]=<a href='http://www.ibm.com/f3/x3'>f3</a>"
- +"\n[f4]=<a href='/f4/x4'>f4</a>"
- +"\n[f5]=<a href='/f5/x5'>f5</a>"
- +"\n[f6]=<a href='http://www.ibm.com/f6/x6'>f6</a>"
- +"\n[f7]=<a href='http://www.ibm.com/f7/x7'>f7</a>"
- +"\n[f8]=<a href='/f8/x8'>f8</a>"
- +"\n[f9]=<a href='/f9/x9'>f9</a>"
- +"\n[fa]=<a href='http://www.ibm.com/fa/xa#MY_LABEL'>fa</a>"
- +"\n[fb]=<a href='http://www.ibm.com/fb/xb?label=MY_LABEL&foo=bar'>MY_LABEL</a>"
- +"\n[fc]=<a href='http://www.ibm.com/fc/xc?foo=bar&label=MY_LABEL'>MY_LABEL</a>"
- +"\n[fd]=<a href='http://www.ibm.com/fd/xd?label2=MY_LABEL&foo=bar'>fd</a>"
- +"\n[fe]=<a href='http://www.ibm.com/fe/xe?foo=bar&label2=MY_LABEL'>fe</a>"
- ;
- assertEquals(expected, r);
-
- s.setProperty(SERIALIZER_relativeUriBase, null);
-
- s.setProperty(SERIALIZER_absolutePathUriBase, "http://foo");
- r = strip(s.serialize(t));
- expected = ""
- +"\n[f0]=<a href='f0/x0'>f0</a>"
- +"\n[f1]=<a href='f1/x1'>f1</a>"
- +"\n[f2]=<a href='http://foo/f2/x2'>f2</a>"
- +"\n[f3]=<a href='http://www.ibm.com/f3/x3'>f3</a>"
- +"\n[f4]=<a href='f4/x4'>f4</a>"
- +"\n[f5]=<a href='http://foo/f5/x5'>f5</a>"
- +"\n[f6]=<a href='http://www.ibm.com/f6/x6'>f6</a>"
- +"\n[f7]=<a href='http://www.ibm.com/f7/x7'>f7</a>"
- +"\n[f8]=<a href='f8/x8'>f8</a>"
- +"\n[f9]=<a href='f9/x9'>f9</a>"
- +"\n[fa]=<a href='http://www.ibm.com/fa/xa#MY_LABEL'>fa</a>"
- +"\n[fb]=<a href='http://www.ibm.com/fb/xb?label=MY_LABEL&foo=bar'>MY_LABEL</a>"
- +"\n[fc]=<a href='http://www.ibm.com/fc/xc?foo=bar&label=MY_LABEL'>MY_LABEL</a>"
- +"\n[fd]=<a href='http://www.ibm.com/fd/xd?label2=MY_LABEL&foo=bar'>fd</a>"
- +"\n[fe]=<a href='http://www.ibm.com/fe/xe?foo=bar&label2=MY_LABEL'>fe</a>"
- ;
- assertEquals(expected, r);
-
- s.setProperty(SERIALIZER_absolutePathUriBase, "http://foo/");
- r = strip(s.serialize(t));
- expected = ""
- +"\n[f0]=<a href='f0/x0'>f0</a>"
- +"\n[f1]=<a href='f1/x1'>f1</a>"
- +"\n[f2]=<a href='http://foo/f2/x2'>f2</a>"
- +"\n[f3]=<a href='http://www.ibm.com/f3/x3'>f3</a>"
- +"\n[f4]=<a href='f4/x4'>f4</a>"
- +"\n[f5]=<a href='http://foo/f5/x5'>f5</a>"
- +"\n[f6]=<a href='http://www.ibm.com/f6/x6'>f6</a>"
- +"\n[f7]=<a href='http://www.ibm.com/f7/x7'>f7</a>"
- +"\n[f8]=<a href='f8/x8'>f8</a>"
- +"\n[f9]=<a href='f9/x9'>f9</a>"
- +"\n[fa]=<a href='http://www.ibm.com/fa/xa#MY_LABEL'>fa</a>"
- +"\n[fb]=<a href='http://www.ibm.com/fb/xb?label=MY_LABEL&foo=bar'>MY_LABEL</a>"
- +"\n[fc]=<a href='http://www.ibm.com/fc/xc?foo=bar&label=MY_LABEL'>MY_LABEL</a>"
- +"\n[fd]=<a href='http://www.ibm.com/fd/xd?label2=MY_LABEL&foo=bar'>fd</a>"
- +"\n[fe]=<a href='http://www.ibm.com/fe/xe?foo=bar&label2=MY_LABEL'>fe</a>"
- ;
- assertEquals(expected, r);
-
- s.setProperty(SERIALIZER_absolutePathUriBase, ""); // Same as null.
- r = strip(s.serialize(t));
- expected = ""
- +"\n[f0]=<a href='f0/x0'>f0</a>"
- +"\n[f1]=<a href='f1/x1'>f1</a>"
- +"\n[f2]=<a href='/f2/x2'>f2</a>"
- +"\n[f3]=<a href='http://www.ibm.com/f3/x3'>f3</a>"
- +"\n[f4]=<a href='f4/x4'>f4</a>"
- +"\n[f5]=<a href='/f5/x5'>f5</a>"
- +"\n[f6]=<a href='http://www.ibm.com/f6/x6'>f6</a>"
- +"\n[f7]=<a href='http://www.ibm.com/f7/x7'>f7</a>"
- +"\n[f8]=<a href='f8/x8'>f8</a>"
- +"\n[f9]=<a href='f9/x9'>f9</a>"
- +"\n[fa]=<a href='http://www.ibm.com/fa/xa#MY_LABEL'>fa</a>"
- +"\n[fb]=<a href='http://www.ibm.com/fb/xb?label=MY_LABEL&foo=bar'>MY_LABEL</a>"
- +"\n[fc]=<a href='http://www.ibm.com/fc/xc?foo=bar&label=MY_LABEL'>MY_LABEL</a>"
- +"\n[fd]=<a href='http://www.ibm.com/fd/xd?label2=MY_LABEL&foo=bar'>fd</a>"
- +"\n[fe]=<a href='http://www.ibm.com/fe/xe?foo=bar&label2=MY_LABEL'>fe</a>"
- ;
- assertEquals(expected, r);
- }
-
- private String strip(String html) {
- return html
- .replace("<table type='object'><tr><th><string>key</string></th><th><string>value</string></th></tr>", "")
- .replace("</table>", "")
- .replace("<tr><td><string>", "\n[")
- .replace("</string></td><td>", "]=")
- .replace("</td></tr>", "");
- }
-
- //====================================================================================================
- // Validate that you cannot update properties on locked serializer.
- //====================================================================================================
- @Test
- public void testLockedSerializer() throws Exception {
- HtmlSerializer s = new HtmlSerializer().lock();
- try {
- s.setProperty(XmlSerializerContext.XML_enableNamespaces, true);
- fail("Locked exception not thrown");
- } catch (LockedException e) {}
- try {
- s.setProperty(SerializerContext.SERIALIZER_addClassAttrs, true);
- fail("Locked exception not thrown");
- } catch (LockedException e) {}
- try {
- s.setProperty(BeanContext.BEAN_beanMapPutReturnsOldValue, true);
- fail("Locked exception not thrown");
- } catch (LockedException e) {}
- }
-
- //====================================================================================================
- // Recursion
- //====================================================================================================
- @Test
- public void testRecursion() throws Exception {
- HtmlSerializer s = new HtmlSerializer.Sq();
-
- R1 r1 = new R1();
- R2 r2 = new R2();
- R3 r3 = new R3();
- r1.r2 = r2;
- r2.r3 = r3;
- r3.r1 = r1;
-
- // No recursion detection
- try {
- s.serialize(r1);
- fail("Exception expected!");
- } catch (Exception e) {
- String msg = e.getLocalizedMessage();
- assertTrue(msg.contains("It's recommended you use the SerializerContext.SERIALIZER_detectRecursions setting to help locate the loop."));
- }
-
- // Recursion detection, no ignore
- s.setProperty(SERIALIZER_detectRecursions, true);
- try {
- s.serialize(r1);
- fail("Exception expected!");
- } catch (Exception e) {
- String msg = e.getLocalizedMessage();
- assertTrue(msg.contains("[0]<noname>:org.apache.juneau.html.CT_Common$R1"));
- assertTrue(msg.contains("->[1]r2:org.apache.juneau.html.CT_Common$R2"));
- assertTrue(msg.contains("->[2]r3:org.apache.juneau.html.CT_Common$R3"));
- assertTrue(msg.contains("->[3]r1:org.apache.juneau.html.CT_Common$R1"));
- }
-
- s.setProperty(SERIALIZER_ignoreRecursions, true);
- assertEquals("<table type='object'><tr><th><string>key</string></th><th><string>value</string></th></tr><tr><td><string>name</string></td><td><string>foo</string></td></tr><tr><td><string>r2</string></td><td><table type='object'><tr><th><string>key</string></th><th><string>value</string></th></tr><tr><td><string>name</string></td><td><string>bar</string></td></tr><tr><td><string>r3</string></td><td><table type='object'><tr><th><string>key</string></th><th><string>value</string></th></tr><tr><td><string>name</string></td><td><string>baz</string></td></tr></table></td></tr></table></td></tr></table>",
- s.serialize(r1));
-
- // Make sure this doesn't blow up.
- s.getSchemaSerializer().serialize(r1);
- }
-
- public static class R1 {
- public String name = "foo";
- public R2 r2;
- }
- public static class R2 {
- public String name = "bar";
- public R3 r3;
- }
- public static class R3 {
- public String name = "baz";
- public R1 r1;
- }
-
- //====================================================================================================
- // Basic bean
- //====================================================================================================
- @Test
- public void testBasicBean() throws Exception {
- WriterSerializer s = new HtmlSerializer.Sq().setProperty(SERIALIZER_trimNullProperties, false).setProperty(BEAN_sortProperties, true);
-
- J a = new J();
- a.setF1("J");
- a.setF2(100);
- a.setF3(true);
- assertEquals("<table type='object'><tr><th><string>key</string></th><th><string>value</string></th></tr><tr><td><string>f1</string></td><td><string>J</string></td></tr><tr><td><string>f2</string></td><td><number>100</number></td></tr><tr><td><string>f3</string></td><td><boolean>true</boolean></td></tr></table>", s.serialize(a));
- }
-
- public static class J {
- private String f1 = null;
- private int f2 = -1;
- private boolean f3 = false;
-
- public String getF1() {
- return this.f1;
- }
-
- public void setF1(String f1) {
- this.f1 = f1;
- }
-
- public int getF2() {
- return this.f2;
- }
-
- public void setF2(int f2) {
- this.f2 = f2;
- }
-
- public boolean isF3() {
- return this.f3;
- }
-
- public void setF3(boolean f3) {
- this.f3 = f3;
- }
-
- @Override /* Object */
- public String toString() {
- return ("J(f1: " + this.getF1() + ", f2: " + this.getF2() + ")");
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/html/CT_CommonParser.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/html/CT_CommonParser.java b/org.apache.juneau/src/test/java/org/apache/juneau/html/CT_CommonParser.java
deleted file mode 100755
index 198b826..0000000
--- a/org.apache.juneau/src/test/java/org/apache/juneau/html/CT_CommonParser.java
+++ /dev/null
@@ -1,162 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.html;
-
-import static org.apache.juneau.BeanContext.*;
-import static org.apache.juneau.serializer.SerializerContext.*;
-import static org.junit.Assert.*;
-
-import java.util.*;
-
-import org.apache.juneau.*;
-import org.apache.juneau.parser.*;
-import org.junit.*;
-
-@SuppressWarnings({"rawtypes","serial"})
-public class CT_CommonParser {
-
- //====================================================================================================
- // testFromSerializer
- //====================================================================================================
- @Test
- public void testFromSerializer() throws Exception {
- ReaderParser p = HtmlParser.DEFAULT.clone().setClassLoader(getClass().getClassLoader());
- Map m = null;
- String in;
-
- in = "<table type='object'><tr><th><string>key</string></th><th><string>value</string></th></tr><tr><td><string>a</string></td><td><number>1</number></td></tr></table>";
- m = (Map)p.parse(in, Object.class);
- assertEquals(1, m.get("a"));
-
- in = "<table type='object'><tr><th><string>key</string></th><th><string>value</string></th></tr><tr><td><string>a</string></td><td><number>1</number></td></tr><tr><td><string>b</string></td><td><string>foo bar</string></td></tr></table>";
- m = (Map)p.parse(in, Object.class);
- assertEquals(1, m.get("a"));
- assertEquals("foo bar", m.get("b"));
-
- in = "<table type='object'><tr><th><string>key</string></th><th><string>value</string></th></tr><tr><td><string>a</string></td><td><number>1</number></td></tr><tr><td><string>b</string></td><td><string>foo bar</string></td></tr><tr><td><string>c</string></td><td><boolean>false</boolean></td></tr></table>";
- m = (Map)p.parse(in, Object.class);
- assertEquals(1, m.get("a"));
- assertEquals(false, m.get("c"));
-
- in = " <table type='object'> <tr> <th> <string> key </string> </th> <th> <string> value </string> </th> </tr> <tr> <td> <string> a </string> </td> <td> <number> 1 </number> </td> </tr> <tr> <td> <string> b </string> </td> <td> <string> foo </string> </td> </tr> <tr> <td> <string> c </string> </td> <td> <boolean> false </boolean> </td> </tr> </table> ";
- m = (Map)p.parse(in, Object.class);
- assertEquals(1, m.get("a"));
- assertEquals("foo", m.get("b"));
- assertEquals(false, m.get("c"));
-
- in = "<table type='array'><tr><th>attribute</th></tr><tr><td><string>value</string></td></tr><tr><td><string>value</string></td></tr></table>";
- ObjectList jl = (ObjectList)p.parse(in, Object.class);
- assertEquals("value", jl.getObjectMap(0).getString("attribute"));
- assertEquals("value", jl.getObjectMap(1).getString("attribute"));
-
- A1 t1 = new A1();
- A2 t2 = new A2();
- t2.add(new A3("name0","value0"));
- t2.add(new A3("name1","value1"));
- t1.list = t2;
- in = new HtmlSerializer().setProperty(SERIALIZER_addClassAttrs, true).serialize(t1);
- t1 = (A1)p.parse(in, Object.class);
- assertEquals("value1", t1.list.get(1).value);
-
- in = HtmlSerializer.DEFAULT.serialize(t1);
- t1 = p.parse(in, A1.class);
- assertEquals("value1", t1.list.get(1).value);
- }
-
- public static class A1 {
- public A2 list;
- }
-
- public static class A2 extends LinkedList<A3> {
- }
-
- public static class A3 {
- public String name, value;
- public A3(){}
- public A3(String name, String value) {
- this.name = name;
- this.value = value;
- }
- }
-
- //====================================================================================================
- // Correct handling of unknown properties.
- //====================================================================================================
- @Test
- public void testCorrectHandlingOfUnknownProperties() throws Exception {
- ReaderParser p = new HtmlParser().setProperty(BEAN_ignoreUnknownBeanProperties, true);
- B t;
-
- String in = "<table type='object'><tr><th><string>key</string></th><th><string>value</string></th></tr><tr><td><string>a</string></td><td><number>1</number></td></tr><tr><td><string>unknown</string></td><td><number>1</number></td></tr><tr><td><string>b</string></td><td><number>2</number></td></tr></table>";
- t = p.parse(in, B.class);
- assertEquals(t.a, 1);
- assertEquals(t.b, 2);
-
- try {
- p = new HtmlParser();
- p.parse(in, B.class);
- fail("Exception expected");
- } catch (ParseException e) {}
- }
-
- public static class B {
- public int a, b;
- }
-
- //====================================================================================================
- // Writing to Collection properties with no setters.
- //====================================================================================================
- @Test
- public void testCollectionPropertiesWithNoSetters() throws Exception {
- ReaderParser p = HtmlParser.DEFAULT;
-
- String in = "<table type='object'><tr><th><string>key</string></th><th><string>value</string></th></tr><tr><td><string>ints</string></td><td><ul><li><number>1</number></li><li><number>2</number></li><li><number>3</number></li></ul></td></tr><tr><td><string>beans</string></td><td><table type='array'><tr><th>a</th><th>b</th></tr><tr><td><number>1</number></td><td><number>2</number></td></tr></table></td></tr></table>";
- C t = p.parse(in, C.class);
- assertEquals(t.getInts().size(), 3);
- assertEquals(t.getBeans().get(0).b, 2);
- }
-
- public static class C {
- private Collection<Integer> ints = new LinkedList<Integer>();
- private List<B> beans = new LinkedList<B>();
- public Collection<Integer> getInts() {
- return ints;
- }
- public List<B> getBeans() {
- return beans;
- }
- }
-
- //====================================================================================================
- // Parser listeners.
- //====================================================================================================
- @Test
- public void testParserListeners() throws Exception {
- final List<String> events = new LinkedList<String>();
- HtmlParser p = new HtmlParser().setProperty(BEAN_ignoreUnknownBeanProperties, true);
- p.addListener(
- new ParserListener() {
- @Override /* ParserListener */
- public <T> void onUnknownProperty(String propertyName, Class<T> beanClass, T bean, int line, int col) {
- events.add(propertyName + "," + line + "," + col);
- }
- }
- );
-
- String in = "<table type='object'><tr><th><string>key</string></th><th><string>value</string></th></tr><tr><td><string>a</string></td><td><number>1</number></td></tr><tr><td><string>unknown</string></td><td><string>/foo</string></td></tr><tr><td><string>b</string></td><td><number>2</number></td></tr></table>";
- p.parse(in, B.class);
- assertEquals(1, events.size());
- assertEquals("unknown,-1,-1", events.get(0));
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/html/CT_Html.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/html/CT_Html.java b/org.apache.juneau/src/test/java/org/apache/juneau/html/CT_Html.java
deleted file mode 100755
index 84eb710..0000000
--- a/org.apache.juneau/src/test/java/org/apache/juneau/html/CT_Html.java
+++ /dev/null
@@ -1,389 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.html;
-
-import static org.apache.juneau.html.HtmlSerializerContext.*;
-import static org.apache.juneau.serializer.SerializerContext.*;
-import static org.junit.Assert.*;
-
-import java.util.*;
-
-import org.apache.juneau.*;
-import org.apache.juneau.annotation.*;
-import org.apache.juneau.annotation.Transform;
-import org.apache.juneau.html.annotation.*;
-import org.apache.juneau.serializer.*;
-import org.apache.juneau.testbeans.*;
-import org.apache.juneau.transform.*;
-import org.junit.*;
-
-public class CT_Html {
-
- //====================================================================================================
- // Verifies that lists of maps/beans are converted to tables correctly.
- //====================================================================================================
- @Test
- public void testTables1() throws Exception {
- HtmlSerializer s = HtmlSerializer.DEFAULT_SQ;
- Object[] t;
- String html;
-
- t = new Object[] {new A1(), new A1()};
- html = s.serialize(t);
- assertEquals("<table type='array'><tr><th>f1</th></tr><tr><td><string>f1</string></td></tr><tr><td><string>f1</string></td></tr></table>", html);
-
- t = new Object[] {new A1(), new A2()};
- html = s.serialize(t);
- assertEquals("<table type='array'><tr><th>f1</th></tr><tr><td><string>f1</string></td></tr><tr><td><string>f1</string></td></tr></table>", html);
-
- t = new Object[] {new A1(), new ObjectMap("{f1:'f1'}")};
- html = s.serialize(t);
- assertEquals("<table type='array'><tr><th>f1</th></tr><tr><td><string>f1</string></td></tr><tr><td><string>f1</string></td></tr></table>", html);
-
- t = new Object[] {new ObjectMap("{f1:'f1'}"), new A1()};
- html = s.serialize(t);
- assertEquals("<table type='array'><tr><th>f1</th></tr><tr><td><string>f1</string></td></tr><tr><td><string>f1</string></td></tr></table>", html);
-
- // This should be serialized as a list since the objects have different properties.
- t = new Object[] {new A1(), new ObjectMap("{f2:'f2'}")};
- html = s.serialize(t);
- assertEquals("<ul><li><table type='object'><tr><th><string>key</string></th><th><string>value</string></th></tr><tr><td><string>f1</string></td><td><string>f1</string></td></tr></table></li><li><table type='object'><tr><th><string>key</string></th><th><string>value</string></th></tr><tr><td><string>f2</string></td><td><string>f2</string></td></tr></table></li></ul>", html);
-
- // Tables with some beans with @Bean#properties annotations.
- t = new Object[] {new A1(), new A3()};
- html = s.serialize(t);
- assertEquals("<table type='array'><tr><th>f1</th></tr><tr><td><string>f1</string></td></tr><tr><td><string>f1</string></td></tr></table>", html);
-
- t = new Object[] {new A3(), new A1()};
- html = s.serialize(t);
- assertEquals("<table type='array'><tr><th>f1</th></tr><tr><td><string>f1</string></td></tr><tr><td><string>f1</string></td></tr></table>", html);
-
- // Tables with some beans with @Bean#transforms annotations.
- t = new Object[] {new A4(), new A1()};
- html = s.serialize(t);
- assertEquals("<table type='array'><tr><th>f1</th></tr><tr><td><string>f1</string></td></tr><tr><td><string>f1</string></td></tr></table>", html);
-
- t = new Object[] {new A1(), new A4()};
- html = s.serialize(t);
- assertEquals("<table type='array'><tr><th>f1</th></tr><tr><td><string>f1</string></td></tr><tr><td><string>f1</string></td></tr></table>", html);
-
- t = new Object[] {new A5(), new A1()};
- html = s.serialize(t);
- assertEquals("<table type='array'><tr><th>f1</th></tr><tr><td><string>f1</string></td></tr><tr><td><string>f1</string></td></tr></table>", html);
-
- t = new Object[] {new A1(), new A5()};
- html = s.serialize(t);
- assertEquals("<table type='array'><tr><th>f1</th></tr><tr><td><string>f1</string></td></tr><tr><td><string>f1</string></td></tr></table>", html);
- }
-
- public static class A1 {
- public String f1 = "f1";
- }
-
- public static class A2 {
- public String f1 = "f1";
- }
-
- @Bean(properties="f1")
- public static class A3 {
- public String f1 = "f1";
- public String f2 = "f2";
- }
-
- @Transform(A4Transform.class)
- public static class A4 {
- public String f2 = "f2";
- }
-
- public static class A4Transform extends PojoTransform<A4,A1> {
- @Override /* PojoTransform */
- public A1 transform(A4 o) throws SerializeException {
- return new A1();
- }
- }
-
- @Transform(A5Transform.class)
- public static class A5 {
- public String f2 = "f2";
- }
-
- public static class A5Transform extends PojoTransform<A5,ObjectMap> {
- @Override /* PojoTransform */
- public ObjectMap transform(A5 o) {
- return new ObjectMap().append("f1", "f1");
- }
- }
-
- //====================================================================================================
- // Test URI_ANCHOR_SET options
- //====================================================================================================
- @Test
- public void testAnchorTextOptions() throws Exception {
- HtmlSerializer s = new HtmlSerializer.Sq();
- TestURI t = new TestURI();
- String r;
- String expected = null;
-
- s.setProperty(HTML_uriAnchorText, TO_STRING);
- r = strip(s.serialize(t));
- expected = ""
- +"\n[f0]=<a href='f0/x0'>f0/x0</a>"
- +"\n[f1]=<a href='f1/x1'>f1/x1</a>"
- +"\n[f2]=<a href='/f2/x2'>/f2/x2</a>"
- +"\n[f3]=<a href='http://www.ibm.com/f3/x3'>http://www.ibm.com/f3/x3</a>"
- +"\n[f4]=<a href='f4/x4'>f4/x4</a>"
- +"\n[f5]=<a href='/f5/x5'>/f5/x5</a>"
- +"\n[f6]=<a href='http://www.ibm.com/f6/x6'>http://www.ibm.com/f6/x6</a>"
- +"\n[f7]=<a href='http://www.ibm.com/f7/x7'>http://www.ibm.com/f7/x7</a>"
- +"\n[f8]=<a href='f8/x8'>f8/x8</a>"
- +"\n[f9]=<a href='f9/x9'>f9/x9</a>"
- +"\n[fa]=<a href='http://www.ibm.com/fa/xa#MY_LABEL'>http://www.ibm.com/fa/xa#MY_LABEL</a>"
- +"\n[fb]=<a href='http://www.ibm.com/fb/xb?label=MY_LABEL&foo=bar'>MY_LABEL</a>"
- +"\n[fc]=<a href='http://www.ibm.com/fc/xc?foo=bar&label=MY_LABEL'>MY_LABEL</a>"
- +"\n[fd]=<a href='http://www.ibm.com/fd/xd?label2=MY_LABEL&foo=bar'>http://www.ibm.com/fd/xd?label2=MY_LABEL&foo=bar</a>"
- +"\n[fe]=<a href='http://www.ibm.com/fe/xe?foo=bar&label2=MY_LABEL'>http://www.ibm.com/fe/xe?foo=bar&label2=MY_LABEL</a>";
- assertEquals(expected, r);
-
- s.setProperty(SERIALIZER_absolutePathUriBase, "http://myhost");
- s.setProperty(SERIALIZER_relativeUriBase, "/cr");
- s.setProperty(HTML_uriAnchorText, TO_STRING);
- r = strip(s.serialize(t));
- expected = ""
- +"\n[f0]=<a href='/cr/f0/x0'>f0/x0</a>"
- +"\n[f1]=<a href='/cr/f1/x1'>f1/x1</a>"
- +"\n[f2]=<a href='http://myhost/f2/x2'>/f2/x2</a>"
- +"\n[f3]=<a href='http://www.ibm.com/f3/x3'>http://www.ibm.com/f3/x3</a>"
- +"\n[f4]=<a href='/cr/f4/x4'>f4/x4</a>"
- +"\n[f5]=<a href='http://myhost/f5/x5'>/f5/x5</a>"
- +"\n[f6]=<a href='http://www.ibm.com/f6/x6'>http://www.ibm.com/f6/x6</a>"
- +"\n[f7]=<a href='http://www.ibm.com/f7/x7'>http://www.ibm.com/f7/x7</a>"
- +"\n[f8]=<a href='/cr/f8/x8'>f8/x8</a>"
- +"\n[f9]=<a href='/cr/f9/x9'>f9/x9</a>"
- +"\n[fa]=<a href='http://www.ibm.com/fa/xa#MY_LABEL'>http://www.ibm.com/fa/xa#MY_LABEL</a>"
- +"\n[fb]=<a href='http://www.ibm.com/fb/xb?label=MY_LABEL&foo=bar'>MY_LABEL</a>"
- +"\n[fc]=<a href='http://www.ibm.com/fc/xc?foo=bar&label=MY_LABEL'>MY_LABEL</a>"
- +"\n[fd]=<a href='http://www.ibm.com/fd/xd?label2=MY_LABEL&foo=bar'>http://www.ibm.com/fd/xd?label2=MY_LABEL&foo=bar</a>"
- +"\n[fe]=<a href='http://www.ibm.com/fe/xe?foo=bar&label2=MY_LABEL'>http://www.ibm.com/fe/xe?foo=bar&label2=MY_LABEL</a>";
- assertEquals(expected, r);
-
- s.setProperty(HTML_uriAnchorText, URI);
- r = strip(s.serialize(t));
- expected = ""
- +"\n[f0]=<a href='/cr/f0/x0'>/cr/f0/x0</a>"
- +"\n[f1]=<a href='/cr/f1/x1'>/cr/f1/x1</a>"
- +"\n[f2]=<a href='http://myhost/f2/x2'>http://myhost/f2/x2</a>"
- +"\n[f3]=<a href='http://www.ibm.com/f3/x3'>http://www.ibm.com/f3/x3</a>"
- +"\n[f4]=<a href='/cr/f4/x4'>/cr/f4/x4</a>"
- +"\n[f5]=<a href='http://myhost/f5/x5'>http://myhost/f5/x5</a>"
- +"\n[f6]=<a href='http://www.ibm.com/f6/x6'>http://www.ibm.com/f6/x6</a>"
- +"\n[f7]=<a href='http://www.ibm.com/f7/x7'>http://www.ibm.com/f7/x7</a>"
- +"\n[f8]=<a href='/cr/f8/x8'>/cr/f8/x8</a>"
- +"\n[f9]=<a href='/cr/f9/x9'>/cr/f9/x9</a>"
- +"\n[fa]=<a href='http://www.ibm.com/fa/xa#MY_LABEL'>http://www.ibm.com/fa/xa#MY_LABEL</a>"
- +"\n[fb]=<a href='http://www.ibm.com/fb/xb?label=MY_LABEL&foo=bar'>MY_LABEL</a>"
- +"\n[fc]=<a href='http://www.ibm.com/fc/xc?foo=bar&label=MY_LABEL'>MY_LABEL</a>"
- +"\n[fd]=<a href='http://www.ibm.com/fd/xd?label2=MY_LABEL&foo=bar'>http://www.ibm.com/fd/xd?label2=MY_LABEL&foo=bar</a>"
- +"\n[fe]=<a href='http://www.ibm.com/fe/xe?foo=bar&label2=MY_LABEL'>http://www.ibm.com/fe/xe?foo=bar&label2=MY_LABEL</a>";
- assertEquals(expected, r);
-
- s.setProperty(HTML_uriAnchorText, LAST_TOKEN);
- r = strip(s.serialize(t));
- expected = ""
- +"\n[f0]=<a href='/cr/f0/x0'>x0</a>"
- +"\n[f1]=<a href='/cr/f1/x1'>x1</a>"
- +"\n[f2]=<a href='http://myhost/f2/x2'>x2</a>"
- +"\n[f3]=<a href='http://www.ibm.com/f3/x3'>x3</a>"
- +"\n[f4]=<a href='/cr/f4/x4'>x4</a>"
- +"\n[f5]=<a href='http://myhost/f5/x5'>x5</a>"
- +"\n[f6]=<a href='http://www.ibm.com/f6/x6'>x6</a>"
- +"\n[f7]=<a href='http://www.ibm.com/f7/x7'>x7</a>"
- +"\n[f8]=<a href='/cr/f8/x8'>x8</a>"
- +"\n[f9]=<a href='/cr/f9/x9'>x9</a>"
- +"\n[fa]=<a href='http://www.ibm.com/fa/xa#MY_LABEL'>xa</a>"
- +"\n[fb]=<a href='http://www.ibm.com/fb/xb?label=MY_LABEL&foo=bar'>MY_LABEL</a>"
- +"\n[fc]=<a href='http://www.ibm.com/fc/xc?foo=bar&label=MY_LABEL'>MY_LABEL</a>"
- +"\n[fd]=<a href='http://www.ibm.com/fd/xd?label2=MY_LABEL&foo=bar'>xd</a>"
- +"\n[fe]=<a href='http://www.ibm.com/fe/xe?foo=bar&label2=MY_LABEL'>xe</a>";
- assertEquals(expected, r);
-
- s.setProperty(HTML_uriAnchorText, URI_ANCHOR);
- r = strip(s.serialize(t));
- expected = ""
- +"\n[f0]=<a href='/cr/f0/x0'>f0/x0</a>"
- +"\n[f1]=<a href='/cr/f1/x1'>f1/x1</a>"
- +"\n[f2]=<a href='http://myhost/f2/x2'>/f2/x2</a>"
- +"\n[f3]=<a href='http://www.ibm.com/f3/x3'>http://www.ibm.com/f3/x3</a>"
- +"\n[f4]=<a href='/cr/f4/x4'>f4/x4</a>"
- +"\n[f5]=<a href='http://myhost/f5/x5'>/f5/x5</a>"
- +"\n[f6]=<a href='http://www.ibm.com/f6/x6'>http://www.ibm.com/f6/x6</a>"
- +"\n[f7]=<a href='http://www.ibm.com/f7/x7'>http://www.ibm.com/f7/x7</a>"
- +"\n[f8]=<a href='/cr/f8/x8'>f8/x8</a>"
- +"\n[f9]=<a href='/cr/f9/x9'>f9/x9</a>"
- +"\n[fa]=<a href='http://www.ibm.com/fa/xa#MY_LABEL'>MY_LABEL</a>"
- +"\n[fb]=<a href='http://www.ibm.com/fb/xb?label=MY_LABEL&foo=bar'>MY_LABEL</a>"
- +"\n[fc]=<a href='http://www.ibm.com/fc/xc?foo=bar&label=MY_LABEL'>MY_LABEL</a>"
- +"\n[fd]=<a href='http://www.ibm.com/fd/xd?label2=MY_LABEL&foo=bar'>http://www.ibm.com/fd/xd?label2=MY_LABEL&foo=bar</a>"
- +"\n[fe]=<a href='http://www.ibm.com/fe/xe?foo=bar&label2=MY_LABEL'>http://www.ibm.com/fe/xe?foo=bar&label2=MY_LABEL</a>";
- assertEquals(expected, r);
-
- s.setProperty(HTML_labelParameter, "label2");
- r = strip(s.serialize(t));
- expected = ""
- +"\n[f0]=<a href='/cr/f0/x0'>f0/x0</a>"
- +"\n[f1]=<a href='/cr/f1/x1'>f1/x1</a>"
- +"\n[f2]=<a href='http://myhost/f2/x2'>/f2/x2</a>"
- +"\n[f3]=<a href='http://www.ibm.com/f3/x3'>http://www.ibm.com/f3/x3</a>"
- +"\n[f4]=<a href='/cr/f4/x4'>f4/x4</a>"
- +"\n[f5]=<a href='http://myhost/f5/x5'>/f5/x5</a>"
- +"\n[f6]=<a href='http://www.ibm.com/f6/x6'>http://www.ibm.com/f6/x6</a>"
- +"\n[f7]=<a href='http://www.ibm.com/f7/x7'>http://www.ibm.com/f7/x7</a>"
- +"\n[f8]=<a href='/cr/f8/x8'>f8/x8</a>"
- +"\n[f9]=<a href='/cr/f9/x9'>f9/x9</a>"
- +"\n[fa]=<a href='http://www.ibm.com/fa/xa#MY_LABEL'>MY_LABEL</a>"
- +"\n[fb]=<a href='http://www.ibm.com/fb/xb?label=MY_LABEL&foo=bar'>http://www.ibm.com/fb/xb?label=MY_LABEL&foo=bar</a>"
- +"\n[fc]=<a href='http://www.ibm.com/fc/xc?foo=bar&label=MY_LABEL'>http://www.ibm.com/fc/xc?foo=bar&label=MY_LABEL</a>"
- +"\n[fd]=<a href='http://www.ibm.com/fd/xd?label2=MY_LABEL&foo=bar'>MY_LABEL</a>"
- +"\n[fe]=<a href='http://www.ibm.com/fe/xe?foo=bar&label2=MY_LABEL'>MY_LABEL</a>";
- assertEquals(expected, r);
-
- s.setProperty(HTML_detectLinksInStrings, false);
- r = strip(s.serialize(t));
- expected = ""
- +"\n[f0]=<a href='/cr/f0/x0'>f0/x0</a>"
- +"\n[f1]=<a href='/cr/f1/x1'>f1/x1</a>"
- +"\n[f2]=<a href='http://myhost/f2/x2'>/f2/x2</a>"
- +"\n[f3]=<a href='http://www.ibm.com/f3/x3'>http://www.ibm.com/f3/x3</a>"
- +"\n[f4]=<a href='/cr/f4/x4'>f4/x4</a>"
- +"\n[f5]=<a href='http://myhost/f5/x5'>/f5/x5</a>"
- +"\n[f6]=<a href='http://www.ibm.com/f6/x6'>http://www.ibm.com/f6/x6</a>"
- +"\n[f7]=<a href='http://www.ibm.com/f7/x7'>http://www.ibm.com/f7/x7</a>"
- +"\n[f8]=<a href='/cr/f8/x8'>f8/x8</a>"
- +"\n[f9]=<a href='/cr/f9/x9'>f9/x9</a>"
- +"\n[fa]=<string>http://www.ibm.com/fa/xa#MY_LABEL</string>"
- +"\n[fb]=<string>http://www.ibm.com/fb/xb?label=MY_LABEL&foo=bar</string>"
- +"\n[fc]=<string>http://www.ibm.com/fc/xc?foo=bar&label=MY_LABEL</string>"
- +"\n[fd]=<string>http://www.ibm.com/fd/xd?label2=MY_LABEL&foo=bar</string>"
- +"\n[fe]=<string>http://www.ibm.com/fe/xe?foo=bar&label2=MY_LABEL</string>";
- assertEquals(expected, r);
-
- s.setProperty(HTML_detectLinksInStrings, true);
- s.setProperty(HTML_lookForLabelParameters, false);
- r = strip(s.serialize(t));
- expected = ""
- +"\n[f0]=<a href='/cr/f0/x0'>f0/x0</a>"
- +"\n[f1]=<a href='/cr/f1/x1'>f1/x1</a>"
- +"\n[f2]=<a href='http://myhost/f2/x2'>/f2/x2</a>"
- +"\n[f3]=<a href='http://www.ibm.com/f3/x3'>http://www.ibm.com/f3/x3</a>"
- +"\n[f4]=<a href='/cr/f4/x4'>f4/x4</a>"
- +"\n[f5]=<a href='http://myhost/f5/x5'>/f5/x5</a>"
- +"\n[f6]=<a href='http://www.ibm.com/f6/x6'>http://www.ibm.com/f6/x6</a>"
- +"\n[f7]=<a href='http://www.ibm.com/f7/x7'>http://www.ibm.com/f7/x7</a>"
- +"\n[f8]=<a href='/cr/f8/x8'>f8/x8</a>"
- +"\n[f9]=<a href='/cr/f9/x9'>f9/x9</a>"
- +"\n[fa]=<a href='http://www.ibm.com/fa/xa#MY_LABEL'>MY_LABEL</a>"
- +"\n[fb]=<a href='http://www.ibm.com/fb/xb?label=MY_LABEL&foo=bar'>http://www.ibm.com/fb/xb?label=MY_LABEL&foo=bar</a>"
- +"\n[fc]=<a href='http://www.ibm.com/fc/xc?foo=bar&label=MY_LABEL'>http://www.ibm.com/fc/xc?foo=bar&label=MY_LABEL</a>"
- +"\n[fd]=<a href='http://www.ibm.com/fd/xd?label2=MY_LABEL&foo=bar'>http://www.ibm.com/fd/xd?label2=MY_LABEL&foo=bar</a>"
- +"\n[fe]=<a href='http://www.ibm.com/fe/xe?foo=bar&label2=MY_LABEL'>http://www.ibm.com/fe/xe?foo=bar&label2=MY_LABEL</a>";
- assertEquals(expected, r);
- }
-
- private String strip(String html) {
- return html
- .replace("<table type='object'><tr><th><string>key</string></th><th><string>value</string></th></tr>", "")
- .replace("</table>", "")
- .replace("<tr><td><string>", "\n[")
- .replace("</string></td><td>", "]=")
- .replace("</td></tr>", "");
- }
-
- //====================================================================================================
- // Test @Html.asPlainText annotation on classes and fields
- //====================================================================================================
- @Test
- public void testHtmlAnnotationAsPlainText() throws Exception {
- HtmlSerializer s = new HtmlSerializer.Sq();
- Object o = null;
- String r;
-
- o = new B1();
- r = s.serialize(o);
- assertEquals("<test>", r);
-
- o = new B2();
- r = s.serialize(o);
- assertEquals("<table type='object'><tr><th><string>key</string></th><th><string>value</string></th></tr><tr><td><string>f1</string></td><td><f1></td></tr></table>", r);
- }
-
- @Html(asPlainText=true)
- public static class B1 {
- public String f1 = "<f1>";
- @Override /* Object */
- public String toString() {
- return "<test>";
- }
- }
-
- public static class B2 {
- @Html(asPlainText=true)
- public String f1 = "<f1>";
- }
-
- //====================================================================================================
- // Test @Html.asXml annotation on classes and fields
- //====================================================================================================
- @Test
- public void testHtmlAnnotationAsXml() throws Exception {
- HtmlSerializer s = new HtmlSerializer.Sq();
- Object o = null;
- String r;
-
- o = new C1();
- r = s.serialize(o);
- assertEquals("<object><f1><f1></f1></object>", r);
-
- o = new C2();
- r = s.serialize(o);
- assertEquals("<table type='object'><tr><th><string>key</string></th><th><string>value</string></th></tr><tr><td><string>f1</string></td><td><string><f1></string></td></tr></table>", r);
- }
-
- @Html(asXml=true)
- public static class C1 {
- public String f1 = "<f1>";
- }
-
- public static class C2 {
- @Html(asXml=true)
- public String f1 = "<f1>";
- }
-
- //====================================================================================================
- // Test @Html.noTableHeaders
- //====================================================================================================
- @Test
- public void testNoTableHeaders() throws Exception {
- HtmlSerializer s = new HtmlSerializer.Sq();
- Object o = null;
- String r;
-
- Map m = new MyMap();
- m.put("foo", "bar");
- o = new ObjectList().append(m);
- r = s.serialize(o);
- assertEquals("<ul><li><table type='object'><tr><td><string>foo</string></td><td><string>bar</string></td></tr></table></li></ul>", r);
- }
-
- @Html(noTables=true, noTableHeaders=true)
- public static class MyMap extends LinkedHashMap<String,String> {}
-
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/html/CommonParserTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/html/CommonParserTest.java b/org.apache.juneau/src/test/java/org/apache/juneau/html/CommonParserTest.java
new file mode 100755
index 0000000..c3a970f
--- /dev/null
+++ b/org.apache.juneau/src/test/java/org/apache/juneau/html/CommonParserTest.java
@@ -0,0 +1,162 @@
+/***************************************************************************************************************************
+ * 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.juneau.html;
+
+import static org.apache.juneau.BeanContext.*;
+import static org.apache.juneau.serializer.SerializerContext.*;
+import static org.junit.Assert.*;
+
+import java.util.*;
+
+import org.apache.juneau.*;
+import org.apache.juneau.parser.*;
+import org.junit.*;
+
+@SuppressWarnings({"rawtypes","serial"})
+public class CommonParserTest {
+
+ //====================================================================================================
+ // testFromSerializer
+ //====================================================================================================
+ @Test
+ public void testFromSerializer() throws Exception {
+ ReaderParser p = HtmlParser.DEFAULT.clone().setClassLoader(getClass().getClassLoader());
+ Map m = null;
+ String in;
+
+ in = "<table type='object'><tr><th><string>key</string></th><th><string>value</string></th></tr><tr><td><string>a</string></td><td><number>1</number></td></tr></table>";
+ m = (Map)p.parse(in, Object.class);
+ assertEquals(1, m.get("a"));
+
+ in = "<table type='object'><tr><th><string>key</string></th><th><string>value</string></th></tr><tr><td><string>a</string></td><td><number>1</number></td></tr><tr><td><string>b</string></td><td><string>foo bar</string></td></tr></table>";
+ m = (Map)p.parse(in, Object.class);
+ assertEquals(1, m.get("a"));
+ assertEquals("foo bar", m.get("b"));
+
+ in = "<table type='object'><tr><th><string>key</string></th><th><string>value</string></th></tr><tr><td><string>a</string></td><td><number>1</number></td></tr><tr><td><string>b</string></td><td><string>foo bar</string></td></tr><tr><td><string>c</string></td><td><boolean>false</boolean></td></tr></table>";
+ m = (Map)p.parse(in, Object.class);
+ assertEquals(1, m.get("a"));
+ assertEquals(false, m.get("c"));
+
+ in = " <table type='object'> <tr> <th> <string> key </string> </th> <th> <string> value </string> </th> </tr> <tr> <td> <string> a </string> </td> <td> <number> 1 </number> </td> </tr> <tr> <td> <string> b </string> </td> <td> <string> foo </string> </td> </tr> <tr> <td> <string> c </string> </td> <td> <boolean> false </boolean> </td> </tr> </table> ";
+ m = (Map)p.parse(in, Object.class);
+ assertEquals(1, m.get("a"));
+ assertEquals("foo", m.get("b"));
+ assertEquals(false, m.get("c"));
+
+ in = "<table type='array'><tr><th>attribute</th></tr><tr><td><string>value</string></td></tr><tr><td><string>value</string></td></tr></table>";
+ ObjectList jl = (ObjectList)p.parse(in, Object.class);
+ assertEquals("value", jl.getObjectMap(0).getString("attribute"));
+ assertEquals("value", jl.getObjectMap(1).getString("attribute"));
+
+ A1 t1 = new A1();
+ A2 t2 = new A2();
+ t2.add(new A3("name0","value0"));
+ t2.add(new A3("name1","value1"));
+ t1.list = t2;
+ in = new HtmlSerializer().setProperty(SERIALIZER_addClassAttrs, true).serialize(t1);
+ t1 = (A1)p.parse(in, Object.class);
+ assertEquals("value1", t1.list.get(1).value);
+
+ in = HtmlSerializer.DEFAULT.serialize(t1);
+ t1 = p.parse(in, A1.class);
+ assertEquals("value1", t1.list.get(1).value);
+ }
+
+ public static class A1 {
+ public A2 list;
+ }
+
+ public static class A2 extends LinkedList<A3> {
+ }
+
+ public static class A3 {
+ public String name, value;
+ public A3(){}
+ public A3(String name, String value) {
+ this.name = name;
+ this.value = value;
+ }
+ }
+
+ //====================================================================================================
+ // Correct handling of unknown properties.
+ //====================================================================================================
+ @Test
+ public void testCorrectHandlingOfUnknownProperties() throws Exception {
+ ReaderParser p = new HtmlParser().setProperty(BEAN_ignoreUnknownBeanProperties, true);
+ B t;
+
+ String in = "<table type='object'><tr><th><string>key</string></th><th><string>value</string></th></tr><tr><td><string>a</string></td><td><number>1</number></td></tr><tr><td><string>unknown</string></td><td><number>1</number></td></tr><tr><td><string>b</string></td><td><number>2</number></td></tr></table>";
+ t = p.parse(in, B.class);
+ assertEquals(t.a, 1);
+ assertEquals(t.b, 2);
+
+ try {
+ p = new HtmlParser();
+ p.parse(in, B.class);
+ fail("Exception expected");
+ } catch (ParseException e) {}
+ }
+
+ public static class B {
+ public int a, b;
+ }
+
+ //====================================================================================================
+ // Writing to Collection properties with no setters.
+ //====================================================================================================
+ @Test
+ public void testCollectionPropertiesWithNoSetters() throws Exception {
+ ReaderParser p = HtmlParser.DEFAULT;
+
+ String in = "<table type='object'><tr><th><string>key</string></th><th><string>value</string></th></tr><tr><td><string>ints</string></td><td><ul><li><number>1</number></li><li><number>2</number></li><li><number>3</number></li></ul></td></tr><tr><td><string>beans</string></td><td><table type='array'><tr><th>a</th><th>b</th></tr><tr><td><number>1</number></td><td><number>2</number></td></tr></table></td></tr></table>";
+ C t = p.parse(in, C.class);
+ assertEquals(t.getInts().size(), 3);
+ assertEquals(t.getBeans().get(0).b, 2);
+ }
+
+ public static class C {
+ private Collection<Integer> ints = new LinkedList<Integer>();
+ private List<B> beans = new LinkedList<B>();
+ public Collection<Integer> getInts() {
+ return ints;
+ }
+ public List<B> getBeans() {
+ return beans;
+ }
+ }
+
+ //====================================================================================================
+ // Parser listeners.
+ //====================================================================================================
+ @Test
+ public void testParserListeners() throws Exception {
+ final List<String> events = new LinkedList<String>();
+ HtmlParser p = new HtmlParser().setProperty(BEAN_ignoreUnknownBeanProperties, true);
+ p.addListener(
+ new ParserListener() {
+ @Override /* ParserListener */
+ public <T> void onUnknownProperty(String propertyName, Class<T> beanClass, T bean, int line, int col) {
+ events.add(propertyName + "," + line + "," + col);
+ }
+ }
+ );
+
+ String in = "<table type='object'><tr><th><string>key</string></th><th><string>value</string></th></tr><tr><td><string>a</string></td><td><number>1</number></td></tr><tr><td><string>unknown</string></td><td><string>/foo</string></td></tr><tr><td><string>b</string></td><td><number>2</number></td></tr></table>";
+ p.parse(in, B.class);
+ assertEquals(1, events.size());
+ assertEquals("unknown,-1,-1", events.get(0));
+ }
+
+}
[40/44] incubator-juneau git commit: Rename CT_* testcases.
Posted by ja...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestPaths.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestPaths.java b/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestPaths.java
deleted file mode 100755
index 6f4e317..0000000
--- a/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestPaths.java
+++ /dev/null
@@ -1,1368 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.server;
-
-import static org.junit.Assert.*;
-
-import org.apache.juneau.*;
-import org.apache.juneau.client.*;
-import org.apache.juneau.json.*;
-import org.junit.*;
-
-public class CT_TestPaths {
-
- private static String URL = "/testPaths";
-
- //====================================================================================================
- // Basic tests
- //====================================================================================================
- @Test
- public void testBasic() throws Exception {
- RestClient client = new TestRestClient(JsonSerializer.DEFAULT, JsonParser.DEFAULT);
- ObjectMap r;
- String url;
-
- // [/test/testPaths]
- // {
- // pathInfo:null,
- // pathInfoUndecoded:null,
- // pathInfoParts:[],
- // pathRemainder:null,
- // pathRemainderUndecoded:null,
- // requestURI:'/jazz/juneau/test/testPaths',
- // requestParentURI:'/jazz/juneau/test',
- // requestURL:'https://localhost:9443/jazz/juneau/test/testPaths',
- // servletPath:'/juneau/test/testPaths',
- // relativeServletURI:'/jazz/juneau/test/testPaths',
- // pathRemainder2:null
- // }
- url = URL;
- r = client.doGet(url).getResponse(ObjectMap.class);
- assertNull(r.getString("pathInfo"));
- assertNull(r.getString("pathInfoUndecoded"));
- assertEquals("[]", r.getObjectList("pathInfoParts").toString());
- assertNull(r.getString("pathRemainder"));
- assertNull(r.getString("pathRemainderUndecoded"));
- assertNull(r.getString("pathRemainder2"));
- assertTrue(r.getString("requestURI").endsWith("/testPaths"));
- assertTrue(r.getString("requestParentURI").endsWith("/"));
- assertTrue(r.getString("requestURL").endsWith("/testPaths"));
- assertTrue(r.getString("servletPath").endsWith("/testPaths"));
- assertTrue(r.getString("servletURI").endsWith("/testPaths"));
- assertTrue(r.getString("relativeServletURI").endsWith("/testPaths"));
- assertEquals(1, (int)r.getInt("method"));
-
-
- // [/test/testPaths/]
- // {
- // pathInfo: '/',
- // pathInfoUndecoded: '/',
- // pathInfoParts: [
- // ],
- // pathRemainder: '',
- // pathRemainderUndecoded: '',
- // requestURI: '/jazz/juneau/test/testPaths/',
- // requestParentURI: '/jazz/juneau/test',
- // requestURL: 'https://localhost:9443/jazz/juneau/test/testPaths/',
- // servletPath: '/juneau/test/testPaths',
- // relativeServletURI: '/jazz/juneau/test/testPaths',
- // pathRemainder2: ''
- // }
- url = URL + '/';
- r = client.doGet(url).getResponse(ObjectMap.class);
- assertEquals("/", r.getString("pathInfo"));
- assertEquals("/", r.getString("pathInfoUndecoded"));
- assertEquals("[]", r.getObjectList("pathInfoParts").toString());
- assertEquals("", r.getString("pathRemainder"));
- assertEquals("", r.getString("pathRemainderUndecoded"));
- assertEquals("", r.getString("pathRemainder2"));
- assertTrue(r.getString("requestURI").endsWith("/testPaths/"));
- assertTrue(r.getString("requestParentURI").endsWith("/"));
- assertTrue(r.getString("requestURL").endsWith("/testPaths/"));
- assertTrue(r.getString("servletPath").endsWith("/testPaths"));
- assertTrue(r.getString("servletURI").endsWith("/testPaths"));
- assertTrue(r.getString("relativeServletURI").endsWith("/testPaths"));
- assertEquals(1, (int)r.getInt("method"));
-
- // [/test/testPaths//]
- // {
- // pathInfo: '//',
- // pathInfoParts: [''],
- // pathRemainder: '/',
- // requestURI: '/jazz/juneau/test/testPaths//',
- // requestParentURI: '/jazz/juneau/test',
- // requestURL: 'https://localhost:9443/jazz/juneau/test/testPaths//',
- // servletPath: '/juneau/test/testPaths',
- // relativeServletURI: '/jazz/juneau/test/testPaths',
- // pathRemainder2: '/'
- // }
- url = URL + "//";
- r = client.doGet(url).getResponse(ObjectMap.class);
- assertEquals("//", r.getString("pathInfo"));
- assertEquals("['']", r.getObjectList("pathInfoParts").toString());
- assertEquals("/", r.getString("pathRemainder"));
- assertEquals("/", r.getString("pathRemainder2"));
- assertTrue(r.getString("requestURI").endsWith("/testPaths//"));
- assertTrue(r.getString("requestParentURI").endsWith("/"));
- assertTrue(r.getString("requestURL").endsWith("/testPaths//"));
- assertTrue(r.getString("servletPath").endsWith("/testPaths"));
- assertTrue(r.getString("servletURI").endsWith("/testPaths"));
- assertTrue(r.getString("relativeServletURI").endsWith("/testPaths"));
- assertEquals(1, (int)r.getInt("method"));
-
- // [/test/testPaths///]
- // {
- // pathInfo: '///',
- // pathInfoParts: ['',''],
- // pathRemainder: '//',
- // requestURI: '/jazz/juneau/test/testPaths///',
- // requestParentURI: '/jazz/juneau/test',
- // requestURL: 'https://localhost:9443/jazz/juneau/test/testPaths///',
- // servletPath: '/juneau/test/testPaths',
- // relativeServletURI: '/jazz/juneau/test/testPaths',
- // pathRemainder2: '//'
- // }
- url = URL + "///";
- r = client.doGet(url).getResponse(ObjectMap.class);
- assertEquals("///", r.getString("pathInfo"));
- assertEquals("['','']", r.getObjectList("pathInfoParts").toString());
- assertEquals("//", r.getString("pathRemainder"));
- assertEquals("//", r.getString("pathRemainder2"));
- assertTrue(r.getString("requestURI").endsWith("/testPaths///"));
- assertTrue(r.getString("requestParentURI").endsWith("/"));
- assertTrue(r.getString("requestURL").endsWith("/testPaths///"));
- assertTrue(r.getString("servletPath").endsWith("/testPaths"));
- assertTrue(r.getString("servletURI").endsWith("/testPaths"));
- assertTrue(r.getString("relativeServletURI").endsWith("/testPaths"));
- assertEquals(1, (int)r.getInt("method"));
-
- // [/test/testPaths/foo/bar]
- // {
- // pathInfo: '/foo/bar',
- // pathInfoParts: [
- // 'foo',
- // 'bar'
- // ],
- // pathRemainder: 'foo/bar',
- // requestURI: '/jazz/juneau/test/testPaths/foo/bar',
- // requestParentURI: '/jazz/juneau/test/testPaths/foo',
- // requestURL: 'https://localhost:9443/jazz/juneau/test/testPaths/foo/bar',
- // servletPath: '/juneau/test/testPaths',
- // relativeServletURI: '/jazz/juneau/test/testPaths',
- // pathRemainder2: 'foo/bar'
- // }
- url = URL + "/foo/bar";
- r = client.doGet(url).getResponse(ObjectMap.class);
- assertEquals("/foo/bar", r.getString("pathInfo"));
- assertEquals("['foo','bar']", r.getObjectList("pathInfoParts").toString());
- assertEquals("foo/bar", r.getString("pathRemainder"));
- assertEquals("foo/bar", r.getString("pathRemainder2"));
- assertTrue(r.getString("requestURI").endsWith("/testPaths/foo/bar"));
- assertTrue(r.getString("requestParentURI").endsWith("/testPaths/foo"));
- assertTrue(r.getString("requestURL").endsWith("/testPaths/foo/bar"));
- assertTrue(r.getString("servletPath").endsWith("/testPaths"));
- assertTrue(r.getString("servletURI").endsWith("/testPaths"));
- assertTrue(r.getString("relativeServletURI").endsWith("/testPaths"));
- assertEquals(1, (int)r.getInt("method"));
-
- // [/test/testPaths/foo/bar/]
- // {
- // pathInfo: '/foo/bar/',
- // pathInfoParts: [
- // 'foo',
- // 'bar'
- // ],
- // pathRemainder: 'foo/bar/',
- // requestURI: '/jazz/juneau/test/testPaths/foo/bar/',
- // requestParentURI: '/jazz/juneau/test/testPaths/foo',
- // requestURL: 'https://localhost:9443/jazz/juneau/test/testPaths/foo/bar/',
- // servletPath: '/juneau/test/testPaths',
- // relativeServletURI: '/jazz/juneau/test/testPaths',
- // pathRemainder2: 'foo/bar/'
- // }
- url = URL + "/foo/bar/";
- r = client.doGet(url).getResponse(ObjectMap.class);
- assertEquals("/foo/bar/", r.getString("pathInfo"));
- assertEquals("['foo','bar']", r.getObjectList("pathInfoParts").toString());
- assertEquals("foo/bar/", r.getString("pathRemainder"));
- assertEquals("foo/bar/", r.getString("pathRemainder2"));
- assertTrue(r.getString("requestURI").endsWith("/testPaths/foo/bar/"));
- assertTrue(r.getString("requestParentURI").endsWith("/testPaths/foo"));
- assertTrue(r.getString("requestURL").endsWith("/testPaths/foo/bar/"));
- assertTrue(r.getString("servletPath").endsWith("/testPaths"));
- assertTrue(r.getString("servletURI").endsWith("/testPaths"));
- assertTrue(r.getString("relativeServletURI").endsWith("/testPaths"));
- assertEquals(1, (int)r.getInt("method"));
-
- // [/test/testPaths//foo//bar//]
- // {
- // pathInfo: '//foo//bar//',
- // pathInfoParts: [
- // '',
- // 'foo',
- // '',
- // 'bar',
- // ''
- // ],
- // pathRemainder: '/foo//bar//',
- // requestURI: '/jazz/juneau/test/testPaths//foo//bar//',
- // requestParentURI: '/jazz/juneau/test/testPaths//foo',
- // requestURL: 'https://localhost:9443/jazz/juneau/test/testPaths//foo//bar//',
- // servletPath: '/juneau/test/testPaths',
- // relativeServletURI: '/jazz/juneau/test/testPaths',
- // pathRemainder2: '/foo//bar//'
- // }
- url = URL + "//foo//bar//";
- r = client.doGet(url).getResponse(ObjectMap.class);
- assertEquals("//foo//bar//", r.getString("pathInfo"));
- assertEquals("['','foo','','bar','']", r.getObjectList("pathInfoParts").toString());
- assertEquals("/foo//bar//", r.getString("pathRemainder"));
- assertEquals("/foo//bar//", r.getString("pathRemainder2"));
- assertTrue(r.getString("requestURI").endsWith("/testPaths//foo//bar//"));
- assertTrue(r.getString("requestParentURI").endsWith("/testPaths//foo/"));
- assertTrue(r.getString("requestURL").endsWith("/testPaths//foo//bar//"));
- assertTrue(r.getString("servletPath").endsWith("/testPaths"));
- assertTrue(r.getString("servletURI").endsWith("/testPaths"));
- assertTrue(r.getString("relativeServletURI").endsWith("/testPaths"));
- assertEquals(1, (int)r.getInt("method"));
-
- // [/test/testPaths/foo%2Fbar]
- // {
- // pathInfo: '/foo//bar',
- // pathInfoUndecoded: '/foo%2F%2Fbar',
- // pathInfoParts: [
- // 'foo//bar'
- // ],
- // pathRemainder: 'foo//bar',
- // pathRemainderUndecoded: 'foo%2F%2Fbar',
- // requestURI: '/jazz/juneau/test/testPaths/foo%2F%2Fbar',
- // requestParentURI: '/jazz/juneau/test/testPaths',
- // requestURL: 'https://localhost:9443/jazz/juneau/test/testPaths/foo%2F%2Fbar',
- // servletPath: '/juneau/test/testPaths',
- // servletURI: 'https://localhost:9443/jazz/juneau/test/testPaths',
- // servletParentURI: 'https://localhost:9443/jazz/juneau/test',
- // relativeServletURI: '/jazz/juneau/test/testPaths',
- // pathRemainder2: 'foo//bar',
- // method: 1
- // }
- url = URL + "/foo%2F%2Fbar";
- r = client.doGet(url).getResponse(ObjectMap.class);
- assertEquals("/foo//bar", r.getString("pathInfo"));
- assertEquals("/foo%2F%2Fbar", r.getString("pathInfoUndecoded"));
- assertEquals("['foo//bar']", r.getObjectList("pathInfoParts").toString());
- assertEquals("foo//bar", r.getString("pathRemainder"));
- assertEquals("foo%2F%2Fbar", r.getString("pathRemainderUndecoded"));
- assertEquals("foo//bar", r.getString("pathRemainder2"));
- assertTrue(r.getString("requestURI").endsWith("/testPaths/foo%2F%2Fbar"));
- assertTrue(r.getString("requestParentURI").endsWith("/testPaths"));
- assertTrue(r.getString("requestURL").endsWith("/testPaths/foo%2F%2Fbar"));
- assertTrue(r.getString("servletPath").endsWith("/testPaths"));
- assertTrue(r.getString("servletURI").endsWith("/testPaths"));
- assertTrue(r.getString("relativeServletURI").endsWith("/testPaths"));
- assertEquals(1, (int)r.getInt("method"));
-
- // [/test/testPaths//foo%2Fbar//]
- // {
- // pathInfo: '//foo//bar//',
- // pathInfoUndecoded: '//foo%2F%2Fbar//',
- // pathInfoParts: [
- // '',
- // 'foo//bar',
- // ''
- // ],
- // pathRemainder: '/foo//bar//',
- // pathRemainderUndecoded: '/foo%2F%2Fbar//',
- // requestURI: '/jazz/juneau/test/testPaths//foo%2F%2Fbar//',
- // requestParentURI: '/jazz/juneau/test/testPaths/',
- // requestURL: 'https://localhost:9443/jazz/juneau/test/testPaths//foo%2F%2Fbar//',
- // servletPath: '/juneau/test/testPaths',
- // servletURI: 'https://localhost:9443/jazz/juneau/test/testPaths',
- // servletParentURI: 'https://localhost:9443/jazz/juneau/test',
- // relativeServletURI: '/jazz/juneau/test/testPaths',
- // pathRemainder2: '/foo//bar//',
- // method: 1
- // }
- url = URL + "//foo%2F%2Fbar//";
- r = client.doGet(url).getResponse(ObjectMap.class);
- assertEquals("//foo//bar//", r.getString("pathInfo"));
- assertEquals("//foo%2F%2Fbar//", r.getString("pathInfoUndecoded"));
- assertEquals("['','foo//bar','']", r.getObjectList("pathInfoParts").toString());
- assertEquals("/foo//bar//", r.getString("pathRemainder"));
- assertEquals("/foo%2F%2Fbar//", r.getString("pathRemainderUndecoded"));
- assertEquals("/foo//bar//", r.getString("pathRemainder2"));
- assertTrue(r.getString("requestURI").endsWith("/testPaths//foo%2F%2Fbar//"));
- assertTrue(r.getString("requestParentURI").endsWith("/testPaths/"));
- assertTrue(r.getString("requestURL").endsWith("/testPaths//foo%2F%2Fbar//"));
- assertTrue(r.getString("servletPath").endsWith("/testPaths"));
- assertTrue(r.getString("servletURI").endsWith("/testPaths"));
- assertTrue(r.getString("relativeServletURI").endsWith("/testPaths"));
- assertEquals(1, (int)r.getInt("method"));
-
- // [/test/testPaths/test2]
- // {
- // pathInfo: '/test2',
- // pathInfoParts: [
- // 'test2'
- // ],
- // pathRemainder: null,
- // requestURI: '/jazz/juneau/test/testPaths/test2',
- // requestParentURI: '/jazz/juneau/test/testPaths',
- // requestURL: 'https://localhost:9443/jazz/juneau/test/testPaths/test2',
- // servletPath: '/juneau/test/testPaths',
- // servletURI: 'https://localhost:9443/jazz/juneau/test/testPaths',
- // servletParentURI: 'https://localhost:9443/jazz/juneau/test',
- // relativeServletURI: '/jazz/juneau/test/testPaths',
- // pathRemainder2: null,
- // method: 2
- // }
- url = URL + "/test2";
- r = client.doGet(url).getResponse(ObjectMap.class);
- assertEquals("/test2", r.getString("pathInfo"));
- assertEquals("['test2']", r.getObjectList("pathInfoParts").toString());
- assertNull(r.getString("pathRemainder"));
- assertNull(r.getString("pathRemainder2"));
- assertTrue(r.getString("requestURI").endsWith("/testPaths/test2"));
- assertTrue(r.getString("requestParentURI").endsWith("/testPaths"));
- assertTrue(r.getString("requestURL").endsWith("/testPaths/test2"));
- assertTrue(r.getString("servletPath").endsWith("/testPaths"));
- assertTrue(r.getString("servletURI").endsWith("/testPaths"));
- assertTrue(r.getString("relativeServletURI").endsWith("/testPaths"));
- assertEquals(2, (int)r.getInt("method"));
-
-
- // [/test/testPaths/test2/]
- // {
- // pathInfo: '/test2/',
- // pathInfoParts: [
- // 'test2'
- // ],
- // pathRemainder: '',
- // requestURI: '/jazz/juneau/test/testPaths/test2/',
- // requestParentURI: '/jazz/juneau/test/testPaths',
- // requestURL: 'https://localhost:9443/jazz/juneau/test/testPaths/test2/',
- // servletPath: '/juneau/test/testPaths',
- // servletURI: 'https://localhost:9443/jazz/juneau/test/testPaths',
- // servletParentURI: 'https://localhost:9443/jazz/juneau/test',
- // relativeServletURI: '/jazz/juneau/test/testPaths',
- // pathRemainder2: '',
- // method: 2
- // }
- url = URL + "/test2/";
- r = client.doGet(url).getResponse(ObjectMap.class);
- assertEquals("/test2/", r.getString("pathInfo"));
- assertEquals("['test2']", r.getObjectList("pathInfoParts").toString());
- assertEquals("", r.getString("pathRemainder"));
- assertEquals("", r.getString("pathRemainder2"));
- assertTrue(r.getString("requestURI").endsWith("/testPaths/test2/"));
- assertTrue(r.getString("requestParentURI").endsWith("/testPaths"));
- assertTrue(r.getString("requestURL").endsWith("/testPaths/test2/"));
- assertTrue(r.getString("servletPath").endsWith("/testPaths"));
- assertTrue(r.getString("servletURI").endsWith("/testPaths"));
- assertTrue(r.getString("relativeServletURI").endsWith("/testPaths"));
- assertEquals(2, (int)r.getInt("method"));
-
- // [/test/testPaths/test2//]
- // {
- // pathInfo: '/test2//',
- // pathInfoParts: [
- // 'test2',
- // ''
- // ],
- // pathRemainder: '/',
- // requestURI: '/jazz/juneau/test/testPaths/test2//',
- // requestParentURI: '/jazz/juneau/test/testPaths',
- // requestURL: 'https://localhost:9443/jazz/juneau/test/testPaths/test2//',
- // servletPath: '/juneau/test/testPaths',
- // servletURI: 'https://localhost:9443/jazz/juneau/test/testPaths',
- // servletParentURI: 'https://localhost:9443/jazz/juneau/test',
- // relativeServletURI: '/jazz/juneau/test/testPaths',
- // pathRemainder2: '/',
- // method: 2
- // }
- url = URL + "/test2//";
- r = client.doGet(url).getResponse(ObjectMap.class);
- assertEquals("/test2//", r.getString("pathInfo"));
- assertEquals("['test2','']", r.getObjectList("pathInfoParts").toString());
- assertEquals("/", r.getString("pathRemainder"));
- assertEquals("/", r.getString("pathRemainder2"));
- assertTrue(r.getString("requestURI").endsWith("/testPaths/test2//"));
- assertTrue(r.getString("requestParentURI").endsWith("/testPaths"));
- assertTrue(r.getString("requestURL").endsWith("/testPaths/test2//"));
- assertTrue(r.getString("servletPath").endsWith("/testPaths"));
- assertTrue(r.getString("servletURI").endsWith("/testPaths"));
- assertTrue(r.getString("relativeServletURI").endsWith("/testPaths"));
- assertEquals(2, (int)r.getInt("method"));
-
- // [/test/testPaths/test2///]
- // {
- // pathInfo: '/test2///',
- // pathInfoParts: [
- // 'test2',
- // '',
- // ''
- // ],
- // pathRemainder: '//',
- // requestURI: '/jazz/juneau/test/testPaths/test2///',
- // requestParentURI: '/jazz/juneau/test/testPaths',
- // requestURL: 'https://localhost:9443/jazz/juneau/test/testPaths/test2///',
- // servletPath: '/juneau/test/testPaths',
- // servletURI: 'https://localhost:9443/jazz/juneau/test/testPaths',
- // servletParentURI: 'https://localhost:9443/jazz/juneau/test',
- // relativeServletURI: '/jazz/juneau/test/testPaths',
- // pathRemainder2: '//',
- // method: 2
- // }
- url = URL + "/test2///";
- r = client.doGet(url).getResponse(ObjectMap.class);
- assertEquals("/test2///", r.getString("pathInfo"));
- assertEquals("['test2','','']", r.getObjectList("pathInfoParts").toString());
- assertEquals("//", r.getString("pathRemainder"));
- assertEquals("//", r.getString("pathRemainder2"));
- assertTrue(r.getString("requestURI").endsWith("/testPaths/test2///"));
- assertTrue(r.getString("requestParentURI").endsWith("/testPaths"));
- assertTrue(r.getString("requestURL").endsWith("/testPaths/test2///"));
- assertTrue(r.getString("servletPath").endsWith("/testPaths"));
- assertTrue(r.getString("servletURI").endsWith("/testPaths"));
- assertTrue(r.getString("relativeServletURI").endsWith("/testPaths"));
- assertEquals(2, (int)r.getInt("method"));
-
- // [/test/testPaths/test2/foo/bar]
- // {
- // pathInfo: '/test2/foo/bar',
- // pathInfoParts: [
- // 'test2',
- // 'foo',
- // 'bar'
- // ],
- // pathRemainder: 'foo/bar',
- // requestURI: '/jazz/juneau/test/testPaths/test2/foo/bar',
- // requestParentURI: '/jazz/juneau/test/testPaths/test2/foo',
- // requestURL: 'https://localhost:9443/jazz/juneau/test/testPaths/test2/foo/bar',
- // servletPath: '/juneau/test/testPaths',
- // servletURI: 'https://localhost:9443/jazz/juneau/test/testPaths',
- // servletParentURI: 'https://localhost:9443/jazz/juneau/test',
- // relativeServletURI: '/jazz/juneau/test/testPaths',
- // pathRemainder2: 'foo/bar',
- // method: 2
- // }
- url = URL + "/test2/foo/bar";
- r = client.doGet(url).getResponse(ObjectMap.class);
- assertEquals("/test2/foo/bar", r.getString("pathInfo"));
- assertEquals("['test2','foo','bar']", r.getObjectList("pathInfoParts").toString());
- assertEquals("foo/bar", r.getString("pathRemainder"));
- assertEquals("foo/bar", r.getString("pathRemainder2"));
- assertTrue(r.getString("requestURI").endsWith("/testPaths/test2/foo/bar"));
- assertTrue(r.getString("requestParentURI").endsWith("/testPaths/test2/foo"));
- assertTrue(r.getString("requestURL").endsWith("/testPaths/test2/foo/bar"));
- assertTrue(r.getString("servletPath").endsWith("/testPaths"));
- assertTrue(r.getString("servletURI").endsWith("/testPaths"));
- assertTrue(r.getString("relativeServletURI").endsWith("/testPaths"));
- assertEquals(2, (int)r.getInt("method"));
-
- // [/test/testPaths/test2/foo/bar/]
- // {
- // pathInfo: '/test2/foo/bar/',
- // pathInfoParts: [
- // 'test2',
- // 'foo',
- // 'bar'
- // ],
- // pathRemainder: 'foo/bar/',
- // requestURI: '/jazz/juneau/test/testPaths/test2/foo/bar/',
- // requestParentURI: '/jazz/juneau/test/testPaths/test2/foo',
- // requestURL: 'https://localhost:9443/jazz/juneau/test/testPaths/test2/foo/bar/',
- // servletPath: '/juneau/test/testPaths',
- // servletURI: 'https://localhost:9443/jazz/juneau/test/testPaths',
- // servletParentURI: 'https://localhost:9443/jazz/juneau/test',
- // relativeServletURI: '/jazz/juneau/test/testPaths',
- // pathRemainder2: 'foo/bar/',
- // method: 2
- // }
- url = URL + "/test2/foo/bar/";
- r = client.doGet(url).getResponse(ObjectMap.class);
- assertEquals("/test2/foo/bar/", r.getString("pathInfo"));
- assertEquals("['test2','foo','bar']", r.getObjectList("pathInfoParts").toString());
- assertEquals("foo/bar/", r.getString("pathRemainder"));
- assertEquals("foo/bar/", r.getString("pathRemainder2"));
- assertTrue(r.getString("requestURI").endsWith("/testPaths/test2/foo/bar/"));
- assertTrue(r.getString("requestParentURI").endsWith("/testPaths/test2/foo"));
- assertTrue(r.getString("requestURL").endsWith("/testPaths/test2/foo/bar/"));
- assertTrue(r.getString("servletPath").endsWith("/testPaths"));
- assertTrue(r.getString("servletURI").endsWith("/testPaths"));
- assertTrue(r.getString("relativeServletURI").endsWith("/testPaths"));
- assertEquals(2, (int)r.getInt("method"));
-
- // [/test/testPaths/test2//foo//bar//]
- // {
- // pathInfo: '/test2//foo//bar//',
- // pathInfoParts: [
- // 'test2',
- // '',
- // 'foo',
- // '',
- // 'bar',
- // ''
- // ],
- // pathRemainder: '/foo//bar//',
- // requestURI: '/jazz/juneau/test/testPaths/test2//foo//bar//',
- // requestParentURI: '/jazz/juneau/test/testPaths/test2//foo/',
- // requestURL: 'https://localhost:9443/jazz/juneau/test/testPaths/test2//foo//bar//',
- // servletPath: '/juneau/test/testPaths',
- // servletURI: 'https://localhost:9443/jazz/juneau/test/testPaths',
- // servletParentURI: 'https://localhost:9443/jazz/juneau/test',
- // relativeServletURI: '/jazz/juneau/test/testPaths',
- // pathRemainder2: '/foo//bar//',
- // method: 2
- // }
- url = URL + "/test2//foo//bar//";
- r = client.doGet(url).getResponse(ObjectMap.class);
- assertEquals("/test2//foo//bar//", r.getString("pathInfo"));
- assertEquals("['test2','','foo','','bar','']", r.getObjectList("pathInfoParts").toString());
- assertEquals("/foo//bar//", r.getString("pathRemainder"));
- assertEquals("/foo//bar//", r.getString("pathRemainder2"));
- assertTrue(r.getString("requestURI").endsWith("/testPaths/test2//foo//bar//"));
- assertTrue(r.getString("requestParentURI").endsWith("/testPaths/test2//foo/"));
- assertTrue(r.getString("requestURL").endsWith("/testPaths/test2//foo//bar//"));
- assertTrue(r.getString("servletPath").endsWith("/testPaths"));
- assertTrue(r.getString("servletURI").endsWith("/testPaths"));
- assertTrue(r.getString("relativeServletURI").endsWith("/testPaths"));
- assertEquals(2, (int)r.getInt("method"));
-
- // [/test/testPaths/test2/foo%2Fbar]
- // {
- // pathInfo: '/test2/foo//bar',
- // pathInfoUndecoded: '/test2/foo%2F%2Fbar',
- // pathInfoParts: [
- // 'test2',
- // 'foo//bar'
- // ],
- // pathRemainder: 'foo//bar',
- // pathRemainderUndecoded: 'foo%2F%2Fbar',
- // requestURI: '/jazz/juneau/test/testPaths/test2/foo%2F%2Fbar',
- // requestParentURI: '/jazz/juneau/test/testPaths/test2',
- // requestURL: 'https://localhost:9443/jazz/juneau/test/testPaths/test2/foo%2F%2Fbar',
- // servletPath: '/juneau/test/testPaths',
- // servletURI: 'https://localhost:9443/jazz/juneau/test/testPaths',
- // servletParentURI: 'https://localhost:9443/jazz/juneau/test',
- // relativeServletURI: '/jazz/juneau/test/testPaths',
- // pathRemainder2: 'foo//bar',
- // method: 2
- // }
- url = URL + "/test2/foo%2F%2Fbar";
- r = client.doGet(url).getResponse(ObjectMap.class);
- assertEquals("/test2/foo//bar", r.getString("pathInfo"));
- assertEquals("/test2/foo%2F%2Fbar", r.getString("pathInfoUndecoded"));
- assertEquals("['test2','foo//bar']", r.getObjectList("pathInfoParts").toString());
- assertEquals("foo//bar", r.getString("pathRemainder"));
- assertEquals("foo%2F%2Fbar", r.getString("pathRemainderUndecoded"));
- assertEquals("foo//bar", r.getString("pathRemainder2"));
- assertTrue(r.getString("requestURI").endsWith("/testPaths/test2/foo%2F%2Fbar"));
- assertTrue(r.getString("requestParentURI").endsWith("/testPaths/test2"));
- assertTrue(r.getString("requestURL").endsWith("/testPaths/test2/foo%2F%2Fbar"));
- assertTrue(r.getString("servletPath").endsWith("/testPaths"));
- assertTrue(r.getString("servletURI").endsWith("/testPaths"));
- assertTrue(r.getString("relativeServletURI").endsWith("/testPaths"));
- assertEquals(2, (int)r.getInt("method"));
-
- // [/test/testPaths/test2//foo%2Fbar//]
- // {
- // pathInfo: '/test2//foo//bar//',
- // pathInfoUndecoded: '/test2//foo%2F%2Fbar//',
- // pathInfoParts: [
- // 'test2',
- // '',
- // 'foo//bar',
- // ''
- // ],
- // pathRemainder: '/foo//bar//',
- // pathRemainderUndecoded: '/foo%2F%2Fbar//',
- // requestURI: '/jazz/juneau/test/testPaths/test2//foo%2F%2Fbar//',
- // requestParentURI: '/jazz/juneau/test/testPaths/test2/',
- // requestURL: 'https://localhost:9443/jazz/juneau/test/testPaths/test2//foo%2F%2Fbar//',
- // servletPath: '/juneau/test/testPaths',
- // servletURI: 'https://localhost:9443/jazz/juneau/test/testPaths',
- // servletParentURI: 'https://localhost:9443/jazz/juneau/test',
- // relativeServletURI: '/jazz/juneau/test/testPaths',
- // pathRemainder2: '/foo//bar//',
- // method: 2
- // }
- url = URL + "/test2//foo%2F%2Fbar//";
- r = client.doGet(url).getResponse(ObjectMap.class);
- assertEquals("/test2//foo//bar//", r.getString("pathInfo"));
- assertEquals("/test2//foo%2F%2Fbar//", r.getString("pathInfoUndecoded"));
- assertEquals("['test2','','foo//bar','']", r.getObjectList("pathInfoParts").toString());
- assertEquals("/foo//bar//", r.getString("pathRemainder"));
- assertEquals("/foo%2F%2Fbar//", r.getString("pathRemainderUndecoded"));
- assertEquals("/foo//bar//", r.getString("pathRemainder2"));
- assertTrue(r.getString("requestURI").endsWith("/testPaths/test2//foo%2F%2Fbar//"));
- assertTrue(r.getString("requestParentURI").endsWith("/testPaths/test2/"));
- assertTrue(r.getString("requestURL").endsWith("/testPaths/test2//foo%2F%2Fbar//"));
- assertTrue(r.getString("servletPath").endsWith("/testPaths"));
- assertTrue(r.getString("servletURI").endsWith("/testPaths"));
- assertTrue(r.getString("relativeServletURI").endsWith("/testPaths"));
- assertEquals(2, (int)r.getInt("method"));
-
- // [/test/testPaths/a]
- // {
- // pathInfo: null,
- // pathInfoParts: [
- // ],
- // pathRemainder: null,
- // requestURI: '/jazz/juneau/test/testPaths/a',
- // requestParentURI: '/jazz/juneau/test/testPaths',
- // requestURL: 'https://localhost:9443/jazz/juneau/test/testPaths/a',
- // servletPath: '/juneau/test/testPaths/a',
- // servletURI: 'https://localhost:9443/jazz/juneau/test/testPaths/a',
- // servletParentURI: 'https://localhost:9443/jazz/juneau/test/testPaths',
- // relativeServletURI: '/jazz/juneau/test/testPaths/a',
- // pathRemainder2: null,
- // method: 3
- // }
- url = URL + "/a";
- r = client.doGet(url).getResponse(ObjectMap.class);
- assertNull(r.getString("pathInfo"));
- assertEquals("[]", r.getObjectList("pathInfoParts").toString());
- assertNull(r.getString("pathRemainder"));
- assertNull(r.getString("pathRemainder2"));
- assertTrue(r.getString("requestURI").endsWith("/testPaths/a"));
- assertTrue(r.getString("requestParentURI").endsWith("/testPaths"));
- assertTrue(r.getString("requestURL").endsWith("/testPaths/a"));
- assertTrue(r.getString("servletPath").endsWith("/testPaths/a"));
- assertTrue(r.getString("servletURI").endsWith("/testPaths/a"));
- assertTrue(r.getString("servletParentURI").endsWith("/testPaths"));
- assertTrue(r.getString("relativeServletURI").endsWith("/testPaths/a"));
- assertEquals(3, (int)r.getInt("method"));
-
- // [/test/testPaths/a/]
- // {
- // pathInfo: '/',
- // pathInfoParts: [
- // ],
- // pathRemainder: '',
- // requestURI: '/jazz/juneau/test/testPaths/a/',
- // requestParentURI: '/jazz/juneau/test/testPaths',
- // requestURL: 'https://localhost:9443/jazz/juneau/test/testPaths/a/',
- // servletPath: '/juneau/test/testPaths/a',
- // servletURI: 'https://localhost:9443/jazz/juneau/test/testPaths/a',
- // servletParentURI: 'https://localhost:9443/jazz/juneau/test/testPaths',
- // relativeServletURI: '/jazz/juneau/test/testPaths/a',
- // pathRemainder2: '',
- // method: 3
- // }
- url = URL + "/a/";
- r = client.doGet(url).getResponse(ObjectMap.class);
- assertEquals("/", r.getString("pathInfo"));
- assertEquals("[]", r.getObjectList("pathInfoParts").toString());
- assertEquals("", r.getString("pathRemainder"));
- assertEquals("", r.getString("pathRemainder2"));
- assertTrue(r.getString("requestURI").endsWith("/testPaths/a/"));
- assertTrue(r.getString("requestParentURI").endsWith("/testPaths"));
- assertTrue(r.getString("requestURL").endsWith("/testPaths/a/"));
- assertTrue(r.getString("servletPath").endsWith("/testPaths/a"));
- assertTrue(r.getString("servletURI").endsWith("/testPaths/a"));
- assertTrue(r.getString("servletParentURI").endsWith("/testPaths"));
- assertTrue(r.getString("relativeServletURI").endsWith("/testPaths/a"));
- assertEquals(3, (int)r.getInt("method"));
-
- // [/test/testPaths/a//]
- // {
- // pathInfo: '//',
- // pathInfoParts: [
- // ''
- // ],
- // pathRemainder: '/',
- // requestURI: '/jazz/juneau/test/testPaths/a//',
- // requestParentURI: '/jazz/juneau/test/testPaths',
- // requestURL: 'https://localhost:9443/jazz/juneau/test/testPaths/a//',
- // servletPath: '/juneau/test/testPaths/a',
- // servletURI: 'https://localhost:9443/jazz/juneau/test/testPaths/a',
- // servletParentURI: 'https://localhost:9443/jazz/juneau/test/testPaths',
- // relativeServletURI: '/jazz/juneau/test/testPaths/a',
- // pathRemainder2: '/',
- // method: 3
- // }
- url = URL + "/a//";
- r = client.doGet(url).getResponse(ObjectMap.class);
- assertEquals("//", r.getString("pathInfo"));
- assertEquals("['']", r.getObjectList("pathInfoParts").toString());
- assertEquals("/", r.getString("pathRemainder"));
- assertEquals("/", r.getString("pathRemainder2"));
- assertTrue(r.getString("requestURI").endsWith("/testPaths/a//"));
- assertTrue(r.getString("requestParentURI").endsWith("/testPaths"));
- assertTrue(r.getString("requestURL").endsWith("/testPaths/a//"));
- assertTrue(r.getString("servletPath").endsWith("/testPaths/a"));
- assertTrue(r.getString("servletURI").endsWith("/testPaths/a"));
- assertTrue(r.getString("servletParentURI").endsWith("/testPaths"));
- assertTrue(r.getString("relativeServletURI").endsWith("/testPaths/a"));
- assertEquals(3, (int)r.getInt("method"));
-
- // [/test/testPaths/a///]
- // {
- // pathInfo: '///',
- // pathInfoParts: [
- // '',
- // ''
- // ],
- // pathRemainder: '//',
- // requestURI: '/jazz/juneau/test/testPaths/a///',
- // requestParentURI: '/jazz/juneau/test/testPaths',
- // requestURL: 'https://localhost:9443/jazz/juneau/test/testPaths/a///',
- // servletPath: '/juneau/test/testPaths/a',
- // servletURI: 'https://localhost:9443/jazz/juneau/test/testPaths/a',
- // servletParentURI: 'https://localhost:9443/jazz/juneau/test/testPaths',
- // relativeServletURI: '/jazz/juneau/test/testPaths/a',
- // pathRemainder2: '//',
- // method: 3
- // }
- url = URL + "/a///";
- r = client.doGet(url).getResponse(ObjectMap.class);
- assertEquals("///", r.getString("pathInfo"));
- assertEquals("['','']", r.getObjectList("pathInfoParts").toString());
- assertEquals("//", r.getString("pathRemainder"));
- assertEquals("//", r.getString("pathRemainder2"));
- assertTrue(r.getString("requestURI").endsWith("/testPaths/a///"));
- assertTrue(r.getString("requestParentURI").endsWith("/testPaths"));
- assertTrue(r.getString("requestURL").endsWith("/testPaths/a///"));
- assertTrue(r.getString("servletPath").endsWith("/testPaths/a"));
- assertTrue(r.getString("servletURI").endsWith("/testPaths/a"));
- assertTrue(r.getString("servletParentURI").endsWith("/testPaths"));
- assertTrue(r.getString("relativeServletURI").endsWith("/testPaths/a"));
- assertEquals(3, (int)r.getInt("method"));
-
- // [/test/testPaths/a/foo/bar]
- // {
- // pathInfo: '/foo/bar',
- // pathInfoParts: [
- // 'foo',
- // 'bar'
- // ],
- // pathRemainder: 'foo/bar',
- // requestURI: '/jazz/juneau/test/testPaths/a/foo/bar',
- // requestParentURI: '/jazz/juneau/test/testPaths/a/foo',
- // requestURL: 'https://localhost:9443/jazz/juneau/test/testPaths/a/foo/bar',
- // servletPath: '/juneau/test/testPaths/a',
- // servletURI: 'https://localhost:9443/jazz/juneau/test/testPaths/a',
- // servletParentURI: 'https://localhost:9443/jazz/juneau/test/testPaths',
- // relativeServletURI: '/jazz/juneau/test/testPaths/a',
- // pathRemainder2: 'foo/bar',
- // method: 3
- // }
- url = URL + "/a/foo/bar";
- r = client.doGet(url).getResponse(ObjectMap.class);
- assertEquals("/foo/bar", r.getString("pathInfo"));
- assertEquals("['foo','bar']", r.getObjectList("pathInfoParts").toString());
- assertEquals("foo/bar", r.getString("pathRemainder"));
- assertEquals("foo/bar", r.getString("pathRemainder2"));
- assertTrue(r.getString("requestURI").endsWith("/testPaths/a/foo/bar"));
- assertTrue(r.getString("requestParentURI").endsWith("/testPaths/a/foo"));
- assertTrue(r.getString("requestURL").endsWith("/testPaths/a/foo/bar"));
- assertTrue(r.getString("servletPath").endsWith("/testPaths/a"));
- assertTrue(r.getString("servletURI").endsWith("/testPaths/a"));
- assertTrue(r.getString("servletParentURI").endsWith("/testPaths"));
- assertTrue(r.getString("relativeServletURI").endsWith("/testPaths/a"));
- assertEquals(3, (int)r.getInt("method"));
-
- // [/test/testPaths/a/foo/bar/]
- // {
- // pathInfo: '/foo/bar/',
- // pathInfoParts: [
- // 'foo',
- // 'bar'
- // ],
- // pathRemainder: 'foo/bar/',
- // requestURI: '/jazz/juneau/test/testPaths/a/foo/bar/',
- // requestParentURI: '/jazz/juneau/test/testPaths/a/foo',
- // requestURL: 'https://localhost:9443/jazz/juneau/test/testPaths/a/foo/bar/',
- // servletPath: '/juneau/test/testPaths/a',
- // servletURI: 'https://localhost:9443/jazz/juneau/test/testPaths/a',
- // servletParentURI: 'https://localhost:9443/jazz/juneau/test/testPaths',
- // relativeServletURI: '/jazz/juneau/test/testPaths/a',
- // pathRemainder2: 'foo/bar/',
- // method: 3
- // }
- url = URL + "/a/foo/bar/";
- r = client.doGet(url).getResponse(ObjectMap.class);
- assertEquals("/foo/bar/", r.getString("pathInfo"));
- assertEquals("['foo','bar']", r.getObjectList("pathInfoParts").toString());
- assertEquals("foo/bar/", r.getString("pathRemainder"));
- assertEquals("foo/bar/", r.getString("pathRemainder2"));
- assertTrue(r.getString("requestURI").endsWith("/testPaths/a/foo/bar/"));
- assertTrue(r.getString("requestParentURI").endsWith("/testPaths/a/foo"));
- assertTrue(r.getString("requestURL").endsWith("/testPaths/a/foo/bar/"));
- assertTrue(r.getString("servletPath").endsWith("/testPaths/a"));
- assertTrue(r.getString("servletURI").endsWith("/testPaths/a"));
- assertTrue(r.getString("servletParentURI").endsWith("/testPaths"));
- assertTrue(r.getString("relativeServletURI").endsWith("/testPaths/a"));
- assertEquals(3, (int)r.getInt("method"));
-
- // [/test/testPaths/a//foo//bar//]
- // {
- // pathInfo: '//foo//bar//',
- // pathInfoParts: [
- // '',
- // 'foo',
- // '',
- // 'bar',
- // ''
- // ],
- // pathRemainder: '/foo//bar//',
- // requestURI: '/jazz/juneau/test/testPaths/a//foo//bar//',
- // requestParentURI: '/jazz/juneau/test/testPaths/a//foo/',
- // requestURL: 'https://localhost:9443/jazz/juneau/test/testPaths/a//foo//bar//',
- // servletPath: '/juneau/test/testPaths/a',
- // servletURI: 'https://localhost:9443/jazz/juneau/test/testPaths/a',
- // servletParentURI: 'https://localhost:9443/jazz/juneau/test/testPaths',
- // relativeServletURI: '/jazz/juneau/test/testPaths/a',
- // pathRemainder2: '/foo//bar//',
- // method: 3
- // }
- url = URL + "/a//foo//bar//";
- r = client.doGet(url).getResponse(ObjectMap.class);
- assertEquals("//foo//bar//", r.getString("pathInfo"));
- assertEquals("['','foo','','bar','']", r.getObjectList("pathInfoParts").toString());
- assertEquals("/foo//bar//", r.getString("pathRemainder"));
- assertEquals("/foo//bar//", r.getString("pathRemainder2"));
- assertTrue(r.getString("requestURI").endsWith("/testPaths/a//foo//bar//"));
- assertTrue(r.getString("requestParentURI").endsWith("/testPaths/a//foo/"));
- assertTrue(r.getString("requestURL").endsWith("/testPaths/a//foo//bar//"));
- assertTrue(r.getString("servletPath").endsWith("/testPaths/a"));
- assertTrue(r.getString("servletURI").endsWith("/testPaths/a"));
- assertTrue(r.getString("servletParentURI").endsWith("/testPaths"));
- assertTrue(r.getString("relativeServletURI").endsWith("/testPaths/a"));
- assertEquals(3, (int)r.getInt("method"));
-
- // [/test/testPaths/a/foo%2Fbar]
- // {
- // pathInfo: '/foo//bar',
- // pathInfoUndecoded: '/foo%2F%2Fbar',
- // pathInfoParts: [
- // 'foo//bar'
- // ],
- // pathRemainder: 'foo//bar',
- // pathRemainderUndecoded: 'foo%2F%2Fbar',
- // requestURI: '/jazz/juneau/test/testPaths/a/foo%2F%2Fbar',
- // requestParentURI: '/jazz/juneau/test/testPaths/a',
- // requestURL: 'https://localhost:9443/jazz/juneau/test/testPaths/a/foo%2F%2Fbar',
- // servletPath: '/juneau/test/testPaths/a',
- // servletURI: 'https://localhost:9443/jazz/juneau/test/testPaths/a',
- // servletParentURI: 'https://localhost:9443/jazz/juneau/test/testPaths',
- // relativeServletURI: '/jazz/juneau/test/testPaths/a',
- // pathRemainder2: 'foo//bar',
- // method: 3
- // }
- url = URL + "/a/foo%2F%2Fbar";
- r = client.doGet(url).getResponse(ObjectMap.class);
- assertEquals("/foo//bar", r.getString("pathInfo"));
- assertEquals("/foo%2F%2Fbar", r.getString("pathInfoUndecoded"));
- assertEquals("['foo//bar']", r.getObjectList("pathInfoParts").toString());
- assertEquals("foo//bar", r.getString("pathRemainder"));
- assertEquals("foo%2F%2Fbar", r.getString("pathRemainderUndecoded"));
- assertEquals("foo//bar", r.getString("pathRemainder2"));
- assertTrue(r.getString("requestURI").endsWith("/testPaths/a/foo%2F%2Fbar"));
- assertTrue(r.getString("requestParentURI").endsWith("/testPaths/a"));
- assertTrue(r.getString("requestURL").endsWith("/testPaths/a/foo%2F%2Fbar"));
- assertTrue(r.getString("servletPath").endsWith("/testPaths/a"));
- assertTrue(r.getString("servletURI").endsWith("/testPaths/a"));
- assertTrue(r.getString("servletParentURI").endsWith("/testPaths"));
- assertTrue(r.getString("relativeServletURI").endsWith("/testPaths/a"));
- assertEquals(3, (int)r.getInt("method"));
-
- // [/test/testPaths/a//foo%2Fbar//]
- // {
- // pathInfo: '//foo//bar//',
- // pathInfoUndecoded: '//foo%2F%2Fbar//',
- // pathInfoParts: [
- // '',
- // 'foo//bar',
- // ''
- // ],
- // pathRemainder: '/foo//bar//',
- // pathRemainderUndecoded: '/foo%2F%2Fbar//',
- // requestURI: '/jazz/juneau/test/testPaths/a//foo%2F%2Fbar//',
- // requestParentURI: '/jazz/juneau/test/testPaths/a/',
- // requestURL: 'https://localhost:9443/jazz/juneau/test/testPaths/a//foo%2F%2Fbar//',
- // servletPath: '/juneau/test/testPaths/a',
- // servletURI: 'https://localhost:9443/jazz/juneau/test/testPaths/a',
- // servletParentURI: 'https://localhost:9443/jazz/juneau/test/testPaths',
- // relativeServletURI: '/jazz/juneau/test/testPaths/a',
- // pathRemainder2: '/foo//bar//',
- // method: 3
- // }
- url = URL + "/a//foo%2F%2Fbar//";
- r = client.doGet(url).getResponse(ObjectMap.class);
- assertEquals("//foo//bar//", r.getString("pathInfo"));
- assertEquals("//foo%2F%2Fbar//", r.getString("pathInfoUndecoded"));
- assertEquals("['','foo//bar','']", r.getObjectList("pathInfoParts").toString());
- assertEquals("/foo//bar//", r.getString("pathRemainder"));
- assertEquals("/foo%2F%2Fbar//", r.getString("pathRemainderUndecoded"));
- assertEquals("/foo//bar//", r.getString("pathRemainder2"));
- assertTrue(r.getString("requestURI").endsWith("/testPaths/a//foo%2F%2Fbar//"));
- assertTrue(r.getString("requestParentURI").endsWith("/testPaths/a/"));
- assertTrue(r.getString("requestURL").endsWith("/testPaths/a//foo%2F%2Fbar//"));
- assertTrue(r.getString("servletPath").endsWith("/testPaths/a"));
- assertTrue(r.getString("servletURI").endsWith("/testPaths/a"));
- assertTrue(r.getString("servletParentURI").endsWith("/testPaths"));
- assertTrue(r.getString("relativeServletURI").endsWith("/testPaths/a"));
- assertEquals(3, (int)r.getInt("method"));
-
-
- // [/test/testPaths/a/test2]
- // {
- // pathInfo: '/test2',
- // pathInfoParts: [
- // 'test2'
- // ],
- // pathRemainder: null,
- // requestURI: '/jazz/juneau/test/testPaths/a/test2',
- // requestParentURI: '/jazz/juneau/test/testPaths/a',
- // requestURL: 'https://localhost:9443/jazz/juneau/test/testPaths/a/test2',
- // servletPath: '/juneau/test/testPaths/a',
- // servletURI: 'https://localhost:9443/jazz/juneau/test/testPaths/a',
- // servletParentURI: 'https://localhost:9443/jazz/juneau/test/testPaths',
- // relativeServletURI: '/jazz/juneau/test/testPaths/a',
- // pathRemainder2: null,
- // method: 4
- // }
- url = URL + "/a/test2";
- r = client.doGet(url).getResponse(ObjectMap.class);
- assertEquals("/test2", r.getString("pathInfo"));
- assertEquals("['test2']", r.getObjectList("pathInfoParts").toString());
- assertNull(r.getString("pathRemainder"));
- assertNull(r.getString("pathRemainder2"));
- assertTrue(r.getString("requestURI").endsWith("/testPaths/a/test2"));
- assertTrue(r.getString("requestParentURI").endsWith("/testPaths/a"));
- assertTrue(r.getString("requestURL").endsWith("/testPaths/a/test2"));
- assertTrue(r.getString("servletPath").endsWith("/testPaths/a"));
- assertTrue(r.getString("servletURI").endsWith("/testPaths/a"));
- assertTrue(r.getString("servletParentURI").endsWith("/testPaths"));
- assertTrue(r.getString("relativeServletURI").endsWith("/testPaths/a"));
- assertEquals(4, (int)r.getInt("method"));
-
- // [/test/testPaths/a/test2/]
- // {
- // pathInfo: '/test2/',
- // pathInfoParts: [
- // 'test2'
- // ],
- // pathRemainder: '',
- // requestURI: '/jazz/juneau/test/testPaths/a/test2/',
- // requestParentURI: '/jazz/juneau/test/testPaths/a',
- // requestURL: 'https://localhost:9443/jazz/juneau/test/testPaths/a/test2/',
- // servletPath: '/juneau/test/testPaths/a',
- // servletURI: 'https://localhost:9443/jazz/juneau/test/testPaths/a',
- // servletParentURI: 'https://localhost:9443/jazz/juneau/test/testPaths',
- // relativeServletURI: '/jazz/juneau/test/testPaths/a',
- // pathRemainder2: '',
- // method: 4
- // }
- url = URL + "/a/test2/";
- r = client.doGet(url).getResponse(ObjectMap.class);
- assertEquals("/test2/", r.getString("pathInfo"));
- assertEquals("['test2']", r.getObjectList("pathInfoParts").toString());
- assertEquals("", r.getString("pathRemainder"));
- assertEquals("", r.getString("pathRemainder2"));
- assertTrue(r.getString("requestURI").endsWith("/testPaths/a/test2/"));
- assertTrue(r.getString("requestParentURI").endsWith("/testPaths/a"));
- assertTrue(r.getString("requestURL").endsWith("/testPaths/a/test2/"));
- assertTrue(r.getString("servletPath").endsWith("/testPaths/a"));
- assertTrue(r.getString("servletURI").endsWith("/testPaths/a"));
- assertTrue(r.getString("servletParentURI").endsWith("/testPaths"));
- assertTrue(r.getString("relativeServletURI").endsWith("/testPaths/a"));
- assertEquals(4, (int)r.getInt("method"));
-
- // [/test/testPaths/a/test2//]
- // {
- // pathInfo: '/test2//',
- // pathInfoParts: [
- // 'test2',
- // ''
- // ],
- // pathRemainder: '/',
- // requestURI: '/jazz/juneau/test/testPaths/a/test2//',
- // requestParentURI: '/jazz/juneau/test/testPaths/a',
- // requestURL: 'https://localhost:9443/jazz/juneau/test/testPaths/a/test2//',
- // servletPath: '/juneau/test/testPaths/a',
- // servletURI: 'https://localhost:9443/jazz/juneau/test/testPaths/a',
- // servletParentURI: 'https://localhost:9443/jazz/juneau/test/testPaths',
- // relativeServletURI: '/jazz/juneau/test/testPaths/a',
- // pathRemainder2: '/',
- // method: 4
- // }
- url = URL + "/a/test2//";
- r = client.doGet(url).getResponse(ObjectMap.class);
- assertEquals("/test2//", r.getString("pathInfo"));
- assertEquals("['test2','']", r.getObjectList("pathInfoParts").toString());
- assertEquals("/", r.getString("pathRemainder"));
- assertEquals("/", r.getString("pathRemainder2"));
- assertTrue(r.getString("requestURI").endsWith("/testPaths/a/test2//"));
- assertTrue(r.getString("requestParentURI").endsWith("/testPaths/a"));
- assertTrue(r.getString("requestURL").endsWith("/testPaths/a/test2//"));
- assertTrue(r.getString("servletPath").endsWith("/testPaths/a"));
- assertTrue(r.getString("servletURI").endsWith("/testPaths/a"));
- assertTrue(r.getString("servletParentURI").endsWith("/testPaths"));
- assertTrue(r.getString("relativeServletURI").endsWith("/testPaths/a"));
- assertEquals(4, (int)r.getInt("method"));
-
- // [/test/testPaths/a/test2///]
- // {
- // pathInfo: '/test2///',
- // pathInfoParts: [
- // 'test2',
- // '',
- // ''
- // ],
- // pathRemainder: '//',
- // requestURI: '/jazz/juneau/test/testPaths/a/test2///',
- // requestParentURI: '/jazz/juneau/test/testPaths/a',
- // requestURL: 'https://localhost:9443/jazz/juneau/test/testPaths/a/test2///',
- // servletPath: '/juneau/test/testPaths/a',
- // servletURI: 'https://localhost:9443/jazz/juneau/test/testPaths/a',
- // servletParentURI: 'https://localhost:9443/jazz/juneau/test/testPaths',
- // relativeServletURI: '/jazz/juneau/test/testPaths/a',
- // pathRemainder2: '//',
- // method: 4
- // }
- url = URL + "/a/test2///";
- r = client.doGet(url).getResponse(ObjectMap.class);
- assertEquals("/test2///", r.getString("pathInfo"));
- assertEquals("['test2','','']", r.getObjectList("pathInfoParts").toString());
- assertEquals("//", r.getString("pathRemainder"));
- assertEquals("//", r.getString("pathRemainder2"));
- assertTrue(r.getString("requestURI").endsWith("/testPaths/a/test2///"));
- assertTrue(r.getString("requestParentURI").endsWith("/testPaths/a"));
- assertTrue(r.getString("requestURL").endsWith("/testPaths/a/test2///"));
- assertTrue(r.getString("servletPath").endsWith("/testPaths/a"));
- assertTrue(r.getString("servletURI").endsWith("/testPaths/a"));
- assertTrue(r.getString("servletParentURI").endsWith("/testPaths"));
- assertTrue(r.getString("relativeServletURI").endsWith("/testPaths/a"));
- assertEquals(4, (int)r.getInt("method"));
-
- // [/test/testPaths/a/test2/foo/bar]
- // {
- // pathInfo: '/test2/foo/bar',
- // pathInfoParts: [
- // 'test2',
- // 'foo',
- // 'bar'
- // ],
- // pathRemainder: 'foo/bar',
- // requestURI: '/jazz/juneau/test/testPaths/a/test2/foo/bar',
- // requestParentURI: '/jazz/juneau/test/testPaths/a/test2/foo',
- // requestURL: 'https://localhost:9443/jazz/juneau/test/testPaths/a/test2/foo/bar',
- // servletPath: '/juneau/test/testPaths/a',
- // servletURI: 'https://localhost:9443/jazz/juneau/test/testPaths/a',
- // servletParentURI: 'https://localhost:9443/jazz/juneau/test/testPaths',
- // relativeServletURI: '/jazz/juneau/test/testPaths/a',
- // pathRemainder2: 'foo/bar',
- // method: 4
- // }
- url = URL + "/a/test2/foo/bar";
- r = client.doGet(url).getResponse(ObjectMap.class);
- assertEquals("/test2/foo/bar", r.getString("pathInfo"));
- assertEquals("['test2','foo','bar']", r.getObjectList("pathInfoParts").toString());
- assertEquals("foo/bar", r.getString("pathRemainder"));
- assertEquals("foo/bar", r.getString("pathRemainder2"));
- assertTrue(r.getString("requestURI").endsWith("/testPaths/a/test2/foo/bar"));
- assertTrue(r.getString("requestParentURI").endsWith("/testPaths/a/test2/foo"));
- assertTrue(r.getString("requestURL").endsWith("/testPaths/a/test2/foo/bar"));
- assertTrue(r.getString("servletPath").endsWith("/testPaths/a"));
- assertTrue(r.getString("servletURI").endsWith("/testPaths/a"));
- assertTrue(r.getString("servletParentURI").endsWith("/testPaths"));
- assertTrue(r.getString("relativeServletURI").endsWith("/testPaths/a"));
- assertEquals(4, (int)r.getInt("method"));
-
- // [/test/testPaths/a/test2/foo/bar/]
- // {
- // pathInfo: '/test2/foo/bar/',
- // pathInfoParts: [
- // 'test2',
- // 'foo',
- // 'bar'
- // ],
- // pathRemainder: 'foo/bar/',
- // requestURI: '/jazz/juneau/test/testPaths/a/test2/foo/bar/',
- // requestParentURI: '/jazz/juneau/test/testPaths/a/test2/foo',
- // requestURL: 'https://localhost:9443/jazz/juneau/test/testPaths/a/test2/foo/bar/',
- // servletPath: '/juneau/test/testPaths/a',
- // servletURI: 'https://localhost:9443/jazz/juneau/test/testPaths/a',
- // servletParentURI: 'https://localhost:9443/jazz/juneau/test/testPaths',
- // relativeServletURI: '/jazz/juneau/test/testPaths/a',
- // pathRemainder2: 'foo/bar/',
- // method: 4
- // }
- url = URL + "/a/test2/foo/bar/";
- r = client.doGet(url).getResponse(ObjectMap.class);
- assertEquals("/test2/foo/bar/", r.getString("pathInfo"));
- assertEquals("['test2','foo','bar']", r.getObjectList("pathInfoParts").toString());
- assertEquals("foo/bar/", r.getString("pathRemainder"));
- assertEquals("foo/bar/", r.getString("pathRemainder2"));
- assertTrue(r.getString("requestURI").endsWith("/testPaths/a/test2/foo/bar/"));
- assertTrue(r.getString("requestParentURI").endsWith("/testPaths/a/test2/foo"));
- assertTrue(r.getString("requestURL").endsWith("/testPaths/a/test2/foo/bar/"));
- assertTrue(r.getString("servletPath").endsWith("/testPaths/a"));
- assertTrue(r.getString("servletURI").endsWith("/testPaths/a"));
- assertTrue(r.getString("servletParentURI").endsWith("/testPaths"));
- assertTrue(r.getString("relativeServletURI").endsWith("/testPaths/a"));
- assertEquals(4, (int)r.getInt("method"));
-
- // [/test/testPaths/a/test2//foo//bar//]
- // {
- // pathInfo: '/test2//foo//bar//',
- // pathInfoParts: [
- // 'test2',
- // '',
- // 'foo',
- // '',
- // 'bar',
- // ''
- // ],
- // pathRemainder: '/foo//bar//',
- // requestURI: '/jazz/juneau/test/testPaths/a/test2//foo//bar//',
- // requestParentURI: '/jazz/juneau/test/testPaths/a/test2//foo/',
- // requestURL: 'https://localhost:9443/jazz/juneau/test/testPaths/a/test2//foo//bar//',
- // servletPath: '/juneau/test/testPaths/a',
- // servletURI: 'https://localhost:9443/jazz/juneau/test/testPaths/a',
- // servletParentURI: 'https://localhost:9443/jazz/juneau/test/testPaths',
- // relativeServletURI: '/jazz/juneau/test/testPaths/a',
- // pathRemainder2: '/foo//bar//',
- // method: 4
- // }
- url = URL + "/a/test2//foo//bar//";
- r = client.doGet(url).getResponse(ObjectMap.class);
- assertEquals("/test2//foo//bar//", r.getString("pathInfo"));
- assertEquals("['test2','','foo','','bar','']", r.getObjectList("pathInfoParts").toString());
- assertEquals("/foo//bar//", r.getString("pathRemainder"));
- assertEquals("/foo//bar//", r.getString("pathRemainder2"));
- assertTrue(r.getString("requestURI").endsWith("/testPaths/a/test2//foo//bar//"));
- assertTrue(r.getString("requestParentURI").endsWith("/testPaths/a/test2//foo/"));
- assertTrue(r.getString("requestURL").endsWith("/testPaths/a/test2//foo//bar//"));
- assertTrue(r.getString("servletPath").endsWith("/testPaths/a"));
- assertTrue(r.getString("servletURI").endsWith("/testPaths/a"));
- assertTrue(r.getString("servletParentURI").endsWith("/testPaths"));
- assertTrue(r.getString("relativeServletURI").endsWith("/testPaths/a"));
- assertEquals(4, (int)r.getInt("method"));
-
- // [/test/testPaths/a/test2/foo%2Fbar]
- // {
- // pathInfo: '/test2/foo//bar',
- // pathInfoUndecoded: '/test2/foo%2F%2Fbar',
- // pathInfoParts: [
- // 'test2',
- // 'foo//bar'
- // ],
- // pathRemainder: 'foo//bar',
- // pathRemainderUndecoded: 'foo%2F%2Fbar',
- // requestURI: '/jazz/juneau/test/testPaths/a/test2/foo%2F%2Fbar',
- // requestParentURI: '/jazz/juneau/test/testPaths/a/test2',
- // requestURL: 'https://localhost:9443/jazz/juneau/test/testPaths/a/test2/foo%2F%2Fbar',
- // servletPath: '/juneau/test/testPaths/a',
- // servletURI: 'https://localhost:9443/jazz/juneau/test/testPaths/a',
- // servletParentURI: 'https://localhost:9443/jazz/juneau/test/testPaths',
- // relativeServletURI: '/jazz/juneau/test/testPaths/a',
- // pathRemainder2: 'foo//bar',
- // method: 4
- // }
- url = URL + "/a/test2/foo%2F%2Fbar";
- r = client.doGet(url).getResponse(ObjectMap.class);
- assertEquals("/test2/foo//bar", r.getString("pathInfo"));
- assertEquals("/test2/foo%2F%2Fbar", r.getString("pathInfoUndecoded"));
- assertEquals("['test2','foo//bar']", r.getObjectList("pathInfoParts").toString());
- assertEquals("foo//bar", r.getString("pathRemainder"));
- assertEquals("foo%2F%2Fbar", r.getString("pathRemainderUndecoded"));
- assertEquals("foo//bar", r.getString("pathRemainder2"));
- assertTrue(r.getString("requestURI").endsWith("/testPaths/a/test2/foo%2F%2Fbar"));
- assertTrue(r.getString("requestParentURI").endsWith("/testPaths/a/test2"));
- assertTrue(r.getString("requestURL").endsWith("/testPaths/a/test2/foo%2F%2Fbar"));
- assertTrue(r.getString("servletPath").endsWith("/testPaths/a"));
- assertTrue(r.getString("servletURI").endsWith("/testPaths/a"));
- assertTrue(r.getString("servletParentURI").endsWith("/testPaths"));
- assertTrue(r.getString("relativeServletURI").endsWith("/testPaths/a"));
- assertEquals(4, (int)r.getInt("method"));
-
- // [/test/testPaths/a/test2//foo%2Fbar//]
- // {
- // pathInfo: '/test2//foo//bar//',
- // pathInfoUndecoded: '/test2//foo%2F%2Fbar//',
- // pathInfoParts: [
- // 'test2',
- // '',
- // 'foo//bar',
- // ''
- // ],
- // pathRemainder: '/foo//bar//',
- // pathRemainderUndecoded: '/foo%2F%2Fbar//',
- // requestURI: '/jazz/juneau/test/testPaths/a/test2//foo%2F%2Fbar//',
- // requestParentURI: '/jazz/juneau/test/testPaths/a/test2/',
- // requestURL: 'https://localhost:9443/jazz/juneau/test/testPaths/a/test2//foo%2F%2Fbar//',
- // servletPath: '/juneau/test/testPaths/a',
- // servletURI: 'https://localhost:9443/jazz/juneau/test/testPaths/a',
- // servletParentURI: 'https://localhost:9443/jazz/juneau/test/testPaths',
- // relativeServletURI: '/jazz/juneau/test/testPaths/a',
- // pathRemainder2: '/foo//bar//',
- // method: 4
- // }
- url = URL + "/a/test2//foo%2F%2Fbar//";
- r = client.doGet(url).getResponse(ObjectMap.class);
- assertEquals("/test2//foo//bar//", r.getString("pathInfo"));
- assertEquals("/test2//foo%2F%2Fbar//", r.getString("pathInfoUndecoded"));
- assertEquals("['test2','','foo//bar','']", r.getObjectList("pathInfoParts").toString());
- assertEquals("/foo//bar//", r.getString("pathRemainder"));
- assertEquals("/foo%2F%2Fbar//", r.getString("pathRemainderUndecoded"));
- assertEquals("/foo//bar//", r.getString("pathRemainder2"));
- assertTrue(r.getString("requestURI").endsWith("/testPaths/a/test2//foo%2F%2Fbar//"));
- assertTrue(r.getString("requestParentURI").endsWith("/testPaths/a/test2/"));
- assertTrue(r.getString("requestURL").endsWith("/testPaths/a/test2//foo%2F%2Fbar//"));
- assertTrue(r.getString("servletPath").endsWith("/testPaths/a"));
- assertTrue(r.getString("servletURI").endsWith("/testPaths/a"));
- assertTrue(r.getString("servletParentURI").endsWith("/testPaths"));
- assertTrue(r.getString("relativeServletURI").endsWith("/testPaths/a"));
- assertEquals(4, (int)r.getInt("method"));
-
- //--------------------------------------------------------------------------------
- // Spaces
- //--------------------------------------------------------------------------------
- url = URL + "/%20";
- r = client.doGet(url).getResponse(ObjectMap.class);
- assertEquals("/ ", r.getString("pathInfo"));
- assertEquals("/%20", r.getString("pathInfoUndecoded"));
- assertEquals("[' ']", r.getObjectList("pathInfoParts").toString());
- assertEquals(" ", r.getString("pathRemainder"));
- assertEquals("%20", r.getString("pathRemainderUndecoded"));
- assertEquals(" ", r.getString("pathRemainder2"));
- assertTrue(r.getString("requestURI").endsWith("/testPaths/%20"));
- assertTrue(r.getString("requestParentURI").endsWith("/testPaths"));
- assertTrue(r.getString("requestURL").endsWith("/testPaths/%20"));
- assertTrue(r.getString("servletPath").endsWith("/testPaths"));
- assertTrue(r.getString("servletURI").endsWith("/testPaths"));
- assertTrue(r.getString("relativeServletURI").endsWith("/testPaths"));
- assertEquals(1, (int)r.getInt("method"));
-
- url = URL + "/test2/%20";
- r = client.doGet(url).getResponse(ObjectMap.class);
- assertEquals("/test2/ ", r.getString("pathInfo"));
- assertEquals("/test2/%20", r.getString("pathInfoUndecoded"));
- assertEquals("['test2',' ']", r.getObjectList("pathInfoParts").toString());
- assertEquals(" ", r.getString("pathRemainder"));
- assertEquals("%20", r.getString("pathRemainderUndecoded"));
- assertEquals(" ", r.getString("pathRemainder2"));
- assertTrue(r.getString("requestURI").endsWith("/testPaths/test2/%20"));
- assertTrue(r.getString("requestParentURI").endsWith("/testPaths/test2"));
- assertTrue(r.getString("requestURL").endsWith("/testPaths/test2/%20"));
- assertTrue(r.getString("servletPath").endsWith("/testPaths"));
- assertTrue(r.getString("servletURI").endsWith("/testPaths"));
- assertTrue(r.getString("relativeServletURI").endsWith("/testPaths"));
- assertEquals(2, (int)r.getInt("method"));
-
- url = URL + "/a/%20";
- r = client.doGet(url).getResponse(ObjectMap.class);
- assertEquals("/ ", r.getString("pathInfo"));
- assertEquals("/%20", r.getString("pathInfoUndecoded"));
- assertEquals("[' ']", r.getObjectList("pathInfoParts").toString());
- assertEquals(" ", r.getString("pathRemainder"));
- assertEquals("%20", r.getString("pathRemainderUndecoded"));
- assertEquals(" ", r.getString("pathRemainder2"));
- assertTrue(r.getString("requestURI").endsWith("/testPaths/a/%20"));
- assertTrue(r.getString("requestParentURI").endsWith("/testPaths/a"));
- assertTrue(r.getString("requestURL").endsWith("/testPaths/a/%20"));
- assertTrue(r.getString("servletPath").endsWith("/testPaths/a"));
- assertTrue(r.getString("servletURI").endsWith("/testPaths/a"));
- assertTrue(r.getString("servletParentURI").endsWith("/testPaths"));
- assertTrue(r.getString("relativeServletURI").endsWith("/testPaths/a"));
- assertEquals(3, (int)r.getInt("method"));
-
- url = URL + "/a/test2/%20";
- r = client.doGet(url).getResponse(ObjectMap.class);
- assertEquals("/test2/ ", r.getString("pathInfo"));
- assertEquals("/test2/%20", r.getString("pathInfoUndecoded"));
- assertEquals("['test2',' ']", r.getObjectList("pathInfoParts").toString());
- assertEquals(" ", r.getString("pathRemainder"));
- assertEquals("%20", r.getString("pathRemainderUndecoded"));
- assertEquals(" ", r.getString("pathRemainder2"));
- assertTrue(r.getString("requestURI").endsWith("/testPaths/a/test2/%20"));
- assertTrue(r.getString("requestParentURI").endsWith("/testPaths/a/test2"));
- assertTrue(r.getString("requestURL").endsWith("/testPaths/a/test2/%20"));
- assertTrue(r.getString("servletPath").endsWith("/testPaths/a"));
- assertTrue(r.getString("servletURI").endsWith("/testPaths/a"));
- assertTrue(r.getString("servletParentURI").endsWith("/testPaths"));
- assertTrue(r.getString("relativeServletURI").endsWith("/testPaths/a"));
- assertEquals(4, (int)r.getInt("method"));
-
- url = URL + "/+";
- r = client.doGet(url).getResponse(ObjectMap.class);
- assertEquals("/ ", r.getString("pathInfo"));
- assertEquals("/+", r.getString("pathInfoUndecoded"));
- assertEquals("[' ']", r.getObjectList("pathInfoParts").toString());
- assertEquals(" ", r.getString("pathRemainder"));
- assertEquals("+", r.getString("pathRemainderUndecoded"));
- assertEquals(" ", r.getString("pathRemainder2"));
- assertTrue(r.getString("requestURI").endsWith("/testPaths/+"));
- assertTrue(r.getString("requestParentURI").endsWith("/testPaths"));
- assertTrue(r.getString("requestURL").endsWith("/testPaths/+"));
- assertTrue(r.getString("servletPath").endsWith("/testPaths"));
- assertTrue(r.getString("servletURI").endsWith("/testPaths"));
- assertTrue(r.getString("relativeServletURI").endsWith("/testPaths"));
- assertEquals(1, (int)r.getInt("method"));
-
- url = URL + "/test2/+";
- r = client.doGet(url).getResponse(ObjectMap.class);
- assertEquals("/test2/ ", r.getString("pathInfo"));
- assertEquals("/test2/+", r.getString("pathInfoUndecoded"));
- assertEquals("['test2',' ']", r.getObjectList("pathInfoParts").toString());
- assertEquals(" ", r.getString("pathRemainder"));
- assertEquals("+", r.getString("pathRemainderUndecoded"));
- assertEquals(" ", r.getString("pathRemainder2"));
- assertTrue(r.getString("requestURI").endsWith("/testPaths/test2/+"));
- assertTrue(r.getString("requestParentURI").endsWith("/testPaths/test2"));
- assertTrue(r.getString("requestURL").endsWith("/testPaths/test2/+"));
- assertTrue(r.getString("servletPath").endsWith("/testPaths"));
- assertTrue(r.getString("servletURI").endsWith("/testPaths"));
- assertTrue(r.getString("relativeServletURI").endsWith("/testPaths"));
- assertEquals(2, (int)r.getInt("method"));
-
- url = URL + "/a/+";
- r = client.doGet(url).getResponse(ObjectMap.class);
- assertEquals("/ ", r.getString("pathInfo"));
- assertEquals("/+", r.getString("pathInfoUndecoded"));
- assertEquals("[' ']", r.getObjectList("pathInfoParts").toString());
- assertEquals(" ", r.getString("pathRemainder"));
- assertEquals("+", r.getString("pathRemainderUndecoded"));
- assertEquals(" ", r.getString("pathRemainder2"));
- assertTrue(r.getString("requestURI").endsWith("/testPaths/a/+"));
- assertTrue(r.getString("requestParentURI").endsWith("/testPaths/a"));
- assertTrue(r.getString("requestURL").endsWith("/testPaths/a/+"));
- assertTrue(r.getString("servletPath").endsWith("/testPaths/a"));
- assertTrue(r.getString("servletURI").endsWith("/testPaths/a"));
- assertTrue(r.getString("servletParentURI").endsWith("/testPaths"));
- assertTrue(r.getString("relativeServletURI").endsWith("/testPaths/a"));
- assertEquals(3, (int)r.getInt("method"));
-
- url = URL + "/a/test2/+";
- r = client.doGet(url).getResponse(ObjectMap.class);
- assertEquals("/test2/ ", r.getString("pathInfo"));
- assertEquals("/test2/+", r.getString("pathInfoUndecoded"));
- assertEquals("['test2',' ']", r.getObjectList("pathInfoParts").toString());
- assertEquals(" ", r.getString("pathRemainder"));
- assertEquals("+", r.getString("pathRemainderUndecoded"));
- assertEquals(" ", r.getString("pathRemainder2"));
- assertTrue(r.getString("requestURI").endsWith("/testPaths/a/test2/+"));
- assertTrue(r.getString("requestParentURI").endsWith("/testPaths/a/test2"));
- assertTrue(r.getString("requestURL").endsWith("/testPaths/a/test2/+"));
- assertTrue(r.getString("servletPath").endsWith("/testPaths/a"));
- assertTrue(r.getString("servletURI").endsWith("/testPaths/a"));
- assertTrue(r.getString("servletParentURI").endsWith("/testPaths"));
- assertTrue(r.getString("relativeServletURI").endsWith("/testPaths/a"));
- assertEquals(4, (int)r.getInt("method"));
-
- client.closeQuietly();
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestProperties.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestProperties.java b/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestProperties.java
deleted file mode 100755
index f66ad17..0000000
--- a/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestProperties.java
+++ /dev/null
@@ -1,48 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.server;
-
-import static org.junit.Assert.*;
-
-import org.apache.juneau.client.*;
-import org.apache.juneau.json.*;
-import org.junit.*;
-
-public class CT_TestProperties {
-
- private static String URL = "/testProperties";
-
- //====================================================================================================
- // Properties defined on method.
- //====================================================================================================
- @Test
- public void testPropertiesDefinedOnMethod() throws Exception {
- RestClient client = new TestRestClient(JsonSerializer.DEFAULT, JsonParser.DEFAULT);
- String r = client.doGet(URL + "/testPropertiesDefinedOnMethod").getResponseAsString();
- assertTrue(r.matches("A1=a1,A2=c,B1=b1,B2=c,C=c,R1a=.*/testProperties/testPropertiesDefinedOnMethod,R1b=.*/testProperties,R2=bar,R3=baz,R4=a1,R5=c,R6=c"));
-
- client.closeQuietly();
- }
-
- //====================================================================================================
- // Make sure attributes/parameters/headers are available through ctx.getProperties().
- //====================================================================================================
- @Test
- public void testProperties() throws Exception {
- RestClient client = new TestRestClient(JsonSerializer.DEFAULT, JsonParser.DEFAULT);
- String r = client.doGet(URL + "/testProperties/a1?P=p1").setHeader("H", "h1").getResponseAsString();
- assertEquals("A=a1,P=p1,H=h1", r);
-
- client.closeQuietly();
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestRestClient.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestRestClient.java b/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestRestClient.java
deleted file mode 100755
index b3109d4..0000000
--- a/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestRestClient.java
+++ /dev/null
@@ -1,199 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.server;
-
-import static org.apache.juneau.server.TestUtils.*;
-import static org.junit.Assert.*;
-
-import java.util.*;
-import java.util.regex.*;
-
-import org.apache.http.entity.*;
-import org.apache.juneau.client.*;
-import org.apache.juneau.json.*;
-import org.junit.*;
-
-public class CT_TestRestClient {
-
- private static String URL = "/testRestClient";
-
- //====================================================================================================
- // successPattern()
- //====================================================================================================
- @Test
- public void testSuccessPattern() throws Exception {
- RestClient c = new TestRestClient(JsonSerializer.DEFAULT, JsonParser.DEFAULT);
- String r;
- int rc;
-
- r = c.doPost(URL, new StringEntity("xxxSUCCESSxxx")).successPattern("SUCCESS").getResponseAsString();
- assertEquals("xxxSUCCESSxxx", r);
- rc = c.doPost(URL, new StringEntity("xxxSUCCESSxxx")).successPattern("SUCCESS").run();
- assertEquals(200, rc);
-
- try {
- r = c.doPost(URL, new StringEntity("xxxFAILURExxx")).successPattern("SUCCESS").getResponseAsString();
- fail();
- } catch (RestCallException e) {
- assertEquals("Success pattern not detected.", e.getLocalizedMessage());
- }
-
- c.closeQuietly();
- }
-
- //====================================================================================================
- // failurePattern()
- //====================================================================================================
- @Test
- public void testFailurePattern() throws Exception {
- RestClient c = new TestRestClient(JsonSerializer.DEFAULT, JsonParser.DEFAULT);
- String r;
- int rc;
-
- r = c.doPost(URL, new StringEntity("xxxSUCCESSxxx")).failurePattern("FAILURE").getResponseAsString();
- assertEquals("xxxSUCCESSxxx", r);
- rc = c.doPost(URL, new StringEntity("xxxSUCCESSxxx")).failurePattern("FAILURE").run();
- assertEquals(200, rc);
-
- try {
- r = c.doPost(URL, new StringEntity("xxxFAILURExxx")).failurePattern("FAILURE").getResponseAsString();
- fail();
- } catch (RestCallException e) {
- assertEquals("Failure pattern detected.", e.getLocalizedMessage());
- }
-
- try {
- r = c.doPost(URL, new StringEntity("xxxERRORxxx")).failurePattern("FAILURE|ERROR").getResponseAsString();
- fail();
- } catch (RestCallException e) {
- assertEquals("Failure pattern detected.", e.getLocalizedMessage());
- }
-
- c.closeQuietly();
- }
-
- //====================================================================================================
- // captureResponse()/getCapturedResponse()
- //====================================================================================================
- @Test
- public void testCaptureResponse() throws Exception {
- RestClient c = new TestRestClient(JsonSerializer.DEFAULT, JsonParser.DEFAULT);
- RestCall rc = c.doPost(URL, new StringEntity("xxx")).captureResponse();
-
- try {
- rc.getCapturedResponse();
- fail();
- } catch (IllegalStateException e) {
- assertEquals("This method cannot be called until the response has been consumed.", e.getLocalizedMessage());
- }
- rc.run();
- assertEquals("xxx", rc.getCapturedResponse());
- assertEquals("xxx", rc.getCapturedResponse());
-
- rc = c.doPost(URL, new StringEntity("xxx")).captureResponse();
- assertEquals("xxx", rc.getResponseAsString());
- assertEquals("xxx", rc.getCapturedResponse());
- assertEquals("xxx", rc.getCapturedResponse());
-
- try {
- rc.getResponseAsString();
- fail();
- } catch (IllegalStateException e) {
- assertEquals("Method cannot be called. Response has already been consumed.", e.getLocalizedMessage());
- }
-
- c.closeQuietly();
- }
-
- //====================================================================================================
- // addResponsePattern()
- //====================================================================================================
- @Test
- public void testAddResponsePattern() throws Exception {
- RestClient c = new TestRestClient(JsonSerializer.DEFAULT, JsonParser.DEFAULT);
- String r;
-
- final List<String> l = new ArrayList<String>();
- ResponsePattern p = new ResponsePattern("x=(\\d+),y=(\\S+)") {
- @Override
- public void onMatch(RestCall restCall, Matcher m) throws RestCallException {
- l.add(m.group(1)+'/'+m.group(2));
- }
- @Override
- public void onNoMatch(RestCall restCall) throws RestCallException {
- throw new RestCallException("Pattern not found!");
- }
- };
-
- r = c.doPost(URL, new StringEntity("x=1,y=2")).addResponsePattern(p).getResponseAsString();
- assertEquals("x=1,y=2", r);
- assertObjectEquals("['1/2']", l);
-
- l.clear();
-
- r = c.doPost(URL, new StringEntity("x=1,y=2\nx=3,y=4")).addResponsePattern(p).getResponseAsString();
- assertEquals("x=1,y=2\nx=3,y=4", r);
- assertObjectEquals("['1/2','3/4']", l);
-
- try {
- c.doPost(URL, new StringEntity("x=1")).addResponsePattern(p).run();
- fail();
- } catch (RestCallException e) {
- assertEquals("Pattern not found!", e.getLocalizedMessage());
- assertEquals(0, e.getResponseCode());
- }
-
- // Two patterns!
- ResponsePattern p1 = new ResponsePattern("x=(\\d+)") {
- @Override
- public void onMatch(RestCall restCall, Matcher m) throws RestCallException {
- l.add("x="+m.group(1));
- }
- @Override
- public void onNoMatch(RestCall restCall) throws RestCallException {
- throw new RestCallException("Pattern x not found!");
- }
- };
- ResponsePattern p2 = new ResponsePattern("y=(\\S+)") {
- @Override
- public void onMatch(RestCall restCall, Matcher m) throws RestCallException {
- l.add("y="+m.group(1));
- }
- @Override
- public void onNoMatch(RestCall restCall) throws RestCallException {
- throw new RestCallException("Pattern y not found!");
- }
- };
-
- l.clear();
- r = c.doPost(URL, new StringEntity("x=1,y=2\nx=3,y=4")).addResponsePattern(p1).addResponsePattern(p2).getResponseAsString();
- assertEquals("x=1,y=2\nx=3,y=4", r);
- assertObjectEquals("['x=1','x=3','y=2','y=4']", l);
-
- try {
- c.doPost(URL, new StringEntity("x=1\nx=3")).addResponsePattern(p1).addResponsePattern(p2).getResponseAsString();
- } catch (RestCallException e) {
- assertEquals("Pattern y not found!", e.getLocalizedMessage());
- assertEquals(0, e.getResponseCode());
- }
-
- try {
- c.doPost(URL, new StringEntity("y=1\ny=3")).addResponsePattern(p1).addResponsePattern(p2).getResponseAsString();
- } catch (RestCallException e) {
- assertEquals("Pattern x not found!", e.getLocalizedMessage());
- assertEquals(0, e.getResponseCode());
- }
-
- c.closeQuietly();
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestSerializers.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestSerializers.java b/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestSerializers.java
deleted file mode 100755
index ac3bf6a..0000000
--- a/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestSerializers.java
+++ /dev/null
@@ -1,152 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.server;
-
-import static javax.servlet.http.HttpServletResponse.*;
-import static org.apache.juneau.server.TestUtils.*;
-import static org.junit.Assert.*;
-
-import org.apache.juneau.client.*;
-import org.apache.juneau.json.*;
-import org.junit.*;
-
-public class CT_TestSerializers {
-
- private static String URL = "/testSerializers";
- private static boolean debug = false;
- private static RestClient client;
-
- @BeforeClass
- public static void beforeClass() {
- client = new TestRestClient(JsonSerializer.DEFAULT, JsonParser.DEFAULT);
- }
-
- @AfterClass
- public static void afterClass() {
- client.closeQuietly();
- }
-
- //====================================================================================================
- // Serializer defined on class.
- //====================================================================================================
- @Test
- public void testSerializerOnClass() throws Exception {
- String url = URL + "/testSerializerOnClass";
-
- client.setAccept("text/a");
- String r = client.doGet(url).getResponseAsString();
- assertEquals("text/a - test1", r);
-
- try {
- client.setAccept("text/b");
- client.doGet(url + "?noTrace=true").getResponseAsString();
- fail("Exception expected");
- } catch (RestCallException e) {
- checkErrorResponse(debug, e, SC_NOT_ACCEPTABLE,
- "Unsupported media-type in request header 'Accept': 'text/b'",
- "Supported media-types: [text/a, ");
- }
-
- client.setAccept("text/json");
- r = client.doGet(url).getResponseAsString();
- assertEquals("\"test1\"", r);
- }
-
- //====================================================================================================
- // Serializer defined on method.
- //====================================================================================================
- @Test
- public void testSerializerOnMethod() throws Exception {
- String url = URL + "/testSerializerOnMethod";
-
- try {
- client.setAccept("text/a");
- client.doGet(url + "?noTrace=true").getResponseAsString();
- fail("Exception expected");
- } catch (RestCallException e) {
- checkErrorResponse(debug, e, SC_NOT_ACCEPTABLE,
- "Unsupported media-type in request header 'Accept': 'text/a'",
- "Supported media-types: [text/b]"
- );
- }
-
- try {
- client.setAccept("text/json");
- client.doGet(url + "?noTrace=true").getResponseAsString();
- fail("Exception expected");
- } catch (RestCallException e) {
- checkErrorResponse(debug, e, SC_NOT_ACCEPTABLE,
- "Unsupported media-type in request header 'Accept': 'text/json'",
- "Supported media-types: [text/b]"
- );
- }
- }
-
- //====================================================================================================
- // Serializer overridden on method.
- //====================================================================================================
- @Test
- public void testSerializerOverriddenOnMethod() throws Exception {
- String url = URL + "/testSerializerOverriddenOnMethod";
-
- client.setAccept("text/a");
- String r = client.doGet(url).getResponseAsString();
- assertEquals("text/c - test3", r);
-
- client.setAccept("text/b");
- r = client.doGet(url).getResponseAsString();
- assertEquals("text/b - test3", r);
-
- client.setAccept("text/json");
- r = client.doGet(url).getResponseAsString();
- assertEquals("\"test3\"", r);
- }
-
- //====================================================================================================
- // Serializer with different Accept than Content-Type.
- //====================================================================================================
- @Test
- public void testSerializerWithDifferentMediaTypes() throws Exception {
- String url = URL + "/testSerializerWithDifferentMediaTypes";
-
- client.setAccept("text/a");
- String r = client.doGet(url).getResponseAsString();
- assertEquals("text/d - test4", r);
-
- client.setAccept("text/d");
- r = client.doGet(url).getResponseAsString();
- assertEquals("text/d - test4", r);
-
- client.setAccept("text/json");
- r = client.doGet(url).getResponseAsString();
- assertEquals("\"test4\"", r);
- }
-
- //====================================================================================================
- // Check for valid 406 error response.
- //====================================================================================================
- @Test
- public void test406() throws Exception {
- String url = URL + "/test406";
-
- try {
- client.setAccept("text/bad");
- client.doGet(url + "?noTrace=true").getResponseAsString();
- fail("Exception expected");
- } catch (RestCallException e) {
- checkErrorResponse(debug, e, SC_NOT_ACCEPTABLE,
- "Unsupported media-type in request header 'Accept': 'text/bad'",
- "Supported media-types: [text/a");
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestStaticFiles.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestStaticFiles.java b/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestStaticFiles.java
deleted file mode 100755
index 46fce22..0000000
--- a/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/CT_TestStaticFiles.java
+++ /dev/null
@@ -1,56 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.server;
-
-import static org.junit.Assert.*;
-
-import org.apache.juneau.client.*;
-import org.apache.juneau.plaintext.*;
-import org.junit.*;
-
-public class CT_TestStaticFiles {
-
- private static String URL = "/testStaticFiles";
-
- //====================================================================================================
- // Tests the @RestResource(staticFiles) annotation.
- //====================================================================================================
- @Test
- public void testXdocs() throws Exception {
- RestClient client = new TestRestClient(PlainTextSerializer.class, PlainTextParser.class);
- String r;
- String url = URL + "/xdocs";
-
- r = client.doGet(url + "/test.txt").getResponseAsString();
- assertEquals("OK-1", r);
- r = client.doGet(url + "/xdocs/test.txt").getResponseAsString();
- assertEquals("OK-2", r);
-
- // For security reasons, paths containing ".." should always return 404.
- try {
- client.doGet(url + "/xdocs/../test.txt?noTrace=true").connect();
- fail("404 exception expected");
- } catch (RestCallException e) {
- assertEquals(404, e.getResponseCode());
- }
-
- try {
- client.doGet(url + "/xdocs/%2E%2E/test.txt?noTrace=true").connect();
- fail("404 exception expected");
- } catch (RestCallException e) {
- assertEquals(404, e.getResponseCode());
- }
-
- client.closeQuietly();
- }
-}
[18/44] incubator-juneau git commit: Rename CT_* testcases.
Posted by ja...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/ini/CT_ConfigMgr.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/ini/CT_ConfigMgr.java b/org.apache.juneau/src/test/java/org/apache/juneau/ini/CT_ConfigMgr.java
deleted file mode 100755
index 465c532..0000000
--- a/org.apache.juneau/src/test/java/org/apache/juneau/ini/CT_ConfigMgr.java
+++ /dev/null
@@ -1,204 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.ini;
-
-import static org.apache.juneau.TestUtils.*;
-import static org.junit.Assert.*;
-
-import java.io.*;
-import java.nio.charset.*;
-
-import org.apache.juneau.internal.*;
-import org.apache.juneau.json.*;
-import org.apache.juneau.svl.*;
-import org.apache.juneau.utils.*;
-import org.junit.*;
-
-public class CT_ConfigMgr {
-
- private static File tempDir;
-
- @BeforeClass
- public static void setup() {
- tempDir = new File(System.getProperty("java.io.tmpdir"), StringUtils.generateUUID(12));
- FileUtils.mkdirs(tempDir, true);
- }
-
- @AfterClass
- public static void teardown() {
- FileUtils.delete(tempDir);
- }
-
- //====================================================================================================
- // get(String path)
- // get(String path, boolean create)
- //====================================================================================================
- @Test
- public void testGet() throws Exception {
- File f;
- ConfigMgr cm = new ConfigMgr(false, new XorEncoder(), JsonSerializer.DEFAULT, JsonParser.DEFAULT, Charset.defaultCharset(), new String[]{tempDir.getAbsolutePath()});
-
- ConfigFile cf = cm.get("TestGet.cfg", true);
- cf.put("Test/A", "a");
-
- f = new File(tempDir, "TestGet.cfg");
- assertTrue(f.exists());
-
- cf.save();
- assertTextEquals("[Test]|A = a|", IOUtils.read(f));
-
- cf = cm.get("TestGet.cfg");
- assertObjectEquals("{'default':{},Test:{A:'a'}}", cf);
-
- ConfigFile cf2 = cm.get(tempDir.getAbsolutePath() + "/TestGet.cfg");
- assertObjectEquals("{'default':{},Test:{A:'a'}}", cf2);
- assertTrue(cf == cf2); // Relative and absolute paths must resolve to same config file.
-
- try { cm.get("TestGet2.cfg"); fail(); } catch (FileNotFoundException e) {}
- try { cm.get(tempDir.getAbsolutePath() + "TestGet2.cfg"); fail(); } catch (FileNotFoundException e) {}
-
- cm.get(tempDir.getAbsolutePath() + "TestGet2.cfg", true);
-
- ConfigMgr cm2 = new ConfigMgr(false, new XorEncoder(), JsonSerializer.DEFAULT, JsonParser.DEFAULT, Charset.defaultCharset(), new String[]{tempDir.getAbsolutePath()});
- cf = cm2.get("TestGet.cfg");
- assertObjectEquals("{'default':{},Test:{A:'a'}}", cf);
-
- cm2 = new ConfigMgr(false, new XorEncoder(), JsonSerializer.DEFAULT, JsonParser.DEFAULT, Charset.defaultCharset(), null);
- try { cf = cm2.get("TestGet.cfg"); fail(); } catch (FileNotFoundException e) {}
-
- String NL = System.getProperty("line.separator");
- cf = cm2.create(new StringReader(("[Test]"+NL+"A = a"+NL)));
- assertObjectEquals("{'default':{},Test:{A:'a'}}", cf);
-
- ConfigMgr cm3 = new ConfigMgr(false, new XorEncoder(), JsonSerializer.DEFAULT, JsonParser.DEFAULT, IOUtils.UTF8, new String[]{tempDir.getAbsolutePath()});
- cf = cm3.get("TestGet.cfg");
- assertObjectEquals("{'default':{},Test:{A:'a'}}", cf);
-
- cm.deleteAll();
- cm2.deleteAll();
- cm3.deleteAll();
- }
-
- //====================================================================================================
- // loadIfModified()
- //====================================================================================================
- @Test
- public void testLoadIfModified() throws Exception {
- ConfigMgr cm = new ConfigMgr(false, new XorEncoder(), JsonSerializer.DEFAULT, JsonParser.DEFAULT, Charset.defaultCharset(), new String[]{tempDir.getAbsolutePath()});
- File f;
- ConfigFile cf = cm.get("TestGet.cfg", true);
- cf.put("Test/A", "a");
-
- f = new File(tempDir, "TestGet.cfg");
- String NL = System.getProperty("line.separator");
- IOUtils.write(f, new StringReader("[Test]"+NL+"A = b"+NL));
- FileUtils.modifyTimestamp(f);
-
- cm.loadIfModified();
- assertEquals("b", cf.getString("Test/A"));
- cm.loadIfModified();
- assertEquals("b", cf.getString("Test/A"));
-
- // Config file with no backing file.
- cf = cm.create();
- cf.put("Test/B", "b");
- cm.loadIfModified();
- cf.loadIfModified();
- assertEquals("b", cf.getString("Test/B"));
-
- cm.deleteAll();
- }
-
- //====================================================================================================
- // read only
- //====================================================================================================
- @Test
- public void testReadOnly() throws Exception {
- ConfigMgr cm = new ConfigMgr(true, new XorEncoder(), JsonSerializer.DEFAULT, JsonParser.DEFAULT, Charset.defaultCharset(), new String[]{tempDir.getAbsolutePath()});
- ConfigFile cf = cm.get("TestGet.cfg", true);
-
- // All these should fail.
- try { cf.loadIfModified(); fail(); } catch (UnsupportedOperationException e) {}
- try { cf.load(); fail(); } catch (UnsupportedOperationException e) {}
- try { cf.load(new StringReader("")); fail(); } catch (UnsupportedOperationException e) {}
- try { cf.put("A","b"); fail(); } catch (UnsupportedOperationException e) {}
- try { cf.put("A","b",true); fail(); } catch (UnsupportedOperationException e) {}
- try { cf.put("A","b"); fail(); } catch (UnsupportedOperationException e) {}
- try { cf.put("A","b",true); fail(); } catch (UnsupportedOperationException e) {}
- try { cf.removeString("A"); fail(); } catch (UnsupportedOperationException e) {}
- try { cf.addLines("A","b=c"); fail(); } catch (UnsupportedOperationException e) {}
- try { cf.addHeaderComments("A", "b=c"); fail(); } catch (UnsupportedOperationException e) {}
- try { cf.clearHeaderComments("A"); fail(); } catch (UnsupportedOperationException e) {}
- try { cf.addSection("A"); fail(); } catch (UnsupportedOperationException e) {}
- try { cf.setSection("A",null); fail(); } catch (UnsupportedOperationException e) {}
- try { cf.removeSection("A"); fail(); } catch (UnsupportedOperationException e) {}
- try { cf.save(); fail(); } catch (UnsupportedOperationException e) {}
- try { cf.merge(cf); fail(); } catch (UnsupportedOperationException e) {}
- try { cf.addListener(new ConfigFileListener(){}); fail(); } catch (UnsupportedOperationException e) {}
-
- // All these should succeed.
- cf.getObject(String.class, "A");
- cf.getObject(String.class, "A", "a");
- cf.getString("A");
- cf.getString("A","a");
- cf.getObject(String.class, "A");
- cf.getObject(String.class, "A", "a");
- cf.getObject(String[].class, "A");
- cf.getStringArray("A");
- cf.getStringArray("A", null);
- cf.getInt("A");
- cf.getInt("A", 0);
- cf.getBoolean("A");
- cf.getBoolean("A", true);
- cf.containsNonEmptyValue("A");
- cf.getSectionMap("A");
- cf.serializeTo(new StringWriter());
- cf.serializeTo(new StringWriter(), ConfigFileFormat.INI);
- cf.getResolving(VarResolver.DEFAULT);
- cf.toWritable();
- }
-
- //====================================================================================================
- // main(String[] args)
- //====================================================================================================
- @Test
- public void testMain() throws Exception {
- System.setProperty("exit.2", "0");
- ConfigMgr cm = new ConfigMgr(false, new XorEncoder(), JsonSerializer.DEFAULT, JsonParser.DEFAULT, Charset.defaultCharset(), new String[]{tempDir.getAbsolutePath()});
-
- ConfigFile cf = cm.get("Test.cfg", true)
- .addLines(null, "# c1", "\t# c2", " c3 ", " ", "x1=1", "x2=true", "x3=null")
- .addLines("s1", "#c4", "k1=1", "#c5 foo=bar", "k2 = true", "k3 = \tnull");
- cf.save();
-
- File configFile = new File(tempDir, "Test.cfg");
- File envFile = new File(tempDir, "Test.bat");
-
- ConfigMgr.main(new String[]{"createBatchEnvFile", "-configFile", configFile.getAbsolutePath(), "-envFile", envFile.getAbsolutePath()});
- String expected = "rem c1|rem c2|rem c3||set x1 = 1|set x2 = true|set x3 = null|rem c4|set s1_k1 = 1|rem c5 foo=bar|set s1_k2 = true|set s1_k3 = null|";
- String actual = IOUtils.read(envFile);
- assertTextEquals(expected, actual);
-
- ConfigMgr.main(new String[]{"createShellEnvFile", "-configFile", configFile.getAbsolutePath(), "-envFile", envFile.getAbsolutePath()});
- expected = "# c1|# c2|# c3||export x1=\"1\"|export x2=\"true\"|export x3=\"null\"|# c4|export s1_k1=\"1\"|# c5 foo=bar|export s1_k2=\"true\"|export s1_k3=\"null\"|";
- actual = IOUtils.read(envFile);
- assertTextEquals(expected, actual);
-
- ConfigMgr.main(new String[]{"setVals", "-configFile", configFile.getAbsolutePath(), "-vals", "x1=2", "s1/k1=2", "s2/k1=3"});
- FileUtils.modifyTimestamp(configFile);
- cf.loadIfModified();
- assertObjectEquals("{'default':{x1:'2',x2:'true',x3:'null'},s1:{k1:'2',k2:'true',k3:'null'},s2:{k1:'3'}}", cf);
-
- ConfigMgr.main(new String[]{});
- }
-}
\ No newline at end of file
[25/44] incubator-juneau git commit: Rename CT_* testcases.
Posted by ja...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/CT_RoundTripBeanMaps.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/CT_RoundTripBeanMaps.java b/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/CT_RoundTripBeanMaps.java
deleted file mode 100755
index 72f7bd4..0000000
--- a/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/CT_RoundTripBeanMaps.java
+++ /dev/null
@@ -1,1012 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.a.rttests;
-
-import static org.apache.juneau.TestUtils.*;
-import static org.junit.Assert.*;
-
-import java.util.*;
-
-import javax.xml.datatype.*;
-
-import org.apache.juneau.*;
-import org.apache.juneau.annotation.*;
-import org.apache.juneau.json.*;
-import org.apache.juneau.json.annotation.*;
-import org.apache.juneau.parser.*;
-import org.apache.juneau.serializer.*;
-import org.apache.juneau.transform.*;
-import org.apache.juneau.transforms.*;
-import org.junit.*;
-
-/**
- * Tests designed to serialize and parse objects to make sure we end up
- * with the same objects for all serializers and parsers.
- */
-@SuppressWarnings({"unchecked","hiding","serial","unused"})
-public class CT_RoundTripBeanMaps extends RoundTripTest {
-
- public CT_RoundTripBeanMaps(String label, Serializer s, Parser p, int flags) throws Exception {
- super(label, s, p, flags);
- }
-
- @Override /* RoundTripTest */
- public Map<Class<?>,Class<?>> getImplClasses() {
- Map<Class<?>,Class<?>> m = new HashMap<Class<?>,Class<?>>();
- m.put(IBean.class, CBean.class);
- return m;
- }
-
- //====================================================================================================
- // IBean/ABean/Bean
- //====================================================================================================
- @Test
- public void testImplClasses() throws Exception {
- IBean bean = new CBean();
-
- bean.setF1("bar");
- bean = roundTrip(bean, IBean.class);
- assertEquals("bar", bean.getF1());
-
- bean.setF1("baz");
- bean = roundTrip(bean, ABean.class);
- assertEquals("baz", bean.getF1());
-
- bean.setF1("bing");
- bean = roundTrip(bean, CBean.class);
- assertEquals("bing", bean.getF1());
- }
-
- //====================================================================================================
- // IBean[]/ABean[]/Bean[]
- //====================================================================================================
- @Test
- public void testImplArrayClasses() throws Exception {
- IBean[] bean = new CBean[]{new CBean()};
-
- bean[0].setF1("bar");
- bean = roundTrip(bean, IBean[].class);
- assertEquals("bar", bean[0].getF1());
-
- bean[0].setF1("baz");
- bean = roundTrip(bean, ABean[].class);
- assertEquals("baz", bean[0].getF1());
-
- bean[0].setF1("bing");
- bean = roundTrip(bean, CBean[].class);
- assertEquals("bing", bean[0].getF1());
- }
-
- //====================================================================================================
- // List<IBean/ABean/Bean>
- //====================================================================================================
- @Test
- public void testImplListClasses() throws Exception {
- List<IBean> l = new LinkedList<IBean>() {{
- add(new CBean());
- }};
-
- l.get(0).setF1("bar");
- l = roundTripCollection(l, List.class, IBean.class);
- assertEquals("bar", l.get(0).getF1());
- l = roundTripCollection(l, LinkedList.class, IBean.class);
- assertEquals("bar", l.get(0).getF1());
-
- l.get(0).setF1("baz");
- l = roundTripCollection(l, List.class, ABean.class);
- assertEquals("baz", l.get(0).getF1());
- l = roundTripCollection(l, LinkedList.class, ABean.class);
- assertEquals("baz", l.get(0).getF1());
-
- l.get(0).setF1("bing");
- l = roundTripCollection(l, List.class, CBean.class);
- assertEquals("bing", l.get(0).getF1());
- l = roundTripCollection(l, LinkedList.class, CBean.class);
- assertEquals("bing", l.get(0).getF1());
- }
-
- //====================================================================================================
- // Map<String,IBean/ABean/Bean>
- //====================================================================================================
- @Test
- public void testImplMap() throws Exception {
- Map<String,IBean> l = new LinkedHashMap<String,IBean>() {{
- put("foo", new CBean());
- }};
-
- l.get("foo").setF1("bar");
- l = roundTripMap(l, Map.class, String.class, IBean.class);
- assertEquals("bar", l.get("foo").getF1());
- l = roundTripMap(l, LinkedHashMap.class, String.class, IBean.class);
- assertEquals("bar", l.get("foo").getF1());
-
- l.get("foo").setF1("baz");
- l = roundTripMap(l, Map.class, String.class, ABean.class);
- assertEquals("baz", l.get("foo").getF1());
- l = roundTripMap(l, LinkedHashMap.class, String.class, ABean.class);
- assertEquals("baz", l.get("foo").getF1());
-
- l.get("foo").setF1("bing");
- l = roundTripMap(l, Map.class, String.class, CBean.class);
- assertEquals("bing", l.get("foo").getF1());
- l = roundTripMap(l, LinkedHashMap.class, String.class, CBean.class);
- assertEquals("bing", l.get("foo").getF1());
- }
-
- //====================================================================================================
- // Map<String,IBean/ABean/Bean>
- //====================================================================================================
- @Test
- public void testImplMap2() throws Exception {
- A b = new A(1);
- b = roundTrip(b);
- if (returnOriginalObject || p == null)
- return;
- assertEquals(0, b.f1);
- assertEquals(0, b.f2);
- assertEquals(1, b.f3);
- assertEquals(1, b.f4);
- assertEquals(0, b.getF5());
- assertEquals(1, b.getF6());
- }
-
- public static interface IBean {
- public String getF1();
- public void setF1(String f1);
- }
-
- public static abstract class ABean implements IBean {
- @Override /* IBean */
- public abstract String getF1();
- @Override /* IBean */
- public abstract void setF1(String f1);
- }
-
- public static class CBean extends ABean {
- private String f1 = "foo";
- @Override /* IBean */
- public String getF1() {
- return f1;
- }
- @Override /* IBean */
- public void setF1(String f1) {
- this.f1 = f1;
- }
- }
-
- public static class A {
-
- @BeanIgnore
- public int f1, f2;
- public int f3, f4;
-
- private int f5, f6;
-
- @BeanIgnore
- public int getF5() {
- return f5;
- }
- public void setF5(int f5) {
- this.f5 = f5;
- }
-
- public int getF6() {
- return f6;
- }
- public void setF6(int f6) {
- this.f6 = f6;
- }
-
- public A() {}
-
- public A(int v) {
- f1 = f2 = f3 = f4 = f5 = f6 = v;
- }
- }
-
- //====================================================================================================
- // Test @Bean(subTypes=xxx)
- //====================================================================================================
- @Test
- public void testSubTypesUsingAnnotation() throws Exception {
- JsonSerializer js = JsonSerializer.DEFAULT_LAX.clone().addTransforms(XMLGregorianCalendarTransform.class);
-
- // Skip validation-only tests
- if (isValidationOnly())
- return;
-
- Serializer s = getSerializer().clone().addTransforms(XMLGregorianCalendarTransform.class);
- Parser p = getParser().clone().addTransforms(XMLGregorianCalendarTransform.class);
-
- B1 b1 = B1.create();
- Object r = s.serialize(b1);
- B b = p.parse(r, B.class);
- assertTrue(b instanceof B1);
- assertObjectEquals("{subType:'B1',f0:'f0',f1:'f1'}", b, js);
-
- B2 b2 = B2.create();
- r = s.serialize(b2);
- b = p.parse(r, B.class);
- assertTrue(b instanceof B2);
- assertObjectEquals("{subType:'B2',f0:'f0',f2:1}", b, js);
-
- B3 b3 = B3.create();
- r = s.serialize(b3);
- b = p.parse(r, B.class);
- assertTrue(b instanceof B3);
- assertObjectEquals("{subType:'B3',f0:'f0',f3:'2001-01-01T12:34:56.789Z'}", b, js);
-}
-
- @Bean(
- subTypeProperty="subType",
- subTypes={
- @BeanSubType(type=B1.class, id="B1"),
- @BeanSubType(type=B2.class, id="B2"),
- @BeanSubType(type=B3.class, id="B3")
- }
- )
- public abstract static class B {
- public String f0 = "f0";
- }
-
- public static class B1 extends B {
- public String f1;
- public static B1 create() {
- B1 b = new B1();
- b.f0 = "f0";
- b.f1 = "f1";
- return b;
- }
- }
-
- public static class B2 extends B {
- public int f2;
- public static B2 create() {
- B2 b = new B2();
- b.f0 = "f0";
- b.f2 = 1;
- return b;
- }
- }
-
- public static class B3 extends B {
- public XMLGregorianCalendar f3;
- public static B3 create() throws Exception {
- B3 b = new B3();
- b.f0 = "f0";
- b.f3 = DatatypeFactory.newInstance().newXMLGregorianCalendar("2001-01-01T12:34:56.789Z");
- return b;
- }
- }
-
- //====================================================================================================
- // Test @Bean(subTypes=xxx) using BeanTransform
- //====================================================================================================
- @Test
- public void testSubTypesUsingBeanTransform() throws Exception {
- JsonSerializer js = JsonSerializer.DEFAULT_LAX.clone().addTransforms(XMLGregorianCalendarTransform.class);
-
- // Skip validation-only tests
- if (isValidationOnly())
- return;
-
- Serializer s = getSerializer().clone().addTransforms(CTransform.class, XMLGregorianCalendarTransform.class);
- Parser p = getParser().clone().addTransforms(CTransform.class, XMLGregorianCalendarTransform.class);
-
- C1 c1 = C1.create();
- Object r = s.serialize(c1);
- C c = p.parse(r, C.class);
- assertTrue(c instanceof C1);
- assertObjectEquals("{f0:'f0',f1:'f1'}", c, js);
-
- C2 c2 = C2.create();
- r = s.serialize(c2);
- c = p.parse(r, C.class);
- assertTrue(c instanceof C2);
- assertObjectEquals("{f0:'f0',f2:1}", c, js);
-
- C3 c3 = C3.create();
- r = s.serialize(c3);
- c = p.parse(r, C.class);
- assertTrue(c instanceof C3);
- assertObjectEquals("{f0:'f0',f3:'2001-01-01T12:34:56.789Z'}", c, js);
- }
-
- public abstract static class C {
- public String f0;
- }
-
- public static class C1 extends C {
- public String f1;
- public static C1 create() {
- C1 c = new C1();
- c.f0 = "f0";
- c.f1 = "f1";
- return c;
- }
- }
-
- public static class C2 extends C {
- public int f2;
- public static C2 create() {
- C2 c = new C2();
- c.f0 = "f0";
- c.f2 = 1;
- return c;
- }
- }
-
- public static class C3 extends C {
- public XMLGregorianCalendar f3;
- public static C3 create() throws Exception {
- C3 c = new C3();
- c.f0 = "f0";
- c.f3 = DatatypeFactory.newInstance().newXMLGregorianCalendar("2001-01-01T12:34:56.789Z");
- return c;
- }
- }
-
- public static class CTransform extends BeanTransform<C> {
- public CTransform() {
- setSubTypeProperty("subType");
- addSubType(C1.class, "C1");
- addSubType(C2.class, "C2");
- addSubType(C3.class, "C3");
- }
- }
-
- //====================================================================================================
- // Test @Bean(subTypeProperty=xxx) with real bean property
- //====================================================================================================
- @Test
- public void testSubTypePropertyWithRealPropertyUsingAnnotation() throws Exception {
- // Skip validation-only tests
- if (isValidationOnly())
- return;
-
- Serializer s = getSerializer();
- Parser p = getParser();
-
- BA1 ba1 = BA1.create();
- Object r = s.serialize(ba1);
- BA b = p.parse(r, BA.class);
- assertTrue(b instanceof BA1);
- assertEquals("BA1", b.subType);
- assertObjectEquals("{subType:'BA1',f0a:'f0a',f0b:'f0b',f1:'f1'}", b);
- }
-
- @Bean(
- subTypeProperty="subType",
- subTypes={
- @BeanSubType(type=BA1.class, id="BA1"),
- @BeanSubType(type=BA2.class, id="BA2")
- }
- )
- public abstract static class BA {
- public String f0a, subType, f0b;
- }
-
- public static class BA1 extends BA {
- public String f1;
- public static BA1 create() {
- BA1 b = new BA1();
- b.f0a = "f0a";
- b.f0b = "f0b";
- b.f1 = "f1";
- b.subType = "xxx";// Should be ignored.
- return b;
- }
- }
-
- public static class BA2 extends BA {
- public String f2;
- }
-
-
- //====================================================================================================
- // Test @Bean(subTypes=xxx) with real bean property using BeanTransform
- //====================================================================================================
- @Test
- public void testSubTypePropertyWithRealPropertyUsingBeanTransform() throws Exception {
- // Skip validation-only tests
- if (isValidationOnly())
- return;
-
- Serializer s = getSerializer().clone().addTransforms(CATransform.class);
- Parser p = getParser().clone().addTransforms(CATransform.class);
-
- CA1 c1 = CA1.create();
- Object r = s.serialize(c1);
- CA c = p.parse(r, CA.class);
- assertTrue(c instanceof CA1);
- assertEquals("CA1", c.subType);
- assertObjectEquals("{f0a:'f0a',subType:'CA1',f0b:'f0b',f1:'f1'}", c);
- }
-
- public abstract static class CA {
- public String f0a, subType, f0b;
- }
-
- public static class CA1 extends CA {
- public String f1;
- public static CA1 create() {
- CA1 c = new CA1();
- c.f0a = "f0a";
- c.f0b = "f0b";
- c.f1 = "f1";
- c.subType = "xxx";// Should be ignored.
- return c;
- }
- }
-
- public static class CA2 extends CA {
- public String f2;
- }
-
- public static class CATransform extends BeanTransform<CA> {
- public CATransform() {
- setSubTypeProperty("subType");
- addSubType(CA1.class, "CA1");
- addSubType(CA2.class, "CA2");
- }
- }
-
- //====================================================================================================
- // Test @Bean(properties=xxx)
- //====================================================================================================
- @Test
- public void testPropertiesUsingAnnotation() throws Exception {
- // Skip validation-only tests
- if (isValidationOnly())
- return;
-
- Serializer s = getSerializer();
- Parser p = getParser();
-
- D1 d = new D1().init();
- Object r = s.serialize(d);
- d = p.parse(r, D1.class);
- assertNull(d.f1);
- assertObjectEquals("{f3:'f3',f2:'f2'}", d);
- }
-
- @Bean(properties={"f3","f2"})
- public static class D1 {
- public String f1, f2, f3;
- public D1 init() {
- f1 = "f1";
- f2 = "f2";
- f3 = "f3";
- return this;
- }
- }
-
- //====================================================================================================
- // Test @Bean(properties=xxx) using BeanTransform
- //====================================================================================================
- @Test
- public void testPropertiesUsingTransform() throws Exception {
- JsonSerializer js = JsonSerializer.DEFAULT_LAX.clone().addTransforms(D2Transform.class);
-
- // Skip validation-only tests
- if (isValidationOnly())
- return;
-
- Serializer s = getSerializer().clone().addTransforms(D2Transform.class);
- Parser p = getParser().clone().addTransforms(D2Transform.class);
-
- D2 d = new D2().init();
- Object r = s.serialize(d);
- d = p.parse(r, D2.class);
- assertNull(d.f1);
- assertObjectEquals("{f3:'f3',f2:'f2'}", d, js);
- }
-
- public static class D2 {
- public String f1, f2, f3;
- public D2 init() {
- f1 = "f1";
- f2 = "f2";
- f3 = "f3";
- return this;
- }
- }
- public static class D2Transform extends BeanTransform<D2> {
- public D2Transform() {
- setProperties("f3","f2");
- }
- }
-
- //====================================================================================================
- // Test @Bean(excludeProperties=xxx)
- //====================================================================================================
- @Test
- public void testExcludePropertiesUsingAnnotation() throws Exception {
- // Skip validation-only tests
- if (isValidationOnly())
- return;
-
- Serializer s = getSerializer();
- Parser p = getParser();
-
- E1 e = new E1().init();
- Object r = s.serialize(e);
- e = p.parse(r, E1.class);
- assertObjectEquals("{f1:'f1',f3:'f3'}", e);
- }
-
- @Bean(excludeProperties={"f2"})
- public static class E1 {
- public String f1, f2, f3;
- public E1 init() {
- f1 = "f1";
- f2 = "f2";
- f3 = "f3";
- return this;
- }
- }
-
- //====================================================================================================
- // Test @Bean(excludeProperties=xxx) using BeanTransform
- //====================================================================================================
- @Test
- public void testExcludePropertiesUsingTransform() throws Exception {
- // Skip validation-only tests
- if (isValidationOnly())
- return;
-
- Serializer s = getSerializer().clone().addTransforms(E2Transform.class);
- Parser p = getParser().clone().addTransforms(E2Transform.class);
-
- E2 e = new E2().init();
- Object r = s.serialize(e);
- e = p.parse(r, E2.class);
- assertObjectEquals("{f1:'f1',f3:'f3'}", e);
- }
-
- public static class E2 {
- public String f1, f2, f3;
- public E2 init() {
- f1 = "f1";
- f2 = "f2";
- f3 = "f3";
- return this;
- }
- }
- public static class E2Transform extends BeanTransform<E2> {
- public E2Transform() {
- setExcludeProperties("f2");
- }
- }
-
- //====================================================================================================
- // Test @Bean(interfaceClass=xxx)
- //====================================================================================================
- @Test
- public void testInterfaceClassUsingAnnotation() throws Exception {
- // Skip validation-only tests
- if (isValidationOnly())
- return;
-
- Serializer s = getSerializer();
- Parser p = getParser();
-
- FA2 t = new FA2().init();
- Object r = s.serialize(t);
- t = p.parse(r, FA2.class);
- assertObjectEquals("{f1:'f1'}", t);
- }
-
- @Bean(interfaceClass=FA1.class)
- public static class FA1 {
- public String f1;
- }
-
- public static class FA2 extends FA1 {
- public String f2;
- public FA2 init() {
- f1 = "f1";
- f2 = "f2";
- return this;
- }
- }
-
- //====================================================================================================
- // Test @Bean(interfaceClass=xxx) using BeanTransform
- //====================================================================================================
- @Test
- public void testInterfaceClassUsingTransform() throws Exception {
- Serializer s;
- Parser p;
- FB2 t;
- Object r;
-
- // Skip validation-only tests
- if (isValidationOnly())
- return;
-
- // --- Transform defined on parent class ---
- s = getSerializer().clone().addTransforms(FB1Transform.class);
- p = getParser().clone().addTransforms(FB1Transform.class);
-
- t = new FB2().init();
- r = s.serialize(t);
- t = p.parse(r, FB2.class);
- assertObjectEquals("{f1:'f1'}", t);
-
- // --- Transform defined on child class class ---
- s = getSerializer().clone().addTransforms(FB2Transform.class);
- p = getParser().clone().addTransforms(FB2Transform.class);
-
- t = new FB2().init();
- r = s.serialize(t);
- t = p.parse(r, FB2.class);
- assertObjectEquals("{f1:'f1'}", t);
-
- // --- Transform defined as plain class ---
- s = getSerializer().clone().addTransforms(FB1.class);
- p = getParser().clone().addTransforms(FB1.class);
-
- t = new FB2().init();
- r = s.serialize(t);
- t = p.parse(r, FB2.class);
- assertObjectEquals("{f1:'f1'}", t);
- }
-
- public static class FB1 {
- public String f1;
- }
-
- public static class FB2 extends FB1 {
- public String f2;
- public FB2 init() {
- f1 = "f1";
- f2 = "f2";
- return this;
- }
- }
- public static class FB1Transform extends BeanTransform<FB1> {
- public FB1Transform() {
- setInterfaceClass(FB1.class);
- }
- }
- public static class FB2Transform extends BeanTransform<FB2> {
- public FB2Transform() {
- setInterfaceClass(FB1.class);
- }
- }
-
- //====================================================================================================
- // testMemberClass
- //====================================================================================================
- @Test
- public void testMemberClass() throws Exception {
- G t = G.create();
- t = roundTrip(t, G.class);
- }
-
- public static class G {
- public int a1;
- public G1 g1;
-
- public static G create() {
- G g = new G();
- g.a1 = 1;
- g.g1.a2 = 2;
- g.g1.g2.a3 = 3;
- return g;
- }
-
- public G() {
- g1 = new G1();
- }
-
- public class G1 {
- public int a2;
- public G2 g2;
-
- public G1() {
- g2 = new G2();
- }
-
- public class G2 {
- public int a3;
- }
- }
- }
-
- //====================================================================================================
- // testMemberClassWithMapClass
- //====================================================================================================
- @Test
- public void testMemberClassWithMapClass() throws Exception {
- H t = H.create();
- t = roundTrip(t, H.class);
- }
-
- public static class H extends LinkedHashMap<String,H.H1> {
-
- static H create() {
- H h = new H();
- h.add("foo", 1, 2);
- return h;
- }
-
- H add(String key, int a2, int a3) {
- H1 h1 = new H1();
- h1.a2 = a2;
- h1.h2.a3 = a3;
- put(key, h1);
- return this;
- }
-
- public class H1 {
- public int a2;
- public H2 h2;
-
- public H1() {
- h2 = new H2();
- }
-
- public class H2 {
- public int a3;
- }
- }
- }
-
- //====================================================================================================
- // testMemberClassWithListClass
- //====================================================================================================
- @Test
- public void testMemberClassWithListClass() throws Exception {
- I t = I.create();
- t = roundTrip(t, I.class);
- }
-
- public static class I extends LinkedList<I.I1> {
-
- static I create() {
- I i = new I();
- i.add(1, 2);
- return i;
- }
-
- I add(int a2, int a3) {
- I1 i1 = new I1();
- i1.a2 = a2;
- i1.i2.a3 = a3;
- super.add(i1);
- return this;
- }
-
- public class I1 {
- public int a2;
- public I2 i2;
-
- public I1() {
- i2 = new I2();
- }
-
- public class I2 {
- public int a3;
- }
- }
- }
-
- //====================================================================================================
- // testMemberClassWithStringConstructor
- //====================================================================================================
- @Test
- public void testMemberClassWithStringConstructor() throws Exception {
- J t = J.create();
- t = roundTrip(t, J.class);
- }
-
- public static class J {
- public J2 j2;
-
- static J create() {
- J j = new J();
- j.init();
- return j;
- }
-
- private void init() {
- j2 = new J2("2");
- }
-
- public class J2 {
- int a2;
-
- public J2(String arg) {
- this.a2 = Integer.parseInt(arg);
- }
-
- @Override /* Object */
- public String toString() {
- return String.valueOf(a2);
- }
- }
- }
-
- //====================================================================================================
- // testBeanPropertyPrecedence
- //====================================================================================================
- @Test
- public void testBeanPropertyPrecedence() throws Exception {
- K t = K.create();
- t = roundTrip(t, K.class);
- }
- public static enum KEnum { FOO, BAR, BAZ }
-
- public static class K {
- private KEnum a, b, c;
-
- static K create() {
- K t = new K();
- t.a = KEnum.FOO;
- t.b = KEnum.BAR;
- t.c = KEnum.BAZ;
- return t;
- }
-
- @BeanIgnore
- public KEnum getA() {
- return KEnum.FOO;
- }
-
- @BeanProperty(name="a")
- public String getA2() {
- return a.toString();
- }
-
- // This method should not be interpreted as the setter for this
- // property because it doesn't match the getter return type above.
- public void setA(KEnum a) {
- throw new RuntimeException("Should not be called!");
- }
-
- public void setA(String a) {
- this.a = KEnum.valueOf(a);
- }
-
- public KEnum getB() {
- return b;
- }
-
- public void setB(String b) {
- throw new RuntimeException("Should not be called!");
- }
-
- public void setB(Object b) {
- throw new RuntimeException("Should not be called!");
- }
-
- public void setB(KEnum b) {
- this.b = b;
- }
-
- public KEnum getC() {
- return c;
- }
-
- public void setC(KEnum c) {
- this.c = c;
- }
-
- public void setC(String c) {
- throw new RuntimeException("Should not be called!");
- }
-
- public void setC(Object c) {
- throw new RuntimeException("Should not be called!");
- }
- }
-
- //====================================================================================================
- // testWrapperAttrAnnotationOnBean
- //====================================================================================================
- @Test
- public void testWrapperAttrAnnotationOnBean() throws Exception {
- L t = L.create();
- t = roundTrip(t, L.class);
-
- Map<String,L> m = new LinkedHashMap<String,L>();
- m.put("bar", L.create());
- roundTripMap(m, LinkedHashMap.class, String.class, L.class);
- }
-
- @Json(wrapperAttr="foo")
- public static class L {
- public int f1;
-
- static L create() {
- L l = new L();
- l.f1 = 1;
- return l;
- }
- }
-
- //====================================================================================================
- // testWrapperAttrAnnotationOnNonBean
- //====================================================================================================
- @Test
- public void testWrapperAttrAnnotationOnNonBean() throws Exception {
- M t = M.create();
- t = roundTrip(t, M.class);
-
- Map<String,M> m = new LinkedHashMap<String,M>();
- m.put("bar", M.create());
- roundTripMap(m, LinkedHashMap.class, String.class, M.class);
- }
-
- @Json(wrapperAttr="foo")
- public static class M {
- int f1;
-
- static M create() {
- M m = new M();
- m.f1 = 1;
- return m;
- }
-
- @Override /* Object */
- public String toString() {
- return String.valueOf(f1);
- }
-
- public static M valueOf(String s) {
- M m = new M();
- m.f1 = Integer.parseInt(s);
- return m;
- }
- }
-
- //====================================================================================================
- // Test parsing into top-level non-static inner classes with outer context.
- //====================================================================================================
- @Test
- public void testParsingIntoTopLevelNonStaticInnerClasses() throws Exception {
- N n = new N(1);
-
- if (returnOriginalObject)
- return;
-
- Serializer s = getSerializer();
- Parser p = getParser();
-
- Object r = s.serialize(n.n2);
- n = new N(2);
- ParserSession session = p.createSession(r, null, null, n);
-
- N.N2 n2 = p.parse(session, BeanContext.DEFAULT.getClassMeta(N.N2.class));
-
- // The inner N2.f1 field should be the value of the outer object passed in through the context.
- assertEquals(2, n2.f1);
- }
-
- public static class N {
- public int f1;
- public N2 n2;
-
- public N(int f1) {
- this.f1 = f1;
- n2 = new N2();
- }
- public class N2 {
- private int f1 = N.this.f1;
- public int dummy = 1;
- }
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/CT_RoundTripClasses.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/CT_RoundTripClasses.java b/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/CT_RoundTripClasses.java
deleted file mode 100644
index ff246e3..0000000
--- a/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/CT_RoundTripClasses.java
+++ /dev/null
@@ -1,53 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.a.rttests;
-
-import static org.apache.juneau.TestUtils.*;
-import static org.junit.Assert.*;
-
-import java.util.*;
-
-import org.apache.juneau.parser.*;
-import org.apache.juneau.serializer.*;
-import org.junit.*;
-
-/**
- * Tests designed to serialize and parse objects to make sure we end up
- * with the same objects for all serializers and parsers.
- */
-public class CT_RoundTripClasses extends RoundTripTest {
-
- public CT_RoundTripClasses(String label, Serializer s, Parser p, int flags) throws Exception {
- super(label, s, p, flags);
- }
-
- @SuppressWarnings("serial")
- @Test
- public void classObjects() throws Exception {
- Object o = String.class;
- o = roundTrip(o);
- assertTrue(o == String.class);
-
- o = new Class[]{String.class};
- o = roundTrip(o);
- assertObjectEquals("['java.lang.String']", o);
-
- o = new LinkedList<Class<?>>(){{add(String.class);add(Integer.class);}};
- o = roundTrip(o);
- assertObjectEquals("['java.lang.String','java.lang.Integer']", o);
-
- o = new LinkedHashMap<Class<?>,Class<?>>(){{put(String.class,String.class);}};
- o = roundTrip(o);
- assertObjectEquals("{'java.lang.String':'java.lang.String'}", o);
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/CT_RoundTripDTOs.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/CT_RoundTripDTOs.java b/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/CT_RoundTripDTOs.java
deleted file mode 100755
index 8e10888..0000000
--- a/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/CT_RoundTripDTOs.java
+++ /dev/null
@@ -1,50 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.a.rttests;
-
-import static org.apache.juneau.TestUtils.*;
-
-import org.apache.juneau.dto.jsonschema.*;
-import org.apache.juneau.parser.*;
-import org.apache.juneau.serializer.*;
-import org.junit.*;
-
-
-/**
- * Tests designed to serialize and parse objects to make sure we end up
- * with the same objects for all serializers and parsers.
- */
-@SuppressWarnings("hiding")
-public class CT_RoundTripDTOs extends RoundTripTest {
-
- public CT_RoundTripDTOs(String label, Serializer s, Parser p, int flags) throws Exception {
- super(label, s, p, flags);
- }
-
- //====================================================================================================
- // org.apache.juneau.test.dto.jsonschema
- //====================================================================================================
- @Test
- public void testJsonSchema1() throws Exception {
- Schema s = CT_JsonSchema.getTest1();
- Schema s2 = roundTrip(s, Schema.class);
- assertEqualObjects(s, s2);
- }
-
- @Test
- public void testJsonSchema2() throws Exception {
- Schema s = CT_JsonSchema.getTest2();
- Schema s2 = roundTrip(s, Schema.class);
- assertEqualObjects(s, s2);
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/CT_RoundTripEnum.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/CT_RoundTripEnum.java b/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/CT_RoundTripEnum.java
deleted file mode 100755
index 3311809..0000000
--- a/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/CT_RoundTripEnum.java
+++ /dev/null
@@ -1,246 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.a.rttests;
-
-import static org.apache.juneau.TestUtils.*;
-import static org.junit.Assert.*;
-
-import java.util.*;
-
-import org.apache.juneau.json.*;
-import org.apache.juneau.parser.*;
-import org.apache.juneau.serializer.*;
-import org.junit.*;
-
-/**
- * Tests designed to serialize and parse objects to make sure we end up
- * with the same objects for all serializers and parsers.
- */
-@SuppressWarnings({"hiding","serial"})
-public class CT_RoundTripEnum extends RoundTripTest {
-
- public CT_RoundTripEnum(String label, Serializer s, Parser p, int flags) throws Exception {
- super(label, s, p, flags);
- }
-
- //====================================================================================================
- // Enum object
- //====================================================================================================
- @Test
- public void testEnumA() throws Exception {
- AEnum t = AEnum.FOO;
- assertObjectEquals("'FOO'", t);
- t = roundTrip(t, AEnum.class);
- assertEquals(AEnum.FOO, t);
- }
-
- @Test
- public void testEnumB() throws Exception {
- WriterSerializer s = new JsonSerializer.Simple().addTransforms(getTransforms());
- BEnum t = BEnum.FOO;
- assertEquals("'xfoo'", s.serialize(t));
- t = roundTrip(t, BEnum.class);
- assertEquals(BEnum.FOO, t);
- }
-
- //====================================================================================================
- // Enum[] object
- //====================================================================================================
- @Test
- public void testEnumArrayA() throws Exception {
- AEnum[] t = {AEnum.FOO,AEnum.BAR,null};
- assertObjectEquals("['FOO','BAR',null]", t);
- t = roundTrip(t, AEnum[].class);
- assertEquals(AEnum.FOO, t[0]);
- assertEquals(AEnum.BAR, t[1]);
- assertNull(t[2]);
- }
-
- @Test
- public void testEnumArrayB() throws Exception {
- BEnum[] t = {BEnum.FOO,BEnum.BAR,null};
- assertObjectEquals("['xfoo','xbar',null]", t);
- t = roundTrip(t, BEnum[].class);
- assertEquals(BEnum.FOO, t[0]);
- assertEquals(BEnum.BAR, t[1]);
- assertNull(t[2]);
- }
-
- //====================================================================================================
- // Enum[][] object
- //====================================================================================================
- @Test
- public void testEnum2dArrayA() throws Exception {
- AEnum[][] t = {{AEnum.FOO,AEnum.BAR,null},null};
- assertObjectEquals("[['FOO','BAR',null],null]", t);
- t = roundTrip(t, AEnum[][].class);
- assertEquals(AEnum.FOO, t[0][0]);
- assertEquals(AEnum.BAR, t[0][1]);
- assertNull(t[0][2]);
- assertNull(t[1]);
- }
-
- @Test
- public void testEnum2dArrayB() throws Exception {
- BEnum[][] t = {{BEnum.FOO,BEnum.BAR,null},null};
- assertObjectEquals("[['xfoo','xbar',null],null]", t);
- t = roundTrip(t, BEnum[][].class);
- assertEquals(BEnum.FOO, t[0][0]);
- assertEquals(BEnum.BAR, t[0][1]);
- assertNull(t[0][2]);
- assertNull(t[1]);
- }
-
- //====================================================================================================
- // Bean with Enum fields
- //====================================================================================================
- @Test
- public void testBeansWithEnumA() throws Exception {
- A t1 = new A().init(), t2;
- t2 = roundTrip(t1, A.class);
- assertEqualObjects(t1, t2);
- assertEquals(AEnum.FOO, t2.f3[0]);
- assertNull(t2.f3[1]);
- assertEquals(AEnum.FOO, t2.f4[0][0]);
- assertNull(t2.f4[0][1]);
- assertNull(t2.f4[1]);
- }
-
- @Test
- public void testBeansWithEnumB() throws Exception {
- B t1 = new B().init(), t2;
- t2 = roundTrip(t1, B.class);
- assertEqualObjects(t1, t2);
- assertEquals(BEnum.FOO, t2.f3[0]);
- assertNull(t2.f3[1]);
- assertEquals(BEnum.FOO, t2.f4[0][0]);
- assertNull(t2.f4[0][1]);
- assertNull(t2.f4[1]);
- }
-
-
- /** Normal Enum */
- public enum AEnum {
- FOO,BAR,BAZ
- }
-
- /** Enum with custom serialized values */
- public enum BEnum {
- FOO("xfoo"), BAR("xbar"), BAZ("xbaz");
-
- private String val;
-
- private BEnum(String val) {
- this.val = val;
- }
-
- @Override /* Object */
- public String toString() {
- return val;
- }
-
- public static BEnum fromString(String val) {
- if (val.equals("xfoo"))
- return FOO;
- if (val.equals("xbar"))
- return BAR;
- if (val.equals("xbaz"))
- return BAZ;
- return null;
- }
- }
-
- public static class A {
-
- // Should have 'enum' attribute.
- public AEnum f1;
-
- private AEnum f2;
- public AEnum getF2() {return f2;}
- public void setF2(AEnum f2) {this.f2 = f2;}
-
- public AEnum[] f3;
- public AEnum[][] f4;
-
- // Should not have 'uniqueSet' attribute.
- public List<AEnum> f5 = new LinkedList<AEnum>();
-
- private List<AEnum> f6 = new LinkedList<AEnum>();
- public List<AEnum> getF6() {return f6;}
- public void setF6(List<AEnum> f6) {this.f6 = f6;}
-
- // Should have 'uniqueSet' attribute.
- public Set<AEnum> f7 = new HashSet<AEnum>();
-
- private Set<AEnum> f8 = new HashSet<AEnum>();
- public Set<AEnum> getF8() {return f8;}
- public void setF8(Set<AEnum> f8) {this.f8 = f8;}
-
- public Map<AEnum,AEnum> f9 = new LinkedHashMap<AEnum,AEnum>();
-
- public A init() {
- f1 = AEnum.FOO;
- f2 = AEnum.BAR;
- f3 = new AEnum[]{AEnum.FOO,null};
- f4 = new AEnum[][]{{AEnum.FOO,null},null};
- f5 = new ArrayList<AEnum>(){{add(AEnum.FOO);}};
- f6 = new ArrayList<AEnum>(){{add(AEnum.FOO);}};
- f7 = new HashSet<AEnum>(){{add(AEnum.FOO);}};
- f8 = new HashSet<AEnum>(){{add(AEnum.FOO);}};
-
- return this;
- }
- }
-
- public static class B {
-
- // Should have 'enum' attribute.
- public BEnum f1;
-
- private BEnum f2;
- public BEnum getF2() {return f2;}
- public void setF2(BEnum f2) {this.f2 = f2;}
-
- public BEnum[] f3;
- public BEnum[][] f4;
-
- // Should not have 'uniqueSet' attribute.
- public List<BEnum> f5 = new LinkedList<BEnum>();
-
- private List<BEnum> f6 = new LinkedList<BEnum>();
- public List<BEnum> getF6() {return f6;}
- public void setF6(List<BEnum> f6) {this.f6 = f6;}
-
- // Should have 'uniqueSet' attribute.
- public Set<BEnum> f7 = new HashSet<BEnum>();
-
- private Set<BEnum> f8 = new HashSet<BEnum>();
- public Set<BEnum> getF8() {return f8;}
- public void setF8(Set<BEnum> f8) {this.f8 = f8;}
-
- public Map<BEnum,BEnum> f9 = new LinkedHashMap<BEnum,BEnum>();
-
- public B init() {
- f1 = BEnum.FOO;
- f2 = BEnum.BAR;
- f3 = new BEnum[]{BEnum.FOO,null};
- f4 = new BEnum[][]{{BEnum.FOO,null},null};
- f5 = new ArrayList<BEnum>(){{add(BEnum.FOO);}};
- f6 = new ArrayList<BEnum>(){{add(BEnum.FOO);}};
- f7 = new HashSet<BEnum>(){{add(BEnum.FOO);}};
- f8 = new HashSet<BEnum>(){{add(BEnum.FOO);}};
-
- return this;
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/CT_RoundTripGenerics.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/CT_RoundTripGenerics.java b/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/CT_RoundTripGenerics.java
deleted file mode 100755
index c0536e4..0000000
--- a/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/CT_RoundTripGenerics.java
+++ /dev/null
@@ -1,97 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.a.rttests;
-
-import static org.apache.juneau.TestUtils.*;
-import static org.junit.Assert.*;
-
-import org.apache.juneau.annotation.*;
-import org.apache.juneau.parser.*;
-import org.apache.juneau.serializer.*;
-import org.junit.*;
-
-/**
- * Tests designed to serialize and parse objects to make sure we end up
- * with the same objects for all serializers and parsers.
- */
-public class CT_RoundTripGenerics extends RoundTripTest {
-
- public CT_RoundTripGenerics(String label, Serializer s, Parser p, int flags) throws Exception {
- super(label, s, p, flags);
- }
-
- //====================================================================================================
- // testBeansWithUnboundTypeVars
- //====================================================================================================
- @SuppressWarnings("rawtypes")
- @Test
- public void testBeansWithUnboundTypeVars() throws Exception {
-
- if (returnOriginalObject)
- return;
-
- // Unbound type variables should be interpreted as Object.
- // During parsing, these become ObjectMaps.
- Pair pair = new Pair<Source,Target>(new Source().init(), new Target().init());
- pair = roundTrip(pair);
- assertSortedObjectEquals("{s:{s1:'a1'},t:{t1:'b1'}}", pair);
- assertEquals("ObjectMap", pair.getS().getClass().getSimpleName());
- assertEquals("ObjectMap", pair.getT().getClass().getSimpleName());
-
- // If you specify a concrete class, the type variables become bound and
- // the property types correctly resolve.
- pair = roundTrip(pair, RealPair.class);
- assertSortedObjectEquals("{s:{s1:'a1'},t:{t1:'b1'}}", pair);
- assertEquals("Source", pair.getS().getClass().getSimpleName());
- assertEquals("Target", pair.getT().getClass().getSimpleName());
- }
-
- // Class with unbound type variables.
- @Bean(properties={"s","t"})
- public static class Pair<S,T> {
- private S s;
- private T t;
-
- public Pair() {}
-
- public Pair(S s, T t) {
- this.s = s;
- this.t = t;
- }
-
- // Getters/setters
- public S getS() { return s; }
- public void setS(S s) { this.s = s; }
- public T getT() { return t; }
- public void setT(T t) { this.t = t; }
- }
-
- // Sublcass with bound type variables.
- public static class RealPair extends Pair<Source,Target> {}
-
- public static class Source {
- public String s1;
- public Source init() {
- this.s1 = "a1";
- return this;
- }
- }
-
- public static class Target {
- public String t1;
- public Target init() {
- this.t1 = "b1";
- return this;
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/CT_RoundTripLargeObjects.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/CT_RoundTripLargeObjects.java b/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/CT_RoundTripLargeObjects.java
deleted file mode 100755
index c096f58..0000000
--- a/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/CT_RoundTripLargeObjects.java
+++ /dev/null
@@ -1,193 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.a.rttests;
-
-import static org.apache.juneau.a.rttests.RoundTripTest.Flags.*;
-import static org.apache.juneau.serializer.SerializerContext.*;
-import static org.apache.juneau.urlencoding.UonSerializerContext.*;
-import static org.apache.juneau.xml.XmlSerializerContext.*;
-
-import java.text.*;
-import java.util.*;
-
-import org.apache.juneau.html.*;
-import org.apache.juneau.json.*;
-import org.apache.juneau.msgpack.*;
-import org.apache.juneau.parser.*;
-import org.apache.juneau.serializer.*;
-import org.apache.juneau.urlencoding.*;
-import org.apache.juneau.xml.*;
-import org.junit.*;
-import org.junit.runners.*;
-
-/**
- * Tests designed to serialize and parse objects to make sure we end up
- * with the same objects for all serializers and parsers.
- */
-@Ignore
-@SuppressWarnings({"hiding","serial"})
-public class CT_RoundTripLargeObjects extends RoundTripTest {
-
- private static final int NUM_RUNS = 10;
- private static final int SIZE_PARAM = 20000;
-
- public CT_RoundTripLargeObjects(String label, Serializer s, Parser p, int flags) throws Exception {
- super(label, s, p, flags);
- }
-
- @Parameterized.Parameters
- public static Collection<Object[]> getPairs() {
- return Arrays.asList(new Object[][] {
- // Full round-trip testing
- { /* 0 */
- "Json DEFAULT",
- new JsonSerializer().setProperty(SERIALIZER_trimNullProperties, false),
- JsonParser.DEFAULT,
- 0
- },
- { /* 1 */
- "Json DEFAULT_LAX",
- new JsonSerializer.Simple().setProperty(SERIALIZER_trimNullProperties, false),
- JsonParser.DEFAULT,
- 0
- },
- { /* 2 */
- "Json DEFAULT_SQ",
- new JsonSerializer.Simple().setProperty(SERIALIZER_trimNullProperties, false),
- JsonParser.DEFAULT,
- 0
- },
- { /* 3 */
- "Xml DEFAULT w/namespaces,validation",
- new XmlSerializer.XmlJsonSq().setProperty(SERIALIZER_trimNullProperties, false).setProperty(XML_addNamespaceUrisToRoot, true).setProperty(SERIALIZER_useIndentation, true),
- XmlParser.DEFAULT,
- CHECK_XML_WHITESPACE | VALIDATE_XML
- },
- { /* 4 */
- "Xml DEFAULT wo/namespaces,validation",
- new XmlSerializer.SimpleXmlJsonSq().setProperty(SERIALIZER_trimNullProperties, false),
- XmlParser.DEFAULT,
- CHECK_XML_WHITESPACE
- },
- { /* 5 */
- "Html",
- new HtmlSerializer().setProperty(SERIALIZER_trimNullProperties, false),
- HtmlParser.DEFAULT,
- CHECK_XML_WHITESPACE
- },
- { /* 6 */
- "UrlEncoding",
- new UrlEncodingSerializer().setProperty(SERIALIZER_trimNullProperties, false).setProperty(UON_simpleMode, false),
- UrlEncodingParser.DEFAULT,
- 0
- },
- { /* 7 */
- "Uon",
- new UonSerializer().setProperty(SERIALIZER_trimNullProperties, false).setProperty(UON_simpleMode, false),
- UonParser.DEFAULT,
- 0
- },
- { /* 8 */
- "MsgPack",
- new MsgPackSerializer().setProperty(SERIALIZER_trimNullProperties, false).setProperty(UON_simpleMode, false),
- MsgPackParser.DEFAULT,
- 0
- },
-// { /* 9 */
-// "Rdf.Xml",
-// new RdfSerializer.Xml().setProperty(SERIALIZER_trimNullProperties, false).setProperty(RDF_addLiteralTypes, true),
-// RdfParser.DEFAULT_XML,
-// 0
-// },
-// { /* 10 */
-// "Rdf.XmlAbbrev",
-// new RdfSerializer.XmlAbbrev().setProperty(SERIALIZER_trimNullProperties, false).setProperty(RDF_addLiteralTypes, true),
-// RdfParser.DEFAULT_XML,
-// 0
-// },
-// { /* 11 */
-// "Rdf.Turtle",
-// new RdfSerializer.Turtle().setProperty(SERIALIZER_trimNullProperties, false).setProperty(RDF_addLiteralTypes, true),
-// RdfParser.DEFAULT_TURTLE,
-// 0
-// },
-// { /* 12 */
-// "Rdf.NTriple",
-// new RdfSerializer.NTriple().setProperty(SERIALIZER_trimNullProperties, false).setProperty(RDF_addLiteralTypes, true),
-// RdfParser.DEFAULT_NTRIPLE,
-// 0
-// },
-// { /* 13 */
-// "Rdf.N3",
-// new RdfSerializer.N3().setProperty(SERIALIZER_trimNullProperties, false).setProperty(RDF_addLiteralTypes, true),
-// RdfParser.DEFAULT_N3,
-// 0
-// },
- });
- }
-
- //====================================================================================================
- // test
- //====================================================================================================
- @Test
- public void testLargeMap() throws Exception {
- long startTime;
- int numRuns = NUM_RUNS;
-
- A a = A.create();
- Serializer s = getSerializer();
- Parser p = getParser();
- System.err.println("\n---Speed test on " + label + "---");
- Object r = "";
-
- // Initialization run.
- r = s.serialize(a);
- System.err.println(MessageFormat.format("Serialized size: {0,number} ", (r instanceof String ? r.toString().length() : ((byte[])r).length)));
- p.parse(r, A.class);
-
- startTime = System.currentTimeMillis();
- for (int i = 0; i < numRuns; i++)
- r = s.serialize(a);
- System.err.println(MessageFormat.format("Average serialize time: {0,number}ms", (System.currentTimeMillis()-startTime)/numRuns));
- startTime = System.currentTimeMillis();
- for (int i = 0; i < numRuns; i++)
- a = p.parse(r, A.class);
- System.err.println(MessageFormat.format("Average parsed time: {0,number}ms", (System.currentTimeMillis()-startTime)/numRuns));
- }
-
- public static class A {
- public A1Map a1Map;
- public A1List a1List;
- public A1[] a1Array;
-
- static A create() {
- A a = new A();
- a.a1Map = new A1Map();
- a.a1List = new A1List();
- for (int i = 0; i < SIZE_PARAM; i++) {
- a.a1Map.put(String.valueOf(i), new A1());
- a.a1List.add(new A1());
- }
- a.a1Array = a.a1List.toArray(new A1[0]);
- return a;
- }
- }
-
- public static class A1 {
- public String f1 = "a123456789b123456789c123456789d123456789e123456789f123456789g123456789h123456789i123456789j123456789";
- }
-
- public static class A1Map extends LinkedHashMap<String,A1> {}
-
- public static class A1List extends LinkedList<A1> {}
-}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/CT_RoundTripMaps.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/CT_RoundTripMaps.java b/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/CT_RoundTripMaps.java
deleted file mode 100755
index 82b2479..0000000
--- a/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/CT_RoundTripMaps.java
+++ /dev/null
@@ -1,215 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.a.rttests;
-
-import static org.apache.juneau.serializer.SerializerContext.*;
-import static org.junit.Assert.*;
-
-import java.util.*;
-
-import org.apache.juneau.html.*;
-import org.apache.juneau.json.*;
-import org.apache.juneau.parser.*;
-import org.apache.juneau.serializer.*;
-import org.apache.juneau.transforms.*;
-import org.apache.juneau.urlencoding.*;
-import org.apache.juneau.xml.*;
-import org.junit.*;
-
-
-
-/**
- * Tests designed to serialize and parse objects to make sure we end up
- * with the same objects for all serializers and parsers.
- */
-@SuppressWarnings({"unchecked","deprecation"})
-public class CT_RoundTripMaps extends RoundTripTest {
-
- public CT_RoundTripMaps(String label, Serializer s, Parser p, int flags) throws Exception {
- super(label, s, p, flags);
- }
-
- @Override /* RoundTripTest */
- public Class<?>[] getTransforms() {
- return new Class<?>[]{
- ByteArrayBase64Transform.class,
- DateTransform.ISO8601DTZ.class,
- CalendarLongTransform.class,
- };
- }
-
- //====================================================================================================
- // Map<Integer,String> test
- //====================================================================================================
- @Test
- public void testMapIntegerString() throws Exception {
- Map<Integer,String> t = new TreeMap<Integer,String>();
- t.put(1, "a");
- t.put(2, null);
- t = roundTripMap(t, TreeMap.class, Integer.class, String.class);
- assertEquals("a", t.get(1));
- assertNull(null, t.get(2));
-
- t = new HashMap<Integer,String>();
- t.put(1, "a");
- t.put(2, null);
- t.put(null, "b");
- t = roundTripMap(t, HashMap.class, Integer.class, String.class);
- assertEquals("a", t.get(1));
- assertNull(t.get(2));
- assertEquals("b", t.get(null));
- }
-
- //====================================================================================================
- // Map<Boolean,String> test
- //====================================================================================================
- @Test
- public void testMapBooleanString() throws Exception {
- Map<Boolean,String> t = new TreeMap<Boolean,String>();
- t.put(true, "a");
- t.put(false, null);
- t = roundTripMap(t, TreeMap.class, Boolean.class, String.class);
- assertEquals("a", t.get(true));
- assertNull(null, t.get(false));
-
- t = new HashMap<Boolean,String>();
- t.put(true, "a");
- t.put(false, null);
- t.put(null, "b");
- t = roundTripMap(t, HashMap.class, Boolean.class, String.class);
- assertEquals("a", t.get(true));
- assertNull(t.get(false));
- assertEquals("b", t.get(null));
- }
-
- //====================================================================================================
- // Map<byte[],String> test
- //====================================================================================================
- @Test
- public void testMapByteArrayString() throws Exception {
-
- // Note, you cannot really test maps with byte[] keys since byte[] does not test for equality.
- // So just test serialization.
- String e;
- Object r;
-
- Map<byte[],String> t = new LinkedHashMap<byte[],String>();
- t.put(new byte[]{1,2,3}, "a");
- t.put(new byte[]{4,5,6}, null);
- t.put(null, "b");
-
- s = new JsonSerializer.Simple().addTransforms(getTransforms()).setProperty(SERIALIZER_trimNullProperties, false);
- e = "{AQID:'a',BAUG:null,null:'b'}";
- r = s.serialize(t);
- assertEquals(e, r);
-
- s = new XmlSerializer.SimpleXmlJsonSq().addTransforms(getTransforms()).setProperty(SERIALIZER_trimNullProperties, false);
- e = "<object><AQID>a</AQID><BAUG nil='true'/><_x0000_>b</_x0000_></object>";
- r = s.serialize(t);
- assertEquals(e, r);
-
- s = new HtmlSerializer.Sq().addTransforms(getTransforms()).setProperty(SERIALIZER_trimNullProperties, false);
- e = "<table type='object'><tr><th><string>key</string></th><th><string>value</string></th></tr><tr><td><string>AQID</string></td><td><string>a</string></td></tr><tr><td><string>BAUG</string></td><td><null/></td></tr><tr><td><null/></td><td><string>b</string></td></tr></table>";
- r = s.serialize(t);
- assertEquals(e, r);
-
- s = new UonSerializer.Encoding().addTransforms(getTransforms()).setProperty(SERIALIZER_trimNullProperties, false);
- e = "$o(AQID=a,BAUG=%00,%00=b)";
- r = s.serialize(t);
- assertEquals(e, r);
-
- s = new UrlEncodingSerializer().addTransforms(getTransforms()).setProperty(SERIALIZER_trimNullProperties, false);
- e = "AQID=a&BAUG=%00&%00=b";
- r = s.serialize(t);
- assertEquals(e, r);
- }
-
- //====================================================================================================
- // Map<Date,String> test
- //====================================================================================================
- @Test
- public void testMapDateString() throws Exception {
- Date td1 = new Date(1,2,3,4,5,6);
- Date td2 = new Date(2,3,4,5,6,7);
-
- Map<Date,String> t = new TreeMap<Date,String>();
- t.put(td1, "a");
- t.put(td2, null);
- t = roundTripMap(t, TreeMap.class, Date.class, String.class);
- assertEquals("a", t.get(td1));
- assertNull(null, t.get(td2));
-
- t = new HashMap<Date,String>();
- t.put(td1, "a");
- t.put(td2, null);
- t.put(null, "b");
- t = roundTripMap(t, HashMap.class, Date.class, String.class);
- assertEquals("a", t.get(td1));
- assertNull(t.get(td2));
- assertEquals("b", t.get(null));
- }
-
- //====================================================================================================
- // Map<Calendar,String> test
- //====================================================================================================
- @Test
- public void testMapCalendarString() throws Exception {
- Calendar td1 = new GregorianCalendar();
- td1.setTime(new Date(1,2,3,4,5,6));
- Calendar td2 = new GregorianCalendar();
- td2.setTime(new Date(2,3,4,5,6,7));
-
- Map<Calendar,String> t = new TreeMap<Calendar,String>();
- t.put(td1, "a");
- t.put(td2, null);
- t = roundTripMap(t, TreeMap.class, GregorianCalendar.class, String.class);
- assertEquals("a", t.get(td1));
- assertNull(null, t.get(td2));
-
- t = new HashMap<Calendar,String>();
- t.put(td1, "a");
- t.put(td2, null);
- t.put(null, "b");
- t = roundTripMap(t, HashMap.class, GregorianCalendar.class, String.class);
- assertEquals("a", t.get(td1));
- assertNull(t.get(td2));
- assertEquals("b", t.get(null));
- }
-
- //====================================================================================================
- // Map<Enum,String> test
- //====================================================================================================
- @Test
- public void testMapEnumString() throws Exception {
-
- Map<TestEnum,String> t = new TreeMap<TestEnum,String>();
- t.put(TestEnum.FOO, "a");
- t.put(TestEnum.BAR, null);
- t = roundTripMap(t, TreeMap.class, TestEnum.class, String.class);
- assertEquals("a", t.get(TestEnum.FOO));
- assertNull(null, t.get(TestEnum.BAR));
-
- t = new HashMap<TestEnum,String>();
- t.put(TestEnum.FOO, "a");
- t.put(TestEnum.BAR, null);
- t.put(null, "b");
- t = roundTripMap(t, HashMap.class, TestEnum.class, String.class);
- assertEquals("a", t.get(TestEnum.FOO));
- assertNull(t.get(TestEnum.BAR));
- assertEquals("b", t.get(null));
- }
-
- public enum TestEnum {
- FOO,BAR,BAZ
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/CT_RoundTripNumericConstructors.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/CT_RoundTripNumericConstructors.java b/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/CT_RoundTripNumericConstructors.java
deleted file mode 100644
index 6780902..0000000
--- a/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/CT_RoundTripNumericConstructors.java
+++ /dev/null
@@ -1,54 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.a.rttests;
-
-import static org.apache.juneau.TestUtils.*;
-import static org.junit.Assert.*;
-
-import java.text.*;
-import java.util.*;
-
-import org.apache.juneau.dto.jsonschema.*;
-import org.apache.juneau.parser.*;
-import org.apache.juneau.serializer.*;
-import org.junit.*;
-
-
-/**
- * Tests designed to serialize and parse objects to make sure we end up
- * with the same objects for all serializers and parsers.
- */
-@SuppressWarnings("hiding")
-public class CT_RoundTripNumericConstructors extends RoundTripTest {
-
- public CT_RoundTripNumericConstructors(String label, Serializer s, Parser p, int flags) throws Exception {
- super(label, s, p, flags);
- }
-
- //====================================================================================================
- // Test parsing numbers to dates.
- //====================================================================================================
- @Test
- public void testParseNumberToDate() throws Exception {
- if (isValidationOnly())
- return;
-
- Serializer s = getSerializer();
- Parser p = getParser();
- Date d = new Date(100, 1, 1);
-
- Object r = s.serialize(d.getTime());
- Date d2 = p.parse(r, Date.class);
- assertEquals(d.getTime(), d2.getTime());
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/CT_RoundTripObjectsAsStrings.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/CT_RoundTripObjectsAsStrings.java b/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/CT_RoundTripObjectsAsStrings.java
deleted file mode 100755
index f244cc7..0000000
--- a/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/CT_RoundTripObjectsAsStrings.java
+++ /dev/null
@@ -1,272 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.a.rttests;
-
-import static org.apache.juneau.TestUtils.*;
-import static org.junit.Assert.*;
-
-import org.apache.juneau.*;
-import org.apache.juneau.parser.*;
-import org.apache.juneau.serializer.*;
-import org.junit.*;
-
-/**
- * Tests to ensure the valueOf(String), fromString(String), parse(String), and parseString(String) methods
- * are used correctly by parsers.
- */
-@SuppressWarnings("unused")
-public class CT_RoundTripObjectsAsStrings extends RoundTripTest {
-
- public CT_RoundTripObjectsAsStrings(String label, Serializer s, Parser p, int flags) throws Exception {
- super(label, s, p, flags);
- }
-
- //====================================================================================================
- // testBasic
- //====================================================================================================
- @Test
- public void testBasic() throws Exception {
- A t = new A().init();
- t = roundTrip(t);
- assertObjectEquals("{a1:{f:'1'},a2:{f:'2'},a3:{f:'3'},a4:{f:'4'}}", t);
- }
-
- public static class A {
- public A1 a1;
- public A2 a2;
- public A3 a3;
- public A4 a4;
-
- public A init() {
- a1 = new A1();
- a1.f = "1";
- a2 = new A2();
- a2.f = "2";
- a3 = new A3();
- a3.f = "3";
- a4 = new A4();
- a4.f = "4";
- return this;
- }
- }
-
- public static class A1 {
- public String f;
- public static A1 fromString(String s) {
- A1 x = new A1();
- x.f = s.substring(3);
- return x;
- }
- @Override /* Object */
- public String toString() {
- return "A1-" + f;
- }
- }
-
- public static class A2 {
- public String f;
- public static A2 valueOf(String s) {
- A2 x = new A2();
- x.f = s.substring(3);
- return x;
- }
- @Override /* Object */
- public String toString() {
- return "A2-" + f;
- }
- }
-
- public static class A3 {
- public String f;
- public static A3 parse(String s) {
- A3 x = new A3();
- x.f = s.substring(3);
- return x;
- }
- @Override /* Object */
- public String toString() {
- return "A3-" + f;
- }
- }
-
- public static class A4 {
- public String f;
- public static A4 parseString(String s) {
- A4 x = new A4();
- x.f = s.substring(3);
- return x;
- }
- @Override /* Object */
- public String toString() {
- return "A4-" + f;
- }
- }
-
- //====================================================================================================
- // testEnumWithOverriddenStringValue
- // The B1 enum should serialize as "X1" but the B2 enum should serialize as "X-1".
- //====================================================================================================
- @Test
- public void testEnumWithOverriddenStringValue() throws Exception {
- B t = new B().init();
- if (! returnOriginalObject) {
- Object r = getSerializer().serialize(t);
- assertTrue(TestUtils.toString(r).contains("X-2"));
- }
- t = roundTrip(t);
- assertObjectEquals("{b1:'X1',b2:'X-2'}", t);
- }
-
- public static class B {
- public B1 b1;
- public B2 b2;
-
- public B init() {
- b1 = B1.X1;
- b2 = B2.X2;
- return this;
- }
-
- }
-
- public static enum B1 {
- X1(1),
- X2(2),
- X3(3);
-
- private int i;
- B1(int i) {
- this.i = i;
- }
- }
-
- public static enum B2 {
- X1(1),
- X2(2),
- X3(3);
-
- private int i;
- B2(int i) {
- this.i = i;
- }
-
- @Override /* Object */
- public String toString() {
- return "X-" + i;
- }
-
- public static B2 fromString(String s) {
- return valueOf("X" + s.substring(2));
- }
- }
-
- //====================================================================================================
- // testMethodOrdering
- //====================================================================================================
- @Test
- public void testOrdering() throws Exception {
- C t = new C().init();
- t = roundTrip(t);
- assertObjectEquals("{c1:{f:'1'},c2:{f:'2'},c3:{f:'3'},c4:{f:'4'}}", t);
- }
-
- public static class C {
- public C1 c1;
- public C2 c2;
- public C3 c3;
- public C4 c4;
-
- public C init() {
- c1 = new C1();
- c1.f = "1";
- c2 = new C2();
- c2.f = "2";
- c3 = new C3();
- c3.f = "3";
- c4 = new C4();
- c4.f = "4";
- return this;
- }
- }
-
- public static class C1 {
- public String f;
- public static C2 valueOf(String s) {
- throw new RuntimeException("Shouldn't be called!");
- }
- public static C2 parse(String s) {
- throw new RuntimeException("Shouldn't be called!");
- }
- public static C2 parseString(String s) {
- throw new RuntimeException("Shouldn't be called!");
- }
- public static C1 fromString(String s) {
- C1 x = new C1();
- x.f = s.substring(3);
- return x;
- }
-
- @Override /* Object */
- public String toString() {
- return "C1-" + f;
- }
- }
-
- public static class C2 {
- public String f;
- public static C2 parse(String s) {
- throw new RuntimeException("Shouldn't be called!");
- }
- public static C2 parseString(String s) {
- throw new RuntimeException("Shouldn't be called!");
- }
- public static C2 valueOf(String s) {
- C2 x = new C2();
- x.f = s.substring(3);
- return x;
- }
- @Override /* Object */
- public String toString() {
- return "C2-" + f;
- }
- }
-
- public static class C3 {
- public String f;
- public static C2 parseString(String s) {
- throw new RuntimeException("Shouldn't be called!");
- }
- public static C3 parse(String s) {
- C3 x = new C3();
- x.f = s.substring(3);
- return x;
- }
- @Override /* Object */
- public String toString() {
- return "C3-" + f;
- }
- }
-
- public static class C4 {
- public String f;
- public static C4 parseString(String s) {
- C4 x = new C4();
- x.f = s.substring(3);
- return x;
- }
- @Override /* Object */
- public String toString() {
- return "C4" + f;
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/CT_RoundTripObjectsWithSpecialMethods.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/CT_RoundTripObjectsWithSpecialMethods.java b/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/CT_RoundTripObjectsWithSpecialMethods.java
deleted file mode 100755
index 0cd8df2..0000000
--- a/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/CT_RoundTripObjectsWithSpecialMethods.java
+++ /dev/null
@@ -1,116 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.a.rttests;
-
-import static org.apache.juneau.TestUtils.*;
-import static org.junit.Assert.*;
-
-import java.util.*;
-
-import org.apache.juneau.annotation.*;
-import org.apache.juneau.json.*;
-import org.apache.juneau.parser.*;
-import org.apache.juneau.serializer.*;
-import org.junit.*;
-
-
-
-/**
- * Tests designed to serialize and parse objects to make sure we end up
- * with the same objects for all serializers and parsers.
- */
-public class CT_RoundTripObjectsWithSpecialMethods extends RoundTripTest {
-
- public CT_RoundTripObjectsWithSpecialMethods(String label, Serializer s, Parser p, int flags) throws Exception {
- super(label, s, p, flags);
- }
-
- //====================================================================================================
- // @NameProperty method.
- //====================================================================================================
- @Test
- public void testNameProperty() throws Exception {
- A t = new A().init();
- t = roundTrip(t);
- assertObjectEquals("{a2:{f2:2},m:{k1:{f2:2}}}", t);
- if (isValidationOnly())
- return;
- assertEquals("a2", t.a2.name);
- assertEquals("k1", t.m.get("k1").name);
- }
-
- public static class A {
- public A2 a2;
- public Map<String,A2> m;
-
- A init() {
- a2 = new A2().init();
- m = new LinkedHashMap<String,A2>();
- m.put("k1", new A2().init());
- return this;
- }
-
- }
- public static class A2 {
- String name;
- public int f2;
-
- @NameProperty
- protected void setName(String name) {
- this.name = name;
- }
-
- A2 init() {
- f2 = 2;
- return this;
- }
- }
-
- //====================================================================================================
- // @ParentProperty method.
- //====================================================================================================
- @Test
- public void testParentProperty() throws Exception {
- B t = new B().init();
- t = roundTrip(t);
- if (isValidationOnly())
- return;
- assertEquals(t.f1, t.b2.parent.f1);
- }
-
- public static class B {
- public int f1;
- public B2 b2;
-
- B init() {
- f1 = 1;
- b2 = new B2().init();
- return this;
- }
-
- }
- public static class B2 {
- B parent;
- public int f2;
-
- @ParentProperty
- protected void setParent(B parent) {
- this.parent = parent;
- }
-
- B2 init() {
- f2 = 2;
- return this;
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/CT_RoundTripPrimitiveObjectBeans.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/CT_RoundTripPrimitiveObjectBeans.java b/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/CT_RoundTripPrimitiveObjectBeans.java
deleted file mode 100755
index f0dc2b3..0000000
--- a/org.apache.juneau/src/test/java/org/apache/juneau/a/rttests/CT_RoundTripPrimitiveObjectBeans.java
+++ /dev/null
@@ -1,197 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.a.rttests;
-
-import static org.junit.Assert.*;
-
-import org.apache.juneau.jena.*;
-import org.apache.juneau.parser.*;
-import org.apache.juneau.serializer.*;
-import org.apache.juneau.testbeans.*;
-import org.junit.*;
-
-/**
- * Tests designed to serialize and parse objects to make sure we end up
- * with the same objects for all serializers and parsers.
- */
-public class CT_RoundTripPrimitiveObjectBeans extends RoundTripTest {
-
- public CT_RoundTripPrimitiveObjectBeans(String label, Serializer s, Parser p, int flags) throws Exception {
- super(label, s, p, flags);
- }
-
- //====================================================================================================
- // testPrimitiveObjectsBean
- //====================================================================================================
- @Test
- public void testPrimitiveObjectsBean() throws Exception {
- PrimitiveObjectsBean t = new PrimitiveObjectsBean().init();
- t = roundTrip(t, PrimitiveObjectsBean.class);
- t = roundTrip(t, PrimitiveObjectsBean.class);
-
- // primitives
- assertEquals(Boolean.valueOf(true), t.poBoolean);
- assertEquals(Byte.valueOf((byte)1), t.poByte);
- assertEquals(Character.valueOf('a'), t.poChar);
- assertEquals(Short.valueOf("2"), t.poShort);
- assertEquals(Integer.valueOf(3), t.poInt);
- assertEquals(Long.valueOf(4), t.poLong);
- assertEquals(Float.valueOf(5), t.poFloat);
- assertEquals(Double.valueOf(6), t.poDouble);
- assertEquals(Integer.valueOf(7), t.poNumber);
- assertEquals(8, t.poBigInteger.intValue());
- assertTrue(t.poBigDecimal.floatValue() == 9f);
-
- // uninitialized primitives
- assertNull(t.pouBoolean);
- assertNull(t.pouByte);
- assertNull(t.pouChar);
- assertNull(t.pouShort);
- assertNull(t.pouInt);
- assertNull(t.pouLong);
- assertNull(t.pouFloat);
- assertNull(t.pouDouble);
- assertNull(t.pouNumber);
- assertNull(t.pouBigInteger);
- assertNull(t.pouBigDecimal);
-
- // primitive arrays
- assertEquals(Boolean.valueOf(false), t.poaBoolean[1][0]);
- assertEquals(Byte.valueOf((byte)2), t.poaByte[1][0]);
- assertEquals(Character.valueOf('b'), t.poaChar[1][0]);
- assertEquals(Short.valueOf("2"), t.poaShort[1][0]);
- assertEquals(Integer.valueOf(2), t.poaInt[1][0]);
- assertEquals(Long.valueOf(2), t.poaLong[1][0]);
- assertEquals(Float.valueOf(2), t.poaFloat[1][0]);
- assertEquals(Double.valueOf(2), t.poaDouble[1][0]);
- assertEquals(Integer.valueOf(2), t.poaNumber[1][0]);
- assertEquals(2, t.poaBigInteger[1][0].intValue());
- assertEquals(2, t.poaBigDecimal[1][0].intValue());
- assertNull(t.poaBoolean[2]);
- assertNull(t.poaByte[2]);
- assertNull(t.poaChar[2]);
- assertNull(t.poaShort[2]);
- assertNull(t.poaInt[2]);
- assertNull(t.poaLong[2]);
- assertNull(t.poaFloat[2]);
- assertNull(t.poaDouble[2]);
- assertNull(t.poaNumber[2]);
- assertNull(t.poaBigInteger[2]);
- assertNull(t.poaBigDecimal[2]);
-
- // uninitialized primitive arrays
- assertNull(t.poauBoolean);
- assertNull(t.poauByte);
- assertNull(t.poauChar);
- assertNull(t.poauShort);
- assertNull(t.poauInt);
- assertNull(t.poauLong);
- assertNull(t.poauFloat);
- assertNull(t.poauDouble);
- assertNull(t.poauNumber);
- assertNull(t.poauBigInteger);
- assertNull(t.poauBigDecimal);
-
- // anonymous list of object primitive arrays
- assertEquals(Boolean.valueOf(true), t.poalBoolean.get(0)[0]);
- assertEquals(Byte.valueOf((byte)1), t.poalByte.get(0)[0]);
- assertEquals(Character.valueOf('a'), t.poalChar.get(0)[0]);
- assertEquals(Short.valueOf((short)1), t.poalShort.get(0)[0]);
- assertEquals(Integer.valueOf(1), t.poalInt.get(0)[0]);
- assertEquals(Long.valueOf(1l), t.poalLong.get(0)[0]);
- assertEquals(Float.valueOf(1f), t.poalFloat.get(0)[0]);
- assertEquals(Double.valueOf(1d), t.poalDouble.get(0)[0]);
- assertEquals(1, t.poalBigInteger.get(0)[0].intValue());
- assertEquals(1, t.poalBigDecimal.get(0)[0].intValue());
- assertNull(t.poalBoolean.get(1));
- assertNull(t.poalByte.get(1));
- assertNull(t.poalChar.get(1));
- assertNull(t.poalShort.get(1));
- assertNull(t.poalInt.get(1));
- assertNull(t.poalLong.get(1));
- assertNull(t.poalFloat.get(1));
- assertNull(t.poalDouble.get(1));
- assertNull(t.poalNumber.get(1));
- assertNull(t.poalBigInteger.get(1));
- assertNull(t.poalBigDecimal.get(1));
-
- // regular list of object primitive arrays
- assertEquals(Boolean.valueOf(true), t.polBoolean.get(0)[0]);
- assertEquals(Byte.valueOf((byte)1), t.polByte.get(0)[0]);
- assertEquals(Character.valueOf('a'), t.polChar.get(0)[0]);
- assertEquals(Short.valueOf((short)1), t.polShort.get(0)[0]);
- assertEquals(Integer.valueOf(1), t.polInt.get(0)[0]);
- assertEquals(Long.valueOf(1l), t.polLong.get(0)[0]);
- assertEquals(Float.valueOf(1f), t.polFloat.get(0)[0]);
- assertEquals(Double.valueOf(1d), t.polDouble.get(0)[0]);
- assertEquals(1, t.polBigInteger.get(0)[0].intValue());
- assertEquals(1, t.polBigDecimal.get(0)[0].intValue());
- assertNull(t.polBoolean.get(1));
- assertNull(t.polByte.get(1));
- assertNull(t.polChar.get(1));
- assertNull(t.polShort.get(1));
- assertNull(t.polInt.get(1));
- assertNull(t.polLong.get(1));
- assertNull(t.polFloat.get(1));
- assertNull(t.polDouble.get(1));
- assertNull(t.polNumber.get(1));
- assertNull(t.polBigInteger.get(1));
- assertNull(t.polBigDecimal.get(1));
- }
-
- //====================================================================================================
- // testPrimitiveAtomicObjectsBean
- //====================================================================================================
- @Test
- public void testPrimitiveAtomicObjectsBean() throws Exception {
-
- // Jena does not support parsing into AtomicIntegers and AtomicLongs.
- if (getSerializer() instanceof RdfSerializer)
- return;
-
- PrimitiveAtomicObjectsBean t = new PrimitiveAtomicObjectsBean().init();
- t = roundTrip(t, PrimitiveAtomicObjectsBean.class);
- t = roundTrip(t, PrimitiveAtomicObjectsBean.class);
-
- // primitives
- assertEquals(1, t.poAtomicInteger.intValue());
- assertEquals(2, t.poAtomicLong.intValue());
-
- // uninitialized primitives
- assertNull(t.pouAtomicInteger);
- assertNull(t.pouAtomicLong);
-
- // primitive arrays
- assertEquals(2, t.poaAtomicInteger[1][0].intValue());
- assertEquals(2, t.poaAtomicLong[1][0].intValue());
- assertNull(t.poaAtomicInteger[2]);
- assertNull(t.poaAtomicLong[2]);
-
- // uninitialized primitive arrays
- assertNull(t.poauAtomicInteger);
- assertNull(t.poauAtomicLong);
-
- // anonymous list of object primitive arrays
- assertEquals(1, t.poalAtomicInteger.get(0)[0].intValue());
- assertEquals(1, t.poalAtomicLong.get(0)[0].intValue());
- assertNull(t.poalAtomicInteger.get(1));
- assertNull(t.poalAtomicLong.get(1));
-
- // regular list of object primitive arrays
- assertEquals(1, t.polAtomicInteger.get(0)[0].intValue());
- assertEquals(1, t.polAtomicLong.get(0)[0].intValue());
- assertNull(t.polAtomicInteger.get(1));
- assertNull(t.polAtomicLong.get(1));
- }
-
-}
[33/44] incubator-juneau git commit: Rename CT_* testcases.
Posted by ja...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/BeanConfigTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/BeanConfigTest.java b/org.apache.juneau/src/test/java/org/apache/juneau/BeanConfigTest.java
new file mode 100755
index 0000000..923134d
--- /dev/null
+++ b/org.apache.juneau/src/test/java/org/apache/juneau/BeanConfigTest.java
@@ -0,0 +1,849 @@
+/***************************************************************************************************************************
+ * 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.juneau;
+
+import static org.apache.juneau.BeanContext.*;
+import static org.junit.Assert.*;
+
+import java.io.*;
+import java.lang.reflect.*;
+import java.util.*;
+
+import org.apache.juneau.annotation.*;
+import org.apache.juneau.json.*;
+import org.apache.juneau.parser.*;
+import org.apache.juneau.transform.*;
+import org.junit.*;
+
+@SuppressWarnings({"unchecked","rawtypes","serial"})
+public class BeanConfigTest {
+
+ //====================================================================================================
+ // testBasic
+ //====================================================================================================
+ @Test
+ public void testBasic() throws Exception {
+
+ BeanContext bc = BeanContext.DEFAULT;
+
+ Person p1 = new Person();
+ p1.setName("John Doe");
+ p1.setAge(25);
+
+ Address a = new Address("101 Main St.", "Las Vegas", "NV", "89101");
+ AddressablePerson p2 = new AddressablePerson();
+ p2.setName("Jane Doe");
+ p2.setAge(21);
+ p2.setAddress(a);
+
+ // setup the reference results
+ Map m1 = new LinkedHashMap();
+ m1.put("name", p1.getName());
+ m1.put("age", new Integer(p1.getAge()));
+
+ Map m2 = new LinkedHashMap();
+ m2.put("street", a.getStreet());
+ m2.put("city", a.getCity());
+ m2.put("state", a.getState());
+ m2.put("zip", a.getZip());
+
+ Map m3 = new LinkedHashMap();
+ m3.put("name", p2.getName());
+ m3.put("age", new Integer(p2.getAge()));
+ m3.put("address", p2.getAddress());
+
+ Map pm1 = bc.forBean(p1);
+
+ if (pm1.size() != m1.size())
+ fail("Bean Map size failed for: " + p1 + " / " + pm1.size()+ " / " + m1.size());
+
+ if (!pm1.keySet().equals(m1.keySet()))
+ fail("Bean Map key set equality failed for: " + p1 + " / " + pm1.keySet() + " / " + m1.keySet());
+
+ if (!m1.keySet().equals(pm1.keySet()))
+ fail("Bean Map key set reverse equality failed for: " + p1 + " / " + pm1.keySet() + " / " + m1.keySet());
+
+ if (!pm1.equals(m1))
+ fail("Bean Map equality failed for: " + p1 + " / " + pm1 + " / " + m1);
+
+ if (!m1.equals(pm1))
+ fail("Bean Map reverse equality failed for: " + p1 + " / " + pm1 + " / " + m1);
+
+ BeanMap bm1 = null;
+ try {
+ bm1 = bc.newBeanMap(Address.class);
+ fail("Address returned as a new bean type, but shouldn't be since it doesn't have a default constructor.");
+ } catch (BeanRuntimeException e) {
+ // Good.
+ }
+ bm1 = bc.forBean(new Address("street", "city", "state", "zip"));
+
+ BeanMap bm2 = bc.newBeanMap(java.lang.Integer.class);
+ if (bm2 != null)
+ fail("java.lang.Integer incorrectly desingated as bean type.");
+
+ BeanMap bm3 = bc.newBeanMap(java.lang.Class.class);
+ if (bm3 != null)
+ fail("java.lang.Class incorrectly desingated as bean type.");
+
+ Map m4 = bm1;
+ if (m4.keySet().size() != m2.size())
+ fail("Bean Adapter map's key set has wrong size: " + a + " / " + m4.keySet().size() + " / " + m2.size());
+
+ Iterator iter = m4.keySet().iterator();
+ Set temp = new HashSet();
+ int count = 0;
+ while (iter.hasNext()) {
+ temp.add(iter.next());
+ count++;
+ }
+ if (count != m2.size())
+ fail("Iteration count over bean adpater key set failed: " + a + " / " + count + " / " + m2.size());
+
+ if (!m2.keySet().equals(temp))
+ fail("Iteration over bean adpater key set failed: " + a + " / " + m4.keySet() + " / " + m2.keySet());
+
+ BeanMap bm4 = bc.forBean(p2);
+ if (bm4 == null) {
+ fail("Failed to identify class as bean type: " + p2.getClass());
+ return;
+ }
+
+ Map m5 = bm4;
+ Set es1 = m5.entrySet();
+
+ if (!es1.equals(m3.entrySet()))
+ fail("Entry set equality failed: " + p2 + " / " + es1 + " / " + m3.entrySet());
+
+ if (!m3.entrySet().equals(es1))
+ fail("Entry set reverse equality failed: " + p2 + " / " + es1 + " / " + m3.entrySet());
+
+ iter = es1.iterator();
+ temp = new HashSet();
+ count = 0;
+ while (iter.hasNext()) {
+ temp.add(iter.next());
+ count++;
+ }
+ if (count != m3.size())
+ fail("Iteration count over bean adpater entry set failed: " + a + " / " + count + " / " + m3.size());
+
+ if (!m3.entrySet().equals(temp))
+ fail("Iteration over bean adpater entry set failed: " + a + " / " + es1 + " / " + m3.entrySet());
+ }
+
+ public static class Person {
+ private String name;
+ private int age;
+
+ public Person() {
+ this.name = null;
+ this.age = -1;
+ }
+
+ public String getName() {
+ return this.name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public int getAge() {
+ return this.age;
+ }
+
+ public void setAge(int age) {
+ this.age = age;
+ }
+
+ @Override /* Object */
+ public String toString() {
+ return ("Person(name: " + this.getName() + ", age: "
+ + this.getAge() + ")");
+ }
+ }
+
+ public static class Address {
+ protected String street;
+ protected String city;
+ protected String state;
+ protected String zip;
+
+ public Address(String street, String city, String state, String zip) {
+ this.street = street;
+ this.city = city;
+ this.state = state;
+ this.zip = zip;
+ }
+
+ public String getStreet() {
+ return this.street;
+ }
+
+ public String getCity() {
+ return this.city;
+ }
+
+ public String getState() {
+ return this.state;
+ }
+
+ public String getZip() {
+ return this.zip;
+ }
+
+ @Override /* Object */
+ public boolean equals(Object o) {
+ if (o == null)
+ return false;
+ if (this == o)
+ return true;
+ if (this.getClass() != o.getClass())
+ return false;
+ Address a = (Address) o;
+
+ String v1 = this.getStreet();
+ String v2 = a.getStreet();
+ if ((v1 == null) ? (v2 != null) : (!v1.equals(v2)))
+ return false;
+
+ v1 = this.getCity();
+ v2 = a.getCity();
+ if ((v1 == null) ? (v2 != null) : (!v1.equals(v2)))
+ return false;
+
+ v1 = this.getState();
+ v2 = a.getState();
+ if ((v1 == null) ? (v2 != null) : (!v1.equals(v2)))
+ return false;
+
+ v1 = this.getZip();
+ v2 = a.getZip();
+ return ((v1 == null) ? (v2 == null) : (v1.equals(v2)));
+ }
+
+ @Override /* Object */
+ public int hashCode() {
+ int code = 0;
+ if (this.street != null)
+ code ^= this.street.hashCode();
+ if (this.city != null)
+ code ^= this.city.hashCode();
+ if (this.state != null)
+ code ^= this.state.hashCode();
+ if (this.zip != null)
+ code ^= this.zip.hashCode();
+ return code;
+ }
+
+ @Override /* Object */
+ public String toString() {
+ return ("Address(street: " + this.getStreet() + ", city: "
+ + this.getCity() + ", state: " + this.getState()
+ + ", zip: " + this.getZip() + ")");
+ }
+ }
+
+ public static class AddressablePerson extends Person {
+ private Address address;
+
+ public AddressablePerson() {
+ this.address = null;
+ }
+
+ public Address getAddress() {
+ return this.address;
+ }
+
+ public void setAddress(Address addr) {
+ this.address = addr;
+ }
+
+ @Override /* Object */
+ public String toString() {
+ return super.toString() + "@" + this.address;
+ }
+ }
+
+ //====================================================================================================
+ // Exhaustive test of BeanContext.convertToType();
+ //====================================================================================================
+ @Test
+ public void testBeanContextConvertToType() throws Exception {
+ BeanContext bc = BeanContext.DEFAULT;
+ Object o;
+
+ // Primitive nulls.
+ o = null;
+ assertEquals(new Integer(0), bc.convertToType(o, Integer.TYPE));
+ assertEquals(new Short((short) 0), bc.convertToType(o, Short.TYPE));
+ assertEquals(new Long(0), bc.convertToType(o, Long.TYPE));
+ assertEquals(new Float(0), bc.convertToType(o, Float.TYPE));
+ assertEquals(new Double(0), bc.convertToType(o, Double.TYPE));
+ assertEquals(new Byte((byte) 0), bc.convertToType(o, Byte.TYPE));
+ assertEquals(new Character((char) 0), bc.convertToType(o, Character.TYPE));
+ assertEquals(Boolean.FALSE, bc.convertToType(o, Boolean.TYPE));
+
+ o = "1";
+
+ assertEquals(new Integer(1), bc.convertToType(o, Integer.class));
+ assertEquals(new Short((short) 1), bc.convertToType(o, Short.class));
+ assertEquals(new Long(1), bc.convertToType(o, Long.class));
+ assertEquals(new Float(1), bc.convertToType(o, Float.class));
+ assertEquals(new Double(1), bc.convertToType(o, Double.class));
+ assertEquals(new Byte((byte) 1), bc.convertToType(o, Byte.class));
+ assertEquals(new Character('1'), bc.convertToType(o, Character.class));
+ assertEquals(Boolean.FALSE, bc.convertToType(o, Boolean.class));
+
+ assertEquals(new Integer(1), bc.convertToType(o, Integer.TYPE));
+ assertEquals(new Short((short) 1), bc.convertToType(o, Short.TYPE));
+ assertEquals(new Long(1), bc.convertToType(o, Long.TYPE));
+ assertEquals(new Float(1), bc.convertToType(o, Float.TYPE));
+ assertEquals(new Double(1), bc.convertToType(o, Double.TYPE));
+ assertEquals(new Byte((byte) 1), bc.convertToType(o, Byte.TYPE));
+ assertEquals(new Character('1'), bc.convertToType(o, Character.TYPE));
+ assertEquals(Boolean.FALSE, bc.convertToType(o, Boolean.TYPE));
+
+ o = new Integer(1);
+
+ assertEquals(new Integer(1), bc.convertToType(o, Integer.TYPE));
+ assertEquals(new Short((short) 1), bc.convertToType(o, Short.TYPE));
+ assertEquals(new Long(1), bc.convertToType(o, Long.TYPE));
+ assertEquals(new Float(1), bc.convertToType(o, Float.TYPE));
+ assertEquals(new Double(1), bc.convertToType(o, Double.TYPE));
+ assertEquals(new Byte((byte) 1), bc.convertToType(o, Byte.TYPE));
+ assertEquals(new Character('1'), bc.convertToType(o, Character.TYPE));
+ assertEquals(Boolean.TRUE, bc.convertToType(o, Boolean.TYPE));
+
+ o = new Integer(0);
+ assertEquals(Boolean.FALSE, bc.convertToType(o, Boolean.TYPE));
+
+ // Bean
+ o = "{name:'x',age:123}";
+ assertEquals("x", bc.convertToType(o, Person.class).getName());
+ assertEquals(123, bc.convertToType(o, Person.class).getAge());
+
+ // Read-only bean
+ o = "{name:'x',age:123}";
+ assertEquals("x", bc.convertToType(o, ReadOnlyPerson.class).getName());
+ assertEquals(123, bc.convertToType(o, ReadOnlyPerson.class).getAge());
+
+ // Class with forString(String) method.
+ o = UUID.randomUUID();
+ assertEquals(o, bc.convertToType(o.toString(), UUID.class));
+
+ // Class with Constructor(String).
+ o = "xxx";
+ File file = bc.convertToType(o, File.class);
+ assertEquals("xxx", file.getName());
+
+ // List of ints to array
+ o = new ObjectList(1, 2, 3);
+ assertEquals(1, bc.convertToType(o, int[].class)[0]);
+
+ // List of beans to array
+ o = new ObjectList(new ReadOnlyPerson("x", 123));
+ assertEquals("x", bc.convertToType(o, ReadOnlyPerson[].class)[0].getName());
+
+ // Multi-dimensional array of beans.
+ o = new ObjectList().append(new ObjectList(new ReadOnlyPerson("x", 123)));
+ assertEquals("x", bc.convertToType(o, ReadOnlyPerson[][].class)[0][0].getName());
+
+ // Array of strings to array of ints
+ o = new String[] { "1", "2", "3" };
+ assertEquals(new Integer(1), bc.convertToType(o, Integer[].class)[0]);
+ assertEquals(1, bc.convertToType(o, int[].class)[0]);
+
+ // Array to list
+ o = new Integer[] { 1, 2, 3 };
+ assertEquals(new Integer(1), bc.convertToType(o, LinkedList.class).get(0));
+
+ // HashMap to TreeMap
+ o = new HashMap<Integer, String>() {{ put(1, "foo"); }};
+ assertEquals("foo", bc.convertToType(o, TreeMap.class).firstEntry().getValue());
+
+ // String to TreeMap
+ o = "{1:'foo'}";
+ assertEquals("foo", bc.convertToType(o, TreeMap.class).firstEntry().getValue());
+
+ // String to generic Map
+ assertEquals("foo", bc.convertToType(o, Map.class).values().iterator().next());
+
+ // Array to String
+ o = new Object[] { "a", 1, false };
+ assertEquals("['a',1,false]", bc.convertToType(o, String.class));
+ o = new Object[][] { { "a", 1, false } };
+ assertEquals("[['a',1,false]]", bc.convertToType(o, String.class));
+
+ }
+
+ //====================================================================================================
+ // Test properties set through a constructor.
+ //====================================================================================================
+ @Test
+ public void testReadOnlyProperties() throws Exception {
+ BeanContext bc = BeanContext.DEFAULT;
+ Object o;
+
+ // Bean to String
+ o = new ReadOnlyPerson("x", 123);
+ assertEquals("{name:'x',age:123}", bc.convertToType(o, String.class));
+
+ // List of Maps to array of beans.
+ o = new ObjectList(new ObjectMap("{name:'x',age:1}"), new ObjectMap("{name:'y',age:2}"));
+ assertEquals(1, bc.convertToType(o, ReadOnlyPerson[].class)[0].getAge());
+ }
+
+
+ @Bean(properties={"name","age"})
+ public static class ReadOnlyPerson {
+ private final String name;
+ private final int age;
+
+ @BeanConstructor(properties = { "name", "age" })
+ public ReadOnlyPerson(String name, int age) {
+ this.name = name;
+ this.age = age;
+ }
+
+ public String getName() {
+ return this.name;
+ }
+
+ public int getAge() {
+ return this.age;
+ }
+
+ @Override /* Object */
+ public String toString() {
+ return "toString():name=" + name + ",age=" + age;
+ }
+ }
+
+ //====================================================================================================
+ // testEnums
+ //====================================================================================================
+ @Test
+ public void testEnums() throws Exception {
+ BeanContext bc = BeanContext.DEFAULT;
+ Object o;
+
+ // Enum
+ o = "ENUM2";
+ assertEquals(TestEnum.ENUM2, bc.convertToType(o, TestEnum.class));
+ assertEquals("ENUM2", bc.convertToType(TestEnum.ENUM2, String.class));
+
+ // Array of enums
+ o = new String[] { "ENUM2" };
+ assertEquals(TestEnum.ENUM2, bc.convertToType(o, TestEnum[].class)[0]);
+ }
+
+ public enum TestEnum {
+ ENUM1, ENUM2, ENUM3
+ }
+
+ //====================================================================================================
+ // testProxyHandler
+ //====================================================================================================
+ @Test
+ public void testProxyHandler() throws Exception {
+ BeanContext bc = ContextFactory.create().setClassLoader(A.class.getClassLoader()).getBeanContext();
+
+ A f1 = (A) Proxy.newProxyInstance(this.getClass()
+ .getClassLoader(), new Class[] { A.class },
+ new AHandler());
+
+ BeanMap bm1 = bc.forBean(f1);
+ if (bm1 == null) {
+ fail("Failed to obtain bean adapter for proxy: " + f1);
+ return;
+ }
+
+ BeanMap bm2 = bc.newBeanMap(A.class);
+ if (bm2 == null) {
+ fail("Failed to create dynamic proxy bean for interface: " + A.class.getName());
+ return;
+ }
+ bm2.put("a", "Hello");
+ bm2.put("b", new Integer(50));
+ f1.setA("Hello");
+ f1.setB(50);
+
+ if (!bm2.get("a").equals("Hello"))
+ fail("Failed to set string property 'a' on dynamic proxy bean. " + bm2);
+
+ if (!bm2.get("b").equals(new Integer(50)))
+ fail("Failed to set string property 'b' on dynamic proxy bean. " + bm2);
+
+ if (!bm1.equals(bm2))
+ fail("Failed equality test of dynamic proxies beans: " + bm1 + " / " + bm2);
+
+ if (!bm2.equals(bm1))
+ fail("Failed reverse equality test of dynamic proxies beans: " + bm1 + " / " + bm2);
+ }
+
+ public static interface A {
+ String getA();
+
+ void setA(String a);
+
+ int getB();
+
+ void setB(int b);
+ }
+
+ public static class AHandler implements InvocationHandler {
+ private Map map;
+
+ public AHandler() {
+ this.map = new HashMap();
+ this.map.put("a", "");
+ this.map.put("b", new Integer(0));
+ }
+
+ @Override /* InvocationHandler */
+ public Object invoke(Object proxy, Method method, Object[] args)
+ throws Throwable {
+ String methodName = method.getName();
+ if (methodName.equals("getA")) {
+ return this.map.get("a");
+ }
+ if (methodName.equals("setA")) {
+ this.map.put("a", args[0]);
+ return null;
+ }
+ if (methodName.equals("getB")) {
+ return this.map.get("b");
+ }
+ if (methodName.equals("setB")) {
+ this.map.put("b", args[0]);
+ return null;
+ }
+ if (methodName.equals("toString")) {
+ return this.map.toString();
+ }
+ return null;
+ }
+ }
+
+ //====================================================================================================
+ // testGetClassMetaFromString
+ //====================================================================================================
+ @Test
+ public void testGetClassMetaFromString() throws Exception {
+ BeanContext bc = BeanContext.DEFAULT;
+ assertEquals("java.lang.String[]", bc.getClassMetaFromString("java.lang.String[]").toString());
+ assertEquals("java.lang.String[]", bc.getClassMetaFromString("[Ljava.lang.String;").toString());
+ assertEquals("java.lang.String[][]", bc.getClassMetaFromString("java.lang.String[][]").toString());
+ assertEquals("java.lang.String[][]", bc.getClassMetaFromString("[[Ljava.lang.String;").toString());
+ assertEquals("boolean", bc.getClassMetaFromString("boolean").toString());
+ }
+
+ //====================================================================================================
+ // testFluentStyleSetters
+ //====================================================================================================
+ @Test
+ public void testFluentStyleSetters() throws Exception {
+ B2 t = new B2().init();
+ BeanMap m = BeanContext.DEFAULT.forBean(t);
+ m.put("f1", 2);
+ assertEquals(t.f1, 2);
+ }
+
+ public static class B {
+ int f1;
+ public int getF1() { return f1; }
+ public B setF1(int f1) { this.f1 = f1; return this; }
+ }
+
+ public static class B2 extends B {
+ @Override /* B */
+ public B2 setF1(int f1) { this.f1 = f1; return this; }
+ public B2 init() { this.f1 = 1; return this;}
+ }
+
+ //====================================================================================================
+ // testClassMetaCaching
+ //====================================================================================================
+ @Test
+ public void testClassMetaCaching() throws Exception {
+ Parser p1, p2;
+
+ p1 = new JsonParser();
+ p2 = new JsonParser();
+ assertSameCache(p1, p2);
+
+ p1.setProperty(BEAN_beansRequireDefaultConstructor, true);
+ assertDifferentCache(p1, p2);
+ p2.setProperty(BEAN_beansRequireDefaultConstructor, true);
+ assertSameCache(p1, p2);
+
+ p1.setProperty(BEAN_beansRequireSerializable, true);
+ assertDifferentCache(p1, p2);
+ p2.setProperty(BEAN_beansRequireSerializable, true);
+ assertSameCache(p1, p2);
+
+ p1.setProperty(BEAN_beansRequireSettersForGetters, true);
+ assertDifferentCache(p1, p2);
+ p2.setProperty(BEAN_beansRequireSettersForGetters, true);
+ assertSameCache(p1, p2);
+
+ p1.setProperty(BEAN_beansRequireSomeProperties, false);
+ assertDifferentCache(p1, p2);
+ p2.setProperty(BEAN_beansRequireSomeProperties, false);
+ assertSameCache(p1, p2);
+
+ p1.setProperty(BEAN_beanMapPutReturnsOldValue, true);
+ assertDifferentCache(p1, p2);
+ p2.setProperty(BEAN_beanMapPutReturnsOldValue, true);
+ assertSameCache(p1, p2);
+
+ p1.setProperty(BEAN_beanConstructorVisibility, Visibility.DEFAULT);
+ assertDifferentCache(p1, p2);
+ p2.setProperty(BEAN_beanConstructorVisibility, Visibility.DEFAULT);
+ assertSameCache(p1, p2);
+ p1.setProperty(BEAN_beanConstructorVisibility, Visibility.NONE);
+ assertDifferentCache(p1, p2);
+ p2.setProperty(BEAN_beanConstructorVisibility, Visibility.NONE);
+ assertSameCache(p1, p2);
+ p1.setProperty(BEAN_beanConstructorVisibility, Visibility.PRIVATE);
+ assertDifferentCache(p1, p2);
+ p2.setProperty(BEAN_beanConstructorVisibility, Visibility.PRIVATE);
+ assertSameCache(p1, p2);
+ p1.setProperty(BEAN_beanConstructorVisibility, Visibility.PROTECTED);
+ assertDifferentCache(p1, p2);
+ p2.setProperty(BEAN_beanConstructorVisibility, Visibility.PROTECTED);
+ assertSameCache(p1, p2);
+
+ p1.setProperty(BEAN_beanClassVisibility, Visibility.DEFAULT);
+ assertDifferentCache(p1, p2);
+ p2.setProperty(BEAN_beanClassVisibility, Visibility.DEFAULT);
+ assertSameCache(p1, p2);
+ p1.setProperty(BEAN_beanClassVisibility, Visibility.NONE);
+ assertDifferentCache(p1, p2);
+ p2.setProperty(BEAN_beanClassVisibility, Visibility.NONE);
+ assertSameCache(p1, p2);
+ p1.setProperty(BEAN_beanClassVisibility, Visibility.PRIVATE);
+ assertDifferentCache(p1, p2);
+ p2.setProperty(BEAN_beanClassVisibility, Visibility.PRIVATE);
+ assertSameCache(p1, p2);
+ p1.setProperty(BEAN_beanClassVisibility, Visibility.PROTECTED);
+ assertDifferentCache(p1, p2);
+ p2.setProperty(BEAN_beanClassVisibility, Visibility.PROTECTED);
+ assertSameCache(p1, p2);
+
+ p1.setProperty(BEAN_beanFieldVisibility, Visibility.DEFAULT);
+ assertDifferentCache(p1, p2);
+ p2.setProperty(BEAN_beanFieldVisibility, Visibility.DEFAULT);
+ assertSameCache(p1, p2);
+ p1.setProperty(BEAN_beanFieldVisibility, Visibility.NONE);
+ assertDifferentCache(p1, p2);
+ p2.setProperty(BEAN_beanFieldVisibility, Visibility.NONE);
+ assertSameCache(p1, p2);
+ p1.setProperty(BEAN_beanFieldVisibility, Visibility.PRIVATE);
+ assertDifferentCache(p1, p2);
+ p2.setProperty(BEAN_beanFieldVisibility, Visibility.PRIVATE);
+ assertSameCache(p1, p2);
+ p1.setProperty(BEAN_beanFieldVisibility, Visibility.PROTECTED);
+ assertDifferentCache(p1, p2);
+ p2.setProperty(BEAN_beanFieldVisibility, Visibility.PROTECTED);
+ assertSameCache(p1, p2);
+
+ p1.setProperty(BEAN_methodVisibility, Visibility.DEFAULT);
+ assertDifferentCache(p1, p2);
+ p2.setProperty(BEAN_methodVisibility, Visibility.DEFAULT);
+ assertSameCache(p1, p2);
+ p1.setProperty(BEAN_methodVisibility, Visibility.NONE);
+ assertDifferentCache(p1, p2);
+ p2.setProperty(BEAN_methodVisibility, Visibility.NONE);
+ assertSameCache(p1, p2);
+ p1.setProperty(BEAN_methodVisibility, Visibility.PRIVATE);
+ assertDifferentCache(p1, p2);
+ p2.setProperty(BEAN_methodVisibility, Visibility.PRIVATE);
+ assertSameCache(p1, p2);
+ p1.setProperty(BEAN_methodVisibility, Visibility.PROTECTED);
+ assertDifferentCache(p1, p2);
+ p2.setProperty(BEAN_methodVisibility, Visibility.PROTECTED);
+ assertSameCache(p1, p2);
+
+ p1.setProperty(BEAN_useJavaBeanIntrospector, true);
+ assertDifferentCache(p1, p2);
+ p2.setProperty(BEAN_useJavaBeanIntrospector, true);
+ assertSameCache(p1, p2);
+
+ p1.setProperty(BEAN_useInterfaceProxies, false);
+ assertDifferentCache(p1, p2);
+ p2.setProperty(BEAN_useInterfaceProxies, false);
+ assertSameCache(p1, p2);
+
+ p1.setProperty(BEAN_ignoreUnknownBeanProperties, true);
+ assertDifferentCache(p1, p2);
+ p2.setProperty(BEAN_ignoreUnknownBeanProperties, true);
+ assertSameCache(p1, p2);
+
+ p1.setProperty(BEAN_ignoreUnknownNullBeanProperties, false);
+ assertDifferentCache(p1, p2);
+ p2.setProperty(BEAN_ignoreUnknownNullBeanProperties, false);
+ assertSameCache(p1, p2);
+
+ p1.setProperty(BEAN_ignorePropertiesWithoutSetters, false);
+ assertDifferentCache(p1, p2);
+ p2.setProperty(BEAN_ignorePropertiesWithoutSetters, false);
+ assertSameCache(p1, p2);
+
+ p1.setProperty(BEAN_ignoreInvocationExceptionsOnGetters, true);
+ assertDifferentCache(p1, p2);
+ p2.setProperty(BEAN_ignoreInvocationExceptionsOnGetters, true);
+ assertSameCache(p1, p2);
+
+ p1.setProperty(BEAN_ignoreInvocationExceptionsOnSetters, true);
+ assertDifferentCache(p1, p2);
+ p2.setProperty(BEAN_ignoreInvocationExceptionsOnSetters, true);
+ assertSameCache(p1, p2);
+
+ p1.setProperty(BEAN_notBeanPackages_add, "foo");
+ assertDifferentCache(p1, p2);
+ p2.setProperty(BEAN_notBeanPackages_add, "foo");
+ assertSameCache(p1, p2);
+ p1.setProperty(BEAN_notBeanPackages_add, "bar");
+ assertDifferentCache(p1, p2);
+ p2.setProperty(BEAN_notBeanPackages_add, "bar");
+ assertSameCache(p1, p2);
+ p1.setProperty(BEAN_notBeanPackages_add, "baz");
+ p1.setProperty(BEAN_notBeanPackages_add, "bing");
+ assertDifferentCache(p1, p2);
+ p2.setProperty(BEAN_notBeanPackages_add, "bing");
+ p2.setProperty(BEAN_notBeanPackages_add, "baz");
+ assertSameCache(p1, p2);
+
+ p1.setProperty(BEAN_notBeanPackages_remove, "bar");
+ assertDifferentCache(p1, p2);
+ p2.setProperty(BEAN_notBeanPackages_remove, "bar");
+ assertSameCache(p1, p2);
+
+ p1.addTransforms(DummyPojoTransformA.class);
+ assertDifferentCache(p1, p2);
+ p2.addTransforms(DummyPojoTransformA.class);
+ assertSameCache(p1, p2);
+ p1.addTransforms(DummyPojoTransformB.class,DummyPojoTransformC.class); // Order of filters is important!
+ p2.addTransforms(DummyPojoTransformC.class,DummyPojoTransformB.class);
+ assertDifferentCache(p1, p2);
+
+ p1 = new JsonParser();
+ p2 = new JsonParser();
+ p1.addTransforms(DummyBeanTransformA.class);
+ assertDifferentCache(p1, p2);
+ p2.addTransforms(DummyBeanTransformA.class);
+ assertSameCache(p1, p2);
+ p1.addTransforms(DummyBeanTransformB.class,DummyBeanTransformC.class); // Order of filters is important!
+ p2.addTransforms(DummyBeanTransformC.class,DummyBeanTransformB.class);
+ assertDifferentCache(p1, p2);
+ }
+
+ public static class DummyPojoTransformA extends PojoTransform<A,ObjectMap> {}
+ public static class DummyPojoTransformB extends PojoTransform<B,ObjectMap> {}
+ public static class DummyPojoTransformC extends PojoTransform<C,ObjectMap> {}
+ public static class DummyBeanTransformA extends BeanTransform<A> {}
+ public static class DummyBeanTransformB extends BeanTransform<B> {}
+ public static class DummyBeanTransformC extends BeanTransform<C> {}
+ public static class C {}
+
+ private void assertSameCache(Parser p1, Parser p2) {
+ assertTrue(p1.getBeanContext().hasSameCache(p2.getBeanContext()));
+ assertTrue(p1.getBeanContext().hashCode() == p2.getBeanContext().hashCode());
+ }
+
+ private void assertDifferentCache(Parser p1, Parser p2) {
+ assertFalse(p1.getBeanContext().hasSameCache(p2.getBeanContext()));
+ assertFalse(p1.getBeanContext().hashCode() == p2.getBeanContext().hashCode());
+ }
+
+ //====================================================================================================
+ // testNotABeanReasons
+ //====================================================================================================
+ @Test
+ public void testNotABeanNonStaticInnerClass() throws Exception {
+ BeanContext bc = BeanContext.DEFAULT;
+ ClassMeta cm = bc.getClassMeta(C1.class);
+ assertFalse(cm.canCreateNewInstance());
+ }
+
+ public class C1 {
+ public int f1;
+ }
+
+ //====================================================================================================
+ // testAddingToArrayProperty
+ // This tests the speed of the BeanMap.add() method against array properties.
+ // For performance reasons, array properties are stored as temporary ArrayLists until the
+ // BeanMap.getBean() method is called.
+ //====================================================================================================
+ @Test(timeout=1000) // Should be around 100ms at most.
+ public void testAddingToArrayProperty() throws Exception {
+ BeanContext bc = BeanContext.DEFAULT;
+ BeanMap<D> bm = bc.newBeanMap(D.class);
+ for (int i = 0; i < 5000; i++) {
+ bm.add("f1", i);
+ bm.add("f2", i);
+ bm.add("f3", i);
+ bm.add("f4", i);
+ }
+ D d = bm.getBean();
+ assertEquals(d.f1.length, 5000);
+ assertEquals(d.f2.length, 5000);
+ assertEquals(d.f3.length, 5003);
+ assertEquals(d.f4.length, 5003);
+ }
+
+ public class D {
+ public int[] f1;
+ private int[] f2;
+ public int[] f3 = new int[]{1,2,3};
+ private int[] f4 = new int[]{1,2,3};
+ public int[] getF2() {return f2;}
+ public void setF2(int[] f2) {this.f2 = f2;}
+ public int[] getF4() {return f4;}
+ public void setF4(int[] f4) {this.f4 = f4;}
+ }
+
+ //====================================================================================================
+ // testClassClassMeta
+ // Make sure we can get ClassMeta objects against the Class class.
+ //====================================================================================================
+ @Test
+ public void testClassClassMeta() throws Exception {
+ ClassMeta cm = BeanContext.DEFAULT.getClassMeta(Class.class);
+ assertNotNull(cm);
+
+ cm = BeanContext.DEFAULT.getClassMeta(Class[].class);
+ assertNotNull(cm);
+ }
+
+ //====================================================================================================
+ // testBlanks
+ //====================================================================================================
+ @Test
+ public void testBlanks() throws Exception {
+ BeanContext bc = BeanContext.DEFAULT;
+
+ // Blanks get interpreted as the default value for primitives and null for boxed objects.
+ assertEquals(0, (int)bc.convertToType("", int.class));
+ assertNull(bc.convertToType("", Integer.class));
+
+ // Booleans are handled different since 'new Boolean("")' is valid and resolves to false
+ // while 'new Integer("")' produces an exception.
+ assertEquals(false, (boolean)bc.convertToType("", boolean.class));
+ assertEquals(false, bc.convertToType("", Boolean.class));
+ }
+}
\ No newline at end of file
[30/44] incubator-juneau git commit: Rename CT_* testcases.
Posted by ja...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/CT_BeanMap.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/CT_BeanMap.java b/org.apache.juneau/src/test/java/org/apache/juneau/CT_BeanMap.java
deleted file mode 100755
index 838e05b..0000000
--- a/org.apache.juneau/src/test/java/org/apache/juneau/CT_BeanMap.java
+++ /dev/null
@@ -1,1920 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau;
-
-import static org.apache.juneau.BeanContext.*;
-import static org.apache.juneau.TestUtils.*;
-import static org.junit.Assert.*;
-
-import java.util.*;
-
-import org.apache.juneau.annotation.*;
-import org.apache.juneau.html.*;
-import org.apache.juneau.json.*;
-import org.apache.juneau.parser.*;
-import org.apache.juneau.transforms.*;
-import org.apache.juneau.urlencoding.*;
-import org.apache.juneau.utils.*;
-import org.apache.juneau.xml.*;
-import org.junit.*;
-
-@SuppressWarnings({"unchecked","rawtypes","hiding","serial","unused"})
-public class CT_BeanMap {
-
- JsonSerializer serializer = JsonSerializer.DEFAULT_LAX.clone().setClassLoader(CT_BeanMap.class.getClassLoader());
-
- //====================================================================================================
- // Primitive field properties
- //====================================================================================================
- @Test
- public void testPrimitiveFieldProperties() {
- A t = new A();
- Map m = BeanContext.DEFAULT.forBean(t);
-
- // Make sure setting primitive values to null causes them to get default values.
- m.put("i1", null);
- m.put("s1", null);
- m.put("l1", null);
- m.put("d1", null);
- m.put("f1", null);
- m.put("b1", null);
- assertEquals(new Integer(0), m.get("i1"));
- assertEquals(new Short((short)0), m.get("s1"));
- assertEquals(new Long(0l), m.get("l1"));
- assertEquals(new Double(0d), m.get("d1"));
- assertEquals(new Float(0f), m.get("f1"));
- assertEquals(new Boolean(false), m.get("b1"));
-
- // Make sure setting non-primitive values to null causes them to set to null.
- m.put("i2", null);
- m.put("s2", null);
- m.put("l2", null);
- m.put("d2", null);
- m.put("f2", null);
- m.put("b2", null);
- assertNull(m.get("i2"));
- assertNull(m.get("s2"));
- assertNull(m.get("l2"));
- assertNull(m.get("d2"));
- assertNull(m.get("f2"));
- assertNull(m.get("b2"));
-
- // Make sure setting them all to an integer is kosher.
- m.put("i1", 1);
- m.put("s1", 1);
- m.put("l1", 1);
- m.put("d1", 1);
- m.put("f1", 1);
- m.put("i2", 1);
- m.put("s2", 1);
- m.put("l2", 1);
- m.put("d2", 1);
- m.put("f2", 1);
- assertEquals(new Integer(1), m.get("i1"));
- assertEquals(new Integer(1), m.get("i2"));
- assertEquals(new Short((short)1), m.get("s1"));
- assertEquals(new Short((short)1), m.get("s2"));
- assertEquals(new Long(1), m.get("l1"));
- assertEquals(new Long(1), m.get("l2"));
- assertEquals(new Double(1), m.get("d1"));
- assertEquals(new Double(1), m.get("d2"));
- assertEquals(new Float(1), m.get("f1"));
- assertEquals(new Float(1), m.get("f2"));
-
- m.put("b1", true);
- m.put("b2", new Boolean(true));
- assertEquals(new Boolean(true), m.get("b1"));
- assertEquals(new Boolean(true), m.get("b2"));
- }
-
- public static class A {
- public int i1;
- public Integer i2;
- public short s1;
- public Short s2;
- public long l1;
- public Long l2;
- public double d1;
- public Double d2;
- public float f1;
- public Float f2;
- public boolean b1;
- public Boolean b2;
- }
-
- //====================================================================================================
- // Primitive method properties
- //====================================================================================================
- @Test
- public void testPrimitiveMethodProperties() {
- B t = new B();
- Map m = BeanContext.DEFAULT.forBean(t);
-
- // Make sure setting primitive values to null causes them to get default values.
- m.put("i1", null);
- m.put("s1", null);
- m.put("l1", null);
- m.put("d1", null);
- m.put("f1", null);
- m.put("b1", null);
- assertEquals(new Integer(0), m.get("i1"));
- assertEquals(new Short((short)0), m.get("s1"));
- assertEquals(new Long(0l), m.get("l1"));
- assertEquals(new Double(0d), m.get("d1"));
- assertEquals(new Float(0f), m.get("f1"));
- assertEquals(new Boolean(false), m.get("b1"));
-
- // Make sure setting non-primitive values to null causes them to set to null.
- m.put("i2", null);
- m.put("s2", null);
- m.put("l2", null);
- m.put("d2", null);
- m.put("f2", null);
- m.put("b2", null);
- assertNull(m.get("i2"));
- assertNull(m.get("s2"));
- assertNull(m.get("l2"));
- assertNull(m.get("d2"));
- assertNull(m.get("f2"));
- assertNull(m.get("b2"));
-
- // Make sure setting them all to an integer is kosher.
- m.put("i1", 1);
- m.put("s1", 1);
- m.put("l1", 1);
- m.put("d1", 1);
- m.put("f1", 1);
- m.put("i2", 1);
- m.put("s2", 1);
- m.put("l2", 1);
- m.put("d2", 1);
- m.put("f2", 1);
- assertEquals(new Integer(1), m.get("i1"));
- assertEquals(new Integer(1), m.get("i2"));
- assertEquals(new Short((short)1), m.get("s1"));
- assertEquals(new Short((short)1), m.get("s2"));
- assertEquals(new Long(1), m.get("l1"));
- assertEquals(new Long(1), m.get("l2"));
- assertEquals(new Double(1), m.get("d1"));
- assertEquals(new Double(1), m.get("d2"));
- assertEquals(new Float(1), m.get("f1"));
- assertEquals(new Float(1), m.get("f2"));
-
- m.put("b1", true);
- m.put("b2", true);
- assertEquals(new Boolean(true), m.get("b1"));
- assertEquals(new Boolean(true), m.get("b2"));
- }
-
- public static class B {
- private int i1;
- private Integer i2;
- private short s1;
- private Short s2;
- private long l1;
- private Long l2;
- private double d1;
- private Double d2;
- private float f1;
- private Float f2;
- private boolean b1;
- private Boolean b2;
-
- public int getI1() {return i1;}
- public void setI1(int i1) {this.i1 = i1;}
- public Integer getI2() {return i2;}
- public void setI2(Integer i2) {this.i2 = i2;}
-
- public short getS1() {return s1;}
- public void setS1(short s1) {this.s1 = s1;}
- public Short getS2() {return s2;}
- public void setS2(Short s2) {this.s2 = s2;}
-
- public long getL1() {return l1;}
- public void setL1(long l1) {this.l1 = l1;}
- public Long getL2() {return l2;}
- public void setL2(Long l2) {this.l2 = l2;}
-
- public double getD1() {return d1;}
- public void setD1(double d1) {this.d1 = d1;}
- public Double getD2() {return d2;}
- public void setD2(Double d2) {this.d2 = d2;}
-
- public float getF1() {return f1;}
- public void setF1(float f1) {this.f1 = f1;}
- public Float getF2() {return f2;}
- public void setF2(Float f2) {this.f2 = f2;}
-
- public boolean getB1() {return b1;}
- public void setB1(boolean b1) {this.b1 = b1;}
- public Boolean getB2() {return b2;}
- public void setB2(Boolean b2) {this.b2 = b2;}
- }
-
- //====================================================================================================
- // testCollectionFieldProperties
- //====================================================================================================
- @Test
- public void testCollectionFieldProperties() throws Exception {
- C t = new C();
- Map m = BeanContext.DEFAULT.forBean(t);
-
- // Non-initialized list fields.
- m.put("l1", new ObjectList("[1,2,3]"));
- m.put("al1", new ObjectList("[1,2,3]"));
- m.put("ll1", new ObjectList("[1,2,3]"));
- m.put("c1", new ObjectList("[1,2,3]"));
- m.put("jl1", new ObjectList("[1,2,3]"));
-
- // al1 should be initialized with an ArrayList, since it's not a superclass of ObjectList.
- assertEquals(ArrayList.class.getName(), m.get("al1").getClass().getName());
-
- // The rest are proper superclasses of ObjectList.
- assertEquals(ObjectList.class.getName(), m.get("l1").getClass().getName());
- assertEquals(LinkedList.class.getName(), m.get("ll1").getClass().getName());
- assertEquals(ObjectList.class.getName(), m.get("c1").getClass().getName());
- assertEquals(ObjectList.class.getName(), m.get("jl1").getClass().getName());
-
- // Non-initialized map fields.
- m.put("m1", new ObjectMap("{foo:'bar'}"));
- m.put("hm1", new ObjectMap("{foo:'bar'}"));
- m.put("jm1", new ObjectMap("{foo:'bar'}"));
- m.put("tm1", new ObjectMap("{foo:'bar'}"));
-
- // tm1 should be initialized with TreeMap, since it's not a superclass of ObjectMap.
- assertEquals(TreeMap.class.getName(), m.get("tm1").getClass().getName());
-
- // The rest are propert superclasses of ObjectMap
- assertEquals(ObjectMap.class.getName(), m.get("m1").getClass().getName());
- assertEquals(HashMap.class.getName(), m.get("hm1").getClass().getName());
- assertEquals(ObjectMap.class.getName(), m.get("jm1").getClass().getName());
-
- // Initialized fields should reuse existing field value.
- m.put("l2", new ObjectList("[1,2,3]"));
- m.put("al2", new ObjectList("[1,2,3]"));
- m.put("ll2", new ObjectList("[1,2,3]"));
- m.put("c2", new ObjectList("[1,2,3]"));
- m.put("m2", new ObjectMap("{foo:'bar'}"));
- m.put("hm2", new ObjectMap("{foo:'bar'}"));
- m.put("tm2", new ObjectMap("{foo:'bar'}"));
- m.put("jm2", new ObjectMap("{foo:'bar'}"));
- m.put("jl2", new ObjectList("[1,2,3]"));
-
- assertEquals(ArrayList.class.getName(), m.get("l2").getClass().getName());
- assertEquals(ArrayList.class.getName(), m.get("al2").getClass().getName());
- assertEquals(LinkedList.class.getName(), m.get("ll2").getClass().getName());
- assertEquals(ArrayList.class.getName(), m.get("c2").getClass().getName());
- assertEquals(HashMap.class.getName(), m.get("m2").getClass().getName());
- assertEquals(HashMap.class.getName(), m.get("hm2").getClass().getName());
- assertEquals(TreeMap.class.getName(), m.get("tm2").getClass().getName());
- assertEquals(ObjectMap.class.getName(), m.get("jm2").getClass().getName());
- assertEquals(ObjectList.class.getName(), m.get("jl2").getClass().getName());
- }
-
- public static class C {
- public List l1;
- public ArrayList al1;
- public LinkedList ll1;
- public Collection c1;
- public Map m1;
- public HashMap hm1;
- public ObjectMap jm1;
- public TreeMap tm1;
- public ObjectList jl1;
- public List l2 = new ArrayList();
- public ArrayList al2 = new ArrayList();
- public LinkedList ll2 = new LinkedList();
- public Collection c2 = new ArrayList();
- public Map m2 = new HashMap();
- public HashMap hm2 = new HashMap();
- public TreeMap tm2 = new TreeMap();
- public ObjectMap jm2 = new ObjectMap();
- public ObjectList jl2 = new ObjectList();
- }
-
- //====================================================================================================
- // testCollectionMethodProperties
- //====================================================================================================
- @Test
- public void testCollectionMethodProperties() throws Exception {
- D t = new D();
- Map m = BeanContext.DEFAULT.forBean(t);
-
- // Non-initialized list fields.
- m.put("l1", new ObjectList("[1,2,3]"));
- m.put("al1", new ObjectList("[1,2,3]"));
- m.put("ll1", new ObjectList("[1,2,3]"));
- m.put("c1", new ObjectList("[1,2,3]"));
- m.put("jl1", new ObjectList("[1,2,3]"));
-
- // al1 should be initialized with an ArrayList, since it's not a superclass of ObjectList.
- assertEquals(ArrayList.class.getName(), m.get("al1").getClass().getName());
-
- // The rest are proper superclasses of ObjectList.
- assertEquals(ObjectList.class.getName(), m.get("l1").getClass().getName());
- assertEquals(LinkedList.class.getName(), m.get("ll1").getClass().getName());
- assertEquals(ObjectList.class.getName(), m.get("c1").getClass().getName());
- assertEquals(ObjectList.class.getName(), m.get("jl1").getClass().getName());
-
- // Non-initialized map fields.
- m.put("m1", new ObjectMap("{foo:'bar'}"));
- m.put("hm1", new ObjectMap("{foo:'bar'}"));
- m.put("jm1", new ObjectMap("{foo:'bar'}"));
- m.put("tm1", new ObjectMap("{foo:'bar'}"));
-
- // tm1 should be initialized with TreeMap, since it's not a superclass of ObjectMap.
- assertEquals(TreeMap.class.getName(), m.get("tm1").getClass().getName());
-
- // The rest are propert superclasses of ObjectMap
- assertEquals(ObjectMap.class.getName(), m.get("m1").getClass().getName());
- assertEquals(HashMap.class.getName(), m.get("hm1").getClass().getName());
- assertEquals(ObjectMap.class.getName(), m.get("jm1").getClass().getName());
-
- // Initialized fields should reuse existing field value.
- m.put("l2", new ObjectList("[1,2,3]"));
- m.put("al2", new ObjectList("[1,2,3]"));
- m.put("ll2", new ObjectList("[1,2,3]"));
- m.put("c2", new ObjectList("[1,2,3]"));
- m.put("m2", new ObjectMap("{foo:'bar'}"));
- m.put("hm2", new ObjectMap("{foo:'bar'}"));
- m.put("tm2", new ObjectMap("{foo:'bar'}"));
- m.put("jm2", new ObjectMap("{foo:'bar'}"));
- m.put("jl2", new ObjectList("[1,2,3]"));
-
- assertEquals(ArrayList.class.getName(), m.get("l2").getClass().getName());
- assertEquals(ArrayList.class.getName(), m.get("al2").getClass().getName());
- assertEquals(LinkedList.class.getName(), m.get("ll2").getClass().getName());
- assertEquals(ArrayList.class.getName(), m.get("c2").getClass().getName());
- assertEquals(HashMap.class.getName(), m.get("m2").getClass().getName());
- assertEquals(HashMap.class.getName(), m.get("hm2").getClass().getName());
- assertEquals(TreeMap.class.getName(), m.get("tm2").getClass().getName());
- assertEquals(ObjectMap.class.getName(), m.get("jm2").getClass().getName());
- assertEquals(ObjectList.class.getName(), m.get("jl2").getClass().getName());
- }
-
- public static class D {
- private List l1;
- public List getL1() {return l1;}
- public void setL1(List l1) {this.l1 = l1;}
-
- private ArrayList al1;
- public ArrayList getAl1() {return al1;}
- public void setAl1(ArrayList al1) {this.al1 = al1;}
-
- private LinkedList ll1;
- public LinkedList getLl1() {return ll1;}
- public void setLl1(LinkedList ll1) {this.ll1 = ll1;}
-
- private Collection c1;
- public Collection getC1() {return c1;}
- public void setC1(Collection c1) {this.c1 = c1;}
-
- private Map m1;
- public Map getM1() {return m1;}
- public void setM1(Map m1) {this.m1 = m1;}
-
- private HashMap hm1;
- public HashMap getHm1() {return hm1;}
- public void setHm1(HashMap hm1) {this.hm1 = hm1;}
-
- private ObjectMap jm1;
- public ObjectMap getJm1() {return jm1;}
- public void setJm1(ObjectMap jm1) {this.jm1 = jm1;}
-
- private TreeMap tm1;
- public TreeMap getTm1() {return tm1;}
- public void setTm1(TreeMap tm1) {this.tm1 = tm1;}
-
- private ObjectList jl1;
- public ObjectList getJl1() {return jl1;}
- public void setJl1(ObjectList jl1) {this.jl1 = jl1;}
-
- private List l2 = new ArrayList();
- public List getL2() {return l2;}
- public void setL2(List l2) {this.l2 = l2;}
-
- private ArrayList al2 = new ArrayList();
- public ArrayList getAl2() {return al2;}
- public void setAl2(ArrayList al2) {this.al2 = al2;}
-
- private LinkedList ll2 = new LinkedList();
- public LinkedList getLl2() {return ll2;}
- public void setLl2(LinkedList ll2) {this.ll2 = ll2;}
-
- private Collection c2 = new ArrayList();
- public Collection getC2() {return c2;}
- public void setC2(Collection c2) {this.c2 = c2;}
-
- private Map m2 = new HashMap();
- public Map getM2() {return m2;}
- public void setM2(Map m2) {this.m2 = m2;}
-
- private HashMap hm2 = new HashMap();
- public HashMap getHm2() {return hm2;}
- public void setHm2(HashMap hm2) {this.hm2 = hm2;}
-
- private TreeMap tm2 = new TreeMap();
- public TreeMap getTm2() {return tm2;}
- public void setTm2(TreeMap tm2) {this.tm2 = tm2;}
-
- private ObjectMap jm2 = new ObjectMap();
- public ObjectMap getJm2() {return jm2;}
- public void setJm2(ObjectMap jm2) {this.jm2 = jm2;}
-
- private ObjectList jl2 = new ObjectList();
- public ObjectList getJl2() {return jl2;}
- public void setJl2(ObjectList jl2) {this.jl2 = jl2;}
- }
-
- //====================================================================================================
- // testArrayProperties
- //====================================================================================================
- @Test
- public void testArrayProperties() throws Exception {
- D1 t = new D1();
- BeanContext bc = getBeanContext();
- Map m = bc.forBean(t);
- m.put("b", new ObjectMap("{s:'foo'}"));
- assertNotNull(t.b);
- assertEquals("foo", t.b.s);
-
- Map m2 = new TreeMap();
- m2.put("s", "bar");
- m.put("b", m2);
- assertNotNull(t.b);
- assertEquals("bar", t.b.s);
-
- m.put("b", new D2());
- assertEquals("default", t.b.s);
-
- JsonParser p = new JsonParser().setClassLoader(CT_BeanMap.class.getClassLoader());
- m.put("lb1", new ObjectList("[{_class:'"+D2.class.getName()+"',s:'foobar'}]", p));
- assertEquals(ObjectList.class.getName(), t.lb1.getClass().getName());
- assertEquals(D2.class.getName(), t.lb1.get(0).getClass().getName());
- assertEquals("foobar", (t.lb1.get(0)).s);
-
- m.put("lb2", new ObjectList("[{_class:'"+D2.class.getName()+"',s:'foobar'}]", p));
- assertEquals(ArrayList.class.getName(), t.lb2.getClass().getName());
- assertEquals(D2.class.getName(), t.lb2.get(0).getClass().getName());
- assertEquals("foobar", (t.lb2.get(0)).s);
-
- m.put("ab1", new ObjectList("[{_class:'"+D2.class.getName()+"',s:'foobar'}]", p));
- assertEquals("[L"+D2.class.getName()+";", t.ab1.getClass().getName());
- assertEquals(D2.class.getName(), t.ab1[0].getClass().getName());
- assertEquals("foobar", t.ab1[0].s);
-
- m.put("ab2", new ObjectList("[{_class:'"+D2.class.getName()+"',s:'foobar'}]", p));
- assertEquals("[L"+D2.class.getName()+";", t.ab2.getClass().getName());
- assertEquals(D2.class.getName(), t.ab2[0].getClass().getName());
- assertEquals("foobar", t.ab2[0].s);
- }
-
- public static class D1 {
- public D2 b;
- public List<D2> lb1;
- public List<D2> lb2 = new ArrayList<D2>();
- public D2[] ab1;
- public D2[] ab2 = new D2[0];
- }
-
- public static class D2 {
- public String s = "default";
- }
-
- //====================================================================================================
- // testArrayPropertiesInObjectList
- //====================================================================================================
- @Test
- public void testArrayPropertiesInObjectList() throws Exception {
- E t = new E();
- Map m = BeanContext.DEFAULT.forBean(t);
- m.put("s", new ObjectList("['foo']"));
- m.put("s2", new ObjectList("[['foo']]"));
- m.put("i", new ObjectList("[1,2,3]"));
- m.put("i2", new ObjectList("[[1,2,3],[4,5,6]]"));
- assertEquals("{s:['foo'],s2:[['foo']],i:[1,2,3],i2:[[1,2,3],[4,5,6]]}", JsonSerializer.DEFAULT_LAX.serialize(t));
- m.put("i", new ObjectList("[null,null,null]"));
- m.put("i2", new ObjectList("[[null,null,null],[null,null,null]]"));
- assertEquals("{s:['foo'],s2:[['foo']],i:[0,0,0],i2:[[0,0,0],[0,0,0]]}", JsonSerializer.DEFAULT_LAX.serialize(t));
- }
-
- public static class E {
- public String[] s;
- public String[][] s2;
- public int[] i;
- public int[][] i2;
- }
-
- //====================================================================================================
- // BeanMap.invokeMethod()
- //====================================================================================================
- @Test
- public void testInvokeMethod() throws Exception {
- F t5 = new F();
- ReaderParser p = JsonParser.DEFAULT;
- BeanMap m = BeanContext.DEFAULT.forBean(t5);
- new PojoIntrospector(t5, p).invokeMethod("doSetAProperty(java.lang.String)", "['baz']");
- assertEquals("baz", m.get("prop"));
- }
-
- public static class F {
- public String prop;
-
- public boolean doSetAProperty(String prop) {
- this.prop = prop;
- return true;
- }
- }
-
- //====================================================================================================
- // @BeanProperty tests
- //====================================================================================================
- @Test
- public void testBeanPropertyAnnotation() throws Exception {
- G1 t6 = new G1();
- BeanMap m = BeanContext.DEFAULT.forBean(t6);
-
- try {
- m.put("l1", "[{a:'a',i:1}]");
- throw new Exception("Expected exception on unsettable field.");
- } catch (Exception e) {
- // Good.
- }
-
- m.put("l2", "[{a:'a',i:1}]");
- assertEquals("java.util.LinkedList", m.get("l2").getClass().getName());
- assertEquals("org.apache.juneau.CT_BeanMap$G", ((List)m.get("l2")).get(0).getClass().getName());
-
- m.put("l3", "[{a:'a',i:1}]");
- assertEquals("org.apache.juneau.ObjectList", m.get("l3").getClass().getName());
- assertEquals("org.apache.juneau.CT_BeanMap$G", ((List)m.get("l3")).get(0).getClass().getName());
-
- m.put("l4", "[{a:'a',i:1}]");
- assertEquals("java.util.LinkedList", m.get("l4").getClass().getName());
- assertEquals("org.apache.juneau.CT_BeanMap$G", ((List)m.get("l4")).get(0).getClass().getName());
-
- try {
- m.put("m1", "[{a:'a',i:1}]");
- throw new Exception("Expected exception on unsettable field.");
- } catch (Exception e) {
- // Good.
- }
-
- m.put("m2", "[{a:'a',i:1}]");
- assertEquals("java.util.LinkedList", m.get("m2").getClass().getName());
- assertEquals("org.apache.juneau.CT_BeanMap$G", ((List)m.get("m2")).get(0).getClass().getName());
-
- m.put("m3", "[{a:'a',i:1}]");
- assertEquals("org.apache.juneau.ObjectList", m.get("m3").getClass().getName());
- assertEquals("org.apache.juneau.CT_BeanMap$G", ((List)m.get("m3")).get(0).getClass().getName());
-
- m.put("m4", "[{a:'a',i:1}]");
- assertEquals("java.util.LinkedList", m.get("m4").getClass().getName());
- assertEquals("org.apache.juneau.CT_BeanMap$G", ((List)m.get("m4")).get(0).getClass().getName());
- }
-
- public static class G {
- public String a;
- public int i;
- }
-
- public static class G1 {
-
- public List<G> l1;
-
- public List<G> l2 = new LinkedList<G>();
-
- @BeanProperty(type=List.class,params={G.class})
- public List<G> l3;
-
- @BeanProperty(type=LinkedList.class,params={G.class})
- public List<G> l4;
-
- private List<G> m1;
- public List<G> getM1() { return m1; }
- public void setM1(List<G> m1) { this.m1 = m1; }
-
- private List<G> m2 = new LinkedList<G>();
- public List<G> getM2() { return m2; }
- public void setM2(List<G> m2) { this.m2 = m2; }
-
- private List<G> m3;
- @BeanProperty(type=List.class,params={G.class})
- public List<G> getM3() { return m3; }
- public void setM3(List<G> m3) { this.m3 = m3; }
-
- private List<G> m4;
- @BeanProperty(type=LinkedList.class,params={G.class})
- public List<G> getM4() { return m4; }
- public void setM4(List<G> m4) { this.m4 = m4; }
- }
-
- //====================================================================================================
- // Enum tests
- //====================================================================================================
- @Test
- public void testEnum() throws Exception {
- BeanContext bc = getBeanContext();
-
- // Initialize existing bean.
- H t7 = new H();
- BeanMap m = bc.forBean(t7);
- m.put("enum1", "ONE");
- m.put("enum2", "TWO");
- assertEquals("{enum1:'ONE',enum2:'TWO'}", serializer.serialize(t7));
- assertEquals(HEnum.ONE, t7.enum1);
- assertEquals(HEnum.TWO, t7.getEnum2());
-
- // Use BeanContext to create bean instance.
- m = BeanContext.DEFAULT.newBeanMap(H.class).load("{enum1:'TWO',enum2:'THREE'}");
- assertEquals("{enum1:'TWO',enum2:'THREE'}", serializer.serialize(m.getBean()));
- t7 = (H)m.getBean();
- assertEquals(HEnum.TWO, t7.enum1);
- assertEquals(HEnum.THREE, t7.getEnum2());
-
- // Create instance directly from JSON.
- JsonParser p = new JsonParser().setClassLoader(CT_BeanMap.class.getClassLoader());
- t7 = (H)p.parse("{_class:'"+H.class.getName()+"',enum1:'THREE',enum2:'ONE'}", Object.class);
- assertEquals("{enum1:'THREE',enum2:'ONE'}", serializer.serialize(t7));
- assertEquals(HEnum.THREE, t7.enum1);
- assertEquals(HEnum.ONE, t7.getEnum2());
- }
-
- public static enum HEnum {
- ONE, TWO, THREE
- }
-
- public static class H {
-
- public HEnum enum1;
-
- private HEnum enum2;
-
- public HEnum getEnum2() {
- return enum2;
- }
-
- public void setEnum2(HEnum enum2) {
- this.enum2 = enum2;
- }
- }
-
- //====================================================================================================
- // Automatic detection of generic types
- //====================================================================================================
- @Test
- public void testAutomaticDetectionOfGenericTypes() throws Exception {
- BeanMap bm = BeanContext.DEFAULT.newBeanMap(I.class);
- assertEquals(String.class, bm.getProperty("p1").getMeta().getClassMeta().getElementType().getInnerClass());
- assertEquals(Integer.class, bm.getProperty("p2").getMeta().getClassMeta().getElementType().getInnerClass());
- assertEquals(Object.class, bm.getProperty("p3").getMeta().getClassMeta().getElementType().getInnerClass());
- assertEquals(String.class, bm.getProperty("p4").getMeta().getClassMeta().getKeyType().getInnerClass());
- assertEquals(Integer.class, bm.getProperty("p4").getMeta().getClassMeta().getValueType().getInnerClass());
- assertEquals(String.class, bm.getProperty("p5").getMeta().getClassMeta().getKeyType().getInnerClass());
- assertEquals(Integer.class, bm.getProperty("p5").getMeta().getClassMeta().getValueType().getInnerClass());
- assertEquals(Object.class, bm.getProperty("p6").getMeta().getClassMeta().getKeyType().getInnerClass());
- assertEquals(Object.class, bm.getProperty("p6").getMeta().getClassMeta().getValueType().getInnerClass());
- }
-
- public static class I {
-
- public List<String> p1;
-
- public List<Integer> getP2() {
- return null;
- }
-
- public List<? extends Integer> p3;
-
- public Map<String,Integer> p4;
-
- public Map<String,Integer> getP5() {
- return null;
- }
-
- public Map<String,? extends Integer> p6;
- }
-
- //====================================================================================================
- // Overriding detection of generic types.
- //====================================================================================================
- @Test
- public void testOverridingDetectionOfGenericTypes() throws Exception {
- BeanMap bm = BeanContext.DEFAULT.newBeanMap(J.class);
- assertEquals(Float.class, bm.getProperty("p1").getMeta().getClassMeta().getElementType().getInnerClass());
- assertEquals(Float.class, bm.getProperty("p2").getMeta().getClassMeta().getElementType().getInnerClass());
- assertEquals(Float.class, bm.getProperty("p3").getMeta().getClassMeta().getElementType().getInnerClass());
- assertEquals(Object.class, bm.getProperty("p4").getMeta().getClassMeta().getKeyType().getInnerClass());
- assertEquals(Float.class, bm.getProperty("p4").getMeta().getClassMeta().getValueType().getInnerClass());
- assertEquals(Object.class, bm.getProperty("p5").getMeta().getClassMeta().getKeyType().getInnerClass());
- assertEquals(Float.class, bm.getProperty("p5").getMeta().getClassMeta().getValueType().getInnerClass());
- assertEquals(String.class, bm.getProperty("p6").getMeta().getClassMeta().getKeyType().getInnerClass());
- assertEquals(Float.class, bm.getProperty("p6").getMeta().getClassMeta().getValueType().getInnerClass());
- }
-
- public static class J {
-
- @BeanProperty(params={Float.class})
- public List<String> p1;
-
- @BeanProperty(params={Float.class})
- public List<Integer> getP2() {
- return null;
- }
-
- @BeanProperty(params={Float.class})
- public List<? extends Integer> p3;
-
- @BeanProperty(params={Object.class, Float.class})
- public Map<String,Integer> p4;
-
- @BeanProperty(params={Object.class, Float.class})
- public Map<String,Integer> getP5() {
- return null;
- }
-
- @BeanProperty(params={String.class, Float.class})
- public Map<String,? extends Integer> p6;
- }
-
- //====================================================================================================
- // Overriding detection of generic types.
- //====================================================================================================
- @Test
- public void testOverridingDetectionOfGenericTypes2() throws Exception {
- BeanMap bm = BeanContext.DEFAULT.newBeanMap(K.class);
- assertEquals(Float.class, bm.getProperty("p1").getMeta().getClassMeta().getElementType().getInnerClass());
- assertEquals(Float.class, bm.getProperty("p2").getMeta().getClassMeta().getElementType().getInnerClass());
- assertEquals(Float.class, bm.getProperty("p3").getMeta().getClassMeta().getElementType().getInnerClass());
- assertEquals(String.class, bm.getProperty("p4").getMeta().getClassMeta().getKeyType().getInnerClass());
- assertEquals(Float.class, bm.getProperty("p4").getMeta().getClassMeta().getValueType().getInnerClass());
- assertEquals(String.class, bm.getProperty("p5").getMeta().getClassMeta().getKeyType().getInnerClass());
- assertEquals(Float.class, bm.getProperty("p5").getMeta().getClassMeta().getValueType().getInnerClass());
- assertEquals(String.class, bm.getProperty("p6").getMeta().getClassMeta().getKeyType().getInnerClass());
- assertEquals(Float.class, bm.getProperty("p6").getMeta().getClassMeta().getValueType().getInnerClass());
- }
-
- public static class K {
-
- @BeanProperty(params=Float.class)
- public List<String> p1;
-
- @BeanProperty(params=Float.class)
- public List<Integer> getP2() {
- return null;
- }
-
- @BeanProperty(params=Float.class)
- public List<? extends Integer> p3;
-
- @BeanProperty(params={String.class,Float.class})
- public Map<String,Integer> p4;
-
- @BeanProperty(params={String.class,Float.class})
- public Map<String,Integer> getP5() {
- return null;
- }
-
- @BeanProperty(params={String.class,Float.class})
- public Map<String,? extends Integer> p6;
- }
-
- //====================================================================================================
- // List<E> subclass properties
- //====================================================================================================
- @Test
- public void testGenericListSubclass() throws Exception {
- BeanMap<L> bm = BeanContext.DEFAULT.newBeanMap(L.class);
- bm.put("list", "[{name:'1',value:'1'},{name:'2',value:'2'}]");
- L b = bm.getBean();
- assertEquals("1", b.list.get(0).name);
- }
-
- public static class L {
- public L1 list;
- }
-
- public static class L1 extends LinkedList<L2> {
- }
-
- public static class L2 {
- public String name, value;
- public L2(){}
- public L2(String name, String value) {
- this.name = name;
- this.value = value;
- }
- }
-
- //====================================================================================================
- // Generic fields.
- //====================================================================================================
- @Test
- public void testGenericFields() throws Exception {
- BeanContext bc = BeanContext.DEFAULT;
-
- M2 t1 = new M2();
- BeanMap<M2> bm = bc.forBean(t1);
- assertEquals(1, bm.get("x"));
-
- M3 t2 = new M3();
- BeanMap<M3> cm = bc.forBean(t2);
- assertEquals(2, cm.get("x"));
-
- M4 t3 = new M4();
- BeanMap<M4> dm = bc.forBean(t3);
- assertEquals(3, dm.get("x"));
-
- M5 t4 = new M5();
- BeanMap<M5> em = bc.forBean(t4);
- assertEquals(4, em.get("x"));
- }
-
- public static class M1<T> {
- public T x;
- }
-
- public static class M2 extends M1<Integer> {
- public M2() {
- this.x = 1;
- }
- }
-
- public static class M3 extends M2 {
- public M3() {
- this.x = 2;
- }
- }
-
- public static class M4<T extends Number> extends M1<T> {
- public M4() {
- this.x = (T)new Integer(3);
- }
- }
-
- public static class M5 extends M4<Integer> {
- public M5() {
- this.x = new Integer(4);
- }
- }
-
- //====================================================================================================
- // Generic methods
- //====================================================================================================
- @Test
- public void testGenericMethods() throws Exception {
- N2 t1 = new N2();
- BeanMap<N2> bm = BeanContext.DEFAULT.forBean(t1);
- assertEquals(1, bm.get("x"));
-
- N3 t2 = new N3();
- BeanMap<N3> cm = BeanContext.DEFAULT.forBean(t2);
- assertEquals(2, cm.get("x"));
-
- N4 t3 = new N4();
- BeanMap<N4> dm = BeanContext.DEFAULT.forBean(t3);
- assertEquals(3, dm.get("x"));
-
- N5 t4 = new N5();
- BeanMap<N5> em = BeanContext.DEFAULT.forBean(t4);
- assertEquals(4, em.get("x"));
- }
-
- public static class N1<T> {
- private T x;
- public void setX(T x) {
- this.x = x;
- }
- public T getX() {
- return x;
- }
- }
-
- public static class N2 extends N1<Integer> {
- public N2() {
- setX(1);
- }
- }
-
- public static class N3 extends N2 {
- public N3() {
- setX(2);
- }
- }
-
- public static class N4<T extends Number> extends N1<T> {
- public N4() {
- setX((T)new Integer(3));
- }
- }
-
- public static class N5 extends N4<Integer> {
- public N5() {
- setX(4);
- }
- }
-
- //====================================================================================================
- // Test ignoreUnknownBeanProperties setting
- //====================================================================================================
- @Test
- public void testIgnoreUnknownBeanPropertiesSetting() throws Exception {
- ReaderParser p = null;
- O t;
-
- // JSON
- String json = "{baz:789,foo:123,bar:456}";
- p = new JsonParser().setProperty(BEAN_ignoreUnknownBeanProperties, true);
- t = p.parse(json, O.class);
- assertEquals(123, t.foo);
-
- try {
- p = JsonParser.DEFAULT;
- t = p.parse(json, O.class);
- fail("Expected exception never occurred");
- } catch (Exception e) {
- // Good.
- }
-
- // XML
- String xml = "<object><baz type='number'>789</baz><foo type='number'>123</foo><bar type='number'>456</bar></object>";
- p = new XmlParser().setProperty(BEAN_ignoreUnknownBeanProperties, true);
- t = p.parse(xml, O.class);
- assertEquals(123, t.foo);
-
- try {
- p = XmlParser.DEFAULT;
- t = p.parse(json, O.class);
- fail("Expected exception never occurred");
- } catch (Exception e) {
- // Good.
- }
-
- // HTML
- String html = "<table type='object'><tr><th><string>key</string></th><th><string>value</string></th></tr><tr><td><string>baz</string></td><td><number>789</number></td></tr><tr><td><string>foo</string></td><td><number>123</number></td></tr><tr><td><string>bar</string></td><td><number>456</number></td></tr></table>";
- p = new HtmlParser().setProperty(BEAN_ignoreUnknownBeanProperties, true);
- t = p.parse(html, O.class);
- assertEquals(123, t.foo);
-
- try {
- p = HtmlParser.DEFAULT;
- t = p.parse(json, O.class);
- fail("Expected exception never occurred");
- } catch (Exception e) {
- // Good.
- }
-
- // UON
- String uon = "(baz=789,foo=123,bar=456)";
- p = new UonParser().setProperty(BEAN_ignoreUnknownBeanProperties, true);
- t = p.parse(uon, O.class);
- assertEquals(123, t.foo);
-
- try {
- p = new UonParser();
- t = p.parse(json, O.class);
- fail("Expected exception never occurred");
- } catch (Exception e) {
- // Good.
- }
-
- // URL-Encoding
- String urlencoding = "baz=789&foo=123&bar=456";
- p = new UrlEncodingParser().setProperty(BEAN_ignoreUnknownBeanProperties, true);
- t = p.parse(urlencoding, O.class);
- assertEquals(123, t.foo);
-
- try {
- p = new UrlEncodingParser();
- t = p.parse(json, O.class);
- fail("Expected exception never occurred");
- } catch (Exception e) {
- // Good.
- }
-
- }
-
- public static class O {
- public int foo;
- }
-
- //====================================================================================================
- // testPropertyNameFactoryDashedLC1
- //====================================================================================================
- @Test
- public void testPropertyNameFactoryDashedLC1() throws Exception {
- BeanContext bc = BeanContext.DEFAULT;
- BeanMap<P1> m = bc.newBeanMap(P1.class).load("{'foo':1,'bar-baz':2,'bing-boo-url':3}");
- assertEquals(1, m.get("foo"));
- assertEquals(2, m.get("bar-baz"));
- assertEquals(3, m.get("bing-boo-url"));
- P1 b = m.getBean();
- assertEquals(1, b.foo);
- assertEquals(2, b.barBaz);
- assertEquals(3, b.bingBooURL);
- m.put("foo", 4);
- m.put("bar-baz", 5);
- m.put("bing-boo-url", 6);
- assertEquals(4, b.foo);
- assertEquals(5, b.barBaz);
- assertEquals(6, b.bingBooURL);
- }
-
- @Bean(propertyNamer=PropertyNamerDashedLC.class)
- public static class P1 {
- public int foo, barBaz, bingBooURL;
- }
-
- //====================================================================================================
- // testPropertyNameFactoryDashedLC2
- //====================================================================================================
- @Test
- public void testPropertyNameFactoryDashedLC2() throws Exception {
- BeanContext bc = BeanContext.DEFAULT_SORTED;
- BeanMap<P2> m = bc.newBeanMap(P2.class).load("{'foo-bar':1,'baz-bing':2}");
- assertEquals(1, m.get("foo-bar"));
- assertEquals(2, m.get("baz-bing"));
- P2 b = m.getBean();
- assertEquals(1, b.getFooBar());
- assertEquals(2, b.getBazBING());
- m.put("foo-bar", 3);
- m.put("baz-bing", 4);
- assertEquals(3, b.getFooBar());
- assertEquals(4, b.getBazBING());
- }
-
- @Bean(propertyNamer=PropertyNamerDashedLC.class)
- public static class P2 {
- private int fooBar, bazBING;
- public int getFooBar() {
- return fooBar;
- }
- public void setFooBar(int fooBar) {
- this.fooBar = fooBar;
- }
- public int getBazBING() {
- return bazBING;
- }
- public void setBazBING(int bazBING) {
- this.bazBING = bazBING;
- }
- }
-
- //====================================================================================================
- // testBeanWithFluentStyleSetters
- //====================================================================================================
- @Test
- public void testBeanWithFluentStyleSetters() throws Exception {
- Q2 t = new Q2();
- BeanMap m = BeanContext.DEFAULT_SORTED.forBean(t);
- m.put("f1", 1);
- m.put("f2", 2);
- m.put("f3", 3);
-
- assertSortedObjectEquals("{f1:1,f2:2,f3:0}", m);
- }
-
- public static class Q1 {}
-
- public static class Q2 extends Q1 {
- private int f1, f2, f3;
-
- public Q1 setF1(int f1) {
- this.f1 = f1;
- return this;
- }
-
- public Q2 setF2(int f2) {
- this.f2 = f2;
- return this;
- }
-
- // Shouldn't be detected as a setter.
- public String setF3(int f3) {
- this.f3 = f3;
- return null;
- }
-
- public int getF1() { return f1; }
- public int getF2() { return f2; }
- public int getF3() { return f3; }
- }
-
- //====================================================================================================
- // testCastWithNormalBean
- //====================================================================================================
- @Test
- public void testCastWithNormalBean() throws Exception {
- BeanContext bc = getBeanContext();
-
- // With _class
- ObjectMap m = new ObjectMap(bc);
- m.put("_class", R2.class.getName());
- m.put("f1", 1);
- m.put("f2", "2");
-
- R2 t = (R2)m.cast();
- assertEquals(1, t.f1);
-
- t = (R2)m.cast(R1.class);
- assertEquals(1, t.f1);
- assertEquals(2, t.f2);
-
- t = (R2)m.cast(bc.getClassMeta(R1.class));
- assertEquals(1, t.f1);
- assertEquals(2, t.f2);
-
- // Without _class
- m = new ObjectMap(bc);
- m.put("f1", 1);
- m.put("f2", "2");
-
- m = (ObjectMap)m.cast();
- assertEquals(1, t.f1);
- assertEquals(2, t.f2);
-
- t = m.cast(R2.class);
- assertEquals(1, t.f1);
- assertEquals(2, t.f2);
-
- t = m.cast(bc.getClassMeta(R2.class));
- assertEquals(1, t.f1);
- assertEquals(2, t.f2);
- }
-
- // Bean with no properties
- public static class R1 {
- public int f1;
- }
-
- public static class R2 extends R1 {
- public int f2;
- }
-
- //====================================================================================================
- // testCastWithNestedBean
- //====================================================================================================
- @Test
- public void testCastWithNestedBean() throws Exception {
- BeanContext bc = getBeanContext();
-
- // With _class
- ObjectMap m = new ObjectMap(bc);
- m.put("_class", S.class.getName());
- m.put("f1", new ObjectMap(bc).append("_class", R1.class.getName()).append("f1", 1));
-
- S t = (S)m.cast();
- assertEquals(1, t.f1.f1);
-
- t = m.cast(S.class);
- assertEquals(1, t.f1.f1);
-
- t = m.cast(bc.getClassMeta(S.class));
- assertEquals(1, t.f1.f1);
-
- // Without _class
- m = new ObjectMap(bc);
- m.put("f1", new ObjectMap(bc).append("_class", R1.class.getName()).append("f1", 1));
-
- m = (ObjectMap)m.cast();
- assertEquals(1, t.f1.f1);
-
- t = m.cast(S.class);
- assertEquals(1, t.f1.f1);
-
- t = m.cast(bc.getClassMeta(S.class));
- assertEquals(1, t.f1.f1);
- }
-
- public static class S {
- public R1 f1;
- }
-
- //====================================================================================================
- // testCastToAnotherMapType
- //====================================================================================================
- @Test
- public void testCastToAnotherMapType() throws Exception {
- BeanContext bc = BeanContext.DEFAULT;
- Map m2;
-
- // With _class
- ObjectMap m = new ObjectMap();
- m.put("_class", TreeMap.class.getName());
- m.put("1", "ONE");
-
- m2 = (Map)m.cast();
- assertTrue(m2 instanceof TreeMap);
- assertEquals("ONE", m2.get("1"));
-
- m2 = m.cast(Map.class);
- assertTrue(m2 instanceof TreeMap);
- assertEquals("ONE", m2.get("1"));
-
- m2 = m.cast(bc.getClassMeta(TreeMap.class));
- assertTrue(m2 instanceof TreeMap);
- assertEquals("ONE", m2.get("1"));
-
- m2 = (Map)m.cast(bc.getMapClassMeta(TreeMap.class, Integer.class, TEnum.class));
- assertTrue(m2 instanceof TreeMap);
- Map.Entry e = (Map.Entry)m2.entrySet().iterator().next();
- assertTrue(e.getKey() instanceof Integer);
- assertTrue(e.getValue() instanceof TEnum);
- assertEquals(TEnum.ONE, m2.get(1));
-
- m2 = m.cast(bc.getClassMeta(TreeMap.class));
- assertTrue(m2 instanceof TreeMap);
- e = (Map.Entry)m2.entrySet().iterator().next();
- assertTrue(e.getKey() instanceof String);
- assertTrue(e.getValue() instanceof String);
- assertEquals("ONE", m2.get("1"));
-
- m2 = (Map)m.cast(bc.getMapClassMeta(HashMap.class, Integer.class, TEnum.class));
- assertTrue(m2 instanceof HashMap);
- e = (Map.Entry)m2.entrySet().iterator().next();
- assertTrue(e.getKey() instanceof Integer);
- assertTrue(e.getValue() instanceof TEnum);
- assertEquals(TEnum.ONE, m2.get(1));
-
- // Without _class
- m = new ObjectMap();
- m.put("1", "ONE");
-
- m2 = (ObjectMap)m.cast();
- assertTrue(m2 instanceof ObjectMap);
- assertEquals("ONE", m2.get("1"));
-
- m2 = m.cast(Map.class);
- assertTrue(m2 instanceof ObjectMap);
- assertEquals("ONE", m2.get("1"));
-
- m2 = m.cast(bc.getClassMeta(TreeMap.class));
- assertTrue(m2 instanceof TreeMap);
- assertEquals("ONE", m2.get("1"));
-
- m2 = (Map)m.cast(bc.getMapClassMeta(TreeMap.class, Integer.class, TEnum.class));
- assertTrue(m2 instanceof TreeMap);
- e = (Map.Entry)m2.entrySet().iterator().next();
- assertTrue(e.getKey() instanceof Integer);
- assertTrue(e.getValue() instanceof TEnum);
- assertEquals(TEnum.ONE, m2.get(1));
-
- m2 = m.cast(bc.getClassMeta(TreeMap.class));
- assertTrue(m2 instanceof TreeMap);
- e = (Map.Entry)m2.entrySet().iterator().next();
- assertTrue(e.getKey() instanceof String);
- assertTrue(e.getValue() instanceof String);
- assertEquals("ONE", m2.get("1"));
- }
-
- public static enum TEnum {
- ONE, TWO, THREE;
- }
-
- //====================================================================================================
- // testCastToLinkedList
- //====================================================================================================
- @Test
- public void testCastToLinkedList() throws Exception {
- BeanContext bc = BeanContext.DEFAULT;
-
- // With _class
- ObjectMap m = new ObjectMap();
- m.put("_class", LinkedList.class.getName());
- m.put("items", new ObjectList().append("1").append("2"));
-
- List l = (List)m.cast();
- assertTrue(l instanceof LinkedList);
- assertEquals("1", l.get(0));
-
- l = m.cast(List.class);
- assertTrue(l instanceof LinkedList);
- assertEquals("1", l.get(0));
-
- l = m.cast(bc.getClassMeta(List.class));
- assertTrue(l instanceof LinkedList);
- assertEquals("1", l.get(0));
-
- l = m.cast(bc.getClassMeta(ArrayList.class));
- assertTrue(l instanceof ArrayList);
- assertEquals("1", l.get(0));
-
- // Without _class
- m = new ObjectMap();
- m.put("items", new ObjectList().append("1").append("2"));
-
- l = m.cast(List.class);
- assertTrue(l instanceof ObjectList);
- assertEquals("1", l.get(0));
-
- l = m.cast(LinkedList.class);
- assertTrue(l instanceof LinkedList);
- assertEquals("1", l.get(0));
-
- l = m.cast(bc.getClassMeta(List.class));
- assertTrue(l instanceof ObjectList);
- assertEquals("1", l.get(0));
-
- l = m.cast(bc.getClassMeta(ArrayList.class));
- assertTrue(l instanceof ArrayList);
- assertEquals("1", l.get(0));
-
- l = (List)m.cast(bc.getCollectionClassMeta(List.class, Integer.class));
- assertTrue(l instanceof LinkedList);
- assertTrue(l.get(0) instanceof Integer);
- assertEquals(1, l.get(0));
- }
-
- //====================================================================================================
- // testToLinkedListInteger - cast() to LinkedList<Integer>
- //====================================================================================================
- @Test
- public void testToLinkedListInteger() throws Exception {
- BeanContext bc = BeanContext.DEFAULT;
-
- // With _class
- ObjectMap m = new ObjectMap();
- m.put("_class", LinkedList.class.getName() + "<java.lang.Integer>");
- m.put("items", new ObjectList().append("1").append("2"));
-
- List l = (List)m.cast();
- assertTrue(l instanceof LinkedList);
- assertEquals(1, l.get(0));
-
- l = m.cast(List.class);
- assertTrue(l instanceof LinkedList);
- assertEquals(1, l.get(0));
-
- l = m.cast(ArrayList.class);
- assertTrue(l instanceof ArrayList);
- assertEquals(1, l.get(0));
-
- l = m.cast(bc.getClassMeta(List.class));
- assertTrue(l instanceof LinkedList);
- assertEquals(1, l.get(0));
-
- l = m.cast(bc.getClassMeta(ArrayList.class));
- assertTrue(l instanceof ArrayList);
- assertEquals(1, l.get(0));
-
- l = (List)m.cast(bc.getCollectionClassMeta(List.class, String.class));
- assertTrue(l instanceof LinkedList);
- assertTrue(l.get(0) instanceof String);
- assertEquals("1", l.get(0));
-
- // Without _class
- m = new ObjectMap();
- m.put("items", new ObjectList().append("1").append("2"));
-
- l = m.cast(List.class);
- assertTrue(l instanceof ObjectList);
- assertEquals("1", l.get(0));
-
- l = m.cast(ArrayList.class);
- assertTrue(l instanceof ArrayList);
- assertEquals("1", l.get(0));
-
- l = m.cast(bc.getClassMeta(List.class));
- assertTrue(l instanceof ObjectList);
- assertEquals("1", l.get(0));
-
- l = m.cast(bc.getClassMeta(ArrayList.class));
- assertTrue(l instanceof ArrayList);
- assertEquals("1", l.get(0));
-
- l = (List)m.cast(bc.getCollectionClassMeta(List.class, Integer.class));
- assertTrue(l instanceof ObjectList);
- assertTrue(l.get(0) instanceof Integer);
- assertEquals(1, l.get(0));
- }
-
- //====================================================================================================
- // testCastToLinkedListBean - cast() to LinkedList<R1>
- //====================================================================================================
- @Test
- public void testCastToLinkedListBean() throws Exception {
- BeanContext bc = getBeanContext();
-
- // With _class
- ObjectMap m = new ObjectMap(bc);
- m.put("_class", LinkedList.class.getName() + "<"+R1.class.getName()+">");
- m.put("items", new ObjectList(bc).append("{f1:1}"));
-
- List l = (List)m.cast();
- assertTrue(l instanceof LinkedList);
- assertTrue(l.get(0) instanceof R1);
- assertEquals(1, ((R1)l.get(0)).f1);
-
- l = m.cast(List.class);
- assertTrue(l instanceof LinkedList);
- assertTrue(l.get(0) instanceof R1);
- assertEquals(1, ((R1)l.get(0)).f1);
-
- l = m.cast(ArrayList.class);
- assertTrue(l instanceof ArrayList);
- assertTrue(l.get(0) instanceof R1);
- assertEquals(1, ((R1)l.get(0)).f1);
-
- l = m.cast(bc.getClassMeta(List.class));
- assertTrue(l instanceof LinkedList);
- assertTrue(l.get(0) instanceof R1);
- assertEquals(1, ((R1)l.get(0)).f1);
-
- l = m.cast(bc.getClassMeta(ArrayList.class));
- assertTrue(l instanceof ArrayList);
- assertTrue(l.get(0) instanceof R1);
- assertEquals(1, ((R1)l.get(0)).f1);
-
- l = (List)m.cast(bc.getCollectionClassMeta(List.class, HashMap.class));
- assertTrue(l instanceof LinkedList);
- assertTrue(l.get(0) instanceof HashMap);
- assertEquals(1, ((Map)l.get(0)).get("f1"));
-
- // Without _class
- m = new ObjectMap(bc);
- m.put("items", new ObjectList(bc).append("{f1:1}"));
-
- l = m.cast(List.class);
- assertTrue(l instanceof ObjectList);
- assertTrue(l.get(0) instanceof String);
- assertEquals("{f1:1}", l.get(0));
-
- l = m.cast(ArrayList.class);
- assertTrue(l instanceof ArrayList);
- assertTrue(l.get(0) instanceof String);
- assertEquals("{f1:1}", l.get(0));
-
- l = m.cast(bc.getClassMeta(List.class));
- assertTrue(l instanceof ObjectList);
- assertTrue(l.get(0) instanceof String);
- assertEquals("{f1:1}", l.get(0));
-
- l = m.cast(bc.getClassMeta(ArrayList.class));
- assertTrue(l instanceof ArrayList);
- assertTrue(l.get(0) instanceof String);
- assertEquals("{f1:1}", l.get(0));
-
- l = (List)m.cast(bc.getCollectionClassMeta(List.class, R1.class));
- assertTrue(l instanceof LinkedList);
- assertTrue(l.get(0) instanceof R1);
- assertEquals(1, ((R1)l.get(0)).f1);
-
- l = (List)m.cast(bc.getCollectionClassMeta(List.class, HashMap.class));
- assertTrue(l instanceof LinkedList);
- assertTrue(l.get(0) instanceof HashMap);
- assertEquals(1, ((Map)l.get(0)).get("f1"));
-
- l = (List)m.cast(bc.getCollectionClassMeta(List.class, Map.class));
- assertTrue(l instanceof LinkedList);
- assertTrue(l.get(0) instanceof ObjectMap);
- assertEquals(1, ((Map)l.get(0)).get("f1"));
- }
-
- //====================================================================================================
- // testCastToLinkedListUsingTransform - cast() to LinkedList<Calendar> using CalendarTransform
- //====================================================================================================
- @Test
- public void testCastToLinkedListUsingTransform() throws Exception {
- BeanContext bc = ContextFactory.create().addTransforms(CalendarTransform.ISO8601DTZ.class).getBeanContext();
-
- // With _class
- ObjectMap m = new ObjectMap(bc);
- m.put("_class", LinkedList.class.getName() + "<"+Calendar.class.getName()+">");
- m.put("items", new ObjectList().append("2001-07-04T15:30:45Z"));
-
- List l = (List)m.cast();
- assertTrue(l instanceof LinkedList);
- assertEquals(2001, ((Calendar)l.get(0)).get(Calendar.YEAR));
-
- l = m.cast(List.class);
- assertTrue(l instanceof LinkedList);
- assertEquals(2001, ((Calendar)l.get(0)).get(Calendar.YEAR));
-
- l = m.cast(ArrayList.class);
- assertTrue(l instanceof ArrayList);
- assertEquals(2001, ((Calendar)l.get(0)).get(Calendar.YEAR));
-
- m.cast(HashSet.class);
-
- l = m.cast(bc.getClassMeta(List.class));
- assertTrue(l instanceof LinkedList);
- assertEquals(2001, ((Calendar)l.get(0)).get(Calendar.YEAR));
-
- l = m.cast(bc.getClassMeta(ArrayList.class));
- assertTrue(l instanceof ArrayList);
- assertEquals(2001, ((Calendar)l.get(0)).get(Calendar.YEAR));
-
- l = (List)m.cast(bc.getCollectionClassMeta(List.class, String.class));
- assertTrue(l instanceof LinkedList);
- assertTrue(l.get(0) instanceof String);
- assertEquals("2001-07-04T15:30:45Z", l.get(0));
-
- // Without _class
- m = new ObjectMap().setBeanContext(bc);
- m.put("items", new ObjectList().append("2001-07-04T15:30:45Z"));
-
- l = m.cast(List.class);
- assertTrue(l instanceof LinkedList);
-
- l = m.cast(ArrayList.class);
- assertTrue(l instanceof ArrayList);
-
- m.cast(HashSet.class);
-
- l = m.cast(bc.getClassMeta(List.class));
- assertTrue(l instanceof LinkedList);
-
- l = m.cast(bc.getClassMeta(ArrayList.class));
- assertTrue(l instanceof ArrayList);
-
- l = (List)m.cast(bc.getCollectionClassMeta(List.class, Calendar.class));
- assertTrue(l instanceof LinkedList);
- assertTrue(l.get(0) instanceof Calendar);
- assertEquals(2001, ((Calendar)l.get(0)).get(Calendar.YEAR));
- }
-
- //====================================================================================================
- // testCastToStringArray - cast() to String[]
- //====================================================================================================
- @Test
- public void testCastToStringArray() throws Exception {
- BeanContext bc = BeanContext.DEFAULT;
-
- // With _class
- ObjectMap m = new ObjectMap();
- m.put("_class", String[].class.getName());
- m.put("items", new ObjectList().append("1").append("2"));
-
- String[] l = (String[])m.cast();
- assertEquals("1", l[0]);
-
- l = m.cast(String[].class);
- assertEquals("1", l[0]);
-
- StringBuffer[] l2 = m.cast(StringBuffer[].class);
- assertEquals("1", l2[0].toString());
-
- int[] l3 = m.cast(int[].class);
- assertEquals(1, l3[0]);
-
- l = m.cast(bc.getClassMeta(String[].class));
- assertEquals("1", l[0]);
-
- l2 = m.cast(bc.getClassMeta(StringBuffer[].class));
- assertEquals("1", l2[0].toString());
-
- l3 = m.cast(bc.getClassMeta(int[].class));
- assertEquals("1", l2[0].toString());
-
- // Without _class
- m = new ObjectMap();
- m.put("items", new ObjectList().append("1").append("2"));
-
- l = m.cast(String[].class);
- assertEquals("1", l[0]);
-
- l = m.cast(bc.getClassMeta(String[].class));
- assertEquals("1", l[0]);
-
- l2 = m.cast(bc.getClassMeta(StringBuffer[].class));
- assertEquals("1", l[0].toString());
- }
-
- //====================================================================================================
- // testCastToIntArray - cast() to int[]
- //====================================================================================================
- @Test
- public void testCastToIntArray() throws Exception {
- BeanContext bc = BeanContext.DEFAULT;
-
- // With _class
- ObjectMap m = new ObjectMap();
- m.put("_class", int[].class.getName());
- m.put("items", new ObjectList().append("1").append("2"));
-
- int[] l = (int[])m.cast();
- assertEquals(1, l[0]);
-
- l = m.cast(int[].class);
- assertEquals(1, l[0]);
-
- l = m.cast(bc.getClassMeta(int[].class));
- assertEquals(1, l[0]);
-
- long[] l2;
-
- l2 = m.cast(long[].class);
- assertEquals(1, l2[0]);
-
- l2 = m.cast(bc.getClassMeta(long[].class));
- assertEquals(1, l2[0]);
-
- // Without _class
- m = new ObjectMap();
- m.put("items", new ObjectList().append("1").append("2"));
-
- l = m.cast(int[].class);
- assertEquals(1, l[0]);
-
- l = m.cast(bc.getClassMeta(int[].class));
- assertEquals(1, l[0]);
-
- l2 = m.cast(long[].class);
- assertEquals(1, l2[0]);
-
- l2 = m.cast(bc.getClassMeta(long[].class));
- assertEquals(1, l2[0]);
- }
-
- //====================================================================================================
- // testCastToString2dArray - cast() to String[][]
- //====================================================================================================
- @Test
- public void testCastToString2dArray() throws Exception {
- BeanContext bc = BeanContext.DEFAULT;
-
- // With _class
- ObjectMap m = new ObjectMap();
- m.put("_class", String[][].class.getName());
- m.put("items", new ObjectList().append(new ObjectList().append("1")).append(new ObjectList().append("2")));
-
- String[][] l = (String[][])m.cast();
- assertEquals("1", l[0][0]);
- assertEquals("2", l[1][0]);
-
- l = m.cast(String[][].class);
- assertEquals("1", l[0][0]);
-
- l = m.cast(bc.getClassMeta(String[][].class));
- assertEquals("2", l[1][0]);
-
- // Without _class
- m = new ObjectMap();
- m.put("items", new ObjectList().append(new ObjectList().append("1")).append(new ObjectList().append("2")));
-
- l = m.cast(String[][].class);
- assertEquals("1", l[0][0]);
-
- l = m.cast(bc.getClassMeta(String[][].class));
- assertEquals("2", l[1][0]);
- }
-
- //====================================================================================================
- // testCastToInt2dArray - cast() to int[][]
- //====================================================================================================
- @Test
- public void testCastToInt2dArray() throws Exception {
- BeanContext bc = BeanContext.DEFAULT;
-
- // With _class
- ObjectMap m = new ObjectMap();
- m.put("_class", int[][].class.getName());
- m.put("items", new ObjectList().append(new ObjectList().append("1")).append(new ObjectList().append("2")));
-
- int[][] l = (int[][])m.cast();
- assertEquals(1, l[0][0]);
- assertEquals(2, l[1][0]);
-
- l = m.cast(int[][].class);
- assertEquals(1, l[0][0]);
-
- l = m.cast(bc.getClassMeta(int[][].class));
- assertEquals(2, l[1][0]);
-
- // Without _class
- m = new ObjectMap();
- m.put("items", new ObjectList().append(new ObjectList().append("1")).append(new ObjectList().append("2")));
-
- l = m.cast(int[][].class);
- assertEquals(1, l[0][0]);
-
- l = m.cast(bc.getClassMeta(int[][].class));
- assertEquals(2, l[1][0]);
- }
-
- //====================================================================================================
- // testHiddenProperties
- //====================================================================================================
- @Test
- public void testHiddenProperties() throws Exception {
- JsonSerializer s = JsonSerializer.DEFAULT_LAX;
- BeanMeta bm = s.getBeanContext().getBeanMeta(U.class);
- assertNotNull(bm.getPropertyMeta("a"));
- assertNotNull(bm.getPropertyMeta("b"));
- assertNull(bm.getPropertyMeta("c"));
- assertNull(bm.getPropertyMeta("d"));
-
- U t = new U();
- t.a = "a";
- t.b = "b";
- String r = s.serialize(t);
- assertEquals("{a:'a',b:'b'}", r);
-
- // Make sure setters are used if present.
- t = JsonParser.DEFAULT.parse(r, U.class);
- assertEquals("b(setter)", t.b);
- }
-
- public static class U {
- public String a, b;
-
- public String getA() {
- return a;
- }
-
- public void setA(String a) {
- this.a = a;
- }
-
- @BeanIgnore
- public String getB() {
- return b;
- }
-
- public void setB(String b) {
- this.b = b+"(setter)";
- }
-
- @BeanIgnore
- public String c;
-
- @BeanIgnore
- public String getD() {
- return null;
- }
-
- @BeanIgnore
- public void setD(String d) {
- }
- }
-
- //====================================================================================================
- // testBeanPropertyOrder
- //====================================================================================================
- @Test
- public void testBeanPropertyOrder() throws Exception {
- assertObjectEquals("{a1:'1',a2:'2',a3:'3',a4:'4'}", new V2());
- assertObjectEquals("{a3:'3',a4:'4',a5:'5',a6:'6'}", new V3());
- }
-
- public static class V {
- public String a1="1", a2="2";
- }
-
- public static class V2 extends V {
- public String a3="3", a4="4";
- }
-
- @Bean(stopClass=V.class)
- public static class V3 extends V2 {
- public String a5="5", a6="6";
- }
-
- //====================================================================================================
- // testBeanMethodOrder
- //====================================================================================================
- @Test
- public void testBeanMethodOrder() throws Exception {
- assertSortedObjectEquals("{a1:'1',a2:'2',a3:'3',a4:'4'}", new W2());
- assertSortedObjectEquals("{a3:'3',a4:'4',a5:'5',a6:'6'}", new W3());
- }
-
- public static class W {
- public String getA1() {return "1";}
- public String getA2() {return "2";}
- }
-
- public static class W2 extends W {
- public String getA3() {return "3";}
- public String getA4() {return "4";}
- }
-
- @Bean(stopClass=W.class)
- public static class W3 extends W2 {
- public String getA5() {return "5";}
- public String getA6() {return "6";}
- }
-
- //====================================================================================================
- // testResourceDescription
- //====================================================================================================
- @Test
- public void testOverriddenPropertyTypes() throws Exception {
- JsonSerializer s = JsonSerializer.DEFAULT_LAX;
- JsonParser p = JsonParser.DEFAULT;
- String r;
-
- X1 t1 = X1.create();
- r = s.serialize(t1);
- assertEquals("{f1:'1',f2:'2'}", r);
- t1 = p.parse(r, X1.class);
- assertEquals("1", t1.f1);
- assertEquals("2", t1.getF2());
-
- X2 t2 = X2.create();
- r = s.serialize(t2);
- assertEquals("{f1:1,f2:2}", r);
- t2 = p.parse(r, X2.class);
- assertEquals(1, t2.f1.intValue());
- assertEquals(2, t2.getF2().intValue());
- }
-
- public static class X1 {
- public Object f1;
- private Object f2;
-
- static X1 create() {
- X1 x = new X1();
- x.f1 = "1";
- x.f2 = "2";
- return x;
- }
-
- public Object getF2() {
- return f2;
- }
-
- public void setF2(Object f2) {
- this.f2 = f2;
- }
- }
-
- public static class X2 extends X1 {
- public Integer f1;
- private Integer f2;
-
- static X2 create() {
- X2 x = new X2();
- x.f1 = 1;
- x.f2 = 2;
- return x;
- }
-
- @Override /* X1 */
- public Integer getF2() {
- return f2;
- }
-
- public void setF2(Integer f2) {
- this.f2 = f2;
- }
- }
-
- private BeanContext getBeanContext() {
- return ContextFactory.create().setClassLoader(this.getClass().getClassLoader()).getBeanContext();
- }
-
- @Test
- public void testSettingCollectionPropertyMultipleTimes() throws Exception {
-
- BeanMap m = BeanContext.DEFAULT.newBeanMap(Y.class);
- m.put("f1", new ObjectList().append("a"));
- m.put("f1", new ObjectList().append("b"));
- assertEquals("{f1=[b]}", m.toString());
- }
-
- public static class Y {
- public List<String> f1 = new LinkedList<String>();
- }
-
- //====================================================================================================
- // entrySet(false).
- //====================================================================================================
- @Test
- public void testIgnoreNulls() {
- Z z = new Z();
- BeanMap<Z> bm = BeanContext.DEFAULT.forBean(z);
-
- Iterator i = bm.getValues(false, true).iterator();
- assertFalse(i.hasNext());
-
- z.b = "";
- i = bm.getValues(false, true).iterator();
- assertTrue(i.hasNext());
- i.next();
- assertFalse(i.hasNext());
-
- i = bm.getValues(false, false).iterator();
- assertTrue(i.hasNext());
- i.next();
- assertTrue(i.hasNext());
- i.next();
- assertTrue(i.hasNext());
- i.next();
- assertFalse(i.hasNext());
- }
-
- public static class Z {
- public String a, b, c;
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/CT_BeanTransform.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/CT_BeanTransform.java b/org.apache.juneau/src/test/java/org/apache/juneau/CT_BeanTransform.java
deleted file mode 100755
index 86eeb77..0000000
--- a/org.apache.juneau/src/test/java/org/apache/juneau/CT_BeanTransform.java
+++ /dev/null
@@ -1,144 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau;
-
-import static org.junit.Assert.*;
-
-import java.util.*;
-
-import org.apache.juneau.annotation.*;
-import org.apache.juneau.json.*;
-import org.junit.*;
-
-public class CT_BeanTransform {
-
- //====================================================================================================
- // Test sub types
- //====================================================================================================
- @Test
- public void testSubTypes() throws Exception {
- JsonSerializer s = JsonSerializer.DEFAULT_LAX;
- JsonParser p = JsonParser.DEFAULT;
-
- A1 a1 = new A1();
- a1.f1 = "f1";
- a1.fb = new B2();
- ((B2)a1.fb).f2 = "f2";
- String r = s.serialize(a1);
- assertEquals("{subType:'A1',f0:'f0',fb:{subType:'B2',f0b:'f0b',f2:'f2'},f1:'f1'}", r);
-
- A a = p.parse(r, A.class);
- assertTrue(a instanceof A1);
- assertTrue(a.fb instanceof B2);
- assertEquals("f1", ((A1)a).f1);
- assertEquals("f2", ((B2)a.fb).f2);
-
- // Try out-of-order creation.
- r = "{f0:'f0',f1:'f1',subType:'A1',fb:{f0b:'f0b',f2:'f2',subType:'B2'}}";
- a = p.parse(r, A.class);
- assertTrue(a instanceof A1);
- assertTrue(a.fb instanceof B2);
- assertEquals("f1", ((A1)a).f1);
- assertEquals("f2", ((B2)a.fb).f2);
- }
-
- @Bean(
- subTypeProperty="subType",
- subTypes={
- @BeanSubType(type=A1.class, id="A1"),
- @BeanSubType(type=A2.class, id="A2")
- }
- )
- public static abstract class A {
- public String f0 = "f0";
- public B fb;
- }
-
- public static class A1 extends A {
- public String f1;
- }
-
- public static class A2 extends A {
- public String f2;
- }
-
- @Bean(
- subTypeProperty="subType",
- subTypes={
- @BeanSubType(type=B1.class, id="B1"),
- @BeanSubType(type=B2.class, id="B2")
- }
- )
- public static abstract class B {
- public String f0b = "f0b";
- }
-
- public static class B1 extends B {
- public String f1;
- }
-
- public static class B2 extends B {
- public String f2;
- }
-
- //====================================================================================================
- // Test parent class used as transform
- //====================================================================================================
- @Test
- public void testParentClassTransform() throws Exception {
- JsonSerializer s = new JsonSerializer.Simple().addTransforms(C1.class);
-
- C1 c1 = new C2();
- String r = s.serialize(c1);
- assertEquals("{f0:'f0'}", r);
-
- List<C1> l = new LinkedList<C1>();
- l.add(new C2());
- r = s.serialize(l);
- assertEquals("[{f0:'f0'}]", r);
- }
-
- public static class C1 {
- public String f0 = "f0";
- }
-
- public static class C2 extends C1 {
- public String f1 = "f1";
- }
-
- //====================================================================================================
- // Test non-static parent class used as transform
- //====================================================================================================
- @Test
- public void testParentClassTransform2() throws Exception {
- JsonSerializer s = new JsonSerializer.Simple().addTransforms(D1.class);
-
- D1 d1 = new D2();
- String r = s.serialize(d1);
- assertEquals("{f0:'f0'}", r);
-
- List<D1> l = new LinkedList<D1>();
- l.add(new D2());
- r = s.serialize(l);
- assertEquals("[{f0:'f0'}]", r);
- }
-
- public class D1 {
- public String f0 = "f0";
- }
-
- public class D2 extends D1 {
- public String f1 = "f1";
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/CT_ClassMeta.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/CT_ClassMeta.java b/org.apache.juneau/src/test/java/org/apache/juneau/CT_ClassMeta.java
deleted file mode 100755
index f10a0e4..0000000
--- a/org.apache.juneau/src/test/java/org/apache/juneau/CT_ClassMeta.java
+++ /dev/null
@@ -1,281 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau;
-
-import static org.junit.Assert.*;
-
-import java.util.*;
-
-import org.apache.juneau.transform.*;
-import org.junit.*;
-
-@SuppressWarnings({"rawtypes","serial","hiding"})
-public class CT_ClassMeta {
-
- BeanContext bc = BeanContext.DEFAULT;
-
- //====================================================================================================
- // Map<String,String> field
- //====================================================================================================
- public Map<String,String> fa;
-
- @Test
- public void testMap() throws Exception {
- ClassMeta t = bc.getClassMeta(this.getClass().getField("fa").getGenericType());
- assertEquals("java.util.Map<java.lang.String,java.lang.String>", t.toString());
- assertTrue(t.isMap());
- assertFalse(t.isCollection());
- assertNull(t.newInstance());
- assertEquals(Map.class, t.getInnerClass());
- assertEquals(String.class, t.getKeyType().getInnerClass());
- assertEquals(String.class, t.getValueType().getInnerClass());
- }
-
- //====================================================================================================
- // String field
- //====================================================================================================
- public String fb;
-
- @Test
- public void testString() throws Exception {
- ClassMeta t = bc.getClassMeta(this.getClass().getField("fb").getGenericType());
- assertEquals(String.class, t.getInnerClass());
- t = bc.getClassMeta(this.getClass().getField("fb").getType());
- assertEquals(String.class, t.getInnerClass());
- }
-
- //====================================================================================================
- // Map<String,Map<String,Integer>> field
- //====================================================================================================
- public Map<String,Map<String,Integer>> fc;
-
- @Test
- public void testMapWithMapValues() throws Exception {
- ClassMeta t = bc.getClassMeta(this.getClass().getField("fc").getGenericType());
- assertEquals("java.util.Map<java.lang.String,java.util.Map<java.lang.String,java.lang.Integer>>", t.toString());
- t = bc.getClassMeta(this.getClass().getField("fc").getType());
- assertEquals("java.util.Map", t.toString());
- }
-
- //====================================================================================================
- // List<Map<String,List>> field
- //====================================================================================================
- public List<Map<String,List>> fd;
-
- @Test
- public void testListWithMapValues() throws Exception {
- ClassMeta t = bc.getClassMeta(this.getClass().getField("fd").getGenericType());
- assertEquals("java.util.List<java.util.Map<java.lang.String,java.util.List>>", t.toString());
- }
-
- //====================================================================================================
- // List<? extends String> field, List<? super String> field
- //====================================================================================================
- public List<? extends String> fe1;
- public List<? super String> fe2;
-
- @Test
- public void testListWithUpperBoundGenericEntryTypes() throws Exception {
- ClassMeta t = bc.getClassMeta(this.getClass().getField("fe1").getGenericType());
- assertEquals("java.util.List", t.toString());
- t = bc.getClassMeta(this.getClass().getField("fe2").getGenericType());
- assertEquals("java.util.List", t.toString());
- }
-
- //====================================================================================================
- // Bean extends HashMap<String,Object> field
- //====================================================================================================
- public class G extends HashMap<String,Object> {}
- public G g;
-
- @Test
- public void testBeanExtendsMap() throws Exception {
- ClassMeta t = bc.getClassMeta(this.getClass().getField("g").getGenericType());
- assertEquals("org.apache.juneau.CT_ClassMeta$G<java.lang.String,java.lang.Object>", t.toString());
- assertTrue(t.isMap());
- assertFalse(t.isCollection());
- }
-
- //====================================================================================================
- // testTransforms
- // Ensure filters on parent and child classes are properly detected.
- //====================================================================================================
- @Test
- public void testTransforms() throws Exception {
- BeanContext bc;
- ClassMeta<?> ooo, hi1, hc1, hi2, hc2;
-
- bc = ContextFactory.create().getBeanContext();
- ooo = bc.getClassMeta(Object.class);
- hi1 = bc.getClassMeta(HI1.class);
- hc1 = bc.getClassMeta(HC1.class);
- hi2 = bc.getClassMeta(HI2.class);
- hc2 = bc.getClassMeta(HC2.class);
- assertFalse(ooo.hasChildPojoTransforms());
- assertFalse(hi1.hasChildPojoTransforms());
- assertFalse(hc1.hasChildPojoTransforms());
- assertFalse(hi2.hasChildPojoTransforms());
- assertFalse(hc2.hasChildPojoTransforms());
- assertNull(ooo.getPojoTransform());
- assertNull(hi1.getPojoTransform());
- assertNull(hc1.getPojoTransform());
- assertNull(hi2.getPojoTransform());
- assertNull(hc2.getPojoTransform());
- assertEquals(ooo.getTransformedClassMeta().getInnerClass(), Object.class);
- assertEquals(hi1.getTransformedClassMeta().getInnerClass(), HI1.class);
- assertEquals(hc1.getTransformedClassMeta().getInnerClass(), HC1.class);
- assertEquals(hi2.getTransformedClassMeta().getInnerClass(), HI2.class);
- assertEquals(hc2.getTransformedClassMeta().getInnerClass(), HC2.class);
-
- bc = ContextFactory.create().addTransforms(HI1Transform.class).getBeanContext();
- ooo = bc.getClassMeta(Object.class);
- hi1 = bc.getClassMeta(HI1.class);
- hc1 = bc.getClassMeta(HC1.class);
- hi2 = bc.getClassMeta(HI2.class);
- hc2 = bc.getClassMeta(HC2.class);
- assertTrue(ooo.hasChildPojoTransforms());
- assertTrue(hi1.hasChildPojoTransforms());
- assertFalse(hc1.hasChildPojoTransforms());
- assertFalse(hi2.hasChildPojoTransforms());
- assertFalse(hc2.hasChildPojoTransforms());
- assertNull(ooo.getPojoTransform());
- assertEquals(hi1.getPojoTransform().getClass(), HI1Transform.class);
- assertEquals(hc1.getPojoTransform().getClass(), HI1Transform.class);
- assertEquals(hi2.getPojoTransform().getClass(), HI1Transform.class);
- assertEquals(hc2.getPojoTransform().getClass(), HI1Transform.class);
- assertEquals(ooo.getTransformedClassMeta().getInnerClass(), Object.class);
- assertEquals(hi1.getTransformedClassMeta().getInnerClass(), Map.class);
- assertEquals(hc1.getTransformedClassMeta().getInnerClass(), Map.class);
- assertEquals(hi2.getTransformedClassMeta().getInnerClass(), Map.class);
- assertEquals(hc2.getTransformedClassMeta().getInnerClass(), Map.class);
-
- bc = ContextFactory.create().addTransforms(HC1Transform.class).getBeanContext();
- ooo = bc.getClassMeta(Object.class);
- hi1 = bc.getClassMeta(HI1.class);
- hc1 = bc.getClassMeta(HC1.class);
- hi2 = bc.getClassMeta(HI2.class);
- hc2 = bc.getClassMeta(HC2.class);
- assertTrue(ooo.hasChildPojoTransforms());
- assertTrue(hi1.hasChildPojoTransforms());
- assertTrue(hc1.hasChildPojoTransforms());
- assertFalse(hi2.hasChildPojoTransforms());
- assertFalse(hc2.hasChildPojoTransforms());
- assertNull(ooo.getPojoTransform());
- assertNull(hi1.getPojoTransform());
- assertEquals(hc1.getPojoTransform().getClass(), HC1Transform.class);
- assertNull(hi2.getPojoTransform());
- assertEquals(hc2.getPojoTransform().getClass(), HC1Transform.class);
- assertEquals(ooo.getTransformedClassMeta().getInnerClass(), Object.class);
- assertEquals(hi1.getTransformedClassMeta().getInnerClass(), HI1.class);
- assertEquals(hc1.getTransformedClassMeta().getInnerClass(), Map.class);
- assertEquals(hi2.getTransformedClassMeta().getInnerClass(), HI2.class);
- assertEquals(hc2.getTransformedClassMeta().getInnerClass(), Map.class);
-
- bc = ContextFactory.create().addTransforms(HI2Transform.class).getBeanContext();
- ooo = bc.getClassMeta(Object.class);
- hi1 = bc.getClassMeta(HI1.class);
- hc1 = bc.getClassMeta(HC1.class);
- hi2 = bc.getClassMeta(HI2.class);
- hc2 = bc.getClassMeta(HC2.class);
- assertTrue(ooo.hasChildPojoTransforms());
- assertTrue(hi1.hasChildPojoTransforms());
- assertFalse(hc1.hasChildPojoTransforms());
- assertTrue(hi2.hasChildPojoTransforms());
- assertFalse(hc2.hasChildPojoTransforms());
- assertNull(ooo.getPojoTransform());
- assertNull(hi1.getPojoTransform());
- assertNull(hc1.getPojoTransform());
- assertEquals(hi2.getPojoTransform().getClass(), HI2Transform.class);
- assertEquals(hc2.getPojoTransform().getClass(), HI2Transform.class);
- assertEquals(ooo.getTransformedClassMeta().getInnerClass(), Object.class);
- assertEquals(hi1.getTransformedClassMeta().getInnerClass(), HI1.class);
- assertEquals(hc1.getTransformedClassMeta().getInnerClass(), HC1.class);
- assertEquals(hi2.getTransformedClassMeta().getInnerClass(), Map.class);
- assertEquals(hc2.getTransformedClassMeta().getInnerClass(), Map.class);
-
- bc = ContextFactory.create().addTransforms(HC2Transform.class).getBeanContext();
- ooo = bc.getClassMeta(Object.class);
- hi1 = bc.getClassMeta(HI1.class);
- hc1 = bc.getClassMeta(HC1.class);
- hi2 = bc.getClassMeta(HI2.class);
- hc2 = bc.getClassMeta(HC2.class);
- assertTrue(ooo.hasChildPojoTransforms());
- assertTrue(hi1.hasChildPojoTransforms());
- assertTrue(hc1.hasChildPojoTransforms());
- assertTrue(hi2.hasChildPojoTransforms());
- assertTrue(hc2.hasChildPojoTransforms());
- assertNull(ooo.getPojoTransform());
- assertNull(hi1.getPojoTransform());
- assertNull(hc1.getPojoTransform());
- assertNull(hi2.getPojoTransform());
- assertEquals(hc2.getPojoTransform().getClass(), HC2Transform.class);
- assertEquals(ooo.getTransformedClassMeta().getInnerClass(), Object.class);
- assertEquals(hi1.getTransformedClassMeta().getInnerClass(), HI1.class);
- assertEquals(hc1.getTransformedClassMeta().getInnerClass(), HC1.class);
- assertEquals(hi2.getTransformedClassMeta().getInnerClass(), HI2.class);
- assertEquals(hc2.getTransformedClassMeta().getInnerClass(), Map.class);
-
- bc = ContextFactory.create().addTransforms(HI1Transform.class,HC1Transform.class,HI2Transform.class,HC2Transform.class).getBeanContext();
- ooo = bc.getClassMeta(Object.class);
- hi1 = bc.getClassMeta(HI1.class);
- hc1 = bc.getClassMeta(HC1.class);
- hi2 = bc.getClassMeta(HI2.class);
- hc2 = bc.getClassMeta(HC2.class);
- assertTrue(ooo.hasChildPojoTransforms());
- assertTrue(hi1.hasChildPojoTransforms());
- assertTrue(hc1.hasChildPojoTransforms());
- assertTrue(hi2.hasChildPojoTransforms());
- assertTrue(hc2.hasChildPojoTransforms());
- assertNull(ooo.getPojoTransform());
- assertEquals(hi1.getPojoTransform().getClass(), HI1Transform.class);
- assertEquals(hc1.getPojoTransform().getClass(), HI1Transform.class);
- assertEquals(hi2.getPojoTransform().getClass(), HI1Transform.class);
- assertEquals(hc2.getPojoTransform().getClass(), HI1Transform.class);
- assertEquals(ooo.getTransformedClassMeta().getInnerClass(), Object.class);
- assertEquals(hi1.getTransformedClassMeta().getInnerClass(), Map.class);
- assertEquals(hc1.getTransformedClassMeta().getInnerClass(), Map.class);
- assertEquals(hi2.getTransformedClassMeta().getInnerClass(), Map.class);
- assertEquals(hc2.getTransformedClassMeta().getInnerClass(), Map.class);
-
- bc = ContextFactory.create().addTransforms(HC2Transform.class,HI2Transform.class,HC1Transform.class,HI1Transform.class).getBeanContext();
- ooo = bc.getClassMeta(Object.class);
- hi1 = bc.getClassMeta(HI1.class);
- hc1 = bc.getClassMeta(HC1.class);
- hi2 = bc.getClassMeta(HI2.class);
- hc2 = bc.getClassMeta(HC2.class);
- assertTrue(ooo.hasChildPojoTransforms());
- assertTrue(hi1.hasChildPojoTransforms());
- assertTrue(hc1.hasChildPojoTransforms());
- assertTrue(hi2.hasChildPojoTransforms());
- assertTrue(hc2.hasChildPojoTransforms());
- assertNull(ooo.getPojoTransform());
- assertEquals(hi1.getPojoTransform().getClass(), HI1Transform.class);
- assertEquals(hc1.getPojoTransform().getClass(), HC1Transform.class);
- assertEquals(hi2.getPojoTransform().getClass(), HI2Transform.class);
- assertEquals(hc2.getPojoTransform().getClass(), HC2Transform.class);
- assertEquals(ooo.getTransformedClassMeta().getInnerClass(), Object.class);
- assertEquals(hi1.getTransformedClassMeta().getInnerClass(), Map.class);
- assertEquals(hc1.getTransformedClassMeta().getInnerClass(), Map.class);
- assertEquals(hi2.getTransformedClassMeta().getInnerClass(), Map.class);
- assertEquals(hc2.getTransformedClassMeta().getInnerClass(), Map.class);
- }
-
- public interface HI1 {}
- public class HC1 implements HI1 {}
- public interface HI2 extends HI1 {}
- public class HC2 extends HC1 implements HI2 {}
- public static class HC1Transform extends PojoTransform<HC1,Map> {}
- public static class HI1Transform extends PojoTransform<HI1,Map> {}
- public static class HC2Transform extends PojoTransform<HC2,Map> {}
- public static class HI2Transform extends PojoTransform<HI2,Map> {}
-}
[03/44] incubator-juneau git commit: Rename CT_* testcases.
Posted by ja...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/xml/CT_Common.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/xml/CT_Common.java b/org.apache.juneau/src/test/java/org/apache/juneau/xml/CT_Common.java
deleted file mode 100755
index 1c2caa1..0000000
--- a/org.apache.juneau/src/test/java/org/apache/juneau/xml/CT_Common.java
+++ /dev/null
@@ -1,453 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.xml;
-
-import static org.apache.juneau.TestUtils.*;
-import static org.apache.juneau.serializer.SerializerContext.*;
-import static org.apache.juneau.xml.XmlSerializerContext.*;
-import static org.apache.juneau.xml.annotation.XmlFormat.*;
-import static org.junit.Assert.*;
-
-import java.net.*;
-import java.net.URI;
-import java.util.*;
-
-import org.apache.juneau.*;
-import org.apache.juneau.annotation.*;
-import org.apache.juneau.serializer.*;
-import org.apache.juneau.testbeans.*;
-import org.apache.juneau.xml.annotation.*;
-import org.junit.*;
-
-@SuppressWarnings({"serial"})
-public class CT_Common {
-
- //====================================================================================================
- // Trim nulls from beans
- //====================================================================================================
- @Test
- public void testTrimNullsFromBeans() throws Exception {
- XmlSerializer s = new XmlSerializer.SimpleSq();
- XmlParser p = new XmlParser();
- A t1 = A.create(), t2;
-
- s.setProperty(SERIALIZER_trimNullProperties, false);
- String r = s.serialize(t1);
- assertEquals("<object><s1 nil='true'/><s2>s2</s2></object>", r);
- t2 = p.parse(r, A.class);
- assertEqualObjects(t1, t2);
-
- s.setProperty(SERIALIZER_trimNullProperties, true);
- r = s.serialize(t1);
- assertEquals("<object><s2>s2</s2></object>", r);
- t2 = p.parse(r, A.class);
- assertEqualObjects(t1, t2);
- }
-
- public static class A {
- public String s1, s2;
-
- public static A create() {
- A t = new A();
- t.s2 = "s2";
- return t;
- }
- }
-
- //====================================================================================================
- // Trim empty maps
- //====================================================================================================
- @Test
- public void testTrimEmptyMaps() throws Exception {
- XmlSerializer s = new XmlSerializer.SimpleSq();
- XmlParser p = XmlParser.DEFAULT;
- B t1 = B.create(), t2;
- String r;
-
- s.setProperty(SERIALIZER_trimEmptyMaps, false);
- r = s.serialize(t1);
- assertEquals("<object><f1/><f2><f2a nil='true'/><f2b><s2>s2</s2></f2b></f2></object>", r);
- t2 = p.parse(r, B.class);
- assertEqualObjects(t1, t2);
-
- s.setProperty(SERIALIZER_trimEmptyMaps, true);
- r = s.serialize(t1);
- assertEquals("<object><f2><f2a nil='true'/><f2b><s2>s2</s2></f2b></f2></object>", r);
- t2 = p.parse(r, B.class);
- assertNull(t2.f1);
- }
-
- public static class B {
- public TreeMap<String,A> f1, f2;
-
- public static B create() {
- B t = new B();
- t.f1 = new TreeMap<String,A>();
- t.f2 = new TreeMap<String,A>(){{put("f2a",null);put("f2b",A.create());}};
- return t;
- }
- }
-
- //====================================================================================================
- // Trim empty lists
- //====================================================================================================
- @Test
- public void testTrimEmptyLists() throws Exception {
- XmlSerializer s = new XmlSerializer.SimpleSq();
- XmlParser p = XmlParser.DEFAULT;
- C t1 = C.create(), t2;
- String r;
-
- s.setProperty(SERIALIZER_trimEmptyLists, false);
- r = s.serialize(t1);
- assertEquals("<object><f1></f1><f2><null/><object><s2>s2</s2></object></f2></object>", r);
- t2 = p.parse(r, C.class);
- assertEqualObjects(t1, t2);
-
- s.setProperty(SERIALIZER_trimEmptyLists, true);
- r = s.serialize(t1);
- assertEquals("<object><f2><null/><object><s2>s2</s2></object></f2></object>", r);
- t2 = p.parse(r, C.class);
- assertNull(t2.f1);
- }
-
- public static class C {
- public List<A> f1, f2;
-
- public static C create() {
- C t = new C();
- t.f1 = new LinkedList<A>();
- t.f2 = new LinkedList<A>(){{add(null);add(A.create());}};
- return t;
- }
- }
-
- //====================================================================================================
- // Trim empty arrays
- //====================================================================================================
- @Test
- public void testTrimEmptyArrays() throws Exception {
- XmlSerializer s = new XmlSerializer.SimpleSq();
- XmlParser p = XmlParser.DEFAULT;
- D t1 = D.create(), t2;
- String r;
-
- s.setProperty(SERIALIZER_trimEmptyLists, false);
- r = s.serialize(t1);
- assertEquals("<object><f1></f1><f2><null/><object><s2>s2</s2></object></f2></object>", r);
- t2 = p.parse(r, D.class);
- assertEqualObjects(t1, t2);
-
- s.setProperty(SERIALIZER_trimEmptyLists, true);
- r = s.serialize(t1);
- assertEquals("<object><f2><null/><object><s2>s2</s2></object></f2></object>", r);
- t2 = p.parse(r, D.class);
- assertNull(t2.f1);
- }
-
- public static class D {
- public A[] f1, f2;
-
- public static D create() {
- D t = new D();
- t.f1 = new A[]{};
- t.f2 = new A[]{null, A.create()};
- return t;
- }
- }
-
- //====================================================================================================
- // @BeanProperty.properties annotation.
- //====================================================================================================
- @Test
- public void testBeanPropertyProperties() throws Exception {
- XmlSerializer s = XmlSerializer.DEFAULT_SIMPLE_SQ;
- E1 t = new E1();
- String r = s.serialize(t);
- assertEquals("<object><x1 f2='2'><f1>1</f1></x1><x2><f1>1</f1></x2><x3><object f2='2'><f1>1</f1></object></x3><x4><object f2='2'><f1>1</f1></object></x4><x5><object><f1>1</f1></object></x5><x6><object><f1>1</f1></object></x6></object>", r);
- TestUtils.validateXml(t);
- }
-
- public static class E1 {
- @BeanProperty(properties={"f1","f2"}) public E2 x1 = new E2();
- @BeanProperty(properties={"f1","f2"}) public Map<String,Integer> x2 = new LinkedHashMap<String,Integer>() {{
- put("f1",1); put("f3",3);
- }};
- @BeanProperty(properties={"f1","f2"}) public E2[] x3 = {new E2()};
- @BeanProperty(properties={"f1","f2"}) public List<E2> x4 = new LinkedList<E2>() {{
- add(new E2());
- }};
- @BeanProperty(properties={"f1"}) public ObjectMap[] x5 = {new ObjectMap().append("f1",1).append("f3",3)};
- @BeanProperty(properties={"f1"}) public List<ObjectMap> x6 = new LinkedList<ObjectMap>() {{
- add(new ObjectMap().append("f1",1).append("f3",3));
- }};
- }
-
- public static class E2 {
- public int f1 = 1;
- @Xml(format=ATTR) public int f2 = 2;
- public int f3 = 3;
- @Xml(format=ATTR) public int f4 = 4;
- }
-
- //====================================================================================================
- // @BeanProperty.properties annotation on list of beans.
- //====================================================================================================
- @Test
- public void testBeanPropertyPropertiesOnListOfBeans() throws Exception {
- XmlSerializer s = XmlSerializer.DEFAULT_SIMPLE_SQ;
- List<Test7b> l = new LinkedList<Test7b>();
- Test7b t = new Test7b();
- t.x1.add(new Test7b());
- l.add(t);
- String xml = s.serialize(l);
- assertEquals("<array><object><x1><object><x2>2</x2></object></x1><x2>2</x2></object></array>", xml);
- }
-
- public static class Test7b {
- @BeanProperty(properties={"x2"}) public List<Test7b> x1 = new LinkedList<Test7b>();
- public int x2 = 2;
- }
-
- //====================================================================================================
- // Test that URLs and URIs are serialized and parsed correctly.
- //====================================================================================================
- @Test
- public void testURIAttr() throws Exception {
- XmlSerializer s = XmlSerializer.DEFAULT_SIMPLE_SQ;
- XmlParser p = XmlParser.DEFAULT;
-
- G t = new G();
- t.uri = new URI("http://uri");
- t.f1 = new URI("http://f1");
- t.f2 = new URL("http://f2");
-
- String xml = s.serialize(t);
- t = p.parse(xml, G.class);
- assertEquals("http://uri", t.uri.toString());
- assertEquals("http://f1", t.f1.toString());
- assertEquals("http://f2", t.f2.toString());
- }
-
- public static class G {
- @BeanProperty(beanUri=true) public URI uri;
- public URI f1;
- public URL f2;
- }
-
- //====================================================================================================
- // Test URIs with URI_CONTEXT and URI_AUTHORITY
- //====================================================================================================
- @Test
- public void testUris() throws Exception {
- WriterSerializer s = new XmlSerializer.SimpleSq();
- TestURI t = new TestURI();
- String r;
- String expected;
-
- s.setProperty(SERIALIZER_relativeUriBase, null);
- r = s.serialize(t);
- expected = ""
- +"<object f0='f0/x0'>"
- +"<f1>f1/x1</f1>"
- +"<f2>/f2/x2</f2>"
- +"<f3>http://www.ibm.com/f3/x3</f3>"
- +"<f4>f4/x4</f4>"
- +"<f5>/f5/x5</f5>"
- +"<f6>http://www.ibm.com/f6/x6</f6>"
- +"<f7>http://www.ibm.com/f7/x7</f7>"
- +"<f8>f8/x8</f8>"
- +"<f9>f9/x9</f9>"
- +"<fa>http://www.ibm.com/fa/xa#MY_LABEL</fa>"
- +"<fb>http://www.ibm.com/fb/xb?label=MY_LABEL&foo=bar</fb>"
- +"<fc>http://www.ibm.com/fc/xc?foo=bar&label=MY_LABEL</fc>"
- +"<fd>http://www.ibm.com/fd/xd?label2=MY_LABEL&foo=bar</fd>"
- +"<fe>http://www.ibm.com/fe/xe?foo=bar&label2=MY_LABEL</fe>"
- +"</object>";
- assertEquals(expected, r);
-
- s.setProperty(SERIALIZER_relativeUriBase, ""); // Same as null.
- r = s.serialize(t);
- assertEquals(expected, r);
-
- s.setProperty(SERIALIZER_relativeUriBase, "/cr");
- r = s.serialize(t);
- expected = ""
- +"<object f0='/cr/f0/x0'>"
- +"<f1>/cr/f1/x1</f1>"
- +"<f2>/f2/x2</f2>"
- +"<f3>http://www.ibm.com/f3/x3</f3>"
- +"<f4>/cr/f4/x4</f4>"
- +"<f5>/f5/x5</f5>"
- +"<f6>http://www.ibm.com/f6/x6</f6>"
- +"<f7>http://www.ibm.com/f7/x7</f7>"
- +"<f8>/cr/f8/x8</f8>"
- +"<f9>/cr/f9/x9</f9>"
- +"<fa>http://www.ibm.com/fa/xa#MY_LABEL</fa>"
- +"<fb>http://www.ibm.com/fb/xb?label=MY_LABEL&foo=bar</fb>"
- +"<fc>http://www.ibm.com/fc/xc?foo=bar&label=MY_LABEL</fc>"
- +"<fd>http://www.ibm.com/fd/xd?label2=MY_LABEL&foo=bar</fd>"
- +"<fe>http://www.ibm.com/fe/xe?foo=bar&label2=MY_LABEL</fe>"
- +"</object>";
- assertEquals(expected, r);
-
- s.setProperty(SERIALIZER_relativeUriBase, "/cr/"); // Same as above
- r = s.serialize(t);
- assertEquals(expected, r);
-
- s.setProperty(SERIALIZER_relativeUriBase, "/");
- r = s.serialize(t);
- expected = ""
- +"<object f0='/f0/x0'>"
- +"<f1>/f1/x1</f1>"
- +"<f2>/f2/x2</f2>"
- +"<f3>http://www.ibm.com/f3/x3</f3>"
- +"<f4>/f4/x4</f4>"
- +"<f5>/f5/x5</f5>"
- +"<f6>http://www.ibm.com/f6/x6</f6>"
- +"<f7>http://www.ibm.com/f7/x7</f7>"
- +"<f8>/f8/x8</f8>"
- +"<f9>/f9/x9</f9>"
- +"<fa>http://www.ibm.com/fa/xa#MY_LABEL</fa>"
- +"<fb>http://www.ibm.com/fb/xb?label=MY_LABEL&foo=bar</fb>"
- +"<fc>http://www.ibm.com/fc/xc?foo=bar&label=MY_LABEL</fc>"
- +"<fd>http://www.ibm.com/fd/xd?label2=MY_LABEL&foo=bar</fd>"
- +"<fe>http://www.ibm.com/fe/xe?foo=bar&label2=MY_LABEL</fe>"
- +"</object>";
- assertEquals(expected, r);
-
- s.setProperty(SERIALIZER_relativeUriBase, null);
-
- s.setProperty(SERIALIZER_absolutePathUriBase, "http://foo");
- r = s.serialize(t);
- expected = ""
- +"<object f0='f0/x0'>"
- +"<f1>f1/x1</f1>"
- +"<f2>http://foo/f2/x2</f2>"
- +"<f3>http://www.ibm.com/f3/x3</f3>"
- +"<f4>f4/x4</f4>"
- +"<f5>http://foo/f5/x5</f5>"
- +"<f6>http://www.ibm.com/f6/x6</f6>"
- +"<f7>http://www.ibm.com/f7/x7</f7>"
- +"<f8>f8/x8</f8>"
- +"<f9>f9/x9</f9>"
- +"<fa>http://www.ibm.com/fa/xa#MY_LABEL</fa>"
- +"<fb>http://www.ibm.com/fb/xb?label=MY_LABEL&foo=bar</fb>"
- +"<fc>http://www.ibm.com/fc/xc?foo=bar&label=MY_LABEL</fc>"
- +"<fd>http://www.ibm.com/fd/xd?label2=MY_LABEL&foo=bar</fd>"
- +"<fe>http://www.ibm.com/fe/xe?foo=bar&label2=MY_LABEL</fe>"
- +"</object>";
- assertEquals(expected, r);
-
- s.setProperty(SERIALIZER_absolutePathUriBase, "http://foo/");
- r = s.serialize(t);
- assertEquals(expected, r);
-
- s.setProperty(SERIALIZER_absolutePathUriBase, ""); // Same as null.
- r = s.serialize(t);
- expected = ""
- +"<object f0='f0/x0'>"
- +"<f1>f1/x1</f1>"
- +"<f2>/f2/x2</f2>"
- +"<f3>http://www.ibm.com/f3/x3</f3>"
- +"<f4>f4/x4</f4>"
- +"<f5>/f5/x5</f5>"
- +"<f6>http://www.ibm.com/f6/x6</f6>"
- +"<f7>http://www.ibm.com/f7/x7</f7>"
- +"<f8>f8/x8</f8>"
- +"<f9>f9/x9</f9>"
- +"<fa>http://www.ibm.com/fa/xa#MY_LABEL</fa>"
- +"<fb>http://www.ibm.com/fb/xb?label=MY_LABEL&foo=bar</fb>"
- +"<fc>http://www.ibm.com/fc/xc?foo=bar&label=MY_LABEL</fc>"
- +"<fd>http://www.ibm.com/fd/xd?label2=MY_LABEL&foo=bar</fd>"
- +"<fe>http://www.ibm.com/fe/xe?foo=bar&label2=MY_LABEL</fe>"
- +"</object>";
- assertEquals(expected, r);
- }
-
- //====================================================================================================
- // Validate that you cannot update properties on locked serializer.
- //====================================================================================================
- @Test
- public void testLockedSerializer() throws Exception {
- XmlSerializer s = new XmlSerializer().lock();
- try {
- s.setProperty(XmlSerializerContext.XML_enableNamespaces, true);
- fail("Locked exception not thrown");
- } catch (LockedException e) {}
- try {
- s.setProperty(SerializerContext.SERIALIZER_addClassAttrs, true);
- fail("Locked exception not thrown");
- } catch (LockedException e) {}
- try {
- s.setProperty(BeanContext.BEAN_beanMapPutReturnsOldValue, true);
- fail("Locked exception not thrown");
- } catch (LockedException e) {}
- }
-
- //====================================================================================================
- // Recursion
- //====================================================================================================
- @Test
- public void testRecursion() throws Exception {
- XmlSerializer s = new XmlSerializer().setProperty(XML_enableNamespaces, false);
-
- R1 r1 = new R1();
- R2 r2 = new R2();
- R3 r3 = new R3();
- r1.r2 = r2;
- r2.r3 = r3;
- r3.r1 = r1;
-
- // No recursion detection
- try {
- s.serialize(r1);
- fail("Exception expected!");
- } catch (Exception e) {
- String msg = e.getLocalizedMessage();
- assertTrue(msg.contains("It's recommended you use the SerializerContext.SERIALIZER_detectRecursions setting to help locate the loop."));
- }
-
- // Recursion detection, no ignore
- s.setProperty(SERIALIZER_detectRecursions, true);
- try {
- s.serialize(r1);
- fail("Exception expected!");
- } catch (Exception e) {
- String msg = e.getLocalizedMessage();
- assertTrue(msg.contains("[0]<noname>:org.apache.juneau.xml.CT_Common$R1"));
- assertTrue(msg.contains("->[1]r2:org.apache.juneau.xml.CT_Common$R2"));
- assertTrue(msg.contains("->[2]r3:org.apache.juneau.xml.CT_Common$R3"));
- assertTrue(msg.contains("->[3]r1:org.apache.juneau.xml.CT_Common$R1"));
- }
-
- s.setProperty(SERIALIZER_ignoreRecursions, true);
- assertEquals("<object><name>foo</name><r2><name>bar</name><r3><name>baz</name></r3></r2></object>", s.serialize(r1));
-
- // Make sure this doesn't blow up.
- s.getSchemaSerializer().serialize(r1);
- }
-
- public static class R1 {
- public String name = "foo";
- public R2 r2;
- }
- public static class R2 {
- public String name = "bar";
- public R3 r3;
- }
- public static class R3 {
- public String name = "baz";
- public R1 r1;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/xml/CT_CommonParser.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/xml/CT_CommonParser.java b/org.apache.juneau/src/test/java/org/apache/juneau/xml/CT_CommonParser.java
deleted file mode 100755
index 054a042..0000000
--- a/org.apache.juneau/src/test/java/org/apache/juneau/xml/CT_CommonParser.java
+++ /dev/null
@@ -1,179 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.xml;
-
-import static org.apache.juneau.BeanContext.*;
-import static org.junit.Assert.*;
-
-import java.util.*;
-
-import org.apache.juneau.*;
-import org.apache.juneau.parser.*;
-import org.junit.*;
-
-@SuppressWarnings({"rawtypes","serial"})
-public class CT_CommonParser {
-
- //====================================================================================================
- // testFromSerializer
- //====================================================================================================
- @Test
- public void testFromSerializer() throws Exception {
- ReaderParser p = XmlParser.DEFAULT;
-
- Map m = null;
- m = (Map)p.parse("<object><a type='number'>1</a></object>", Object.class);
- assertEquals(1, m.get("a"));
- m = (Map)p.parse("<object><a type='number'>1</a><b type='string'>foo bar</b></object>", Object.class);
- assertEquals(1, m.get("a"));
- assertEquals("foo bar", m.get("b"));
- m = (Map)p.parse("<object><a type='number'>1</a><b type='string'>foo bar</b><c type='boolean'>false</c></object>", Object.class);
- assertEquals(1, m.get("a"));
- assertEquals(false, m.get("c"));
- m = (Map)p.parse(" <object> <a type='number'> 1 </a> <b type='string'> foo </b> <c type='boolean'> false </c> </object> ", Object.class);
- assertEquals(1, m.get("a"));
- assertEquals("foo", m.get("b"));
- assertEquals(false, m.get("c"));
-
- m = (Map)p.parse("<object><x type='string'>org.apache.juneau.test.Person</x><addresses type='array'><object><x type='string'>org.apache.juneau.test.Address</x><city type='string'>city A</city><state type='string'>state A</state><street type='string'>street A</street><zip type='number'>12345</zip></object></addresses></object>", Object.class);
- assertEquals("org.apache.juneau.test.Person", m.get("x"));
- List l = (List)m.get("addresses");
- assertNotNull(l);
- m = (Map)l.get(0);
- assertNotNull(m);
- assertEquals("org.apache.juneau.test.Address", m.get("x"));
- assertEquals("city A", m.get("city"));
- assertEquals("state A", m.get("state"));
- assertEquals("street A", m.get("street"));
- assertEquals(12345, m.get("zip"));
-
- ObjectList jl = (ObjectList)p.parse("<array><object><attribute type='string'>value</attribute></object><object><attribute type='string'>value</attribute></object></array>", Object.class);
- assertEquals("value", jl.getObjectMap(0).getString("attribute"));
- assertEquals("value", jl.getObjectMap(1).getString("attribute"));
-
- try {
- jl = (ObjectList)p.parse("<array><object><attribute type='string'>value</attribute></object><object><attribute type='string'>value</attribute></object></array>", Object.class);
- assertEquals("value", jl.getObjectMap(0).getString("attribute"));
- assertEquals("value", jl.getObjectMap(1).getString("attribute"));
- } catch (Exception e) {
- fail(e.getLocalizedMessage());
- }
-
- A1 t1 = new A1();
- A2 t2 = new A2();
- t2.add(new A3("name0","value0"));
- t2.add(new A3("name1","value1"));
- t1.list = t2;
- String r = XmlSerializer.DEFAULT.serialize(t1);
- t1 = p.parse(r, A1.class);
- assertEquals("value1", t1.list.get(1).value);
-
- r = XmlSerializer.DEFAULT.serialize(t1);
- t1 = p.parse(r, A1.class);
- assertEquals("value1", t1.list.get(1).value);
- }
-
- public static class A1 {
- public A2 list;
- }
-
- public static class A2 extends LinkedList<A3> {
- }
-
- public static class A3 {
- public String name, value;
- public A3(){}
- public A3(String name, String value) {
- this.name = name;
- this.value = value;
- }
- }
-
- //====================================================================================================
- // Correct handling of unknown properties.
- //====================================================================================================
- @Test
- public void testCorrectHandlingOfUnknownProperties() throws Exception {
- ReaderParser p = new XmlParser().setProperty(BEAN_ignoreUnknownBeanProperties, true);
- B t;
-
- String in = "<object><a>1</a><unknown>foo</unknown><b>2</b></object>";
- t = p.parse(in, B.class);
- assertEquals(t.a, 1);
- assertEquals(t.b, 2);
-
- in = "<object><a>1</a><unknown><object><a type='string'>foo</a></object></unknown><b>2</b></object>";
- t = p.parse(in, B.class);
- assertEquals(t.a, 1);
- assertEquals(t.b, 2);
-
-
- try {
- p = new XmlParser();
- p.parse(in, B.class);
- fail("Exception expected");
- } catch (ParseException e) {}
- }
-
- public static class B {
- public int a, b;
- }
-
- //====================================================================================================
- // Writing to Collection properties with no setters.
- //====================================================================================================
- @Test
- public void testCollectionPropertiesWithNoSetters() throws Exception {
-
- ReaderParser p = XmlParser.DEFAULT;
-
- String in = "<object><ints type='array'><number>1</number><number>2</number><number>3</number></ints><beans type='array'><object><a type='number'>1</a><b type='number'>2</b></object></beans></object>";
- C t = p.parse(in, C.class);
- assertEquals(t.getInts().size(), 3);
- assertEquals(t.getBeans().get(0).b, 2);
- }
-
- public static class C {
- private Collection<Integer> ints = new LinkedList<Integer>();
- private List<B> beans = new LinkedList<B>();
- public Collection<Integer> getInts() {
- return ints;
- }
- public List<B> getBeans() {
- return beans;
- }
- }
-
- //====================================================================================================
- // Parser listeners.
- //====================================================================================================
- @Test
- public void testParserListeners() throws Exception {
- final List<String> events = new LinkedList<String>();
- XmlParser p = new XmlParser().setProperty(BEAN_ignoreUnknownBeanProperties, true);
- p.addListener(
- new ParserListener() {
- @Override /* ParserListener */
- public <T> void onUnknownProperty(String propertyName, Class<T> beanClass, T bean, int line, int col) {
- events.add(propertyName + "," + line + "," + col);
- }
- }
- );
-
- String in = "<object><a type='number'>1</a><unknownProperty type='string'>foo</unknownProperty><b type='number'>2</b></object>";
- p.parse(in, B.class);
- assertEquals(1, events.size());
- // XML parser may or may not support line numbers.
- assertTrue(events.get(0).startsWith("unknownProperty,"));
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/xml/CT_CommonXml.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/xml/CT_CommonXml.java b/org.apache.juneau/src/test/java/org/apache/juneau/xml/CT_CommonXml.java
deleted file mode 100755
index 3e09246..0000000
--- a/org.apache.juneau/src/test/java/org/apache/juneau/xml/CT_CommonXml.java
+++ /dev/null
@@ -1,81 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.xml;
-
-import static org.apache.juneau.TestUtils.*;
-import static org.apache.juneau.xml.XmlSerializerContext.*;
-import static org.apache.juneau.xml.annotation.XmlFormat.*;
-import static org.junit.Assert.*;
-
-import java.net.*;
-
-import org.apache.juneau.annotation.*;
-import org.apache.juneau.xml.annotation.*;
-import org.junit.*;
-
-public class CT_CommonXml {
-
- //====================================================================================================
- // Test 18a - @Bean.uri annotation
- //====================================================================================================
- @Test
- public void testBeanUriAnnotation() throws Exception {
- XmlParser p = XmlParser.DEFAULT;
- XmlSerializer s = XmlSerializer.DEFAULT_SIMPLE_SQ;
-
- A t = new A("http://foo", 123, "bar");
- String xml = s.serialize(t);
- assertEquals("<object url='http://foo' id='123'><name>bar</name></object>", xml);
-
- t = p.parse(xml, A.class);
- assertEquals("http://foo", t.url.toString());
- assertEquals(123, t.id);
- assertEquals("bar", t.name);
-
- validateXml(t, s);
- }
-
- public static class A {
- @BeanProperty(beanUri=true) public URL url;
- @Xml(format=ATTR) public int id;
- public String name;
- public A() {}
- public A(String url, int id, String name) throws Exception {
- this.url = new URL(url);
- this.id = id;
- this.name = name;
- }
- }
-
- //====================================================================================================
- // Bean.uri annotation, only uri property
- //====================================================================================================
- @Test
- public void testBeanUriAnnotationOnlyUriProperty() throws Exception {
- XmlSerializer s = new XmlSerializer.Sq().setProperty(XML_addNamespaceUrisToRoot, false);
-
- B t = new B("http://foo");
- String xml = s.serialize(t);
- assertEquals("<object url='http://foo'><url2>http://foo/2</url2></object>", xml);
- }
-
- public static class B {
- @BeanProperty(beanUri=true) public URL url;
- public URL url2;
- public B() {}
- public B(String url) throws Exception {
- this.url = new URL(url);
- this.url2 = new URL(url+"/2");
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/xml/CT_Xml.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/xml/CT_Xml.java b/org.apache.juneau/src/test/java/org/apache/juneau/xml/CT_Xml.java
deleted file mode 100755
index 5b71d8e..0000000
--- a/org.apache.juneau/src/test/java/org/apache/juneau/xml/CT_Xml.java
+++ /dev/null
@@ -1,1050 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau.xml;
-
-import static org.apache.juneau.TestUtils.*;
-import static org.apache.juneau.serializer.SerializerContext.*;
-import static org.apache.juneau.xml.XmlSerializerContext.*;
-import static org.apache.juneau.xml.annotation.XmlFormat.*;
-import static org.junit.Assert.*;
-
-import java.net.*;
-import java.util.*;
-
-import org.apache.juneau.*;
-import org.apache.juneau.annotation.*;
-import org.apache.juneau.json.*;
-import org.apache.juneau.xml.annotation.*;
-import org.apache.juneau.xml.xml1a.*;
-import org.apache.juneau.xml.xml1b.*;
-import org.apache.juneau.xml.xml1c.*;
-import org.junit.*;
-
-@SuppressWarnings({"serial"})
-public class CT_Xml {
-
- //====================================================================================================
- // Simple comparison test with JSON serializer
- //====================================================================================================
- @Test
- public void testComparisonWithJson() throws Exception {
- String json1 = readFile(getClass().getResource("/xml/testComparisonWithJson.json").getPath());
- String xml1 = readFile(getClass().getResource("/xml/testComparisonWithJson.xml").getPath());
-
- ObjectMap m = (ObjectMap) XmlParser.DEFAULT.parse(xml1, Object.class);
- String json2 = new JsonSerializer.SimpleReadable().setProperty(SERIALIZER_quoteChar, '"').setProperty(SERIALIZER_trimNullProperties, false).serialize(m);
- assertEquals(json1, json2);
-
- m = (ObjectMap) JsonParser.DEFAULT.parse(json1, Object.class);
- String xml2 = new XmlSerializer.SimpleXmlJsonSq().setProperty(SERIALIZER_useIndentation, true).setProperty(SERIALIZER_trimNullProperties, false).serialize(m);
- assertEquals(xml1, xml2);
- }
-
- //====================================================================================================
- // Test namespacing
- //====================================================================================================
- @Test
- public void testNamespaces() throws Exception {
- String e = readFile(getClass().getResource("/xml/testNamespaces.xml").getPath());
- ObjectMap m = (ObjectMap) JsonParser.DEFAULT.parse(readFile(getClass().getResource("/xml/testComparisonWithJson.json").getPath()), Object.class);
- String r = new XmlSerializer.XmlJsonSq()
- .setProperty(XML_addNamespaceUrisToRoot, true)
- .setProperty(XML_defaultNamespaceUri, "http://www.ibm.com")
- .setProperty(SERIALIZER_useIndentation, true)
- .setProperty(SERIALIZER_trimNullProperties, false)
- .serialize(m);
- assertEquals(e, r);
- }
-
- //====================================================================================================
- // Test bean name annotation
- //====================================================================================================
- @Test
- public void testBeanNameAnnotation() throws Exception {
- String e =
- "<Person1 type='object'>\n"
- + " <name>John Smith</name>\n"
- + " <age type='number'>123</age>\n"
- + "</Person1>\n";
- String r = new XmlSerializer.SimpleXmlJsonSq().setProperty(SERIALIZER_useIndentation, true).serialize(new Person1("John Smith", 123));
- assertEquals(e, r);
- }
-
- /** Class with explicitly specified properties */
- @Bean(properties = { "name", "age" })
- @Xml(name="Person1")
- public static class Person1 {
- public int age;
- private String name;
- protected Person1(String name, int age) {
- this.name = name;
- this.age = age;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- }
-
- //====================================================================================================
- // Test trimNulls property.
- //====================================================================================================
- @Test
- public void testTrimNulls() throws Exception {
- String e =
- "<Person1 type='object'>\n"
- + " <age type='number'>123</age>\n"
- + "</Person1>\n";
- String r = new XmlSerializer.SimpleXmlJsonSq().setProperty(SERIALIZER_useIndentation, true).serialize(new Person1(null, 123));
- assertEquals(e, r);
- }
-
- //====================================================================================================
- // Element name.
- //====================================================================================================
- @Test
- public void testElementName() throws Exception {
- XmlSerializer s = XmlSerializer.DEFAULT_SIMPLE_SQ;
- A t = new A();
- String r = s.serialize(t);
- assertEquals("<foo><f1>1</f1></foo>", r);
- validateXml(t);
- }
-
- @Xml(name="foo")
- public static class A {
- public int f1 = 1;
- }
-
- //====================================================================================================
- // Element name on superclass.
- //====================================================================================================
- @Test
- public void testElementNameOnSuperclass() throws Exception {
- XmlSerializer s = XmlSerializer.DEFAULT_SIMPLE_SQ;
- B2 t = new B2();
- String r = s.serialize(t);
- assertEquals("<foo><f1>1</f1></foo>", r);
- validateXml(t);
- }
-
- public static class B1 extends A {}
- public static class B2 extends B1 {}
-
- //====================================================================================================
- // Element name on interface.
- //====================================================================================================
- @Test
- public void testElementNameOnInterface() throws Exception {
- XmlSerializer s = XmlSerializer.DEFAULT_SIMPLE_SQ;
- C3 t = new C3();
- String r = s.serialize(t);
- assertEquals("<foo><f1>1</f1></foo>", r);
- validateXml(t);
- }
-
- @Xml(name="foo")
- public static interface C1 {}
- public static class C2 implements C1 {}
- public static class C3 extends C2 {
- public int f1 = 1;
- }
-
- //====================================================================================================
- // Element name with invalid XML characters.
- //====================================================================================================
- @Test
- public void testElementNameWithInvalidChars() throws Exception {
- XmlSerializer s = XmlSerializer.DEFAULT_SIMPLE_SQ;
- XmlParser p = XmlParser.DEFAULT;
- D t = new D();
- String r = s.serialize(t);
- assertEquals("<_x007E__x0021__x0040__x0023__x0024__x0025__x005E__x0026__x002A__x0028__x0029___x002B__x0060_-_x003D__x007B__x007D__x007C__x005B__x005D__x005C__x003A__x0022__x003B__x0027__x003C__x003E__x003F__x002C_._x000A__x000D__x0009__x0008_><f1>1</f1></_x007E__x0021__x0040__x0023__x0024__x0025__x005E__x0026__x002A__x0028__x0029___x002B__x0060_-_x003D__x007B__x007D__x007C__x005B__x005D__x005C__x003A__x0022__x003B__x0027__x003C__x003E__x003F__x002C_._x000A__x000D__x0009__x0008_>", r);
- t = p.parse(r, D.class);
- validateXml(t);
- }
-
- @Xml(name="~!@#$%^&*()_+`-={}|[]\\:\";'<>?,.\n\r\t\b")
- public static class D {
- public int f1 = 1;
- }
-
- //====================================================================================================
- // Element name can only be specified on classes.
- //====================================================================================================
- @Test
- public void testElementNameInInvalidLocations() throws Exception {
- XmlSerializer s = XmlSerializer.DEFAULT_SIMPLE_SQ;
- E t = new E();
- try {
- s.serialize(t);
- fail("Exception not thrown");
- } catch (Exception e) {
- assertEquals("org.apache.juneau.xml.CT_Xml$E: Annotation error on property 'f1'. Found @Xml.name annotation can only be specified on types.", e.getLocalizedMessage());
- }
- }
-
- public static class E {
- @Xml(name="foo")
- public int f1 = 1;
- }
-
- //====================================================================================================
- // Element name on collection.
- //====================================================================================================
- @Test
- public void testElementNameOnCollection() throws Exception {
- XmlSerializer s = XmlSerializer.DEFAULT_SIMPLE_SQ;
- XmlParser p = XmlParser.DEFAULT;
- F t = new F();
- t.add("bar");
- String r = s.serialize(t);
- assertEquals("<foo><string>bar</string></foo>", r);
- t = p.parse(r, F.class);
- assertEquals("bar", t.get(0));
- validateXml(t);
- }
-
- @Xml(name="foo")
- public static class F extends LinkedList<String>{}
-
- //====================================================================================================
- // Field of type collection with element name.
- // Element name should be ignored.
- //====================================================================================================
- @Test
- public void testIgnoreCollectionFieldWithElementName() throws Exception {
- XmlSerializer s = XmlSerializer.DEFAULT_SIMPLE_SQ;
- XmlParser p = XmlParser.DEFAULT;
- G t = new G();
- t.f1.add("bar");
- String r = s.serialize(t);
- assertEquals("<bar><f1><string>bar</string></f1></bar>", r);
- t = p.parse(r, G.class);
- validateXml(t);
- }
-
- @Xml(name="bar")
- public static class G {
- public F f1 = new F();
- }
-
- //====================================================================================================
- // Element name on not-a-bean.
- //====================================================================================================
- @Test
- public void testElementNameOnNotABean() throws Exception {
- XmlSerializer s = XmlSerializer.DEFAULT_SIMPLE_SQ;
- H t = new H();
- String r = s.serialize(t);
- assertEquals("<foo>bar</foo>", r);
- }
-
- @Xml(name="foo")
- public static class H {
- @Override /* Object */
- public String toString() {
- return "bar";
- }
- }
-
- //====================================================================================================
- // Fields with element name on not-a-beans.
- // Element name should be used on array field entries, but not regular field.
- //====================================================================================================
- @Test
- public void testFieldsWithElementNameOnNotABeans() throws Exception {
- XmlSerializer s = XmlSerializer.DEFAULT_SIMPLE_SQ;
- I t = new I();
- String r = s.serialize(t);
- assertEquals("<object><f1>bar</f1><f2><foo>bar</foo><foo>bar</foo></f2></object>", r);
- }
-
- public static class I {
- public H f1 = new H();
- public H[] f2 = {
- new H(),
- new H()
- };
- }
-
- //====================================================================================================
- // Element name on beans of a collection.
- //====================================================================================================
- @Test
- public void testElementNameOnBeansOfCollection() throws Exception {
- XmlSerializer s = XmlSerializer.DEFAULT_SIMPLE_SQ;
- Object o = new J1();
- String r = s.serialize(o);
- assertEquals("<foo><f1><bar><f2>2</f2></bar></f1></foo>", r);
- }
-
- @Xml(name="foo")
- public static class J1 {
- @BeanProperty(properties={"f2"}) public List<J2> f1 = new LinkedList<J2>() {{
- add(new J2());
- }};}
-
- @Xml(name="bar")
- public static class J2 {
- public int f2 = 2;
- public int f3 = 3;
- }
-
- //====================================================================================================
- // @Xml.ns without matching nsUri.
- //====================================================================================================
- @Test
- public void testXmlNsWithoutMatchingNsUri() throws Exception {
- XmlSerializer s = XmlSerializer.DEFAULT_SIMPLE_SQ;
- K t = new K();
- try {
- s.serialize(t);
- fail("Exception not thrown");
- } catch (Exception e) {
- assertEquals("Found @Xml.prefix annotation with no matching URI. prefix='foo'", e.getLocalizedMessage());
- }
- }
-
- @Xml(prefix="foo")
- public static class K {
- public int f1;
- }
-
- //====================================================================================================
- // @Xml.format=ATTR.
- //====================================================================================================
- @Test
- public void testXmlFormatAttr() throws Exception {
- XmlSerializer s = XmlSerializer.DEFAULT_SIMPLE_SQ;
- XmlParser p = XmlParser.DEFAULT;
- L t = new L();
- String r = s.serialize(t);
- assertEquals("<object f2='2'><f1>1</f1><f3>3</f3></object>", r);
- t.f1 = 4; t.f2 = 5; t.f3 = 6;
- t = p.parse(s.serialize(t), L.class);
- assertEquals(4, t.f1);
- assertEquals(5, t.f2);
- assertEquals(6, t.f3);
- validateXml(t);
- }
-
- public static class L {
- public int f1 = 1;
- @Xml(format=ATTR)
- public int f2 = 2;
- public int f3 = 3;
- }
-
- //====================================================================================================
- // @Xml.format=ATTR with namespaces.
- //====================================================================================================
- @Test
- public void testXmlFormatAttrWithNs() throws Exception {
- XmlSerializer s = new XmlSerializer.SimpleSq();
- XmlParser p = XmlParser.DEFAULT;
- M t = new M();
- String r = null;
- r = s.serialize(t);
- assertEquals("<object f1='1' f2='2' f3='3'/>", r);
- s.setProperty(XML_enableNamespaces, true).setProperty(XML_addNamespaceUrisToRoot, true).setProperty(XML_autoDetectNamespaces, true).setProperty(SERIALIZER_trimNullProperties, false);
- t.f1 = 4; t.f2 = 5; t.f3 = 6;
- r = s.serialize(t);
- assertEquals("<object xmlns='http://www.ibm.com/2013/Juneau' xmlns:bar='http://bar' xmlns:foo='http://foo' xmlns:baz='http://baz' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' bar:f1='4' foo:f2='5' baz:f3='6'/>", r);
- t = p.parse(r, M.class);
- assertEquals(4, t.f1);
- assertEquals(5, t.f2);
- assertEquals(6, t.f3);
- validateXml(t, s);
- }
-
- @Xml(prefix="bar", namespace="http://bar")
- public static class M {
- @Xml(format=ATTR)
- public int f1 = 1;
- @Xml(prefix="foo", format=ATTR, namespace="http://foo")
- public int f2 = 2;
- @Xml(prefix="baz", namespace="http://baz", format=ATTR)
- public int f3 = 3;
- }
-
- //====================================================================================================
- // _xXXXX_ notation.
- //====================================================================================================
- @Test
- public void testXXXXNotation() throws Exception {
- XmlSerializer s = XmlSerializer.DEFAULT_SIMPLE_SQ;
- XmlParser p = XmlParser.DEFAULT;
- String in, r;
-
- in = "\u0001";
- r = s.serialize(in);
- assertEquals("<string>_x0001_</string>", r);
- in = p.parse(r, String.class);
- assertEquals("\u0001", in);
-
- in = "_x0001_";
- r = s.serialize(in);
- assertEquals("<string>_x005F_x0001_</string>", r);
- in = p.parse(r, String.class);
- assertEquals("_x0001_", in);
-
- in = "_x001_";
- r = s.serialize(in);
- assertEquals("<string>_x001_</string>", r);
- in = p.parse(r, String.class);
- assertEquals("_x001_", in);
-
- in = "_x00001_";
- r = s.serialize(in);
- assertEquals("<string>_x00001_</string>", r);
- in = p.parse(r, String.class);
- assertEquals("_x00001_", in);
-
- in = "_xx001_";
- r = s.serialize(in);
- assertEquals("<string>_xx001_</string>", r);
- in = p.parse(r, String.class);
- assertEquals("_xx001_", in);
- }
-
- //====================================================================================================
- // @Bean.uri annotation formatted as element
- //====================================================================================================
- @Test
- public void testBeanUriAnnotationFormattedAsElement() throws Exception {
- XmlParser p = XmlParser.DEFAULT;
- XmlSerializer s = XmlSerializer.DEFAULT_SIMPLE_SQ;
-
- N t = new N("http://foo",123, "bar");
- String r = s.serialize(t);
- assertEquals("<object><url>http://foo</url><id>123</id><name>bar</name></object>", r);
-
- t = p.parse(r, N.class);
- assertEquals("http://foo", t.url.toString());
- assertEquals(123, t.id);
- assertEquals("bar", t.name);
-
- validateXml(t, s);
- }
-
- public static class N {
- @BeanProperty(beanUri=true) @Xml(format=ELEMENT) public URL url;
- public int id;
- public String name;
- public N() {}
- public N(String url, int id, String name) throws Exception {
- this.url = new URL(url);
- this.id = id;
- this.name = name;
- }
- }
-
- //====================================================================================================
- // @Bean.uri as elements, overridden element names
- //====================================================================================================
- @Test
- public void testOverriddenBeanUriAsElementNames() throws Exception {
- XmlParser p = XmlParser.DEFAULT;
- XmlSerializer s = XmlSerializer.DEFAULT_SIMPLE_SQ;
-
- O t = new O("http://foo", 123, "bar");
- String r = s.serialize(t);
- assertEquals("<object><url2>http://foo</url2><id2>123</id2><name>bar</name></object>", r);
-
- t = p.parse(r, O.class);
- assertEquals("http://foo", t.url.toString());
- assertEquals(123, t.id);
- assertEquals("bar", t.name);
-
- validateXml(t, s);
- }
-
- public static class O {
- @BeanProperty(beanUri=true, name="url2") @Xml(format=ELEMENT) public URL url;
- @BeanProperty(name="id2") public int id;
- public String name;
- public O() {}
- public O(String url, int id, String name) throws Exception {
- this.url = new URL(url);
- this.id = id;
- this.name = name;
- }
- }
-
- //====================================================================================================
- // @Bean.uri and @Bean.id annotations, overridden attribute names
- //====================================================================================================
- @Test
- public void testOverriddenBeanUriAndIdAnnotations() throws Exception {
- XmlParser p = XmlParser.DEFAULT;
- XmlSerializer s = XmlSerializer.DEFAULT_SIMPLE_SQ;
-
- P t = new P("http://foo", 123, "bar");
- String r = s.serialize(t);
- assertEquals("<object url2='http://foo' id2='123'><name>bar</name></object>", r);
-
- t = p.parse(r, P.class);
- assertEquals("http://foo", t.url.toString());
- assertEquals(123, t.id);
- assertEquals("bar", t.name);
-
- validateXml(t, s);
- }
-
- public static class P {
- @BeanProperty(beanUri=true, name="url2") public URL url;
- @BeanProperty(name="id2") @Xml(format=ATTR) public int id;
- public String name;
- public P() {}
- public P(String url, int id, String name) throws Exception {
- this.url = new URL(url);
- this.id = id;
- this.name = name;
- }
- }
-
- //====================================================================================================
- // Namespace on class
- //====================================================================================================
- @Test
- public void testNsOnClass() throws Exception {
- XmlSerializer s = new XmlSerializer.SimpleSq().setProperty(XML_autoDetectNamespaces, false);
- XmlParser p = XmlParser.DEFAULT;
-
- T1 t = new T1();
- String r = s.serialize(t);
- assertEquals("<object><f1>1</f1><f2>2</f2><f3>3</f3><f4>4</f4></object>", r);
- assertTrue(t.equals(p.parse(r, T1.class)));
-
- s.setProperty(XML_enableNamespaces, true).setProperty(XML_addNamespaceUrisToRoot, false);
- r = s.serialize(t);
- assertEquals("<object><foo:f1>1</foo:f1><bar:f2>2</bar:f2><foo:f3>3</foo:f3><baz:f4>4</baz:f4></object>", r);
-
- // Add namespace URIs to root, but don't auto-detect.
- // Only xsi should be added to root.
- s.setProperty(XML_addNamespaceUrisToRoot, true);
- r = s.serialize(t);
- assertEquals("<object xmlns='http://www.ibm.com/2013/Juneau' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><foo:f1>1</foo:f1><bar:f2>2</bar:f2><foo:f3>3</foo:f3><baz:f4>4</baz:f4></object>", r);
-
- // Manually set namespaces
- s.setProperty(XML_namespaces,
- new Namespace[] {
- NamespaceFactory.get("foo","http://foo"),
- NamespaceFactory.get("bar","http://bar"),
- NamespaceFactory.get("baz","http://baz")
- }
- );
- r = s.serialize(t);
- assertEquals("<object xmlns='http://www.ibm.com/2013/Juneau' xmlns:foo='http://foo' xmlns:bar='http://bar' xmlns:baz='http://baz' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><foo:f1>1</foo:f1><bar:f2>2</bar:f2><foo:f3>3</foo:f3><baz:f4>4</baz:f4></object>", r);
- assertTrue(t.equals(p.parse(r, T1.class)));
- validateXml(t, s);
-
- // Auto-detect namespaces.
- s = new XmlSerializer.SimpleSq().setProperty(XML_autoDetectNamespaces, true);
- r = s.serialize(t);
- assertEquals("<object><f1>1</f1><f2>2</f2><f3>3</f3><f4>4</f4></object>", r);
- assertTrue(t.equals(p.parse(r, T1.class)));
-
- s.setProperty(XML_addNamespaceUrisToRoot, true);
- r = s.serialize(t);
- assertEquals("<object><f1>1</f1><f2>2</f2><f3>3</f3><f4>4</f4></object>", r);
- assertTrue(t.equals(p.parse(r, T1.class)));
-
- s.setProperty(XML_enableNamespaces, true);
- r = s.serialize(t);
- assertEquals("<object xmlns='http://www.ibm.com/2013/Juneau' xmlns:foo='http://foo' xmlns:bar='http://bar' xmlns:baz='http://baz' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><foo:f1>1</foo:f1><bar:f2>2</bar:f2><foo:f3>3</foo:f3><baz:f4>4</baz:f4></object>", r);
- assertTrue(t.equals(p.parse(r, T1.class)));
- validateXml(t, s);
- }
-
- //====================================================================================================
- // Namespace on class with element name.
- //====================================================================================================
- @Test
- public void testNsOnClassWithElementName() throws Exception {
- XmlSerializer s = new XmlSerializer.SimpleSq().setProperty(XML_autoDetectNamespaces, false);
- XmlParser p = XmlParser.DEFAULT;
-
- T2 t = new T2();
- String r = s.serialize(t);
- assertEquals("<T2><f1>1</f1><f2>2</f2><f3>3</f3><f4>4</f4></T2>", r);
- assertTrue(t.equals(p.parse(r, T2.class)));
-
- s.setProperty(XML_enableNamespaces, true).setProperty(XML_addNamespaceUrisToRoot, false);
- r = s.serialize(t);
- assertEquals("<foo:T2><foo:f1>1</foo:f1><bar:f2>2</bar:f2><foo:f3>3</foo:f3><baz:f4>4</baz:f4></foo:T2>", r);
-
- // Add namespace URIs to root, but don't auto-detect.
- // Only xsi should be added to root.
- s.setProperty(XML_addNamespaceUrisToRoot, true);
- r = s.serialize(t);
- assertEquals("<foo:T2 xmlns='http://www.ibm.com/2013/Juneau' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><foo:f1>1</foo:f1><bar:f2>2</bar:f2><foo:f3>3</foo:f3><baz:f4>4</baz:f4></foo:T2>", r);
-
- // Manually set namespaces
- s.setProperty(XML_namespaces,
- new Namespace[] {
- NamespaceFactory.get("foo","http://foo"),
- NamespaceFactory.get("bar","http://bar"),
- NamespaceFactory.get("baz","http://baz")
- }
- );
- r = s.serialize(t);
- assertEquals("<foo:T2 xmlns='http://www.ibm.com/2013/Juneau' xmlns:foo='http://foo' xmlns:bar='http://bar' xmlns:baz='http://baz' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><foo:f1>1</foo:f1><bar:f2>2</bar:f2><foo:f3>3</foo:f3><baz:f4>4</baz:f4></foo:T2>", r);
- assertTrue(t.equals(p.parse(r, T2.class)));
- validateXml(t, s);
-
- // Auto-detect namespaces.
- s = new XmlSerializer.SimpleSq().setProperty(XML_autoDetectNamespaces, true);
- r = s.serialize(t);
- assertEquals("<T2><f1>1</f1><f2>2</f2><f3>3</f3><f4>4</f4></T2>", r);
-
- s.setProperty(XML_addNamespaceUrisToRoot, true);
- r = s.serialize(t);
- assertEquals("<T2><f1>1</f1><f2>2</f2><f3>3</f3><f4>4</f4></T2>", r);
-
- s.setProperty(XML_enableNamespaces, true);
- r = s.serialize(t);
- assertEquals("<foo:T2 xmlns='http://www.ibm.com/2013/Juneau' xmlns:foo='http://foo' xmlns:bar='http://bar' xmlns:baz='http://baz' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><foo:f1>1</foo:f1><bar:f2>2</bar:f2><foo:f3>3</foo:f3><baz:f4>4</baz:f4></foo:T2>", r);
- assertTrue(t.equals(p.parse(r, T2.class)));
- validateXml(t, s);
- }
-
-
- //====================================================================================================
- // Namespace on package, no namespace on class.
- //====================================================================================================
- @Test
- public void testNsOnPackageNoNsOnClass() throws Exception {
- XmlSerializer s = new XmlSerializer.SimpleSq();
- XmlParser p = XmlParser.DEFAULT;
-
- T3 t = new T3();
- String r = s.serialize(t);
- assertEquals("<object><f1>1</f1><f2>2</f2><f3>3</f3><f4>4</f4></object>", r);
- assertTrue(t.equals(p.parse(r, T3.class)));
- validateXml(t, s);
-
- s.setProperty(XML_enableNamespaces, true).setProperty(XML_addNamespaceUrisToRoot, false);
- r = s.serialize(t);
- assertEquals("<object><p1:f1>1</p1:f1><bar:f2>2</bar:f2><p1:f3>3</p1:f3><baz:f4>4</baz:f4></object>", r);
-
- // Add namespace URIs to root, but don't auto-detect.
- // Only xsi should be added to root.
- s.setProperty(XML_addNamespaceUrisToRoot, true).setProperty(XML_autoDetectNamespaces, false);
- r = s.serialize(t);
- assertEquals("<object xmlns='http://www.ibm.com/2013/Juneau' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><p1:f1>1</p1:f1><bar:f2>2</bar:f2><p1:f3>3</p1:f3><baz:f4>4</baz:f4></object>", r);
-
- // Manually set namespaces
- s.setProperty(XML_autoDetectNamespaces, false);
- s.setProperty(XML_namespaces,
- new Namespace[] {
- NamespaceFactory.get("p1","http://p1"),
- NamespaceFactory.get("bar","http://bar"),
- NamespaceFactory.get("baz","http://baz")
- }
- );
- r = s.serialize(t);
- assertEquals("<object xmlns='http://www.ibm.com/2013/Juneau' xmlns:p1='http://p1' xmlns:bar='http://bar' xmlns:baz='http://baz' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><p1:f1>1</p1:f1><bar:f2>2</bar:f2><p1:f3>3</p1:f3><baz:f4>4</baz:f4></object>", r);
- assertTrue(t.equals(p.parse(r, T3.class)));
- validateXml(t, s);
-
- // Auto-detect namespaces.
- s = new XmlSerializer.SimpleSq().setProperty(XML_autoDetectNamespaces, true);
- r = s.serialize(t);
- assertEquals("<object><f1>1</f1><f2>2</f2><f3>3</f3><f4>4</f4></object>", r);
-
- s.setProperty(XML_addNamespaceUrisToRoot, true);
- r = s.serialize(t);
- assertEquals("<object><f1>1</f1><f2>2</f2><f3>3</f3><f4>4</f4></object>", r);
-
- s.setProperty(XML_enableNamespaces, true);
- r = s.serialize(t);
- assertEquals("<object xmlns='http://www.ibm.com/2013/Juneau' xmlns:p1='http://p1' xmlns:bar='http://bar' xmlns:baz='http://baz' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><p1:f1>1</p1:f1><bar:f2>2</bar:f2><p1:f3>3</p1:f3><baz:f4>4</baz:f4></object>", r);
- assertTrue(t.equals(p.parse(r, T3.class)));
- validateXml(t, s);
- }
-
- //====================================================================================================
- // Namespace on package, no namespace on class, element name on class.
- //====================================================================================================
- @Test
- public void testNsOnPackageNoNsOnClassElementNameOnClass() throws Exception {
- XmlSerializer s = new XmlSerializer.SimpleSq().setProperty(XML_autoDetectNamespaces, false);
- XmlParser p = XmlParser.DEFAULT;
-
- T4 t = new T4();
- String r = s.serialize(t);
- assertEquals("<T4><f1>1</f1><f2>2</f2><f3>3</f3><f4>4</f4></T4>", r);
- assertTrue(t.equals(p.parse(r, T4.class)));
-
- s.setProperty(XML_enableNamespaces, true).setProperty(XML_addNamespaceUrisToRoot, false);
- r = s.serialize(t);
- assertEquals("<p1:T4><p1:f1>1</p1:f1><bar:f2>2</bar:f2><p1:f3>3</p1:f3><baz:f4>4</baz:f4></p1:T4>", r);
-
- // Add namespace URIs to root, but don't auto-detect.
- // Only xsi should be added to root.
- s.setProperty(XML_addNamespaceUrisToRoot, true);
- r = s.serialize(t);
- assertEquals("<p1:T4 xmlns='http://www.ibm.com/2013/Juneau' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><p1:f1>1</p1:f1><bar:f2>2</bar:f2><p1:f3>3</p1:f3><baz:f4>4</baz:f4></p1:T4>", r);
-
- // Manually set namespaces
- s.setProperty(XML_namespaces,
- new Namespace[] {
- NamespaceFactory.get("foo","http://foo"),
- NamespaceFactory.get("bar","http://bar"),
- NamespaceFactory.get("baz","http://baz"),
- NamespaceFactory.get("p1","http://p1")
- }
- );
- r = s.serialize(t);
- assertEquals("<p1:T4 xmlns='http://www.ibm.com/2013/Juneau' xmlns:foo='http://foo' xmlns:bar='http://bar' xmlns:baz='http://baz' xmlns:p1='http://p1' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><p1:f1>1</p1:f1><bar:f2>2</bar:f2><p1:f3>3</p1:f3><baz:f4>4</baz:f4></p1:T4>", r);
- assertTrue(t.equals(p.parse(r, T4.class)));
- validateXml(t, s);
-
- // Auto-detect namespaces.
- s = new XmlSerializer.SimpleSq().setProperty(XML_autoDetectNamespaces, true);
- r = s.serialize(t);
- assertEquals("<T4><f1>1</f1><f2>2</f2><f3>3</f3><f4>4</f4></T4>", r);
-
- s.setProperty(XML_addNamespaceUrisToRoot, true);
- r = s.serialize(t);
- assertEquals("<T4><f1>1</f1><f2>2</f2><f3>3</f3><f4>4</f4></T4>", r);
-
- s.setProperty(XML_enableNamespaces, true);
- r = s.serialize(t);
- assertEquals("<p1:T4 xmlns='http://www.ibm.com/2013/Juneau' xmlns:p1='http://p1' xmlns:bar='http://bar' xmlns:baz='http://baz' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><p1:f1>1</p1:f1><bar:f2>2</bar:f2><p1:f3>3</p1:f3><baz:f4>4</baz:f4></p1:T4>", r);
- assertTrue(t.equals(p.parse(r, T4.class)));
- validateXml(t, s);
- }
-
- //====================================================================================================
- // Namespace on package, namespace on class, element name on class.
- //====================================================================================================
- @Test
- public void testNsOnPackageNsOnClassElementNameOnClass() throws Exception {
- XmlSerializer s = new XmlSerializer.SimpleSq();
- XmlParser p = XmlParser.DEFAULT;
-
- T5 t = new T5();
- String r = s.serialize(t);
- assertEquals("<T5><f1>1</f1><f2>2</f2><f3>3</f3><f4>4</f4></T5>", r);
- assertTrue(t.equals(p.parse(r, T5.class)));
- validateXml(t, s);
-
- s.setProperty(XML_enableNamespaces, true).setProperty(XML_addNamespaceUrisToRoot, false).setProperty(XML_autoDetectNamespaces, false);
- r = s.serialize(t);
- assertEquals("<foo:T5><foo:f1>1</foo:f1><bar:f2>2</bar:f2><foo:f3>3</foo:f3><baz:f4>4</baz:f4></foo:T5>", r);
-
- // Add namespace URIs to root, but don't auto-detect.
- // Only xsi should be added to root.
- s.setProperty(XML_addNamespaceUrisToRoot, true);
- r = s.serialize(t);
- assertEquals("<foo:T5 xmlns='http://www.ibm.com/2013/Juneau' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><foo:f1>1</foo:f1><bar:f2>2</bar:f2><foo:f3>3</foo:f3><baz:f4>4</baz:f4></foo:T5>", r);
-
- // Manually set namespaces
- s.setProperty(XML_namespaces,
- new Namespace[] {
- NamespaceFactory.get("foo","http://foo"),
- NamespaceFactory.get("bar","http://bar"),
- NamespaceFactory.get("baz","http://baz")
- }
- );
- r = s.serialize(t);
- assertEquals("<foo:T5 xmlns='http://www.ibm.com/2013/Juneau' xmlns:foo='http://foo' xmlns:bar='http://bar' xmlns:baz='http://baz' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><foo:f1>1</foo:f1><bar:f2>2</bar:f2><foo:f3>3</foo:f3><baz:f4>4</baz:f4></foo:T5>", r);
- assertTrue(t.equals(p.parse(r, T5.class)));
- validateXml(t, s);
-
- // Auto-detect namespaces.
- s = new XmlSerializer.SimpleSq().setProperty(XML_autoDetectNamespaces, true);
- r = s.serialize(t);
- assertEquals("<T5><f1>1</f1><f2>2</f2><f3>3</f3><f4>4</f4></T5>", r);
- validateXml(t, s);
-
- s.setProperty(XML_addNamespaceUrisToRoot, true);
- r = s.serialize(t);
- assertEquals("<T5><f1>1</f1><f2>2</f2><f3>3</f3><f4>4</f4></T5>", r);
- validateXml(t, s);
-
- s.setProperty(XML_enableNamespaces, true);
- r = s.serialize(t);
- assertEquals("<foo:T5 xmlns='http://www.ibm.com/2013/Juneau' xmlns:foo='http://foo' xmlns:bar='http://bar' xmlns:baz='http://baz' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><foo:f1>1</foo:f1><bar:f2>2</bar:f2><foo:f3>3</foo:f3><baz:f4>4</baz:f4></foo:T5>", r);
- assertTrue(t.equals(p.parse(r, T5.class)));
- validateXml(t, s);
- }
-
- //====================================================================================================
- // Namespace on package, namespace on class, no element name on class.
- //====================================================================================================
- @Test
- public void testNsOnPackageNsOnClassNoElementNameOnClass() throws Exception {
- XmlSerializer s = new XmlSerializer.SimpleSq().setProperty(XML_autoDetectNamespaces, false);
- XmlParser p = XmlParser.DEFAULT;
-
- T6 t = new T6();
- String r = s.serialize(t);
- assertEquals("<object><f1>1</f1><f2>2</f2><f3>3</f3><f4>4</f4></object>", r);
- assertTrue(t.equals(p.parse(r, T6.class)));
-
- s.setProperty(XML_enableNamespaces, true).setProperty(XML_addNamespaceUrisToRoot, false);
- r = s.serialize(t);
- assertEquals("<object><foo:f1>1</foo:f1><bar:f2>2</bar:f2><foo:f3>3</foo:f3><baz:f4>4</baz:f4></object>", r);
-
- // Add namespace URIs to root, but don't auto-detect.
- // Only xsi should be added to root.
- s.setProperty(XML_addNamespaceUrisToRoot, true).setProperty(XML_autoDetectNamespaces, false);
- r = s.serialize(t);
- assertEquals("<object xmlns='http://www.ibm.com/2013/Juneau' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><foo:f1>1</foo:f1><bar:f2>2</bar:f2><foo:f3>3</foo:f3><baz:f4>4</baz:f4></object>", r);
-
- // Manually set namespaces
- s.setProperty(XML_namespaces,
- new Namespace[] {
- NamespaceFactory.get("foo","http://foo"),
- NamespaceFactory.get("bar","http://bar"),
- NamespaceFactory.get("baz","http://baz")
- }
- );
- r = s.serialize(t);
- assertEquals("<object xmlns='http://www.ibm.com/2013/Juneau' xmlns:foo='http://foo' xmlns:bar='http://bar' xmlns:baz='http://baz' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><foo:f1>1</foo:f1><bar:f2>2</bar:f2><foo:f3>3</foo:f3><baz:f4>4</baz:f4></object>", r);
- assertTrue(t.equals(p.parse(r, T6.class)));
- validateXml(t, s);
-
- // Auto-detect namespaces.
- s = new XmlSerializer.SimpleSq().setProperty(XML_autoDetectNamespaces, true);
- r = s.serialize(t);
- assertEquals("<object><f1>1</f1><f2>2</f2><f3>3</f3><f4>4</f4></object>", r);
- validateXml(t, s);
-
- s.setProperty(XML_addNamespaceUrisToRoot, true);
- r = s.serialize(t);
- assertEquals("<object><f1>1</f1><f2>2</f2><f3>3</f3><f4>4</f4></object>", r);
- validateXml(t, s);
-
- s.setProperty(XML_enableNamespaces, true);
- r = s.serialize(t);
- assertEquals("<object xmlns='http://www.ibm.com/2013/Juneau' xmlns:foo='http://foo' xmlns:bar='http://bar' xmlns:baz='http://baz' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><foo:f1>1</foo:f1><bar:f2>2</bar:f2><foo:f3>3</foo:f3><baz:f4>4</baz:f4></object>", r);
- assertTrue(t.equals(p.parse(r, T6.class)));
- validateXml(t, s);
- }
-
- //====================================================================================================
- // Combination of namespaces and overridden bean property names.
- //====================================================================================================
- @Test
- public void testComboOfNsAndOverriddenBeanPropertyNames() throws Exception {
- XmlSerializer s = new XmlSerializer.SimpleSq().setProperty(XML_autoDetectNamespaces, false);
- XmlParser p = XmlParser.DEFAULT;
-
- T7 t = new T7();
- String r = s.serialize(t);
- assertEquals("<object><g1>1</g1><g2>2</g2><g3>3</g3><g4>4</g4></object>", r);
- assertTrue(t.equals(p.parse(r, T7.class)));
-
- s.setProperty(XML_enableNamespaces, true).setProperty(XML_addNamespaceUrisToRoot, false);
- r = s.serialize(t);
- assertEquals("<object><p1:g1>1</p1:g1><bar:g2>2</bar:g2><p1:g3>3</p1:g3><baz:g4>4</baz:g4></object>", r);
-
- // Add namespace URIs to root, but don't auto-detect.
- // Only xsi should be added to root.
- s.setProperty(XML_addNamespaceUrisToRoot, true).setProperty(XML_autoDetectNamespaces, false);
- r = s.serialize(t);
- assertEquals("<object xmlns='http://www.ibm.com/2013/Juneau' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><p1:g1>1</p1:g1><bar:g2>2</bar:g2><p1:g3>3</p1:g3><baz:g4>4</baz:g4></object>", r);
-
- // Manually set namespaces
- s.setProperty(XML_namespaces,
- new Namespace[] {
- NamespaceFactory.get("foo","http://foo"),
- NamespaceFactory.get("bar","http://bar"),
- NamespaceFactory.get("baz","http://baz"),
- NamespaceFactory.get("p1","http://p1")
- }
- );
- r = s.serialize(t);
- assertEquals("<object xmlns='http://www.ibm.com/2013/Juneau' xmlns:foo='http://foo' xmlns:bar='http://bar' xmlns:baz='http://baz' xmlns:p1='http://p1' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><p1:g1>1</p1:g1><bar:g2>2</bar:g2><p1:g3>3</p1:g3><baz:g4>4</baz:g4></object>", r);
- assertTrue(t.equals(p.parse(r, T7.class)));
-
- // Auto-detect namespaces.
- s = new XmlSerializer.SimpleSq().setProperty(XML_autoDetectNamespaces, true);
- r = s.serialize(t);
- assertEquals("<object><g1>1</g1><g2>2</g2><g3>3</g3><g4>4</g4></object>", r);
-
- s.setProperty(XML_enableNamespaces, false);
- r = s.serialize(t);
- assertEquals("<object><g1>1</g1><g2>2</g2><g3>3</g3><g4>4</g4></object>", r);
-
- s.setProperty(XML_enableNamespaces, true);
- r = s.serialize(t);
- assertEquals("<object xmlns='http://www.ibm.com/2013/Juneau' xmlns:p1='http://p1' xmlns:bar='http://bar' xmlns:baz='http://baz' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><p1:g1>1</p1:g1><bar:g2>2</bar:g2><p1:g3>3</p1:g3><baz:g4>4</baz:g4></object>", r);
- assertTrue(t.equals(p.parse(r, T7.class)));
- validateXml(t, s);
- }
-
- //====================================================================================================
- // @XmlNs annotation
- //====================================================================================================
- @Test
- public void testXmlNsAnnotation() throws Exception {
- XmlSerializer s = new XmlSerializer.SimpleSq().setProperty(XML_autoDetectNamespaces, false);
- XmlParser p = XmlParser.DEFAULT;
-
- T8 t = new T8();
- String r = s.serialize(t);
- assertEquals("<object><f1>1</f1><f2>2</f2><f3>3</f3><f4>4</f4></object>", r);
- assertTrue(t.equals(p.parse(r, T8.class)));
-
- s.setProperty(XML_enableNamespaces, true).setProperty(XML_addNamespaceUrisToRoot, false).setProperty(XML_autoDetectNamespaces, false);
- r = s.serialize(t);
- assertEquals("<object><p2:f1>1</p2:f1><p1:f2>2</p1:f2><c1:f3>3</c1:f3><f1:f4>4</f1:f4></object>", r);
-
- // Add namespace URIs to root, but don't auto-detect.
- // Only xsi should be added to root.
- s.setProperty(XML_addNamespaceUrisToRoot, true);
- r = s.serialize(t);
- assertEquals("<object xmlns='http://www.ibm.com/2013/Juneau' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><p2:f1>1</p2:f1><p1:f2>2</p1:f2><c1:f3>3</c1:f3><f1:f4>4</f1:f4></object>", r);
-
- // Manually set namespaces
- s.setProperty(XML_namespaces,
- new Namespace[] {
- NamespaceFactory.get("foo","http://foo"),
- NamespaceFactory.get("bar","http://bar"),
- NamespaceFactory.get("baz","http://baz")
- }
- );
- r = s.serialize(t);
- assertEquals("<object xmlns='http://www.ibm.com/2013/Juneau' xmlns:foo='http://foo' xmlns:bar='http://bar' xmlns:baz='http://baz' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><p2:f1>1</p2:f1><p1:f2>2</p1:f2><c1:f3>3</c1:f3><f1:f4>4</f1:f4></object>", r);
-
- // Auto-detect namespaces.
- s = new XmlSerializer.SimpleSq().setProperty(XML_autoDetectNamespaces, true);
- r = s.serialize(t);
- assertEquals("<object><f1>1</f1><f2>2</f2><f3>3</f3><f4>4</f4></object>", r);
- assertTrue(t.equals(p.parse(r, T8.class)));
- validateXml(t, s);
-
- s.setProperty(XML_addNamespaceUrisToRoot, true);
- r = s.serialize(t);
- assertEquals("<object><f1>1</f1><f2>2</f2><f3>3</f3><f4>4</f4></object>", r);
- validateXml(t, s);
-
- s.setProperty(XML_enableNamespaces, true);
- r = s.serialize(t);
- assertEquals("<object xmlns='http://www.ibm.com/2013/Juneau' xmlns:p2='http://p2' xmlns:p1='http://p1' xmlns:c1='http://c1' xmlns:f1='http://f1' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><p2:f1>1</p2:f1><p1:f2>2</p1:f2><c1:f3>3</c1:f3><f1:f4>4</f1:f4></object>", r);
- assertTrue(t.equals(p.parse(r, T8.class)));
- validateXml(t, s);
- }
-
- //====================================================================================================
- // @Xml.ns on package, @Xml.nsUri not on package but in @XmlNs.
- //====================================================================================================
- @Test
- public void testXmlNsOnPackageNsUriInXmlNs() throws Exception {
- XmlSerializer s = new XmlSerializer.SimpleSq().setProperty(XML_autoDetectNamespaces, false);
- XmlParser p = XmlParser.DEFAULT;
-
- T9 t = new T9();
- String r = s.serialize(t);
- assertEquals("<object><f1>1</f1></object>", r);
- assertTrue(t.equals(p.parse(r, T9.class)));
-
- s.setProperty(XML_enableNamespaces, true).setProperty(XML_autoDetectNamespaces, false).setProperty(XML_addNamespaceUrisToRoot, false);
- r = s.serialize(t);
- assertEquals("<object><p1:f1>1</p1:f1></object>", r);
-
- // Add namespace URIs to root, but don't auto-detect.
- // Only xsi should be added to root.
- s.setProperty(XML_addNamespaceUrisToRoot, true);
- r = s.serialize(t);
- assertEquals("<object xmlns='http://www.ibm.com/2013/Juneau' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><p1:f1>1</p1:f1></object>", r);
-
- // Manually set namespaces
- s.setProperty(XML_namespaces,
- new Namespace[] {
- NamespaceFactory.get("foo","http://foo"),
- NamespaceFactory.get("bar","http://bar"),
- NamespaceFactory.get("baz","http://baz")
- }
- );
- r = s.serialize(t);
- assertEquals("<object xmlns='http://www.ibm.com/2013/Juneau' xmlns:foo='http://foo' xmlns:bar='http://bar' xmlns:baz='http://baz' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><p1:f1>1</p1:f1></object>", r);
-
- // Auto-detect namespaces.
- s = new XmlSerializer.SimpleSq().setProperty(XML_autoDetectNamespaces, true);
- r = s.serialize(t);
- assertEquals("<object><f1>1</f1></object>", r);
- assertTrue(t.equals(p.parse(r, T9.class)));
- validateXml(t, s);
-
- s.setProperty(XML_addNamespaceUrisToRoot, true);
- r = s.serialize(t);
- assertEquals("<object><f1>1</f1></object>", r);
- validateXml(t, s);
-
- s.setProperty(XML_enableNamespaces, true);
- r = s.serialize(t);
- assertEquals("<object xmlns='http://www.ibm.com/2013/Juneau' xmlns:p1='http://p1' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'><p1:f1>1</p1:f1></object>", r);
- assertTrue(t.equals(p.parse(r, T9.class)));
- validateXml(t, s);
- }
-
- //====================================================================================================
- // @Xml.format=ATTR
- //====================================================================================================
- @Test
- public void testXmlAttrs() throws Exception {
- XmlSerializer s = new XmlSerializer.SimpleSq();
- XmlParser p = XmlParser.DEFAULT;
- String r;
-
- Q t = new Q();
- t.f1 = new URL("http://xf1");
- t.f2 = "xf2";
- t.f3 = "xf3";
- r = s.serialize(t);
- assertEquals("<object f1='http://xf1' f2='xf2' x3='xf3'/>", r);
- t = p.parse(r, Q.class);
- assertEquals("http://xf1", t.f1.toString());
- assertEquals("xf2", t.f2);
- assertEquals("xf3", t.f3);
-
- s.setProperty(XML_enableNamespaces, true).setProperty(XML_addNamespaceUrisToRoot, true).setProperty(XML_autoDetectNamespaces, true);
- r = s.serialize(t);
- assertEquals("<object xmlns='http://www.ibm.com/2013/Juneau' xmlns:ns='http://ns' xmlns:nsf1='http://nsf1' xmlns:nsf3='http://nsf3' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' nsf1:f1='http://xf1' ns:f2='xf2' nsf3:x3='xf3'/>", r);
- validateXml(t, s);
-
- t = p.parse(r, Q.class);
- assertEquals("http://xf1", t.f1.toString());
- assertEquals("xf2", t.f2);
- assertEquals("xf3", t.f3);
- }
-
- @Xml(prefix="ns", namespace="http://ns")
- public static class Q {
-
- @Xml(format=ATTR, prefix="nsf1", namespace="http://nsf1")
- public URL f1;
-
- @Xml(format=ATTR)
- public String f2;
-
- @BeanProperty(name="x3")
- @Xml(format=ATTR, prefix="nsf3", namespace="http://nsf3")
- public String f3;
-
- public Q() throws Exception {
- f1 = new URL("http://f1");
- f2 = "f2";
- f3 = "f3";
- }
- }
-}
\ No newline at end of file
[31/44] incubator-juneau git commit: Rename CT_* testcases.
Posted by ja...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau/src/test/java/org/apache/juneau/CT_BeanConfig.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau/src/test/java/org/apache/juneau/CT_BeanConfig.java b/org.apache.juneau/src/test/java/org/apache/juneau/CT_BeanConfig.java
deleted file mode 100755
index eb99e97..0000000
--- a/org.apache.juneau/src/test/java/org/apache/juneau/CT_BeanConfig.java
+++ /dev/null
@@ -1,849 +0,0 @@
-/***************************************************************************************************************************
- * 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.juneau;
-
-import static org.apache.juneau.BeanContext.*;
-import static org.junit.Assert.*;
-
-import java.io.*;
-import java.lang.reflect.*;
-import java.util.*;
-
-import org.apache.juneau.annotation.*;
-import org.apache.juneau.json.*;
-import org.apache.juneau.parser.*;
-import org.apache.juneau.transform.*;
-import org.junit.*;
-
-@SuppressWarnings({"unchecked","rawtypes","serial"})
-public class CT_BeanConfig {
-
- //====================================================================================================
- // testBasic
- //====================================================================================================
- @Test
- public void testBasic() throws Exception {
-
- BeanContext bc = BeanContext.DEFAULT;
-
- Person p1 = new Person();
- p1.setName("John Doe");
- p1.setAge(25);
-
- Address a = new Address("101 Main St.", "Las Vegas", "NV", "89101");
- AddressablePerson p2 = new AddressablePerson();
- p2.setName("Jane Doe");
- p2.setAge(21);
- p2.setAddress(a);
-
- // setup the reference results
- Map m1 = new LinkedHashMap();
- m1.put("name", p1.getName());
- m1.put("age", new Integer(p1.getAge()));
-
- Map m2 = new LinkedHashMap();
- m2.put("street", a.getStreet());
- m2.put("city", a.getCity());
- m2.put("state", a.getState());
- m2.put("zip", a.getZip());
-
- Map m3 = new LinkedHashMap();
- m3.put("name", p2.getName());
- m3.put("age", new Integer(p2.getAge()));
- m3.put("address", p2.getAddress());
-
- Map pm1 = bc.forBean(p1);
-
- if (pm1.size() != m1.size())
- fail("Bean Map size failed for: " + p1 + " / " + pm1.size()+ " / " + m1.size());
-
- if (!pm1.keySet().equals(m1.keySet()))
- fail("Bean Map key set equality failed for: " + p1 + " / " + pm1.keySet() + " / " + m1.keySet());
-
- if (!m1.keySet().equals(pm1.keySet()))
- fail("Bean Map key set reverse equality failed for: " + p1 + " / " + pm1.keySet() + " / " + m1.keySet());
-
- if (!pm1.equals(m1))
- fail("Bean Map equality failed for: " + p1 + " / " + pm1 + " / " + m1);
-
- if (!m1.equals(pm1))
- fail("Bean Map reverse equality failed for: " + p1 + " / " + pm1 + " / " + m1);
-
- BeanMap bm1 = null;
- try {
- bm1 = bc.newBeanMap(Address.class);
- fail("Address returned as a new bean type, but shouldn't be since it doesn't have a default constructor.");
- } catch (BeanRuntimeException e) {
- // Good.
- }
- bm1 = bc.forBean(new Address("street", "city", "state", "zip"));
-
- BeanMap bm2 = bc.newBeanMap(java.lang.Integer.class);
- if (bm2 != null)
- fail("java.lang.Integer incorrectly desingated as bean type.");
-
- BeanMap bm3 = bc.newBeanMap(java.lang.Class.class);
- if (bm3 != null)
- fail("java.lang.Class incorrectly desingated as bean type.");
-
- Map m4 = bm1;
- if (m4.keySet().size() != m2.size())
- fail("Bean Adapter map's key set has wrong size: " + a + " / " + m4.keySet().size() + " / " + m2.size());
-
- Iterator iter = m4.keySet().iterator();
- Set temp = new HashSet();
- int count = 0;
- while (iter.hasNext()) {
- temp.add(iter.next());
- count++;
- }
- if (count != m2.size())
- fail("Iteration count over bean adpater key set failed: " + a + " / " + count + " / " + m2.size());
-
- if (!m2.keySet().equals(temp))
- fail("Iteration over bean adpater key set failed: " + a + " / " + m4.keySet() + " / " + m2.keySet());
-
- BeanMap bm4 = bc.forBean(p2);
- if (bm4 == null) {
- fail("Failed to identify class as bean type: " + p2.getClass());
- return;
- }
-
- Map m5 = bm4;
- Set es1 = m5.entrySet();
-
- if (!es1.equals(m3.entrySet()))
- fail("Entry set equality failed: " + p2 + " / " + es1 + " / " + m3.entrySet());
-
- if (!m3.entrySet().equals(es1))
- fail("Entry set reverse equality failed: " + p2 + " / " + es1 + " / " + m3.entrySet());
-
- iter = es1.iterator();
- temp = new HashSet();
- count = 0;
- while (iter.hasNext()) {
- temp.add(iter.next());
- count++;
- }
- if (count != m3.size())
- fail("Iteration count over bean adpater entry set failed: " + a + " / " + count + " / " + m3.size());
-
- if (!m3.entrySet().equals(temp))
- fail("Iteration over bean adpater entry set failed: " + a + " / " + es1 + " / " + m3.entrySet());
- }
-
- public static class Person {
- private String name;
- private int age;
-
- public Person() {
- this.name = null;
- this.age = -1;
- }
-
- public String getName() {
- return this.name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- public int getAge() {
- return this.age;
- }
-
- public void setAge(int age) {
- this.age = age;
- }
-
- @Override /* Object */
- public String toString() {
- return ("Person(name: " + this.getName() + ", age: "
- + this.getAge() + ")");
- }
- }
-
- public static class Address {
- protected String street;
- protected String city;
- protected String state;
- protected String zip;
-
- public Address(String street, String city, String state, String zip) {
- this.street = street;
- this.city = city;
- this.state = state;
- this.zip = zip;
- }
-
- public String getStreet() {
- return this.street;
- }
-
- public String getCity() {
- return this.city;
- }
-
- public String getState() {
- return this.state;
- }
-
- public String getZip() {
- return this.zip;
- }
-
- @Override /* Object */
- public boolean equals(Object o) {
- if (o == null)
- return false;
- if (this == o)
- return true;
- if (this.getClass() != o.getClass())
- return false;
- Address a = (Address) o;
-
- String v1 = this.getStreet();
- String v2 = a.getStreet();
- if ((v1 == null) ? (v2 != null) : (!v1.equals(v2)))
- return false;
-
- v1 = this.getCity();
- v2 = a.getCity();
- if ((v1 == null) ? (v2 != null) : (!v1.equals(v2)))
- return false;
-
- v1 = this.getState();
- v2 = a.getState();
- if ((v1 == null) ? (v2 != null) : (!v1.equals(v2)))
- return false;
-
- v1 = this.getZip();
- v2 = a.getZip();
- return ((v1 == null) ? (v2 == null) : (v1.equals(v2)));
- }
-
- @Override /* Object */
- public int hashCode() {
- int code = 0;
- if (this.street != null)
- code ^= this.street.hashCode();
- if (this.city != null)
- code ^= this.city.hashCode();
- if (this.state != null)
- code ^= this.state.hashCode();
- if (this.zip != null)
- code ^= this.zip.hashCode();
- return code;
- }
-
- @Override /* Object */
- public String toString() {
- return ("Address(street: " + this.getStreet() + ", city: "
- + this.getCity() + ", state: " + this.getState()
- + ", zip: " + this.getZip() + ")");
- }
- }
-
- public static class AddressablePerson extends Person {
- private Address address;
-
- public AddressablePerson() {
- this.address = null;
- }
-
- public Address getAddress() {
- return this.address;
- }
-
- public void setAddress(Address addr) {
- this.address = addr;
- }
-
- @Override /* Object */
- public String toString() {
- return super.toString() + "@" + this.address;
- }
- }
-
- //====================================================================================================
- // Exhaustive test of BeanContext.convertToType();
- //====================================================================================================
- @Test
- public void testBeanContextConvertToType() throws Exception {
- BeanContext bc = BeanContext.DEFAULT;
- Object o;
-
- // Primitive nulls.
- o = null;
- assertEquals(new Integer(0), bc.convertToType(o, Integer.TYPE));
- assertEquals(new Short((short) 0), bc.convertToType(o, Short.TYPE));
- assertEquals(new Long(0), bc.convertToType(o, Long.TYPE));
- assertEquals(new Float(0), bc.convertToType(o, Float.TYPE));
- assertEquals(new Double(0), bc.convertToType(o, Double.TYPE));
- assertEquals(new Byte((byte) 0), bc.convertToType(o, Byte.TYPE));
- assertEquals(new Character((char) 0), bc.convertToType(o, Character.TYPE));
- assertEquals(Boolean.FALSE, bc.convertToType(o, Boolean.TYPE));
-
- o = "1";
-
- assertEquals(new Integer(1), bc.convertToType(o, Integer.class));
- assertEquals(new Short((short) 1), bc.convertToType(o, Short.class));
- assertEquals(new Long(1), bc.convertToType(o, Long.class));
- assertEquals(new Float(1), bc.convertToType(o, Float.class));
- assertEquals(new Double(1), bc.convertToType(o, Double.class));
- assertEquals(new Byte((byte) 1), bc.convertToType(o, Byte.class));
- assertEquals(new Character('1'), bc.convertToType(o, Character.class));
- assertEquals(Boolean.FALSE, bc.convertToType(o, Boolean.class));
-
- assertEquals(new Integer(1), bc.convertToType(o, Integer.TYPE));
- assertEquals(new Short((short) 1), bc.convertToType(o, Short.TYPE));
- assertEquals(new Long(1), bc.convertToType(o, Long.TYPE));
- assertEquals(new Float(1), bc.convertToType(o, Float.TYPE));
- assertEquals(new Double(1), bc.convertToType(o, Double.TYPE));
- assertEquals(new Byte((byte) 1), bc.convertToType(o, Byte.TYPE));
- assertEquals(new Character('1'), bc.convertToType(o, Character.TYPE));
- assertEquals(Boolean.FALSE, bc.convertToType(o, Boolean.TYPE));
-
- o = new Integer(1);
-
- assertEquals(new Integer(1), bc.convertToType(o, Integer.TYPE));
- assertEquals(new Short((short) 1), bc.convertToType(o, Short.TYPE));
- assertEquals(new Long(1), bc.convertToType(o, Long.TYPE));
- assertEquals(new Float(1), bc.convertToType(o, Float.TYPE));
- assertEquals(new Double(1), bc.convertToType(o, Double.TYPE));
- assertEquals(new Byte((byte) 1), bc.convertToType(o, Byte.TYPE));
- assertEquals(new Character('1'), bc.convertToType(o, Character.TYPE));
- assertEquals(Boolean.TRUE, bc.convertToType(o, Boolean.TYPE));
-
- o = new Integer(0);
- assertEquals(Boolean.FALSE, bc.convertToType(o, Boolean.TYPE));
-
- // Bean
- o = "{name:'x',age:123}";
- assertEquals("x", bc.convertToType(o, Person.class).getName());
- assertEquals(123, bc.convertToType(o, Person.class).getAge());
-
- // Read-only bean
- o = "{name:'x',age:123}";
- assertEquals("x", bc.convertToType(o, ReadOnlyPerson.class).getName());
- assertEquals(123, bc.convertToType(o, ReadOnlyPerson.class).getAge());
-
- // Class with forString(String) method.
- o = UUID.randomUUID();
- assertEquals(o, bc.convertToType(o.toString(), UUID.class));
-
- // Class with Constructor(String).
- o = "xxx";
- File file = bc.convertToType(o, File.class);
- assertEquals("xxx", file.getName());
-
- // List of ints to array
- o = new ObjectList(1, 2, 3);
- assertEquals(1, bc.convertToType(o, int[].class)[0]);
-
- // List of beans to array
- o = new ObjectList(new ReadOnlyPerson("x", 123));
- assertEquals("x", bc.convertToType(o, ReadOnlyPerson[].class)[0].getName());
-
- // Multi-dimensional array of beans.
- o = new ObjectList().append(new ObjectList(new ReadOnlyPerson("x", 123)));
- assertEquals("x", bc.convertToType(o, ReadOnlyPerson[][].class)[0][0].getName());
-
- // Array of strings to array of ints
- o = new String[] { "1", "2", "3" };
- assertEquals(new Integer(1), bc.convertToType(o, Integer[].class)[0]);
- assertEquals(1, bc.convertToType(o, int[].class)[0]);
-
- // Array to list
- o = new Integer[] { 1, 2, 3 };
- assertEquals(new Integer(1), bc.convertToType(o, LinkedList.class).get(0));
-
- // HashMap to TreeMap
- o = new HashMap<Integer, String>() {{ put(1, "foo"); }};
- assertEquals("foo", bc.convertToType(o, TreeMap.class).firstEntry().getValue());
-
- // String to TreeMap
- o = "{1:'foo'}";
- assertEquals("foo", bc.convertToType(o, TreeMap.class).firstEntry().getValue());
-
- // String to generic Map
- assertEquals("foo", bc.convertToType(o, Map.class).values().iterator().next());
-
- // Array to String
- o = new Object[] { "a", 1, false };
- assertEquals("['a',1,false]", bc.convertToType(o, String.class));
- o = new Object[][] { { "a", 1, false } };
- assertEquals("[['a',1,false]]", bc.convertToType(o, String.class));
-
- }
-
- //====================================================================================================
- // Test properties set through a constructor.
- //====================================================================================================
- @Test
- public void testReadOnlyProperties() throws Exception {
- BeanContext bc = BeanContext.DEFAULT;
- Object o;
-
- // Bean to String
- o = new ReadOnlyPerson("x", 123);
- assertEquals("{name:'x',age:123}", bc.convertToType(o, String.class));
-
- // List of Maps to array of beans.
- o = new ObjectList(new ObjectMap("{name:'x',age:1}"), new ObjectMap("{name:'y',age:2}"));
- assertEquals(1, bc.convertToType(o, ReadOnlyPerson[].class)[0].getAge());
- }
-
-
- @Bean(properties={"name","age"})
- public static class ReadOnlyPerson {
- private final String name;
- private final int age;
-
- @BeanConstructor(properties = { "name", "age" })
- public ReadOnlyPerson(String name, int age) {
- this.name = name;
- this.age = age;
- }
-
- public String getName() {
- return this.name;
- }
-
- public int getAge() {
- return this.age;
- }
-
- @Override /* Object */
- public String toString() {
- return "toString():name=" + name + ",age=" + age;
- }
- }
-
- //====================================================================================================
- // testEnums
- //====================================================================================================
- @Test
- public void testEnums() throws Exception {
- BeanContext bc = BeanContext.DEFAULT;
- Object o;
-
- // Enum
- o = "ENUM2";
- assertEquals(TestEnum.ENUM2, bc.convertToType(o, TestEnum.class));
- assertEquals("ENUM2", bc.convertToType(TestEnum.ENUM2, String.class));
-
- // Array of enums
- o = new String[] { "ENUM2" };
- assertEquals(TestEnum.ENUM2, bc.convertToType(o, TestEnum[].class)[0]);
- }
-
- public enum TestEnum {
- ENUM1, ENUM2, ENUM3
- }
-
- //====================================================================================================
- // testProxyHandler
- //====================================================================================================
- @Test
- public void testProxyHandler() throws Exception {
- BeanContext bc = ContextFactory.create().setClassLoader(A.class.getClassLoader()).getBeanContext();
-
- A f1 = (A) Proxy.newProxyInstance(this.getClass()
- .getClassLoader(), new Class[] { A.class },
- new AHandler());
-
- BeanMap bm1 = bc.forBean(f1);
- if (bm1 == null) {
- fail("Failed to obtain bean adapter for proxy: " + f1);
- return;
- }
-
- BeanMap bm2 = bc.newBeanMap(A.class);
- if (bm2 == null) {
- fail("Failed to create dynamic proxy bean for interface: " + A.class.getName());
- return;
- }
- bm2.put("a", "Hello");
- bm2.put("b", new Integer(50));
- f1.setA("Hello");
- f1.setB(50);
-
- if (!bm2.get("a").equals("Hello"))
- fail("Failed to set string property 'a' on dynamic proxy bean. " + bm2);
-
- if (!bm2.get("b").equals(new Integer(50)))
- fail("Failed to set string property 'b' on dynamic proxy bean. " + bm2);
-
- if (!bm1.equals(bm2))
- fail("Failed equality test of dynamic proxies beans: " + bm1 + " / " + bm2);
-
- if (!bm2.equals(bm1))
- fail("Failed reverse equality test of dynamic proxies beans: " + bm1 + " / " + bm2);
- }
-
- public static interface A {
- String getA();
-
- void setA(String a);
-
- int getB();
-
- void setB(int b);
- }
-
- public static class AHandler implements InvocationHandler {
- private Map map;
-
- public AHandler() {
- this.map = new HashMap();
- this.map.put("a", "");
- this.map.put("b", new Integer(0));
- }
-
- @Override /* InvocationHandler */
- public Object invoke(Object proxy, Method method, Object[] args)
- throws Throwable {
- String methodName = method.getName();
- if (methodName.equals("getA")) {
- return this.map.get("a");
- }
- if (methodName.equals("setA")) {
- this.map.put("a", args[0]);
- return null;
- }
- if (methodName.equals("getB")) {
- return this.map.get("b");
- }
- if (methodName.equals("setB")) {
- this.map.put("b", args[0]);
- return null;
- }
- if (methodName.equals("toString")) {
- return this.map.toString();
- }
- return null;
- }
- }
-
- //====================================================================================================
- // testGetClassMetaFromString
- //====================================================================================================
- @Test
- public void testGetClassMetaFromString() throws Exception {
- BeanContext bc = BeanContext.DEFAULT;
- assertEquals("java.lang.String[]", bc.getClassMetaFromString("java.lang.String[]").toString());
- assertEquals("java.lang.String[]", bc.getClassMetaFromString("[Ljava.lang.String;").toString());
- assertEquals("java.lang.String[][]", bc.getClassMetaFromString("java.lang.String[][]").toString());
- assertEquals("java.lang.String[][]", bc.getClassMetaFromString("[[Ljava.lang.String;").toString());
- assertEquals("boolean", bc.getClassMetaFromString("boolean").toString());
- }
-
- //====================================================================================================
- // testFluentStyleSetters
- //====================================================================================================
- @Test
- public void testFluentStyleSetters() throws Exception {
- B2 t = new B2().init();
- BeanMap m = BeanContext.DEFAULT.forBean(t);
- m.put("f1", 2);
- assertEquals(t.f1, 2);
- }
-
- public static class B {
- int f1;
- public int getF1() { return f1; }
- public B setF1(int f1) { this.f1 = f1; return this; }
- }
-
- public static class B2 extends B {
- @Override /* B */
- public B2 setF1(int f1) { this.f1 = f1; return this; }
- public B2 init() { this.f1 = 1; return this;}
- }
-
- //====================================================================================================
- // testClassMetaCaching
- //====================================================================================================
- @Test
- public void testClassMetaCaching() throws Exception {
- Parser p1, p2;
-
- p1 = new JsonParser();
- p2 = new JsonParser();
- assertSameCache(p1, p2);
-
- p1.setProperty(BEAN_beansRequireDefaultConstructor, true);
- assertDifferentCache(p1, p2);
- p2.setProperty(BEAN_beansRequireDefaultConstructor, true);
- assertSameCache(p1, p2);
-
- p1.setProperty(BEAN_beansRequireSerializable, true);
- assertDifferentCache(p1, p2);
- p2.setProperty(BEAN_beansRequireSerializable, true);
- assertSameCache(p1, p2);
-
- p1.setProperty(BEAN_beansRequireSettersForGetters, true);
- assertDifferentCache(p1, p2);
- p2.setProperty(BEAN_beansRequireSettersForGetters, true);
- assertSameCache(p1, p2);
-
- p1.setProperty(BEAN_beansRequireSomeProperties, false);
- assertDifferentCache(p1, p2);
- p2.setProperty(BEAN_beansRequireSomeProperties, false);
- assertSameCache(p1, p2);
-
- p1.setProperty(BEAN_beanMapPutReturnsOldValue, true);
- assertDifferentCache(p1, p2);
- p2.setProperty(BEAN_beanMapPutReturnsOldValue, true);
- assertSameCache(p1, p2);
-
- p1.setProperty(BEAN_beanConstructorVisibility, Visibility.DEFAULT);
- assertDifferentCache(p1, p2);
- p2.setProperty(BEAN_beanConstructorVisibility, Visibility.DEFAULT);
- assertSameCache(p1, p2);
- p1.setProperty(BEAN_beanConstructorVisibility, Visibility.NONE);
- assertDifferentCache(p1, p2);
- p2.setProperty(BEAN_beanConstructorVisibility, Visibility.NONE);
- assertSameCache(p1, p2);
- p1.setProperty(BEAN_beanConstructorVisibility, Visibility.PRIVATE);
- assertDifferentCache(p1, p2);
- p2.setProperty(BEAN_beanConstructorVisibility, Visibility.PRIVATE);
- assertSameCache(p1, p2);
- p1.setProperty(BEAN_beanConstructorVisibility, Visibility.PROTECTED);
- assertDifferentCache(p1, p2);
- p2.setProperty(BEAN_beanConstructorVisibility, Visibility.PROTECTED);
- assertSameCache(p1, p2);
-
- p1.setProperty(BEAN_beanClassVisibility, Visibility.DEFAULT);
- assertDifferentCache(p1, p2);
- p2.setProperty(BEAN_beanClassVisibility, Visibility.DEFAULT);
- assertSameCache(p1, p2);
- p1.setProperty(BEAN_beanClassVisibility, Visibility.NONE);
- assertDifferentCache(p1, p2);
- p2.setProperty(BEAN_beanClassVisibility, Visibility.NONE);
- assertSameCache(p1, p2);
- p1.setProperty(BEAN_beanClassVisibility, Visibility.PRIVATE);
- assertDifferentCache(p1, p2);
- p2.setProperty(BEAN_beanClassVisibility, Visibility.PRIVATE);
- assertSameCache(p1, p2);
- p1.setProperty(BEAN_beanClassVisibility, Visibility.PROTECTED);
- assertDifferentCache(p1, p2);
- p2.setProperty(BEAN_beanClassVisibility, Visibility.PROTECTED);
- assertSameCache(p1, p2);
-
- p1.setProperty(BEAN_beanFieldVisibility, Visibility.DEFAULT);
- assertDifferentCache(p1, p2);
- p2.setProperty(BEAN_beanFieldVisibility, Visibility.DEFAULT);
- assertSameCache(p1, p2);
- p1.setProperty(BEAN_beanFieldVisibility, Visibility.NONE);
- assertDifferentCache(p1, p2);
- p2.setProperty(BEAN_beanFieldVisibility, Visibility.NONE);
- assertSameCache(p1, p2);
- p1.setProperty(BEAN_beanFieldVisibility, Visibility.PRIVATE);
- assertDifferentCache(p1, p2);
- p2.setProperty(BEAN_beanFieldVisibility, Visibility.PRIVATE);
- assertSameCache(p1, p2);
- p1.setProperty(BEAN_beanFieldVisibility, Visibility.PROTECTED);
- assertDifferentCache(p1, p2);
- p2.setProperty(BEAN_beanFieldVisibility, Visibility.PROTECTED);
- assertSameCache(p1, p2);
-
- p1.setProperty(BEAN_methodVisibility, Visibility.DEFAULT);
- assertDifferentCache(p1, p2);
- p2.setProperty(BEAN_methodVisibility, Visibility.DEFAULT);
- assertSameCache(p1, p2);
- p1.setProperty(BEAN_methodVisibility, Visibility.NONE);
- assertDifferentCache(p1, p2);
- p2.setProperty(BEAN_methodVisibility, Visibility.NONE);
- assertSameCache(p1, p2);
- p1.setProperty(BEAN_methodVisibility, Visibility.PRIVATE);
- assertDifferentCache(p1, p2);
- p2.setProperty(BEAN_methodVisibility, Visibility.PRIVATE);
- assertSameCache(p1, p2);
- p1.setProperty(BEAN_methodVisibility, Visibility.PROTECTED);
- assertDifferentCache(p1, p2);
- p2.setProperty(BEAN_methodVisibility, Visibility.PROTECTED);
- assertSameCache(p1, p2);
-
- p1.setProperty(BEAN_useJavaBeanIntrospector, true);
- assertDifferentCache(p1, p2);
- p2.setProperty(BEAN_useJavaBeanIntrospector, true);
- assertSameCache(p1, p2);
-
- p1.setProperty(BEAN_useInterfaceProxies, false);
- assertDifferentCache(p1, p2);
- p2.setProperty(BEAN_useInterfaceProxies, false);
- assertSameCache(p1, p2);
-
- p1.setProperty(BEAN_ignoreUnknownBeanProperties, true);
- assertDifferentCache(p1, p2);
- p2.setProperty(BEAN_ignoreUnknownBeanProperties, true);
- assertSameCache(p1, p2);
-
- p1.setProperty(BEAN_ignoreUnknownNullBeanProperties, false);
- assertDifferentCache(p1, p2);
- p2.setProperty(BEAN_ignoreUnknownNullBeanProperties, false);
- assertSameCache(p1, p2);
-
- p1.setProperty(BEAN_ignorePropertiesWithoutSetters, false);
- assertDifferentCache(p1, p2);
- p2.setProperty(BEAN_ignorePropertiesWithoutSetters, false);
- assertSameCache(p1, p2);
-
- p1.setProperty(BEAN_ignoreInvocationExceptionsOnGetters, true);
- assertDifferentCache(p1, p2);
- p2.setProperty(BEAN_ignoreInvocationExceptionsOnGetters, true);
- assertSameCache(p1, p2);
-
- p1.setProperty(BEAN_ignoreInvocationExceptionsOnSetters, true);
- assertDifferentCache(p1, p2);
- p2.setProperty(BEAN_ignoreInvocationExceptionsOnSetters, true);
- assertSameCache(p1, p2);
-
- p1.setProperty(BEAN_notBeanPackages_add, "foo");
- assertDifferentCache(p1, p2);
- p2.setProperty(BEAN_notBeanPackages_add, "foo");
- assertSameCache(p1, p2);
- p1.setProperty(BEAN_notBeanPackages_add, "bar");
- assertDifferentCache(p1, p2);
- p2.setProperty(BEAN_notBeanPackages_add, "bar");
- assertSameCache(p1, p2);
- p1.setProperty(BEAN_notBeanPackages_add, "baz");
- p1.setProperty(BEAN_notBeanPackages_add, "bing");
- assertDifferentCache(p1, p2);
- p2.setProperty(BEAN_notBeanPackages_add, "bing");
- p2.setProperty(BEAN_notBeanPackages_add, "baz");
- assertSameCache(p1, p2);
-
- p1.setProperty(BEAN_notBeanPackages_remove, "bar");
- assertDifferentCache(p1, p2);
- p2.setProperty(BEAN_notBeanPackages_remove, "bar");
- assertSameCache(p1, p2);
-
- p1.addTransforms(DummyPojoTransformA.class);
- assertDifferentCache(p1, p2);
- p2.addTransforms(DummyPojoTransformA.class);
- assertSameCache(p1, p2);
- p1.addTransforms(DummyPojoTransformB.class,DummyPojoTransformC.class); // Order of filters is important!
- p2.addTransforms(DummyPojoTransformC.class,DummyPojoTransformB.class);
- assertDifferentCache(p1, p2);
-
- p1 = new JsonParser();
- p2 = new JsonParser();
- p1.addTransforms(DummyBeanTransformA.class);
- assertDifferentCache(p1, p2);
- p2.addTransforms(DummyBeanTransformA.class);
- assertSameCache(p1, p2);
- p1.addTransforms(DummyBeanTransformB.class,DummyBeanTransformC.class); // Order of filters is important!
- p2.addTransforms(DummyBeanTransformC.class,DummyBeanTransformB.class);
- assertDifferentCache(p1, p2);
- }
-
- public static class DummyPojoTransformA extends PojoTransform<A,ObjectMap> {}
- public static class DummyPojoTransformB extends PojoTransform<B,ObjectMap> {}
- public static class DummyPojoTransformC extends PojoTransform<C,ObjectMap> {}
- public static class DummyBeanTransformA extends BeanTransform<A> {}
- public static class DummyBeanTransformB extends BeanTransform<B> {}
- public static class DummyBeanTransformC extends BeanTransform<C> {}
- public static class C {}
-
- private void assertSameCache(Parser p1, Parser p2) {
- assertTrue(p1.getBeanContext().hasSameCache(p2.getBeanContext()));
- assertTrue(p1.getBeanContext().hashCode() == p2.getBeanContext().hashCode());
- }
-
- private void assertDifferentCache(Parser p1, Parser p2) {
- assertFalse(p1.getBeanContext().hasSameCache(p2.getBeanContext()));
- assertFalse(p1.getBeanContext().hashCode() == p2.getBeanContext().hashCode());
- }
-
- //====================================================================================================
- // testNotABeanReasons
- //====================================================================================================
- @Test
- public void testNotABeanNonStaticInnerClass() throws Exception {
- BeanContext bc = BeanContext.DEFAULT;
- ClassMeta cm = bc.getClassMeta(C1.class);
- assertFalse(cm.canCreateNewInstance());
- }
-
- public class C1 {
- public int f1;
- }
-
- //====================================================================================================
- // testAddingToArrayProperty
- // This tests the speed of the BeanMap.add() method against array properties.
- // For performance reasons, array properties are stored as temporary ArrayLists until the
- // BeanMap.getBean() method is called.
- //====================================================================================================
- @Test(timeout=1000) // Should be around 100ms at most.
- public void testAddingToArrayProperty() throws Exception {
- BeanContext bc = BeanContext.DEFAULT;
- BeanMap<D> bm = bc.newBeanMap(D.class);
- for (int i = 0; i < 5000; i++) {
- bm.add("f1", i);
- bm.add("f2", i);
- bm.add("f3", i);
- bm.add("f4", i);
- }
- D d = bm.getBean();
- assertEquals(d.f1.length, 5000);
- assertEquals(d.f2.length, 5000);
- assertEquals(d.f3.length, 5003);
- assertEquals(d.f4.length, 5003);
- }
-
- public class D {
- public int[] f1;
- private int[] f2;
- public int[] f3 = new int[]{1,2,3};
- private int[] f4 = new int[]{1,2,3};
- public int[] getF2() {return f2;}
- public void setF2(int[] f2) {this.f2 = f2;}
- public int[] getF4() {return f4;}
- public void setF4(int[] f4) {this.f4 = f4;}
- }
-
- //====================================================================================================
- // testClassClassMeta
- // Make sure we can get ClassMeta objects against the Class class.
- //====================================================================================================
- @Test
- public void testClassClassMeta() throws Exception {
- ClassMeta cm = BeanContext.DEFAULT.getClassMeta(Class.class);
- assertNotNull(cm);
-
- cm = BeanContext.DEFAULT.getClassMeta(Class[].class);
- assertNotNull(cm);
- }
-
- //====================================================================================================
- // testBlanks
- //====================================================================================================
- @Test
- public void testBlanks() throws Exception {
- BeanContext bc = BeanContext.DEFAULT;
-
- // Blanks get interpreted as the default value for primitives and null for boxed objects.
- assertEquals(0, (int)bc.convertToType("", int.class));
- assertNull(bc.convertToType("", Integer.class));
-
- // Booleans are handled different since 'new Boolean("")' is valid and resolves to false
- // while 'new Integer("")' produces an exception.
- assertEquals(false, (boolean)bc.convertToType("", boolean.class));
- assertEquals(false, bc.convertToType("", Boolean.class));
- }
-}
\ No newline at end of file
[36/44] incubator-juneau git commit: Rename CT_* testcases.
Posted by ja...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestParamsTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestParamsTest.java b/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestParamsTest.java
new file mode 100755
index 0000000..309e85f
--- /dev/null
+++ b/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestParamsTest.java
@@ -0,0 +1,716 @@
+/***************************************************************************************************************************
+ * 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.juneau.server;
+
+import static javax.servlet.http.HttpServletResponse.*;
+import static org.apache.juneau.server.TestUtils.*;
+import static org.junit.Assert.*;
+
+import java.util.*;
+
+import org.apache.http.*;
+import org.apache.http.client.entity.*;
+import org.apache.http.entity.*;
+import org.apache.http.message.*;
+import org.apache.juneau.*;
+import org.apache.juneau.client.*;
+import org.apache.juneau.json.*;
+import org.junit.*;
+
+public class TestParamsTest {
+
+ private static String URL = "/testParams";
+ private static boolean debug = false;
+
+ //====================================================================================================
+ // Basic tests
+ //====================================================================================================
+ @Test
+ public void testBasic() throws Exception {
+ RestClient client = new TestRestClient(JsonSerializer.DEFAULT, JsonParser.DEFAULT);
+ RestCall r;
+
+ // @Override
+ // @RestMethod(name="GET",pattern="/")
+ // public void doGet(RestRequest req, RestResponse res) {
+ // res.setOutput("No args");
+ // }
+ r = client.doGet(URL);
+ assertEquals("GET", r.getResponse(String.class));
+
+ r = client.doGet(URL + "/getx?noTrace=true");
+ try {
+ r.connect();
+ fail("Connection should have failed.");
+ } catch (RestCallException e) {
+ checkErrorResponse(debug, e, SC_NOT_FOUND, "Method 'GET' not found on resource with matching pattern on path '/getx'");
+ }
+
+ // @RestMethod(name="GET",pattern="/get1")
+ // public void doGet1(RestRequest req, RestResponse res) {
+ // res.setOutput("/get1");
+ // }
+ r = client.doGet(URL + "/get1");
+ assertEquals("GET /get1", r.getResponse(String.class));
+
+ r = client.doGet(URL + "/get1a?noTrace=true");
+ try {
+ r.connect();
+ fail("Connection should have failed.");
+ } catch (RestCallException e) {
+ checkErrorResponse(debug, e, SC_NOT_FOUND, "Method 'GET' not found on resource with matching pattern on path '/get1a'");
+ }
+
+ // @RestMethod(name="GET",pattern="/get1/{foo}")
+ // public void doGet(RestRequest req, RestResponse res, String foo) {
+ // res.setOutput("/get1/" + foo);
+ // }
+ r = client.doGet(URL + "/get1/foo");
+ assertEquals("GET /get1a foo", r.getResponse(String.class));
+
+ // URL-encoded part should not get decoded before finding method to invoke.
+ // This should match /get1/{foo} and not /get1/{foo}/{bar}
+ // NOTE: When testing on Tomcat, must specify the following system property:
+ // -Dorg.apache.tomcat.util.buf.UDecoder.ALLOW_ENCODED_SLASH=true
+ String x = "x%2Fy+z"; // [x/y z]
+ r = client.doGet(URL + "/get1/"+x);
+ assertEquals("GET /get1a x/y z", r.getResponse(String.class));
+
+ r = client.doGet(URL + "/get1/"+x+"/"+x);
+ assertEquals("GET /get1b x/y z,x/y z", r.getResponse(String.class));
+
+ r = client.doGet(URL + "/get1/foo");
+ assertEquals("GET /get1a foo", r.getResponse(String.class));
+
+ r = client.doGet(URL + "/get1/foo/bar/baz?noTrace=true");
+ try {
+ r.connect();
+ fail("Connection should have failed.");
+ } catch (RestCallException e) {
+ checkErrorResponse(debug, e, SC_NOT_FOUND, "Method 'GET' not found on resource with matching pattern on path '/get1/foo/bar/baz'");
+ }
+
+ // @RestMethod(name="GET",pattern="/get3/{foo}/{bar}/*")
+ // public void doGet3(RestRequest req, RestResponse res, String foo, int bar) {
+ // res.setOutput("/get3/"+foo+"/"+bar+", remainder="+req.getRemainder());
+ // }
+ r = client.doGet(URL + "/get3/foo/123");
+ assertEquals("GET /get3/foo/123 remainder=null", r.getResponse(String.class));
+
+ r = client.doGet(URL + "/get3/foo/123/xxx");
+ assertEquals("GET /get3/foo/123 remainder=xxx", r.getResponse(String.class));
+
+ // // Test method name with overlapping name, remainder allowed.
+ // @RestMethod(name="GET2")
+ // public void get2(RestRequest req, RestResponse res) {
+ // res.setOutput("GET2, remainder="+req.getRemainder());
+ // }
+ r = client.doGet(URL + "?method=get2");
+ assertEquals("GET2 remainder=null", r.getResponse(String.class));
+ r = client.doGet(URL + "/foo/bar?method=get2");
+ assertEquals("GET2 remainder=foo/bar", r.getResponse(String.class));
+ r = client.doGet(URL + "/foo/bar?method=GET2");
+ assertEquals("GET2 remainder=foo/bar", r.getResponse(String.class));
+
+ // // Default POST
+ // @Override
+ // public void doPost(RestRequest req, RestResponse res) {
+ // res.setOutput("POST, remainder="+req.getRemainder());
+ // }
+ r = client.doPost(URL, "");
+ assertEquals("POST remainder=null", r.getResponse(String.class));
+ r = client.doPost(URL + "/foo", "");
+ assertEquals("POST remainder=foo", r.getResponse(String.class));
+
+ // // Bunch of different argument types
+ // @RestMethod(name="POST",pattern="/person/{person}")
+ // public void doPost(RestRequest req, RestResponse res, Person p) {
+ // res.setOutput("POST, /person, name="+p.name+", age="+p.age+" remainder="+req.getRemainder());
+ // }
+ r = client.doPost(URL + "/person/(name=John+Smith,birthDate=Jan+12~,+1952)", "");
+ assertEquals("POST /person/{name=John Smith,birthDate.year=1952} remainder=null", r.getResponse(String.class));
+
+ // Fall through to top-level POST
+ r = client.doPost(URL + "/person/(name:'John+Smith',age:123)/foo", "");
+ assertEquals("POST remainder=person/(name:'John Smith',age:123)/foo", r.getResponse(String.class));
+
+ // // Various primitive types
+ // @RestMethod(name="PUT",pattern="/primitives/{xInt}.{xShort},{xLong}/{xChar}/{xFloat}/{xDouble}/{xByte}/{xBoolean}")
+ // public void doPut1(RestRequest req, RestResponse res, int xInt, short xShort, long xLong, char xChar, float xFloat, double xDouble, byte xByte, boolean xBoolean) {
+ // res.setOutput("PUT, /primitives/"+xInt+"."+xShort+","+xLong+"/"+xChar+"/"+xFloat+"/"+xDouble+"/"+xByte+"/"+xBoolean);
+ // }
+ r = client.doPut(URL + "/primitives/1/2/3/x/4/5/6/true", "");
+ assertEquals("PUT /primitives/1/2/3/x/4.0/5.0/6/true", r.getResponse(String.class));
+
+ // // Various primitive objects
+ // @RestMethod(name="PUT",pattern="/primitiveObjects/{xInt}/{xShort}/{xLong}/{xChar}/{xFloat}/{xDouble}/{xByte}/{xBoolean}")
+ // public void doPut1(RestRequest req, RestResponse res, Integer xInt, Short xShort, Long xLong, Character xChar, Float xFloat, Double xDouble, Byte xByte, Boolean xBoolean) {
+ // res.setOutput("PUT /primitives/"+xInt+"/"+xShort+"/"+xLong+"/"+xChar+"/"+xFloat+"/"+xDouble+"/"+xByte+"/"+xBoolean);
+ // }
+ r = client.doPut(URL + "/primitiveObjects/1/2/3/x/4/5/6/true", "");
+ assertEquals("PUT /primitiveObjects/1/2/3/x/4.0/5.0/6/true", r.getResponse(String.class));
+
+ // // Object with forString(String) method
+ // @RestMethod(name="PUT",pattern="/uuid/{uuid}")
+ // public void doPut1(RestRequest req, RestResponse res, UUID uuid) {
+ // res.setOutput("PUT /uuid/"+uuid);
+ // }
+ UUID uuid = UUID.randomUUID();
+ r = client.doPut(URL + "/uuid/"+uuid, "");
+ assertEquals("PUT /uuid/"+uuid, r.getResponse(String.class));
+
+ client.closeQuietly();
+ }
+
+ //====================================================================================================
+ // @Param annotation - GET
+ //====================================================================================================
+ @Test
+ public void testParamGet() throws Exception {
+ RestClient client = new TestRestClient().setHeader("Accept", "text/plain");
+ String r;
+ String url = URL + "/testParamGet";
+
+ r = client.doGet(url + "?p1=p1&p2=2").getResponseAsString();
+ assertEquals("p1=[p1,p1,p1],p2=[2,2,2]", r);
+
+ r = client.doGet(url + "?p1&p2").getResponseAsString();
+ assertEquals("p1=[null,null,null],p2=[0,null,0]", r);
+
+ r = client.doGet(url).getResponseAsString();
+ assertEquals("p1=[null,null,null],p2=[0,null,0]", r);
+
+ r = client.doGet(url + "?p1").getResponseAsString();
+ assertEquals("p1=[null,null,null],p2=[0,null,0]", r);
+
+ r = client.doGet(url + "?p2").getResponseAsString();
+ assertEquals("p1=[null,null,null],p2=[0,null,0]", r);
+
+ r = client.doGet(url + "?p1=foo&p2").getResponseAsString();
+ assertEquals("p1=[foo,foo,foo],p2=[0,null,0]", r);
+
+ r = client.doGet(url + "?p1&p2=1").getResponseAsString();
+ assertEquals("p1=[null,null,null],p2=[1,1,1]", r);
+
+ String x = "a%2Fb%25c%3Dd+e"; // [x/y%z=a+b]
+ r = client.doGet(url + "?p1="+x+"&p2=1").getResponseAsString();
+ assertEquals("p1=[a/b%c=d e,a/b%c=d e,a/b%c=d e],p2=[1,1,1]", r);
+
+ client.closeQuietly();
+ }
+
+ //====================================================================================================
+ // @Param(format=PLAIN) annotation - GET
+ //====================================================================================================
+ @Test
+ public void testPlainParamGet() throws Exception {
+ RestClient client = new TestRestClient().setHeader("Accept", "text/plain");
+ String r;
+ String url = URL + "/testPlainParamGet";
+
+ r = client.doGet(url + "?p1=(p1)").getResponseAsString();
+ assertEquals("p1=[(p1),(p1),p1]", r);
+
+ r = client.doGet(url + "?p1=$s(p1)").getResponseAsString();
+ assertEquals("p1=[$s(p1),$s(p1),p1]", r);
+
+ client.closeQuietly();
+ }
+
+ //====================================================================================================
+ // @Param annotation - POST
+ //====================================================================================================
+ @Test
+ public void testParamPost() throws Exception {
+ RestClient client = new TestRestClient().setHeader("Accept", "text/plain");
+ String r;
+ String url = URL + "/testParamPost";
+
+ r = client.doFormPost(url, new ObjectMap("{p1:'p1',p2:2}")).getResponseAsString();
+ assertEquals("p1=[p1,p1,p1],p2=[2,$n(2),2]", r);
+
+ r = client.doFormPost(url, new ObjectMap("{p1:null,p2:0}")).getResponseAsString();
+ assertEquals("p1=[null,\u0000,null],p2=[0,$n(0),0]", r);
+
+ r = client.doFormPost(url, new ObjectMap("{}")).getResponseAsString();
+ assertEquals("p1=[null,null,null],p2=[0,null,0]", r);
+
+ r = client.doFormPost(url, new ObjectMap("{p1:null}")).getResponseAsString();
+ assertEquals("p1=[null,\u0000,null],p2=[0,null,0]", r);
+
+ r = client.doFormPost(url, new ObjectMap("{p2:0}")).getResponseAsString();
+ assertEquals("p1=[null,null,null],p2=[0,$n(0),0]", r);
+
+ r = client.doFormPost(url, new ObjectMap("{p1:'foo',p2:0}")).getResponseAsString();
+ assertEquals("p1=[foo,foo,foo],p2=[0,$n(0),0]", r);
+
+ r = client.doFormPost(url, new ObjectMap("{p1:null,p2:1}")).getResponseAsString();
+ assertEquals("p1=[null,\u0000,null],p2=[1,$n(1),1]", r);
+
+ r = client.doFormPost(url, new ObjectMap("{p1:'a/b%c=d e,f/g%h=i j',p2:1}")).getResponseAsString();
+ assertEquals("p1=[a/b%c=d e,f/g%h=i j,a/b%c=d e,f/g%h=i j,a/b%c=d e,f/g%h=i j],p2=[1,$n(1),1]", r);
+
+ client.closeQuietly();
+ }
+
+ //====================================================================================================
+ // @Param(format=PLAIN) annotation - POST
+ //====================================================================================================
+ @Test
+ public void testPlainParamPost() throws Exception {
+ RestClient client = new TestRestClient().setHeader("Accept", "text/plain");
+ String r;
+ String url = URL + "/testPlainParamPost";
+
+ List<NameValuePair> nvps = new ArrayList<NameValuePair>();
+ nvps.add(new BasicNameValuePair("p1", "(p1)"));
+ HttpEntity he = new UrlEncodedFormEntity(nvps);
+
+ r = client.doPost(url, he).getResponseAsString();
+ assertEquals("p1=[(p1),(p1),p1]", r);
+
+ nvps = new ArrayList<NameValuePair>();
+ nvps.add(new BasicNameValuePair("p1", "$s(p1)"));
+ he = new UrlEncodedFormEntity(nvps);
+
+ r = client.doFormPost(url, he).getResponseAsString();
+ assertEquals("p1=[$s(p1),$s(p1),p1]", r);
+
+ client.closeQuietly();
+ }
+
+ //====================================================================================================
+ // @QParam annotation - GET
+ //====================================================================================================
+ @Test
+ public void testQParamGet() throws Exception {
+ RestClient client = new TestRestClient().setHeader("Accept", "text/plain");
+ String r;
+ String url = URL + "/testQParamGet";
+
+ r = client.doGet(url + "?p1=p1&p2=2").getResponseAsString();
+ assertEquals("p1=[p1,p1,p1],p2=[2,2,2]", r);
+
+ r = client.doGet(url + "?p1&p2").getResponseAsString();
+ assertEquals("p1=[null,null,null],p2=[0,null,0]", r);
+
+ r = client.doGet(url).getResponseAsString();
+ assertEquals("p1=[null,null,null],p2=[0,null,0]", r);
+
+ r = client.doGet(url + "?p1").getResponseAsString();
+ assertEquals("p1=[null,null,null],p2=[0,null,0]", r);
+
+ r = client.doGet(url + "?p2").getResponseAsString();
+ assertEquals("p1=[null,null,null],p2=[0,null,0]", r);
+
+ r = client.doGet(url + "?p1=foo&p2").getResponseAsString();
+ assertEquals("p1=[foo,foo,foo],p2=[0,null,0]", r);
+
+ r = client.doGet(url + "?p1&p2=1").getResponseAsString();
+ assertEquals("p1=[null,null,null],p2=[1,1,1]", r);
+
+ String x = "a%2Fb%25c%3Dd+e"; // [x/y%z=a+b]
+ r = client.doGet(url + "?p1="+x+"&p2=1").getResponseAsString();
+ assertEquals("p1=[a/b%c=d e,a/b%c=d e,a/b%c=d e],p2=[1,1,1]", r);
+
+ client.closeQuietly();
+ }
+
+ //====================================================================================================
+ // @QParam(format=PLAIN) annotation - GET
+ //====================================================================================================
+ @Test
+ public void testPlainQParamGet() throws Exception {
+ RestClient client = new TestRestClient().setHeader("Accept", "text/plain");
+ String r;
+ String url = URL + "/testPlainQParamGet";
+
+ r = client.doGet(url + "?p1=(p1)").getResponseAsString();
+ assertEquals("p1=[(p1),(p1),p1]", r);
+
+ r = client.doGet(url + "?p1=$s(p1)").getResponseAsString();
+ assertEquals("p1=[$s(p1),$s(p1),p1]", r);
+
+ client.closeQuietly();
+ }
+
+ //====================================================================================================
+ // @QParam annotation - POST
+ //====================================================================================================
+ @Test
+ public void testQParamPost() throws Exception {
+ RestClient client = new TestRestClient().setHeader("Accept", "text/plain");
+ String r;
+ String url = URL + "/testQParamPost";
+
+ r = client.doFormPost(url, new ObjectMap("{p1:'p1',p2:2}")).getResponseAsString();
+ assertEquals("p1=[null,null,null],p2=[0,null,0]", r);
+
+ r = client.doFormPost(url, new ObjectMap("{p1:null,p2:0}")).getResponseAsString();
+ assertEquals("p1=[null,null,null],p2=[0,null,0]", r);
+
+ r = client.doFormPost(url, new ObjectMap("{}")).getResponseAsString();
+ assertEquals("p1=[null,null,null],p2=[0,null,0]", r);
+
+ r = client.doFormPost(url, new ObjectMap("{p1:null}")).getResponseAsString();
+ assertEquals("p1=[null,null,null],p2=[0,null,0]", r);
+
+ r = client.doFormPost(url, new ObjectMap("{p2:0}")).getResponseAsString();
+ assertEquals("p1=[null,null,null],p2=[0,null,0]", r);
+
+ r = client.doFormPost(url, new ObjectMap("{p1:'foo',p2:0}")).getResponseAsString();
+ assertEquals("p1=[null,null,null],p2=[0,null,0]", r);
+
+ r = client.doFormPost(url, new ObjectMap("{p1:null,p2:1}")).getResponseAsString();
+ assertEquals("p1=[null,null,null],p2=[0,null,0]", r);
+
+ r = client.doFormPost(url, new ObjectMap("{p1:'a/b%c=d e,f/g%h=i j',p2:1}")).getResponseAsString();
+ assertEquals("p1=[null,null,null],p2=[0,null,0]", r);
+
+ client.closeQuietly();
+ }
+
+ //====================================================================================================
+ // @HasParam annotation - GET
+ //====================================================================================================
+ @Test
+ public void testHasParamGet() throws Exception {
+ RestClient client = new TestRestClient().setHeader("Accept", "text/plain");
+ String r;
+ String url = URL + "/testHasParamGet";
+
+ r = client.doGet(url + "?p1=p1&p2=2").getResponseAsString();
+ assertEquals("p1=[true,true],p2=[true,true]", r);
+
+ r = client.doGet(url + "?p1&p2").getResponseAsString();
+ assertEquals("p1=[true,true],p2=[true,true]", r);
+
+ r = client.doGet(url).getResponseAsString();
+ assertEquals("p1=[false,false],p2=[false,false]", r);
+
+ r = client.doGet(url + "?p1").getResponseAsString();
+ assertEquals("p1=[true,true],p2=[false,false]", r);
+
+ r = client.doGet(url + "?p2").getResponseAsString();
+ assertEquals("p1=[false,false],p2=[true,true]", r);
+
+ r = client.doGet(url + "?p1=foo&p2").getResponseAsString();
+ assertEquals("p1=[true,true],p2=[true,true]", r);
+
+ r = client.doGet(url + "?p1&p2=1").getResponseAsString();
+ assertEquals("p1=[true,true],p2=[true,true]", r);
+
+ String x = "x%2Fy%25z%3Da+b"; // [x/y%z=a+b]
+ r = client.doGet(url + "?p1="+x+"&p2=1").getResponseAsString();
+ assertEquals("p1=[true,true],p2=[true,true]", r);
+
+ client.closeQuietly();
+ }
+
+ //====================================================================================================
+ // @HasParam annotation - POST
+ //====================================================================================================
+ @Test
+ public void testHasParamPost() throws Exception {
+ RestClient client = new TestRestClient().setHeader("Accept", "text/plain");
+ String r;
+ String url = URL + "/testHasParamPost";
+
+ r = client.doFormPost(url, new ObjectMap("{p1:'p1',p2:2}")).getResponseAsString();
+ assertEquals("p1=[true,true],p2=[true,true]", r);
+
+ r = client.doFormPost(url, new ObjectMap("{p1:null,p2:0}")).getResponseAsString();
+ assertEquals("p1=[true,true],p2=[true,true]", r);
+
+ r = client.doFormPost(url, new ObjectMap("{}")).getResponseAsString();
+ assertEquals("p1=[false,false],p2=[false,false]", r);
+
+ r = client.doFormPost(url, new ObjectMap("{p1:null}")).getResponseAsString();
+ assertEquals("p1=[true,true],p2=[false,false]", r);
+
+ r = client.doFormPost(url, new ObjectMap("{p2:0}")).getResponseAsString();
+ assertEquals("p1=[false,false],p2=[true,true]", r);
+
+ r = client.doFormPost(url, new ObjectMap("{p1:'foo',p2:0}")).getResponseAsString();
+ assertEquals("p1=[true,true],p2=[true,true]", r);
+
+ r = client.doFormPost(url, new ObjectMap("{p1:null,p2:1}")).getResponseAsString();
+ assertEquals("p1=[true,true],p2=[true,true]", r);
+
+ r = client.doFormPost(url, new ObjectMap("{p1:'a/b%c=d e,f/g%h=i j',p2:1}")).getResponseAsString();
+ assertEquals("p1=[true,true],p2=[true,true]", r);
+
+ client.closeQuietly();
+ }
+
+ //====================================================================================================
+ // @HasQParam annotation - GET
+ //====================================================================================================
+ @Test
+ public void testHasQParamGet() throws Exception {
+ RestClient client = new TestRestClient().setHeader("Accept", "text/plain");
+ String r;
+ String url = URL + "/testHasQParamGet";
+
+ r = client.doGet(url + "?p1=p1&p2=2").getResponseAsString();
+ assertEquals("p1=[true,true],p2=[true,true]", r);
+
+ r = client.doGet(url + "?p1&p2").getResponseAsString();
+ assertEquals("p1=[true,true],p2=[true,true]", r);
+
+ r = client.doGet(url).getResponseAsString();
+ assertEquals("p1=[false,false],p2=[false,false]", r);
+
+ r = client.doGet(url + "?p1").getResponseAsString();
+ assertEquals("p1=[true,true],p2=[false,false]", r);
+
+ r = client.doGet(url + "?p2").getResponseAsString();
+ assertEquals("p1=[false,false],p2=[true,true]", r);
+
+ r = client.doGet(url + "?p1=foo&p2").getResponseAsString();
+ assertEquals("p1=[true,true],p2=[true,true]", r);
+
+ r = client.doGet(url + "?p1&p2=1").getResponseAsString();
+ assertEquals("p1=[true,true],p2=[true,true]", r);
+
+ String x = "x%2Fy%25z%3Da+b"; // [x/y%z=a+b]
+ r = client.doGet(url + "?p1="+x+"&p2=1").getResponseAsString();
+ assertEquals("p1=[true,true],p2=[true,true]", r);
+
+ client.closeQuietly();
+ }
+
+ //====================================================================================================
+ // @HasQParam annotation - POST
+ //====================================================================================================
+ @Test
+ public void testHasQParamPost() throws Exception {
+ RestClient client = new TestRestClient().setHeader("Accept", "text/plain");
+ String r;
+ String url = URL + "/testHasQParamPost";
+
+ r = client.doFormPost(url, new ObjectMap("{p1:'p1',p2:2}")).getResponseAsString();
+ assertEquals("p1=[false,false],p2=[false,false]", r);
+
+ r = client.doFormPost(url, new ObjectMap("{p1:null,p2:0}")).getResponseAsString();
+ assertEquals("p1=[false,false],p2=[false,false]", r);
+
+ r = client.doFormPost(url, new ObjectMap("{}")).getResponseAsString();
+ assertEquals("p1=[false,false],p2=[false,false]", r);
+
+ r = client.doFormPost(url, new ObjectMap("{p1:null}")).getResponseAsString();
+ assertEquals("p1=[false,false],p2=[false,false]", r);
+
+ r = client.doFormPost(url, new ObjectMap("{p2:0}")).getResponseAsString();
+ assertEquals("p1=[false,false],p2=[false,false]", r);
+
+ r = client.doFormPost(url, new ObjectMap("{p1:'foo',p2:0}")).getResponseAsString();
+ assertEquals("p1=[false,false],p2=[false,false]", r);
+
+ r = client.doFormPost(url, new ObjectMap("{p1:null,p2:1}")).getResponseAsString();
+ assertEquals("p1=[false,false],p2=[false,false]", r);
+
+ r = client.doFormPost(url, new ObjectMap("{p1:'a/b%c=d e,f/g%h=i j',p2:1}")).getResponseAsString();
+ assertEquals("p1=[false,false],p2=[false,false]", r);
+
+ client.closeQuietly();
+ }
+
+ //====================================================================================================
+ // Form POSTS with @Content parameter
+ //====================================================================================================
+ @Test
+ public void testFormPostAsContent() throws Exception {
+ RestClient client = new TestRestClient().setHeader("Accept", "text/plain");
+ String r;
+ String url = URL + "/testFormPostAsContent";
+
+ r = client.doFormPost(url, new ObjectMap("{p1:'p1',p2:2}")).getResponseAsString();
+ assertEquals("bean=[{p1:'p1',p2:2}],qp1=[null],qp2=[0],hqp1=[false],hqp2=[false]", r);
+
+ r = client.doFormPost(url, new ObjectMap("{}")).getResponseAsString();
+ assertEquals("bean=[{p2:0}],qp1=[null],qp2=[0],hqp1=[false],hqp2=[false]", r);
+
+ r = client.doFormPost(url+"?p1=p3&p2=4", new ObjectMap("{p1:'p1',p2:2}")).getResponseAsString();
+ assertEquals("bean=[{p1:'p1',p2:2}],qp1=[p3],qp2=[4],hqp1=[true],hqp2=[true]", r);
+
+ r = client.doFormPost(url+"?p1=p3&p2=4", new ObjectMap("{}")).getResponseAsString();
+ assertEquals("bean=[{p2:0}],qp1=[p3],qp2=[4],hqp1=[true],hqp2=[true]", r);
+
+ client.closeQuietly();
+ }
+
+ //====================================================================================================
+ // Test @Param and @QParam annotations when using multi-part parameters (e.g. &key=val1,&key=val2).
+ //====================================================================================================
+ @Test
+ public void testMultiPartParams() throws Exception {
+ RestClient client = new TestRestClient().setHeader("Accept", "text/plain");
+ String r;
+ String url = URL + "/testMultiPartParams";
+
+ String in = ""
+ + "?p1=a&p1=b"
+ + "&p2=1&p2=2"
+ + "&p3=a&p3=b"
+ + "&p4=1&p4=2"
+ + "&p5=a&p5=b"
+ + "&p6=1&p6=2"
+ + "&p7=a&p7=b"
+ + "&p8=1&p8=2"
+ + "&p9=(a=1,b=2,c=false)&p9=(a=3,b=4,c=true)"
+ + "&p10=(a=1,b=2,c=false)&p10=(a=3,b=4,c=true)"
+ + "&p11=(a=1,b=2,c=false)&p11=(a=3,b=4,c=true)"
+ + "&p12=(a=1,b=2,c=false)&p12=(a=3,b=4,c=true)";
+ r = client.doGet(url + in).getResponseAsString();
+ String e = "{"
+ + "p1:['a','b'],"
+ + "p2:[1,2],"
+ + "p3:['a','b'],"
+ + "p4:[1,2],"
+ + "p5:['a','b'],"
+ + "p6:[1,2],"
+ + "p7:['a','b'],"
+ + "p8:[1,2],"
+ + "p9:[{a:'1',b:2,c:false},{a:'3',b:4,c:true}],"
+ + "p10:[{a:'1',b:2,c:false},{a:'3',b:4,c:true}],"
+ + "p11:[{a:'1',b:2,c:false},{a:'3',b:4,c:true}],"
+ + "p12:[{a:'1',b:2,c:false},{a:'3',b:4,c:true}]"
+ +"}";
+ assertEquals(e, r);
+
+ client.closeQuietly();
+ }
+
+ //====================================================================================================
+ // Same as testMultiPartParams(), except make sure single values are still interpreted as collections.
+ //====================================================================================================
+ @Test
+ public void testMultiPartParamsSingleValues() throws Exception {
+ RestClient client = new TestRestClient().setHeader("Accept", "text/plain");
+ String r;
+ String url = URL + "/testMultiPartParams";
+
+ String in = ""
+ + "?p1=a"
+ + "&p2=1"
+ + "&p3=a"
+ + "&p4=1"
+ + "&p5=a"
+ + "&p6=1"
+ + "&p7=a"
+ + "&p8=1"
+ + "&p9=(a=1,b=2,c=false)"
+ + "&p10=(a=1,b=2,c=false)"
+ + "&p11=(a=1,b=2,c=false)"
+ + "&p12=(a=1,b=2,c=false)";
+ r = client.doGet(url + in).getResponseAsString();
+ String e = "{"
+ + "p1:['a'],"
+ + "p2:[1],"
+ + "p3:['a'],"
+ + "p4:[1],"
+ + "p5:['a'],"
+ + "p6:[1],"
+ + "p7:['a'],"
+ + "p8:[1],"
+ + "p9:[{a:'1',b:2,c:false}],"
+ + "p10:[{a:'1',b:2,c:false}],"
+ + "p11:[{a:'1',b:2,c:false}],"
+ + "p12:[{a:'1',b:2,c:false}]"
+ +"}";
+ assertEquals(e, r);
+
+ client.closeQuietly();
+ }
+
+ //====================================================================================================
+ // Test multi-part parameter keys on bean properties of type array/Collection (i.e. &key=val1,&key=val2)
+ // using URLENC_expandedParams property.
+ // A simple round-trip test to verify that both serializing and parsing works.
+ //====================================================================================================
+ @Test
+ public void testFormPostsWithMultiParamsUsingProperty() throws Exception {
+ RestClient client = new TestRestClient()
+ .setHeader("Content-Type", "application/x-www-form-urlencoded")
+ .setHeader("Accept", "application/x-www-form-urlencoded");
+ String r;
+ String url = URL + "/testFormPostsWithMultiParamsUsingProperty";
+
+ String in = ""
+ + "f1=a&f1=b"
+ + "&f2=c&f2=d"
+ + "&f3=1&f3=2"
+ + "&f4=3&f4=4"
+ + "&f5=(e,f)&f5=(g,h)"
+ + "&f6=(i,j)&f6=(k,l)"
+ + "&f7=(a=a,b=1,c=true)&f7=(a=b,b=2,c=false)"
+ + "&f8=(a=a,b=1,c=true)&f8=(a=b,b=2,c=false)"
+ + "&f9=((a=a,b=1,c=true))&f9=((a=b,b=2,c=false))"
+ + "&f10=((a=a,b=1,c=true))&f10=((a=b,b=2,c=false))"
+ + "&f11=a&f11=b"
+ + "&f12=c&f12=d"
+ + "&f13=1&f13=2"
+ + "&f14=3&f14=4"
+ + "&f15=(e,f)&f15=(g,h)"
+ + "&f16=(i,j)&f16=(k,l)"
+ + "&f17=(a=a,b=1,c=true)&f17=(a=b,b=2,c=false)"
+ + "&f18=(a=a,b=1,c=true)&f18=(a=b,b=2,c=false)"
+ + "&f19=((a=a,b=1,c=true))&f19=((a=b,b=2,c=false))"
+ + "&f20=((a=a,b=1,c=true))&f20=((a=b,b=2,c=false))";
+ r = client.doPost(url, new StringEntity(in)).getResponseAsString();
+ assertEquals(in, r);
+
+ client.closeQuietly();
+ }
+
+ //====================================================================================================
+ // Test multi-part parameter keys on bean properties of type array/Collection (i.e. &key=val1,&key=val2)
+ // using @UrlEncoding(expandedParams=true) annotation.
+ // A simple round-trip test to verify that both serializing and parsing works.
+ //====================================================================================================
+ @Test
+ public void testFormPostsWithMultiParamsUsingAnnotation() throws Exception {
+ RestClient client = new TestRestClient()
+ .setHeader("Content-Type", "application/x-www-form-urlencoded")
+ .setHeader("Accept", "application/x-www-form-urlencoded");
+ String r;
+ String url = URL + "/testFormPostsWithMultiParamsUsingAnnotation";
+
+ String in = ""
+ + "f1=a&f1=b"
+ + "&f2=c&f2=d"
+ + "&f3=1&f3=2"
+ + "&f4=3&f4=4"
+ + "&f5=(e,f)&f5=(g,h)"
+ + "&f6=(i,j)&f6=(k,l)"
+ + "&f7=(a=a,b=1,c=true)&f7=(a=b,b=2,c=false)"
+ + "&f8=(a=a,b=1,c=true)&f8=(a=b,b=2,c=false)"
+ + "&f9=((a=a,b=1,c=true))&f9=((a=b,b=2,c=false))"
+ + "&f10=((a=a,b=1,c=true))&f10=((a=b,b=2,c=false))"
+ + "&f11=a&f11=b"
+ + "&f12=c&f12=d"
+ + "&f13=1&f13=2"
+ + "&f14=3&f14=4"
+ + "&f15=(e,f)&f15=(g,h)"
+ + "&f16=(i,j)&f16=(k,l)"
+ + "&f17=(a=a,b=1,c=true)&f17=(a=b,b=2,c=false)"
+ + "&f18=(a=a,b=1,c=true)&f18=(a=b,b=2,c=false)"
+ + "&f19=((a=a,b=1,c=true))&f19=((a=b,b=2,c=false))"
+ + "&f20=((a=a,b=1,c=true))&f20=((a=b,b=2,c=false))";
+ r = client.doPost(url, new StringEntity(in)).getResponseAsString();
+ assertEquals(in, r);
+
+ client.closeQuietly();
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestParsersTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestParsersTest.java b/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestParsersTest.java
new file mode 100755
index 0000000..a3e4f76
--- /dev/null
+++ b/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestParsersTest.java
@@ -0,0 +1,162 @@
+/***************************************************************************************************************************
+ * 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.juneau.server;
+
+import static javax.servlet.http.HttpServletResponse.*;
+import static org.apache.juneau.server.TestUtils.*;
+import static org.junit.Assert.*;
+
+import org.apache.juneau.client.*;
+import org.apache.juneau.plaintext.*;
+import org.junit.*;
+
+public class TestParsersTest {
+
+ private static String URL = "/testParsers";
+ private static boolean debug = false;
+
+ //====================================================================================================
+ // Parser defined on class.
+ //====================================================================================================
+ @Test
+ public void testParserOnClass() throws Exception {
+ RestClient client = new TestRestClient(PlainTextSerializer.class, PlainTextParser.class);
+ String url = URL + "/testParserOnClass";
+
+ client.setContentType("text/a");
+ String r = client.doPut(url, "test1").getResponseAsString();
+ assertEquals("text/a - test1", r);
+
+ try {
+ client.setContentType("text/b");
+ client.doPut(url + "?noTrace=true", "test1").getResponseAsString();
+ fail("Exception expected");
+ } catch (RestCallException e) {
+ checkErrorResponse(debug, e, SC_UNSUPPORTED_MEDIA_TYPE,
+ "Unsupported media-type in request header 'Content-Type': 'text/b'",
+ "Supported media-types: [text/a"
+ );
+ }
+
+ client.setContentType("text/json").setAccept("text/json");
+ r = client.doPut(url, "'test1'").getResponseAsString();
+ assertEquals("\"test1\"", r);
+
+ client.closeQuietly();
+ }
+
+ //====================================================================================================
+ // Parser defined on method.
+ //====================================================================================================
+ @Test
+ public void testParserOnMethod() throws Exception {
+ RestClient client = new TestRestClient(PlainTextSerializer.class, PlainTextParser.class);
+ String url = URL + "/testParserOnMethod";
+
+ client.setContentType("text/b");
+ String r = client.doPut(url, "test2").getResponseAsString();
+ assertEquals("text/b - test2", r);
+
+ try {
+ client.setContentType("text/a");
+ client.doPut(url + "?noTrace=true", "test2").getResponseAsString();
+ fail("Exception expected");
+ } catch (RestCallException e) {
+ checkErrorResponse(debug, e, SC_UNSUPPORTED_MEDIA_TYPE,
+ "Unsupported media-type in request header 'Content-Type': 'text/a'",
+ "Supported media-types: [text/b]"
+ );
+ }
+
+ try {
+ client.setContentType("text/json");
+ r = client.doPut(url + "?noTrace=true", "'test2'").getResponseAsString();
+ fail("Exception expected");
+ } catch (RestCallException e) {
+ checkErrorResponse(debug, e, SC_UNSUPPORTED_MEDIA_TYPE,
+ "Unsupported media-type in request header 'Content-Type': 'text/json'",
+ "Supported media-types: [text/b]"
+ );
+ }
+
+ client.closeQuietly();
+ }
+
+ //====================================================================================================
+ // Parser overridden on method.
+ //====================================================================================================
+ @Test
+ public void testParserOverriddenOnMethod() throws Exception {
+ RestClient client = new TestRestClient(PlainTextSerializer.class, PlainTextParser.class);
+ String url = URL + "/testParserOverriddenOnMethod";
+
+ client.setContentType("text/a");
+ String r = client.doPut(url, "test3").getResponseAsString();
+ assertEquals("text/a - test3", r);
+
+ client.setContentType("text/b");
+ r = client.doPut(url, "test3").getResponseAsString();
+ assertEquals("text/b - test3", r);
+
+ client.setContentType("text/json");
+ r = client.doPut(url, "'test3'").getResponseAsString();
+ assertEquals("test3", r);
+
+ client.closeQuietly();
+ }
+
+ //====================================================================================================
+ // Parser with different Accept than Content-Type.
+ //====================================================================================================
+ @Test
+ public void testParserWithDifferentMediaTypes() throws Exception {
+ RestClient client = new TestRestClient(PlainTextSerializer.class, PlainTextParser.class);
+ String url = URL + "/testParserWithDifferentMediaTypes";
+
+ client.setContentType("text/a");
+ String r = client.doPut(url, "test4").getResponseAsString();
+ assertEquals("text/d - test4", r);
+
+ client.setContentType("text/d");
+ r = client.doPut(url, "test4").getResponseAsString();
+ assertEquals("text/d - test4", r);
+
+ client.setContentType("text/json");
+ r = client.doPut(url, "'test4'").getResponseAsString();
+ assertEquals("test4", r);
+
+ client.closeQuietly();
+ }
+
+ //====================================================================================================
+ // Check for valid error response.
+ //====================================================================================================
+ @Test
+ public void testValidErrorResponse() throws Exception {
+ RestClient client = new TestRestClient(PlainTextSerializer.class, PlainTextParser.class);
+ String url = URL + "/testValidErrorResponse";
+
+ try {
+ client.setContentType("text/bad");
+ client.doPut(url + "?noTrace=true", "test1").getResponseAsString();
+ fail("Exception expected");
+ } catch (RestCallException e) {
+ checkErrorResponse(debug, e, SC_UNSUPPORTED_MEDIA_TYPE,
+ "Unsupported media-type in request header 'Content-Type': 'text/bad'",
+ "Supported media-types: [text/a"
+ );
+ }
+
+ client.closeQuietly();
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/df0f8689/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestPathTest.java
----------------------------------------------------------------------
diff --git a/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestPathTest.java b/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestPathTest.java
new file mode 100755
index 0000000..5ffd5b2
--- /dev/null
+++ b/org.apache.juneau.server.test/src/test/java/org/apache/juneau/server/TestPathTest.java
@@ -0,0 +1,44 @@
+/***************************************************************************************************************************
+ * 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.juneau.server;
+
+import static org.junit.Assert.*;
+
+import org.apache.juneau.client.*;
+import org.apache.juneau.json.*;
+import org.junit.*;
+
+public class TestPathTest {
+
+ private static String URL = "/testPath";
+
+ //====================================================================================================
+ // Basic tests
+ //====================================================================================================
+ @Test
+ public void testBasic() throws Exception {
+ RestClient client = new TestRestClient(JsonSerializer.DEFAULT, JsonParser.DEFAULT);
+ String r = null;
+
+ r = client.doGet(URL).getResponse(String.class);
+ assertEquals("/testPath", r);
+
+ r = client.doGet(URL + "/testPath2").getResponse(String.class);
+ assertEquals("/testPath/testPath2", r);
+
+ r = client.doGet(URL + "/testPath2/testPath3").getResponse(String.class);
+ assertEquals("/testPath/testPath2/testPath3", r);
+
+ client.closeQuietly();
+ }
+}