http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/e4dfdf81/juneau-core-test/src/test/java/org/apache/juneau/ObjectMapTest.java ---------------------------------------------------------------------- diff --git a/juneau-core-test/src/test/java/org/apache/juneau/ObjectMapTest.java b/juneau-core-test/src/test/java/org/apache/juneau/ObjectMapTest.java new file mode 100755 index 0000000..5b27e7a --- /dev/null +++ b/juneau-core-test/src/test/java/org/apache/juneau/ObjectMapTest.java @@ -0,0 +1,314 @@ +// *************************************************************************************************************************** +// * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file * +// * distributed with this work for additional information regarding copyright ownership. The ASF licenses this file * +// * to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance * +// * with the License. You may obtain a copy of the License at * +// * * +// * http://www.apache.org/licenses/LICENSE-2.0 * +// * * +// * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an * +// * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.*; + +@SuppressWarnings("javadoc") +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 = "{'ð¤¢ð¤¢':'ð¤¢ð¤¢'}"; + checkStep(1, in, new ObjectMap(in).getString("ð¤¢ð¤¢"), "ð¤¢ð¤¢"); + } + + 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/e4dfdf81/juneau-core-test/src/test/java/org/apache/juneau/ParserGenericsTest.java ---------------------------------------------------------------------- diff --git a/juneau-core-test/src/test/java/org/apache/juneau/ParserGenericsTest.java b/juneau-core-test/src/test/java/org/apache/juneau/ParserGenericsTest.java new file mode 100755 index 0000000..d1b9491 --- /dev/null +++ b/juneau-core-test/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","javadoc"}) +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/e4dfdf81/juneau-core-test/src/test/java/org/apache/juneau/ParserReaderTest.java ---------------------------------------------------------------------- diff --git a/juneau-core-test/src/test/java/org/apache/juneau/ParserReaderTest.java b/juneau-core-test/src/test/java/org/apache/juneau/ParserReaderTest.java new file mode 100755 index 0000000..82be1ac --- /dev/null +++ b/juneau-core-test/src/test/java/org/apache/juneau/ParserReaderTest.java @@ -0,0 +1,182 @@ +// *************************************************************************************************************************** +// * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file * +// * distributed with this work for additional information regarding copyright ownership. The ASF licenses this file * +// * to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance * +// * with the License. You may obtain a copy of the License at * +// * * +// * http://www.apache.org/licenses/LICENSE-2.0 * +// * * +// * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an * +// * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.*; + +@SuppressWarnings("javadoc") +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/e4dfdf81/juneau-core-test/src/test/java/org/apache/juneau/PojoSwapTest.java ---------------------------------------------------------------------- diff --git a/juneau-core-test/src/test/java/org/apache/juneau/PojoSwapTest.java b/juneau-core-test/src/test/java/org/apache/juneau/PojoSwapTest.java new file mode 100755 index 0000000..d9b7944 --- /dev/null +++ b/juneau-core-test/src/test/java/org/apache/juneau/PojoSwapTest.java @@ -0,0 +1,57 @@ +// *************************************************************************************************************************** +// * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file * +// * distributed with this work for additional information regarding copyright ownership. The ASF licenses this file * +// * to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance * +// * with the License. You may obtain a copy of the License at * +// * * +// * http://www.apache.org/licenses/LICENSE-2.0 * +// * * +// * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an * +// * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.*; + +@SuppressWarnings("javadoc") +public class PojoSwapTest { + + //==================================================================================================== + // Test same type + // If you define a PojoSwap<String,String> filter, then it should be invoked on all strings. + //==================================================================================================== + @Test + public void testSameType() throws Exception { + JsonSerializer s = JsonSerializer.DEFAULT_LAX.clone().addPojoSwaps(ASwap.class); + JsonParser p = JsonParser.DEFAULT.clone().addPojoSwaps(ASwap.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 ASwap extends StringSwap<String> { + @Override + public String swap(BeanSession session, String o) throws SerializeException { + return "x" + o + "x"; + } + + @Override + public String unswap(BeanSession session, String f, ClassMeta<?> hint) throws ParseException { + return f.substring(1, f.length()-1); + } + } +} http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/e4dfdf81/juneau-core-test/src/test/java/org/apache/juneau/PropertyNamerDashedLcTest.java ---------------------------------------------------------------------- diff --git a/juneau-core-test/src/test/java/org/apache/juneau/PropertyNamerDashedLcTest.java b/juneau-core-test/src/test/java/org/apache/juneau/PropertyNamerDashedLcTest.java new file mode 100755 index 0000000..5d2e1f3 --- /dev/null +++ b/juneau-core-test/src/test/java/org/apache/juneau/PropertyNamerDashedLcTest.java @@ -0,0 +1,40 @@ +// *************************************************************************************************************************** +// * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file * +// * distributed with this work for additional information regarding copyright ownership. The ASF licenses this file * +// * to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance * +// * with the License. You may obtain a copy of the License at * +// * * +// * http://www.apache.org/licenses/LICENSE-2.0 * +// * * +// * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an * +// * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.*; + +@SuppressWarnings("javadoc") +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/e4dfdf81/juneau-core-test/src/test/java/org/apache/juneau/TestUtils.java ---------------------------------------------------------------------- diff --git a/juneau-core-test/src/test/java/org/apache/juneau/TestUtils.java b/juneau-core-test/src/test/java/org/apache/juneau/TestUtils.java new file mode 100755 index 0000000..bdf0a77 --- /dev/null +++ b/juneau-core-test/src/test/java/org/apache/juneau/TestUtils.java @@ -0,0 +1,475 @@ +// *************************************************************************************************************************** +// * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file * +// * distributed with this work for additional information regarding copyright ownership. The ASF licenses this file * +// * to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance * +// * with the License. You may obtain a copy of the License at * +// * * +// * http://www.apache.org/licenses/LICENSE-2.0 * +// * * +// * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an * +// * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.serializer.SerializerContext.*; +import static org.apache.juneau.xml.XmlSerializerContext.*; +import static org.junit.Assert.*; + +import java.io.*; +import java.text.*; +import java.util.*; +import java.util.regex.*; + +import javax.xml.*; +import javax.xml.parsers.*; +import javax.xml.transform.dom.*; +import javax.xml.transform.stream.*; +import javax.xml.validation.*; + +import org.apache.juneau.internal.*; +import org.apache.juneau.json.*; +import org.apache.juneau.serializer.*; +import org.apache.juneau.transforms.*; +import org.apache.juneau.xml.*; +import org.junit.*; +import org.w3c.dom.*; +import org.w3c.dom.bootstrap.*; +import org.w3c.dom.ls.*; +import org.xml.sax.*; + +@SuppressWarnings({"javadoc"}) +public class TestUtils { + + private static JsonSerializer js = new JsonSerializer.Simple() + .setProperty(SERIALIZER_trimNullProperties, false); + + private static JsonSerializer jsSorted = new JsonSerializer.Simple() + .setProperty(SERIALIZER_sortCollections, true) + .setProperty(SERIALIZER_sortMaps, true) + .setProperty(SERIALIZER_trimNullProperties, false); + + + private static JsonSerializer js2 = new JsonSerializer.Simple() + .addPojoSwaps(IteratorSwap.class, EnumerationSwap.class); + + private static JsonSerializer js3 = new JsonSerializer.Simple() + .addPojoSwaps(IteratorSwap.class, EnumerationSwap.class) + .setProperty(BEAN_sortProperties, true); + + /** + * Verifies that two objects are equivalent. + * Does this by doing a string comparison after converting both to JSON. + */ + public static void assertEqualObjects(Object o1, Object o2) throws SerializeException { + assertEqualObjects(o1, o2, false); + } + + /** + * Verifies that two objects are equivalent. + * Does this by doing a string comparison after converting both to JSON. + * @param sort If <jk>true</jk> sort maps and collections before comparison. + */ + public static void assertEqualObjects(Object o1, Object o2, boolean sort) throws SerializeException { + JsonSerializer s = (sort ? jsSorted : js); + String s1 = s.serialize(o1); + String s2 = s.serialize(o2); + if (s1.equals(s2)) + return; + throw new ComparisonFailure(null, s1, s2); + } + + /** + * Validates that the whitespace is correct in the specified XML. + */ + public static void checkXmlWhitespace(String out) throws SerializeException { + if (out.indexOf('\u0000') != -1) { + for (String s : out.split("\u0000")) + checkXmlWhitespace(s); + return; + } + + int indent = -1; + Pattern startTag = Pattern.compile("^(\\s*)<[^/>]+(\\s+\\S+=['\"]\\S*['\"])*\\s*>$"); + Pattern endTag = Pattern.compile("^(\\s*)</[^>]+>$"); + Pattern combinedTag = Pattern.compile("^(\\s*)<[^>/]+(\\s+\\S+=['\"]\\S*['\"])*\\s*/>$"); + Pattern contentOnly = Pattern.compile("^(\\s*)[^\\s\\<]+$"); + Pattern tagWithContent = Pattern.compile("^(\\s*)<[^>]+>.*</[^>]+>$"); + String[] lines = out.split("\n"); + try { + for (int i = 0; i < lines.length; i++) { + String line = lines[i]; + Matcher m = startTag.matcher(line); + if (m.matches()) { + indent++; + if (m.group(1).length() != indent) + throw new SerializeException("Wrong indentation detected on start tag line ''{0}''", i+1); + continue; + } + m = endTag.matcher(line); + if (m.matches()) { + if (m.group(1).length() != indent) + throw new SerializeException("Wrong indentation detected on end tag line ''{0}''", i+1); + indent--; + continue; + } + m = combinedTag.matcher(line); + if (m.matches()) { + indent++; + if (m.group(1).length() != indent) + throw new SerializeException("Wrong indentation detected on combined tag line ''{0}''", i+1); + indent--; + continue; + } + m = contentOnly.matcher(line); + if (m.matches()) { + indent++; + if (m.group(1).length() != indent) + throw new SerializeException("Wrong indentation detected on content-only line ''{0}''", i+1); + indent--; + continue; + } + m = tagWithContent.matcher(line); + if (m.matches()) { + indent++; + if (m.group(1).length() != indent) + throw new SerializeException("Wrong indentation detected on tag-with-content line ''{0}''", i+1); + indent--; + continue; + } + throw new SerializeException("Unmatched whitespace line at line number ''{0}''", i+1); + } + if (indent != -1) + throw new SerializeException("Possible unmatched tag. indent=''{0}''", indent); + } catch (SerializeException e) { + printLines(lines); + throw e; + } + } + + private static void printLines(String[] lines) { + for (int i = 0; i < lines.length; i++) + System.err.println(String.format("%4s:" + lines[i], i+1)); + } + + /** + * Validates that the specified XML conforms to the specified schema. + */ + private static void validateXml(String xml, String xmlSchema) throws Exception { + // parse an XML document into a DOM tree + DocumentBuilderFactory f = DocumentBuilderFactory.newInstance(); + f.setNamespaceAware(true); + DocumentBuilder documentBuilder = f.newDocumentBuilder(); + Document document = documentBuilder.parse(new InputSource(new StringReader(xml))); + + // create a SchemaFactory capable of understanding WXS schemas + SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); + + if (xmlSchema.indexOf('\u0000') != -1) { + + // Break it up into a map of namespaceURI->schema document + final Map<String,String> schemas = new HashMap<String,String>(); + String[] ss = xmlSchema.split("\u0000"); + xmlSchema = ss[0]; + for (String s : ss) { + Matcher m = pTargetNs.matcher(s); + if (m.find()) + schemas.put(m.group(1), s); + } + + // Create a custom resolver + factory.setResourceResolver( + new LSResourceResolver() { + + @Override /* LSResourceResolver */ + public LSInput resolveResource(String type, String namespaceURI, String publicId, String systemId, String baseURI) { + + String schema = schemas.get(namespaceURI); + if (schema == null) + throw new RuntimeException(MessageFormat.format("No schema found for namespaceURI ''{0}''", namespaceURI)); + + try { + DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance(); + DOMImplementationLS domImplementationLS = (DOMImplementationLS)registry.getDOMImplementation("LS 3.0"); + LSInput in = domImplementationLS.createLSInput(); + in.setCharacterStream(new StringReader(schema)); + in.setSystemId(systemId); + return in; + + } catch (Exception e) { + throw new RuntimeException(e); + } + } + } + ); + } + + Schema schema = factory.newSchema(new StreamSource(new StringReader(xmlSchema))); + + // create a Validator instance, which can be used to validate an instance document + Validator validator = schema.newValidator(); + + // validate the DOM tree + validator.validate(new DOMSource(document)); + } + + private static Pattern pTargetNs = Pattern.compile("targetNamespace=['\"]([^'\"]+)['\"]"); + + public static void validateXml(Object o) throws Exception { + validateXml(o, XmlSerializer.DEFAULT_NS_SQ); + } + + /** + * Test whitespace and generated schema. + */ + public static void validateXml(Object o, XmlSerializer s) throws Exception { + s = s.clone().setProperty(SERIALIZER_useIndentation, true).setProperty(XML_enableNamespaces, true).setProperty(XML_addNamespaceUrisToRoot, true); + String xml = s.serialize(o); + + String xmlSchema = null; + try { + xmlSchema = s.getSchemaSerializer().serialize(o); + TestUtils.checkXmlWhitespace(xml); + TestUtils.checkXmlWhitespace(xmlSchema); + TestUtils.validateXml(xml, xmlSchema); + } catch (Exception e) { + System.err.println("---XML---"); + System.err.println(xml); + System.err.println("---XMLSchema---"); + System.err.println(xmlSchema); + throw e; + } + } + + /** + * Reads the specified file at the specified path. + * Removes '\r' characters. + * Remove license headers. + */ + public static String readFile(String path) throws Exception { + InputStream is = TestUtils.class.getResourceAsStream(path); + if (is == null) { + is = new FileInputStream(path); + } + String e = IOUtils.read(is); + e = e.replaceAll("\r", ""); + if (path.endsWith(".xml")) { + e = e.replaceAll("(?s)\\<\\!\\-\\-(.*)\\-\\-\\>\\s*", ""); + e = e.replaceAll("\\<\\?.*\\?\\>\\s*", ""); + } else if (path.endsWith(".json")) { + e = e.replaceAll("\\/\\/ \\*.*\\s*", ""); + } + return e; + } + + final protected static char[] hexArray = "0123456789ABCDEF".toCharArray(); + public static String toHex(byte b) { + char[] c = new char[2]; + int v = b & 0xFF; + c[0] = hexArray[v >>> 4]; + c[1] = hexArray[v & 0x0F]; + return new String(c); + } + + public static void debugOut(Object o) { + try { + System.err.println(StringUtils.decodeHex(JsonSerializer.DEFAULT_LAX.serialize(o))); + } catch (SerializeException e) { + e.printStackTrace(); + } + } + + /** + * Sort an XML document by element and attribute names. + * This method is primarily meant for debugging purposes. + */ + private static final String sortXml(String xml) throws Exception { + xml = xml.replaceAll("\\w+\\:", "").replaceAll(">\\s+<", "><"); // Strip out all namespaces and whitespace. + + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + DocumentBuilder db = dbf.newDocumentBuilder(); + Document doc = db.parse(new InputSource(new StringReader(xml))); + + SortedNode n = new SortedNode(doc.getDocumentElement()); + return n.toString(); + } + + /** + * A sorted node in a DOM tree. + */ + private static class SortedNode implements Comparable<SortedNode> { + public String name, text="", attrs=""; + public List<SortedNode> children = new LinkedList<SortedNode>(); + + SortedNode(Element e) { + this.name = e.getNodeName(); + NamedNodeMap attrs = e.getAttributes(); + if (attrs != null) { + StringBuilder sb = new StringBuilder(); + Set<String> attrNames = new TreeSet<String>(); + for (int i = 0; i < attrs.getLength(); i++) + attrNames.add(attrs.item(i).getNodeName()); + for (String n : attrNames) { + Node node = attrs.getNamedItem(n); + sb.append(" ").append(n).append("='").append(node.getNodeValue()).append("'"); + } + this.attrs = sb.toString(); + } + NodeList nl = e.getChildNodes(); + for (int i = 0; i < nl.getLength(); i++) { + Node n = nl.item(i); + if (n instanceof Element) + children.add(new SortedNode((Element)nl.item(i))); + if (n instanceof Text) + this.text += ((Text)n).getNodeValue(); + } + Collections.sort(children); + } + + @Override + public int compareTo(SortedNode n) { + int i = name.compareTo(n.name); + if (i != 0) + return i; + i = attrs.compareTo(n.attrs); + if (i != 0) + return i; + i = text.compareTo(n.text); + if (i != 0) + return i; + return 0; + } + + @Override + public String toString() { + return toString(0, new StringBuilder()).toString(); + } + + public StringBuilder toString(int depth ,StringBuilder sb) { + indent(depth, sb).append("<").append(name).append(attrs); + if (children.isEmpty() && text.isEmpty()) { + sb.append("/>\n"); + return sb; + } + sb.append(">\n"); + if (! text.isEmpty()) + indent(depth+1, sb).append(text).append("\n"); + for (SortedNode c : children) { + c.toString(depth+1, sb); + } + indent(depth, sb).append("</").append(name).append(">\n"); + return sb; + } + } + + private static StringBuilder indent(int depth, StringBuilder sb) { + for (int i = 0; i < depth; i++) + sb.append("\t"); + return sb; + } + + /** + * Compares two XML documents for equality. + * Namespaces are stripped from each and elements/attributes are ordered in alphabetical order, + * then a simple string comparison is performed. + */ + public static final void assertXmlEquals(String expected, String actual) throws Exception { + assertEquals(sortXml(expected), sortXml(actual)); + } + + /** + * Assert that the object equals the specified string after running it through JsonSerializer.DEFAULT_LAX.toString(). + */ + public static void assertObjectEquals(String s, Object o) { + assertObjectEquals(s, o, js2); + } + + /** + * Assert that the object equals the specified string after running it through JsonSerializer.DEFAULT_LAX.toString() + * with BEAN_sortProperties set to true. + */ + public static void assertSortedObjectEquals(String s, Object o) { + assertObjectEquals(s, o, js3); + } + + /** + * Assert that the object equals the specified string after running it through ws.toString(). + */ + public static void assertObjectEquals(String s, Object o, WriterSerializer ws) { + Assert.assertEquals(s, ws.toString(o)); + } + + /** + * Replaces all newlines with pipes, then compares the strings. + */ + public static void assertTextEquals(String s, Object o) { + String s2 = o.toString().replaceAll("\\r?\\n", "|"); + Assert.assertEquals(s, s2); + } + + public static String toReadableBytes(byte[] b) { + StringBuilder sb = new StringBuilder(); + for (byte b2 : b) + sb.append((b2 < ' ' || b2 > 'z') ? String.format("[%02X]", b2) : (char)b2 + " "); + sb.append("\n"); + for (byte b2 : b) + sb.append(String.format("[%02X]", b2)); + return sb.toString(); + } + + public static String toReadableBytes2(byte[] b) { + StringBuilder sb = new StringBuilder(); + for (byte b2 : b) + sb.append(String.format("%02X ", b2)); + return sb.toString().trim(); + } + + /** + * Tries to turn the serialized output to a String. + * If it's a byte[], convert it to a UTF-8 encoded String. + */ + public static String toString(Object o) { + if (o instanceof String) + return (String)o; + try { + return new String((byte[])o, "UTF-8"); + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + } + return null; + } + + private static ThreadLocal<TimeZone> systemTimeZone = new ThreadLocal<TimeZone>(); + private static ThreadLocal<Locale> systemLocale = new ThreadLocal<Locale>(); + + /** + * Temporarily sets the default system timezone to the specified timezone ID. + * Use {@link #unsetTimeZone()} to unset it. + * + * @param name + */ + public static void setTimeZone(String name) { + systemTimeZone.set(TimeZone.getDefault()); + TimeZone.setDefault(TimeZone.getTimeZone(name)); + } + + public static void unsetTimeZone() { + TimeZone.setDefault(systemTimeZone.get()); + } + + /** + * Temporarily sets the default system locale to the specified locale. + * Use {@link #unsetLocale()} to unset it. + * + * @param name + */ + public static void setLocale(Locale locale) { + systemLocale.set(Locale.getDefault()); + Locale.setDefault(locale); + } + + public static void unsetLocale() { + Locale.setDefault(systemLocale.get()); + } +} http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/e4dfdf81/juneau-core-test/src/test/java/org/apache/juneau/VisibilityTest.java ---------------------------------------------------------------------- diff --git a/juneau-core-test/src/test/java/org/apache/juneau/VisibilityTest.java b/juneau-core-test/src/test/java/org/apache/juneau/VisibilityTest.java new file mode 100755 index 0000000..953dd45 --- /dev/null +++ b/juneau-core-test/src/test/java/org/apache/juneau/VisibilityTest.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; + +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.*; + +@SuppressWarnings("javadoc") +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/e4dfdf81/juneau-core-test/src/test/java/org/apache/juneau/XmlValidatorParser.java ---------------------------------------------------------------------- diff --git a/juneau-core-test/src/test/java/org/apache/juneau/XmlValidatorParser.java b/juneau-core-test/src/test/java/org/apache/juneau/XmlValidatorParser.java new file mode 100755 index 0000000..34a3ff9 --- /dev/null +++ b/juneau-core-test/src/test/java/org/apache/juneau/XmlValidatorParser.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; + +import static javax.xml.stream.XMLStreamConstants.*; + +import java.io.*; +import java.lang.reflect.*; +import java.util.*; + +import javax.xml.stream.*; + +import org.apache.juneau.parser.*; +import org.apache.juneau.xml.*; + +/** + * Used to validate that the syntax of XML documents are valid. + */ +@SuppressWarnings({"unchecked","javadoc"}) +public class XmlValidatorParser extends XmlParser { + + public XmlValidatorParser() { + super(); + } + + @Override /* Parser */ + protected <T> T doParse(ParserSession session, ClassMeta<T> type) throws Exception { + return (T)validate(session.getReader()); + } + + public <T> T validate(Reader r) throws Exception { + XMLStreamReader sr = getStaxReader(r); + while(sr.next() != END_DOCUMENT){} + return null; + } + + @Override /* ReaderParser */ + protected <K,V> Map<K,V> doParseIntoMap(ParserSession session, Map<K,V> m, Type keyType, Type valueType) throws Exception { + return (Map<K,V>)validate(session.getReader()); + } + + @Override /* ReaderParser */ + protected <E> Collection<E> doParseIntoCollection(ParserSession session, Collection<E> c, Type elementType) throws Exception { + return (Collection<E>)validate(session.getReader()); + } + + @Override /* ReaderParser */ + protected Object[] doParseArgs(ParserSession session, ClassMeta<?>[] argTypes) throws Exception { + return (Object[])validate(session.getReader()); + } + + protected XMLStreamReader getStaxReader(Reader in) throws Exception { + XMLInputFactory factory = XMLInputFactory.newInstance(); + factory.setProperty("javax.xml.stream.isNamespaceAware", false); + XMLStreamReader parser = factory.createXMLStreamReader(in); + parser.nextTag(); + return parser; + } + + @Override /* Lockable */ + public XmlValidatorParser clone() { + return (XmlValidatorParser)super.clone(); + } +} http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/e4dfdf81/juneau-core-test/src/test/java/org/apache/juneau/a/A1.java ---------------------------------------------------------------------- diff --git a/juneau-core-test/src/test/java/org/apache/juneau/a/A1.java b/juneau-core-test/src/test/java/org/apache/juneau/a/A1.java new file mode 100755 index 0000000..5db099c --- /dev/null +++ b/juneau-core-test/src/test/java/org/apache/juneau/a/A1.java @@ -0,0 +1,191 @@ +// *************************************************************************************************************************** +// * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file * +// * distributed with this work for additional information regarding copyright ownership. The ASF licenses this file * +// * to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance * +// * with the License. You may obtain a copy of the License at * +// * * +// * http://www.apache.org/licenses/LICENSE-2.0 * +// * * +// * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an * +// * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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; + +import org.apache.juneau.annotation.*; + +// Default class +@SuppressWarnings({"unused","synthetic-access","javadoc"}) +@Bean(sort=true) +public class A1 { + public int f1; + protected int f2; + int f3; + private int f4; + + @BeanIgnore + private int f5, f6, f7, f8; + + public int getF5() { return f5; } + public void setF5(int f5) { this.f5 = f5; } + protected int getF6() { return f6; } + protected void setF6(int f6) { this.f6 = f6; } + int getF7() { return f7; } + void setF7(int f7) { this.f7 = f7; } + private int getF8() { return f8; } + private void setF8(int f8) { this.f8 = f8; } + + public A2 g2; + public A3 g3; + public A4 g4; + public A5 g5; + + public static A1 create() { + A1 x = new A1(); + x.f1 = 1; + x.f2 = 2; + x.f3 = 3; + x.f4 = 4; + x.f5 = 5; + x.f6 = 6; + x.f7 = 7; + x.f8 = 8; + x.g2 = new A2(); + x.g2.f1 = 1; + x.g2.f2 = 2; + x.g2.f3 = 3; + x.g2.f4 = 4; + x.g2.f5 = 5; + x.g2.f6 = 6; + x.g2.f7 = 7; + x.g2.f8 = 8; + x.g3 = new A3(); + x.g3.f1 = 1; + x.g3.f2 = 2; + x.g3.f3 = 3; + x.g3.f4 = 4; + x.g3.f5 = 5; + x.g3.f6 = 6; + x.g3.f7 = 7; + x.g3.f8 = 8; + x.g4 = new A4(); + x.g4.f1 = 1; + x.g4.f2 = 2; + x.g4.f3 = 3; + x.g4.f4 = 4; + x.g4.f5 = 5; + x.g4.f6 = 6; + x.g4.f7 = 7; + x.g4.f8 = 8; + x.g5 = new A5(); + x.g5.f1 = 1; + x.g5.f2 = 2; + x.g5.f3 = 3; + x.g5.f4 = 4; + x.g5.f5 = 5; + x.g5.f6 = 6; + x.g5.f7 = 7; + x.g5.f8 = 8; + return x; + } + + @Bean(sort=true) + public static class A2 { + public int f1; + protected int f2; + int f3; + private int f4; + + @BeanIgnore + private int f5, f6, f7, f8; + + public int getF5() { return f5; } + public void setF5(int f5) { this.f5 = f5; } + protected int getF6() { return f6; } + protected void setF6(int f6) { this.f6 = f6; } + int getF7() { return f7; } + void setF7(int f7) { this.f7 = f7; } + private int getF8() { return f8; } + private void setF8(int f8) { this.f8 = f8; } + + @Override /* Object */ + public String toString() { + return "A2"; + } + } + + @Bean(sort=true) + protected static class A3 { + public int f1; + protected int f2; + int f3; + private int f4; + + @BeanIgnore + private int f5, f6, f7, f8; + + public int getF5() { return f5; } + public void setF5(int f5) { this.f5 = f5; } + protected int getF6() { return f6; } + protected void setF6(int f6) { this.f6 = f6; } + int getF7() { return f7; } + void setF7(int f7) { this.f7 = f7; } + private int getF8() { return f8; } + private void setF8(int f8) { this.f8 = f8; } + + @Override /* Object */ + public String toString() { + return "A3"; + } + } + + @Bean(sort=true) + static class A4 { + public int f1; + protected int f2; + int f3; + private int f4; + + @BeanIgnore + private int f5, f6, f7, f8; + + public int getF5() { return f5; } + public void setF5(int f5) { this.f5 = f5; } + protected int getF6() { return f6; } + protected void setF6(int f6) { this.f6 = f6; } + int getF7() { return f7; } + void setF7(int f7) { this.f7 = f7; } + private int getF8() { return f8; } + private void setF8(int f8) { this.f8 = f8; } + + @Override /* Object */ + public String toString() { + return "A4"; + } + } + + @Bean(sort=true) + private static class A5 { + public int f1; + protected int f2; + int f3; + private int f4; + + @BeanIgnore + private int f5, f6, f7, f8; + + public int getF5() { return f5; } + public void setF5(int f5) { this.f5 = f5; } + protected int getF6() { return f6; } + protected void setF6(int f6) { this.f6 = f6; } + int getF7() { return f7; } + void setF7(int f7) { this.f7 = f7; } + private int getF8() { return f8; } + private void setF8(int f8) { this.f8 = f8; } + + @Override /* Object */ + public String toString() { + return "A5"; + } + } +} http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/e4dfdf81/juneau-core-test/src/test/java/org/apache/juneau/a/rttests/RoundTripAddClassAttrsTest.java ---------------------------------------------------------------------- diff --git a/juneau-core-test/src/test/java/org/apache/juneau/a/rttests/RoundTripAddClassAttrsTest.java b/juneau-core-test/src/test/java/org/apache/juneau/a/rttests/RoundTripAddClassAttrsTest.java new file mode 100755 index 0000000..1a7fb26 --- /dev/null +++ b/juneau-core-test/src/test/java/org/apache/juneau/a/rttests/RoundTripAddClassAttrsTest.java @@ -0,0 +1,358 @@ +// *************************************************************************************************************************** +// * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file * +// * distributed with this work for additional information regarding copyright ownership. The ASF licenses this file * +// * to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance * +// * with the License. You may obtain a copy of the License at * +// * * +// * http://www.apache.org/licenses/LICENSE-2.0 * +// * * +// * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an * +// * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.annotation.*; +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. + */ +@SuppressWarnings("javadoc") +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_addBeanTypeProperties, 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_addBeanTypeProperties, 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_addBeanTypeProperties, true).setClassLoader(RoundTripAddClassAttrsTest.class.getClassLoader()), + new JsonParser().setProperty(BEAN_useInterfaceProxies, false).setClassLoader(RoundTripAddClassAttrsTest.class.getClassLoader()), + 0 + }, + { /* 3 */ + "XmlSerializer.DEFAULT/XmlParser.DEFAULT", + new XmlSerializer().setProperty(SERIALIZER_addBeanTypeProperties, 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_addBeanTypeProperties, 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_addBeanTypeProperties, 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_addBeanTypeProperties, 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_addBeanTypeProperties, 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_addBeanTypeProperties, 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_addBeanTypeProperties, 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); + } + + @Override + public Class<?>[] getDictionary() { + return new Class<?>[]{A.class, B.class, C.class, D.class, E.class, F.class}; + } + + //==================================================================================================== + // 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 { + } + + @Bean(typeName="A") + 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()); + } + + //==================================================================================================== + // 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()); + } + + @Bean(typeName="B") + 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()); + } + + @Bean(typeName="C") + 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()); + } + + @Bean(typeName="D") + 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()); + } + + @Bean(typeName="E") + 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()); + } + + @Bean(typeName="F") + 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); + } + } +}
