http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/91a388d0/juneau-samples/src/test/java/org/apache/juneau/rest/samples/TestUtils.java ---------------------------------------------------------------------- diff --git a/juneau-samples/src/test/java/org/apache/juneau/rest/samples/TestUtils.java b/juneau-samples/src/test/java/org/apache/juneau/rest/samples/TestUtils.java new file mode 100644 index 0000000..6610e18 --- /dev/null +++ b/juneau-samples/src/test/java/org/apache/juneau/rest/samples/TestUtils.java @@ -0,0 +1,360 @@ +// *************************************************************************************************************************** +// * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file * +// * distributed with this work for additional information regarding copyright ownership. The ASF licenses this file * +// * to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance * +// * with the License. You may obtain a copy of the License at * +// * * +// * http://www.apache.org/licenses/LICENSE-2.0 * +// * * +// * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an * +// * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * +// * specific language governing permissions and limitations under the License. * +// *************************************************************************************************************************** +package org.apache.juneau.rest.samples; + +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.*; +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.*; + +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; + } + } + + public static String readFile(String p) throws Exception { + InputStream is = TestUtils.class.getResourceAsStream(p); + if (is == null) { + is = new FileInputStream(p); + } + String e = IOUtils.read(is); + e = e.replaceAll("\r", ""); + 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+\\:", ""); // Strip out all namespaces. + + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + dbf.setIgnoringElementContentWhitespace(true); + dbf.setNamespaceAware(false); + DocumentBuilder db = dbf.newDocumentBuilder(); + Document doc = db.parse(new InputSource(new StringReader(xml))); + + DOMSource s = new DOMSource(doc); + + StringWriter sw = new StringWriter(); + StreamResult sr = new StreamResult(sw); + XML_SORT_TRANSFORMER.transform(s, sr); + return sw.toString().replace('"', '\'').replace("\r", ""); + } + + /** + * 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)); + } + + private static Transformer XML_SORT_TRANSFORMER; + static { + try { + String xsl = "" + + " <xsl:stylesheet version='1.0'" + + " xmlns:xsl='http://www.w3.org/1999/XSL/Transform'>" + + " <xsl:output omit-xml-declaration='yes' indent='yes'/>" + + " <xsl:strip-space elements='*'/>" + + " <xsl:template match='node()|@*'>" + + " <xsl:copy>" + + " <xsl:apply-templates select='@*'>" + + " <xsl:sort select='name()'/>" + + " </xsl:apply-templates>" + + " <xsl:apply-templates select='node()'>" + + " <xsl:sort select='name()'/>" + + " <xsl:sort select='text()'/>" + + " </xsl:apply-templates>" + + " </xsl:copy>" + + " </xsl:template>" + + " </xsl:stylesheet>"; + TransformerFactory tf = TransformerFactory.newInstance(); + StreamSource ss = new StreamSource(new StringReader(xsl)); + XML_SORT_TRANSFORMER = tf.newTransformer(ss); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + /** + * 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); + } +}
http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/91a388d0/juneau-samples/src/test/java/org/apache/juneau/rest/samples/_TestSuite.java ---------------------------------------------------------------------- diff --git a/juneau-samples/src/test/java/org/apache/juneau/rest/samples/_TestSuite.java b/juneau-samples/src/test/java/org/apache/juneau/rest/samples/_TestSuite.java new file mode 100644 index 0000000..34c40cb --- /dev/null +++ b/juneau-samples/src/test/java/org/apache/juneau/rest/samples/_TestSuite.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.rest.samples; + +import java.util.*; + +import org.apache.juneau.microservice.*; +import org.junit.*; +import org.junit.runner.*; +import org.junit.runners.*; +import org.junit.runners.Suite.*; + +/** + * Runs all the testcases in this project. + * Starts a REST service running org.apache.juneau.rest.samples.RootResources on port 10000. + * Stops the REST service after running the tests. + */ +@RunWith(Suite.class) +@SuiteClasses({ + AddressBookResourceTest.class, + RootResourcesTest.class, + SampleRemoteableServicesResourceTest.class, + TestMultiPartFormPostsTest.class +}) +public class _TestSuite { + static Microservice microservice; + + @BeforeClass + public static void setUp() { + try { + Locale.setDefault(Locale.US); + microservice = new RestMicroservice().setConfig("samples.cfg", false); + microservice.start(); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + @AfterClass + public static void tearDown() { + try { + microservice.stop(); + } catch (Exception e) { + throw new RuntimeException(e); + } + } +} http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/91a388d0/juneau-samples/src/test/java/org/apache/juneau/server/samples/AddressBookResourceTest.java ---------------------------------------------------------------------- diff --git a/juneau-samples/src/test/java/org/apache/juneau/server/samples/AddressBookResourceTest.java b/juneau-samples/src/test/java/org/apache/juneau/server/samples/AddressBookResourceTest.java deleted file mode 100755 index 4ff5e08..0000000 --- a/juneau-samples/src/test/java/org/apache/juneau/server/samples/AddressBookResourceTest.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 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().addPojoSwaps(CalendarSwap.DateMedium.class); - c.getParser().addPojoSwaps(CalendarSwap.DateMedium.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().addPojoSwaps(CalendarSwap.DateMedium.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.createSession().toBeanMap(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/91a388d0/juneau-samples/src/test/java/org/apache/juneau/server/samples/CT_AddressBookResource_test0.json ---------------------------------------------------------------------- diff --git a/juneau-samples/src/test/java/org/apache/juneau/server/samples/CT_AddressBookResource_test0.json b/juneau-samples/src/test/java/org/apache/juneau/server/samples/CT_AddressBookResource_test0.json deleted file mode 100755 index f8cc23f..0000000 --- a/juneau-samples/src/test/java/org/apache/juneau/server/samples/CT_AddressBookResource_test0.json +++ /dev/null @@ -1,26 +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. * -// *************************************************************************************************************************** -{ - name: "Bill Clinton", - age: 66, - birthDate: "Aug 19, 1946", - addresses: [ - { - street: "a3", - city: "b3", - state: "c3", - zip: 3, - isCurrent: false - } - ] -} \ No newline at end of file http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/91a388d0/juneau-samples/src/test/java/org/apache/juneau/server/samples/RootResourcesTest.java ---------------------------------------------------------------------- diff --git a/juneau-samples/src/test/java/org/apache/juneau/server/samples/RootResourcesTest.java b/juneau-samples/src/test/java/org/apache/juneau/server/samples/RootResourcesTest.java deleted file mode 100755 index 5da5fba..0000000 --- a/juneau-samples/src/test/java/org/apache/juneau/server/samples/RootResourcesTest.java +++ /dev/null @@ -1,147 +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.dto.swagger.*; -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.getObjectMap("info").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.getObjectMap("info").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.getObjectMap("info").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(""); - Swagger o = r.getResponse(Swagger.class); - if (debug) System.err.println(o); - assertEquals("This is an example of a router resource that is used to access other resources.", o.getInfo().getDescription()); - } -} http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/91a388d0/juneau-samples/src/test/java/org/apache/juneau/server/samples/SampleRemoteableServicesResourceTest.java ---------------------------------------------------------------------- diff --git a/juneau-samples/src/test/java/org/apache/juneau/server/samples/SampleRemoteableServicesResourceTest.java b/juneau-samples/src/test/java/org/apache/juneau/server/samples/SampleRemoteableServicesResourceTest.java deleted file mode 100755 index 6cce905..0000000 --- a/juneau-samples/src/test/java/org/apache/juneau/server/samples/SampleRemoteableServicesResourceTest.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 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.addPojoSwaps(CalendarSwap.DateMedium.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/91a388d0/juneau-samples/src/test/java/org/apache/juneau/server/samples/SamplesRestClient.java ---------------------------------------------------------------------- diff --git a/juneau-samples/src/test/java/org/apache/juneau/server/samples/SamplesRestClient.java b/juneau-samples/src/test/java/org/apache/juneau/server/samples/SamplesRestClient.java deleted file mode 100755 index 00a1558..0000000 --- a/juneau-samples/src/test/java/org/apache/juneau/server/samples/SamplesRestClient.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 java.security.*; - -import javax.net.ssl.*; - -import org.apache.http.conn.ssl.*; -import org.apache.http.impl.client.*; -import org.apache.juneau.client.*; -import org.apache.juneau.parser.*; -import org.apache.juneau.serializer.*; - -/** - * REST client with lenient SSL support and lax redirection strategy. - */ -public class SamplesRestClient extends RestClient { - - public SamplesRestClient(Class<? extends Serializer> s, Class<? extends Parser> p) throws InstantiationException { - super(s,p); - setRootUrl(Constants.getSampleUrl()); - } - - public SamplesRestClient(Serializer s, Parser p) { - super(s,p); - setRootUrl(Constants.getSampleUrl()); - } - - public SamplesRestClient() { - setRootUrl(Constants.getSampleUrl()); - } - - public SamplesRestClient(CloseableHttpClient c) { - super(c); - setRootUrl(Constants.getSampleUrl()); - } - - public static SSLConnectionSocketFactory getSSLSocketFactory() throws Exception { - SSLContext sslContext = SSLContext.getInstance("SSL"); - TrustManager tm = new SimpleX509TrustManager(true); - sslContext.init(null, new TrustManager[]{tm}, new SecureRandom()); - return new SSLConnectionSocketFactory(sslContext, new NoopHostnameVerifier()); - } - - @Override /* RestClient */ - protected CloseableHttpClient createHttpClient() throws Exception { - try { - return HttpClients.custom().setSSLSocketFactory(getSSLSocketFactory()).setRedirectStrategy(new LaxRedirectStrategy()).build(); - } catch (KeyStoreException e) { - throw new RuntimeException(e); - } catch (NoSuchAlgorithmException e) { - throw new RuntimeException(e); - } catch (Throwable e) { - e.printStackTrace(); - return null; - } - } -} http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/91a388d0/juneau-samples/src/test/java/org/apache/juneau/server/samples/TestMultiPartFormPostsTest.java ---------------------------------------------------------------------- diff --git a/juneau-samples/src/test/java/org/apache/juneau/server/samples/TestMultiPartFormPostsTest.java b/juneau-samples/src/test/java/org/apache/juneau/server/samples/TestMultiPartFormPostsTest.java deleted file mode 100755 index 47639cb..0000000 --- a/juneau-samples/src/test/java/org/apache/juneau/server/samples/TestMultiPartFormPostsTest.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 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/91a388d0/juneau-samples/src/test/java/org/apache/juneau/server/samples/TestUtils.java ---------------------------------------------------------------------- diff --git a/juneau-samples/src/test/java/org/apache/juneau/server/samples/TestUtils.java b/juneau-samples/src/test/java/org/apache/juneau/server/samples/TestUtils.java deleted file mode 100755 index dce0ac6..0000000 --- a/juneau-samples/src/test/java/org/apache/juneau/server/samples/TestUtils.java +++ /dev/null @@ -1,360 +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.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.*; -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.*; - -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; - } - } - - public static String readFile(String p) throws Exception { - InputStream is = TestUtils.class.getResourceAsStream(p); - if (is == null) { - is = new FileInputStream(p); - } - String e = IOUtils.read(is); - e = e.replaceAll("\r", ""); - 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+\\:", ""); // Strip out all namespaces. - - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - dbf.setIgnoringElementContentWhitespace(true); - dbf.setNamespaceAware(false); - DocumentBuilder db = dbf.newDocumentBuilder(); - Document doc = db.parse(new InputSource(new StringReader(xml))); - - DOMSource s = new DOMSource(doc); - - StringWriter sw = new StringWriter(); - StreamResult sr = new StreamResult(sw); - XML_SORT_TRANSFORMER.transform(s, sr); - return sw.toString().replace('"', '\'').replace("\r", ""); - } - - /** - * 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)); - } - - private static Transformer XML_SORT_TRANSFORMER; - static { - try { - String xsl = "" - + " <xsl:stylesheet version='1.0'" - + " xmlns:xsl='http://www.w3.org/1999/XSL/Transform'>" - + " <xsl:output omit-xml-declaration='yes' indent='yes'/>" - + " <xsl:strip-space elements='*'/>" - + " <xsl:template match='node()|@*'>" - + " <xsl:copy>" - + " <xsl:apply-templates select='@*'>" - + " <xsl:sort select='name()'/>" - + " </xsl:apply-templates>" - + " <xsl:apply-templates select='node()'>" - + " <xsl:sort select='name()'/>" - + " <xsl:sort select='text()'/>" - + " </xsl:apply-templates>" - + " </xsl:copy>" - + " </xsl:template>" - + " </xsl:stylesheet>"; - TransformerFactory tf = TransformerFactory.newInstance(); - StreamSource ss = new StreamSource(new StringReader(xsl)); - XML_SORT_TRANSFORMER = tf.newTransformer(ss); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - - /** - * 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); - } -} http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/91a388d0/juneau-samples/src/test/java/org/apache/juneau/server/samples/_TestSuite.java ---------------------------------------------------------------------- diff --git a/juneau-samples/src/test/java/org/apache/juneau/server/samples/_TestSuite.java b/juneau-samples/src/test/java/org/apache/juneau/server/samples/_TestSuite.java deleted file mode 100644 index f3a751f..0000000 --- a/juneau-samples/src/test/java/org/apache/juneau/server/samples/_TestSuite.java +++ /dev/null @@ -1,57 +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 java.util.*; - -import org.apache.juneau.microservice.*; -import org.junit.*; -import org.junit.runner.*; -import org.junit.runners.*; -import org.junit.runners.Suite.*; - -/** - * Runs all the testcases in this project. - * Starts a REST service running org.apache.juneau.server.samples.RootResources on port 10000. - * Stops the REST service after running the tests. - */ -@RunWith(Suite.class) -@SuiteClasses({ - AddressBookResourceTest.class, - RootResourcesTest.class, - SampleRemoteableServicesResourceTest.class, - TestMultiPartFormPostsTest.class -}) -public class _TestSuite { - static Microservice microservice; - - @BeforeClass - public static void setUp() { - try { - Locale.setDefault(Locale.US); - microservice = new RestMicroservice().setConfig("samples.cfg", false); - microservice.start(); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - - @AfterClass - public static void tearDown() { - try { - microservice.stop(); - } catch (Exception e) { - throw new RuntimeException(e); - } - } -} http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/91a388d0/juneau-samples/war/web.xml ---------------------------------------------------------------------- diff --git a/juneau-samples/war/web.xml b/juneau-samples/war/web.xml index 21695e5..8307159 100755 --- a/juneau-samples/war/web.xml +++ b/juneau-samples/war/web.xml @@ -21,15 +21,15 @@ <servlet> <servlet-name>sample</servlet-name> - <servlet-class>org.apache.juneau.server.samples.RootResources</servlet-class> + <servlet-class>org.apache.juneau.rest.samples.RootResources</servlet-class> </servlet> <servlet> <servlet-name>test</servlet-name> - <servlet-class>org.apache.juneau.server.samples.test.Root</servlet-class> + <servlet-class>org.apache.juneau.rest.samples.test.Root</servlet-class> </servlet> <servlet> <servlet-name>testuris</servlet-name> - <servlet-class>org.apache.juneau.server.samples.test.TestUris</servlet-class> + <servlet-class>org.apache.juneau.rest.samples.test.TestUris</servlet-class> </servlet> <servlet-mapping> http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/91a388d0/juneau-server-test/.gitignore ---------------------------------------------------------------------- diff --git a/juneau-server-test/.gitignore b/juneau-server-test/.gitignore deleted file mode 100644 index 28aac3d..0000000 --- a/juneau-server-test/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -/logs/ -/target/ -/.settings/ -/.classpath http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/91a388d0/juneau-server-test/.project ---------------------------------------------------------------------- diff --git a/juneau-server-test/.project b/juneau-server-test/.project deleted file mode 100644 index b4c5196..0000000 --- a/juneau-server-test/.project +++ /dev/null @@ -1,28 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - *************************************************************************************************************************** - * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file * - * distributed with this work for additional information regarding copyright ownership. The ASF licenses this file * - * to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance * - * with the License. You may obtain a copy of the License at * - * * - * http://www.apache.org/licenses/LICENSE-2.0 * - * * - * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an * - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * - * specific language governing permissions and limitations under the License. * - *************************************************************************************************************************** ---> -<projectDescription> - <name>juneau-server-test</name> - <comment>Tests for Juneau Client and Server. NO_M2ECLIPSE_SUPPORT: Project files created with the maven-eclipse-plugin are not supported in M2Eclipse.</comment> - <projects/> - <buildSpec> - <buildCommand> - <name>org.eclipse.jdt.core.javabuilder</name> - </buildCommand> - </buildSpec> - <natures> - <nature>org.eclipse.jdt.core.javanature</nature> - </natures> -</projectDescription> \ No newline at end of file http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/91a388d0/juneau-server-test/juneau-server-test.cfg ---------------------------------------------------------------------- diff --git a/juneau-server-test/juneau-server-test.cfg b/juneau-server-test/juneau-server-test.cfg deleted file mode 100755 index 2b79931..0000000 --- a/juneau-server-test/juneau-server-test.cfg +++ /dev/null @@ -1,111 +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. * -# *************************************************************************************************************************** - -#================================================================================ -# Basic configuration file for SaaS microservices -# Subprojects can use this as a starting point. -#================================================================================ - -#================================================================================ -# REST settings -#================================================================================ -[REST] - -resources = org.apache.juneau.server.test.Root - -port = 10001 - -# Authentication: NONE, BASIC. -authType = NONE - -# What to do when the config file is saved. -# Possible values: -# NOTHING - Don't do anything. -# RESTART_SERVER - Restart the Jetty server. -# RESTART_SERVICE - Shutdown and exit with code '3'. -saveConfigAction = RESTART_SERVER - -useSsl = false - -#================================================================================ -# Bean properties on the org.eclipse.jetty.util.ssl.SslSocketFactory class -#-------------------------------------------------------------------------------- -# Specify any of the following fields: -# allowRenegotiate (boolean) -# certAlias (String) -# crlPath (String) -# enableCRLDP (boolean) -# enableOCSP (boolean) -# excludeCipherSuites (String[]) -# excludeProtocols (String[]) -# includeCipherSuites (String[]) -# includeProtocols (String...) -# keyManagerPassword (String) -# keyStore (String) -# keyStorePassword (String) -# keyStorePath (String) -# keyStoreProvider (String) -# keyStoreType (String) -# maxCertPathLength (int) -# needClientAuth (boolean) -# ocspResponderURL (String) -# protocol (String) -# provider (String) -# secureRandomAlgorithm (String) -# sessionCachingEnabled (boolean) -# sslKeyManagerFactoryAlgorithm (String) -# sslSessionCacheSize (int) -# sslSessionTimeout (int) -# trustAll (boolean) -# trustManagerFactoryAlgorithm (String) -# trustStore (String) -# trustStorePassword (String) -# trustStoreProvider (String) -# trustStoreType (String) -# validateCerts (boolean) -# validatePeerCerts (boolean) -# wantClientAuth (boolean) -#================================================================================ -[REST-SslContextFactory] -keyStorePath = client_keystore.jks -keyStorePassword* = {HRAaRQoT} -excludeCipherSuites = TLS_DHE.*, TLS_EDH.* -excludeProtocols = SSLv3 -allowRenegotiate = false - -#================================================================================ -# Logger settings -# See FileHandler Java class for details. -#================================================================================ -[Logging] -logDir = logs -logFile = test.%g.log -dateFormat = yyyy.MM.dd hh:mm:ss -format = [{date} {level}] {msg}%n -append = false -limit = 10M -count = 5 -levels = { com.foo.team:'INFO' } -useStackTraceHashes = true -consoleLevel = WARNING - -[Test] -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} -testManifestEntry = $MF{Test-Entry} http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/91a388d0/juneau-server-test/juneau-server-test.launch ---------------------------------------------------------------------- diff --git a/juneau-server-test/juneau-server-test.launch b/juneau-server-test/juneau-server-test.launch deleted file mode 100644 index 6ba4ec3..0000000 --- a/juneau-server-test/juneau-server-test.launch +++ /dev/null @@ -1,29 +0,0 @@ -<?xml version="1.0" encoding="UTF-8" standalone="no"?> -<!-- - *************************************************************************************************************************** - * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file * - * distributed with this work for additional information regarding copyright ownership. The ASF licenses this file * - * to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance * - * with the License. You may obtain a copy of the License at * - * * - * http://www.apache.org/licenses/LICENSE-2.0 * - * * - * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an * - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * - * specific language governing permissions and limitations under the License. * - *************************************************************************************************************************** ---> -<launchConfiguration type="org.eclipse.jdt.launching.localJavaApplication"> -<listAttribute key="org.eclipse.debug.core.MAPPED_RESOURCE_PATHS"> -<listEntry value="/juneau-microservice/src/main/java/org/apache/juneau/microservice/RestMicroservice.java"/> -</listAttribute> -<listAttribute key="org.eclipse.debug.core.MAPPED_RESOURCE_TYPES"> -<listEntry value="1"/> -</listAttribute> -<booleanAttribute key="org.eclipse.jdt.debug.ui.CONSIDER_INHERITED_MAIN" value="true"/> -<booleanAttribute key="org.eclipse.jdt.debug.ui.INCLUDE_EXTERNAL_JARS" value="true"/> -<booleanAttribute key="org.eclipse.jdt.launching.ATTR_USE_START_ON_FIRST_THREAD" value="true"/> -<stringAttribute key="org.eclipse.jdt.launching.MAIN_TYPE" value="org.apache.juneau.microservice.RestMicroservice"/> -<stringAttribute key="org.eclipse.jdt.launching.PROGRAM_ARGUMENTS" value="juneau-server-test.cfg"/> -<stringAttribute key="org.eclipse.jdt.launching.PROJECT_ATTR" value="juneau-server-test"/> -</launchConfiguration> http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/91a388d0/juneau-server-test/pom.xml ---------------------------------------------------------------------- diff --git a/juneau-server-test/pom.xml b/juneau-server-test/pom.xml deleted file mode 100644 index 4e8ee3b..0000000 --- a/juneau-server-test/pom.xml +++ /dev/null @@ -1,70 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - *************************************************************************************************************************** - * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file * - * distributed with this work for additional information regarding copyright ownership. The ASF licenses this file * - * to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance * - * with the License. You may obtain a copy of the License at * - * * - * http://www.apache.org/licenses/LICENSE-2.0 * - * * - * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an * - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * - * specific language governing permissions and limitations under the License. * - *************************************************************************************************************************** ---> -<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> - - <modelVersion>4.0.0</modelVersion> - <artifactId>juneau-server-test</artifactId> - <name>Apache Juneau Server Test</name> - <description>Tests for Juneau Client and Server.</description> - - <parent> - <groupId>org.apache.juneau</groupId> - <artifactId>juneau</artifactId> - <version>6.0.2-incubating-SNAPSHOT</version> - <relativePath>../pom.xml</relativePath> - </parent> - - <properties> - <encoding>UTF-8</encoding> - <maven.javadoc.skip>true</maven.javadoc.skip> - </properties> - - <dependencies> - <dependency> - <groupId>org.apache.juneau</groupId> - <artifactId>juneau-samples</artifactId> - <version>${project.version}</version> - </dependency> - <dependency> - <groupId>junit</groupId> - <artifactId>junit</artifactId> - </dependency> - <dependency> - <groupId>javax.ws.rs</groupId> - <artifactId>jsr311-api</artifactId> - </dependency> - <dependency> - <groupId>javax.servlet</groupId> - <artifactId>javax.servlet-api</artifactId> - </dependency> - </dependencies> - <build> - <plugins> - <plugin> - <groupId>org.apache.maven.plugins</groupId> - <artifactId>maven-surefire-plugin</artifactId> - <version>2.19.1</version> - <configuration> - <includes> - <include> - **/_TestSuite.java - </include> - </includes> - </configuration> - </plugin> - </plugins> - </build> -</project> \ No newline at end of file http://git-wip-us.apache.org/repos/asf/incubator-juneau/blob/91a388d0/juneau-server-test/src/main/java/org/apache/juneau/server/test/AcceptCharsetResource.java ---------------------------------------------------------------------- diff --git a/juneau-server-test/src/main/java/org/apache/juneau/server/test/AcceptCharsetResource.java b/juneau-server-test/src/main/java/org/apache/juneau/server/test/AcceptCharsetResource.java deleted file mode 100755 index 62deae4..0000000 --- a/juneau-server-test/src/main/java/org/apache/juneau/server/test/AcceptCharsetResource.java +++ /dev/null @@ -1,76 +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.test; - -import static org.apache.juneau.server.RestServletContext.*; - -import java.io.*; - -import org.apache.juneau.*; -import org.apache.juneau.annotation.*; -import org.apache.juneau.parser.*; -import org.apache.juneau.plaintext.*; -import org.apache.juneau.serializer.*; -import org.apache.juneau.server.*; -import org.apache.juneau.server.annotation.*; - -/** - * JUnit automated testcase resource. - */ -@RestResource( - path="/testAcceptCharset", - serializers={PlainTextSerializer.class}, - properties={ - // Some versions of Jetty default to ISO8601, so specify UTF-8 for test consistency. - @Property(name=REST_defaultCharset,value="utf-8") - } -) -public class AcceptCharsetResource extends RestServlet { - private static final long serialVersionUID = 1L; - - //==================================================================================================== - // Test that Q-values are being resolved correctly. - //==================================================================================================== - @RestMethod(name="GET", path="/testQValues") - public String testQValues() { - return "foo"; - } - - //==================================================================================================== - // Validate various Accept-Charset variations. - //==================================================================================================== - @RestMethod(name="PUT", path="/testCharsetOnResponse", parsers=TestParser.class, serializers=TestSerializer.class) - public String testCharsetOnResponse(@Body String in) { - return in; - } - - @Consumes("text/plain") - public static class TestParser extends InputStreamParser { - @SuppressWarnings("unchecked") - @Override /* Parser */ - protected <T> T doParse(ParserSession session, ClassMeta<T> type) throws Exception { - return (T)session.getProperties().getString("characterEncoding"); - } - } - - @Produces("text/plain") - public static class TestSerializer extends OutputStreamSerializer { - @Override /* Serializer */ - protected void doSerialize(SerializerSession session, Object o) throws Exception { - Writer w = new OutputStreamWriter(session.getOutputStream()); - w.append(o.toString()).append('/').append(session.getProperties().getString("characterEncoding")); - w.flush(); - w.close(); - } - } -}
