libexml-java-0.0.20080703.orig/0000755000175000017500000000000011111351376015522 5ustar twernertwernerlibexml-java-0.0.20080703.orig/http/0000755000175000017500000000000011111351353016474 5ustar twernertwernerlibexml-java-0.0.20080703.orig/http/src/0000755000175000017500000000000011111351351017261 5ustar twernertwernerlibexml-java-0.0.20080703.orig/http/src/test/0000755000175000017500000000000011111351351020240 5ustar twernertwernerlibexml-java-0.0.20080703.orig/http/src/test/java/0000755000175000017500000000000011111351351021161 5ustar twernertwernerlibexml-java-0.0.20080703.orig/http/src/test/java/net/0000755000175000017500000000000011111351351021747 5ustar twernertwernerlibexml-java-0.0.20080703.orig/http/src/test/java/net/noderunner/0000755000175000017500000000000011111351351024126 5ustar twernertwernerlibexml-java-0.0.20080703.orig/http/src/test/java/net/noderunner/http/0000755000175000017500000000000011111351351025105 5ustar twernertwernerlibexml-java-0.0.20080703.orig/http/src/test/java/net/noderunner/http/GeneralDataPosterTest.java0000644000175000017500000001235010762067376032203 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.http; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.InputStream; /** * This class is for unit testing {@link DataPoster} classes. * * @author Elias Ross * @version 1.0 */ public class GeneralDataPosterTest extends junit.framework.TestCase { public GeneralDataPosterTest(String name) { super(name); } public static void main(String[] args) { junit.textui.TestRunner.run(GeneralDataPosterTest.class); } /* public static junit.framework.TestSuite suite() { return new org.hansel.CoverageDecorator(GeneralDataPosterTest.class, new Class[] { GeneralDataPoster.class }); } */ /** * Doesn't allow marking. */ class ByteArrayInputStream2 extends ByteArrayInputStream { boolean tested = false; ByteArrayInputStream2(byte[] buf) { super(buf); } public boolean markSupported() { tested = true; return false; } public String toString() { return super.toString() + " tested=" + tested; } } public void testChunkLots() throws Exception { int len = 1024 * 64; byte b[] = new byte[len]; ByteArrayOutputStream baos = new ByteArrayOutputStream(); ByteArrayInputStream bais = new ByteArrayInputStream(b); DataPoster poster2 = new GeneralDataPoster(bais, -1); poster2.sendData(baos); InputStream is = new ChunkedInputStream(new ByteArrayInputStream(baos.toByteArray())); int total = 0; while (true) { int got = is.read(b); if (got == -1) break; total += got; } assertEquals("got back lots of bytes", len, total); } public void testChunk() throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ByteArrayInputStream bais = new ByteArrayInputStream(new byte[] { 1, 2, 3 }); DataPoster poster2 = new GeneralDataPoster(bais, -1); poster2.sendData(baos); byte b[] = new byte[3]; InputStream is = new ChunkedInputStream(new ByteArrayInputStream(baos.toByteArray())); int got = is.read(b); assertEquals("got back 3 bytes", 3, got); assertEquals("got back 1 2 3", 1, b[0]); assertEquals("got back 1 2 3", 2, b[1]); assertEquals("got back 1 2 3", 3, b[2]); } public void testRepost() throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ByteArrayInputStream bais = new ByteArrayInputStream(new byte[] { 1, 2, 3 }); DataPoster poster2 = new GeneralDataPoster(bais, 2); poster2.sendData(baos); assertEquals("wrote 2 bytes", 2, baos.size()); poster2.sendData(baos); assertEquals("wrote 4 bytes", 4, baos.size()); poster2.sendData(baos); assertEquals("wrote 6 bytes", 6, baos.size()); } public void testCoverage() throws Exception { GeneralDataPoster gdp = new GeneralDataPoster(); gdp.toString(); gdp.init(null, 0); gdp.init(null, 0); ByteArrayOutputStream bos = new ByteArrayOutputStream(); gdp.sendData(bos); assertEquals(0, bos.size()); } public void testRepostChunked() throws Exception { GeneralDataPoster gdp = new GeneralDataPoster(); // use chunked gdp.init(new ByteArrayInputStream(new byte[]{ 'a', 'b' }), -1); ByteArrayOutputStream bos = new ByteArrayOutputStream(); gdp.sendData(bos); gdp.sendData(bos); byte[] a = bos.toByteArray(); ByteArrayInputStream bais = new ByteArrayInputStream(a); ChunkedInputStream cis; cis = new ChunkedInputStream(bais); assertEquals('a', cis.read()); assertEquals('b', cis.read()); assertEquals(-1, cis.read()); cis.close(); cis = new ChunkedInputStream(bais); assertEquals('a', cis.read()); assertEquals('b', cis.read()); } public void testExceptions() throws Exception { try { new GeneralDataPoster(null, 10); fail("null InputStream with non-zero length"); } catch (IllegalArgumentException e) { } DataPoster poster = new GeneralDataPoster(null, 0); try { poster.sendData(null); fail("null os"); } catch (IllegalArgumentException e) { } ByteArrayOutputStream baos; InputStream bais; DataPoster poster2; baos = new ByteArrayOutputStream(); bais = new ByteArrayInputStream2(new byte[] { 1, 2, 3 }); poster2 = new GeneralDataPoster(bais, 2); poster2.sendData(baos); try { poster2.sendData(baos); fail("cannot reset input stream"); } catch (HttpException e) { } assertEquals("only wrote 2 bytes", 2, baos.size()); baos = new ByteArrayOutputStream(); bais = new ByteArrayInputStream(new byte[] { 1, 2, 3 }); poster2 = new GeneralDataPoster(bais, 4); try { poster2.sendData(baos); fail("not enough data"); } catch (HttpException e) { } assertEquals("only wrote 3 bytes", 3, baos.size()); } } libexml-java-0.0.20080703.orig/http/src/test/java/net/noderunner/http/EasyHttpClientTest.java0000644000175000017500000003116210762067376031541 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.http; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.net.Socket; import java.net.SocketTimeoutException; import java.net.URL; import java.util.HashMap; import java.util.Map; /** * This class is for unit testing {@link EasyHttpClient}. * * @author Elias Ross * @version 1.0 */ public class EasyHttpClientTest extends junit.framework.TestCase { public EasyHttpClientTest(String name) { super(name); } public static class MyHttpServer extends ThreadedHttpServer { boolean doRead = true; boolean doPost = true; boolean doClose = false; boolean fail = false; boolean failAlways = false; int sleep = 1; volatile int requestCount = 0; StatusLine statusLine = StatusLine.HTTP11_200_OK; ServerRequest request; public MyHttpServer() throws IOException { super(); } public void handleRequest(Request req) throws IOException { HttpServer s = req.getServer(); // System.out.println("handleRequest " + s); requestCount++; request = s.readRequest(); // System.out.println("handleRequest " + request); InputStream is = request.getInputStream(); is = HttpUtil.wrapInputStream(is, request.getHeaders()); String result = "got "; if (doRead) { BufferedReader in = new BufferedReader( new InputStreamReader(is)); String line = in.readLine(); result += line; } if (fail) { fail = failAlways; throw new IOException("Told to fail"); } try { Thread.sleep(sleep); } catch (InterruptedException e) { System.out.println("Interrupted"); throw new IOException("Wakeup"); } if (doPost) { MessageHeader mh; mh = new MessageHeader(MessageHeader.FN_CONTENT_LENGTH, "" + result.length()); s.writeResponse(new ServerResponse(statusLine, new MessageHeader[] { mh })); PrintWriter out = new PrintWriter(new OutputStreamWriter(s .getOutputStream())); out.println(result); out.flush(); } else { if (doClose) { MessageHeader mh; mh = new MessageHeader(MessageHeader.FN_CONNECTION, "close"); s.writeResponse(new ServerResponse(statusLine, new MessageHeader[] { mh })); s.getOutputStream().close(); } else { MessageHeader mh; mh = new MessageHeader(MessageHeader.FN_CONTENT_LENGTH, "0"); s.writeResponse(new ServerResponse(statusLine, new MessageHeader[] { mh })); } } } } private class EasyHttpClientFactory2 { HttpClient c; EasyHttpClientFactory2(Socket s) throws IOException { c = new BasicHttpClient(s.getOutputStream(), s.getInputStream()); } public EasyHttpClient makeGetClient(URL url) { return new EasyHttpClient(c, url, Method.GET); } public EasyHttpClient makePostClient(URL url) { return new EasyHttpClient(c, url, Method.POST); } public EasyHttpClient makeClient(URL url, Method method) { return new EasyHttpClient(c, url, method); } } public void testEasyGet() throws Exception { MyHttpServer server = new MyHttpServer(); server.start(); server.doRead = false; Socket s = new Socket("127.0.0.1", server.getPort()); EasyHttpClientFactory2 factory = new EasyHttpClientFactory2(s); URL url = new URL("http://localhost"); EasyHttpClient ec; ec = factory.makeGetClient(url); assertEquals(null, ec.getLastResponse()); ec = factory.makeGetClient(url); BufferedReader br; br = ec.doGet(); String got = HttpUtil.read(br).trim(); assertEquals("got", got); assertEquals("/", server.request.getRequestLine().getRequestURI()); // try again ec.setFile("/otherfile"); HttpUtil.discard(ec.doGet()); assertEquals("/otherfile", server.request.getRequestLine() .getRequestURI()); // try 404 ec.setFile("/otherfile2"); server.statusLine = StatusLine.HTTP11_404; try { HttpUtil.read(ec.doGet()); fail("Bad HTTP status" + ec.getLastResponse()); } catch (HttpException e) { } assertEquals(404, ec.getLastResponse().getStatusLine().getStatusCode()); // ignore 404 ec.setCheckStatus(false); br = ec.doGet(); assertEquals(404, ec.getLastResponse().getStatusLine().getStatusCode()); got = HttpUtil.read(br).trim(); assertEquals("got", got); } public void testEasyPostRetry() throws Exception { MyHttpServer server = new MyHttpServer(); server.start(); server.fail = true; server.failAlways = false; URL url = new URL("http://localhost:" + server.getPort()); EasyHttpClient ec = new EasyHttpClient(url, Method.POST); String body = "abc=def"; BufferedReader br = ec.doPostUrlEncoded(body.getBytes()); String got = HttpUtil.read(br).trim(); assertEquals("got " + body, got); assertTrue("we tossed", server.requestCount >= 2); } public void testEasyPostRetry2() throws Exception { MyHttpServer server = new MyHttpServer(); server.start(); server.fail = true; server.failAlways = true; URL url = new URL("http://localhost:" + server.getPort()); EasyHttpClient ec = new EasyHttpClient(url, Method.POST); try { ec.doPostUrlEncoded("who cares\n".getBytes()); fail("should have failed"); } catch (IOException e) { } assertTrue("failed four times", server.requestCount >= 3); } /** * Doesn't allow marking. */ class ByteArrayInputStream2 extends ByteArrayInputStream { boolean tested = false; ByteArrayInputStream2(byte[] buf) { super(buf); } public boolean markSupported() { tested = true; return false; } public String toString() { return super.toString() + " tested=" + tested; } } public void testEasyPostRetry3() throws IOException { MyHttpServer server = new MyHttpServer(); server.start(); server.fail = true; server.failAlways = true; URL url = new URL("http://localhost:" + server.getPort()); EasyHttpClient ec = new EasyHttpClient(url, Method.POST); String body = "something\n"; ByteArrayInputStream2 is = new ByteArrayInputStream2(body.getBytes()); try { ec.doOperation(is, -1, "text/plain"); fail("cannot re-post " + is.tested + " " + ec.getLastResponse()); } catch (HttpException e) { } } public void testEasyPost() throws Exception { ThreadedHttpServer server = new MyHttpServer(); server.start(); Socket s = new Socket("127.0.0.1", server.getPort()); URL url = new URL("http://localhost/"); EasyHttpClientFactory2 factory = new EasyHttpClientFactory2(s); EasyHttpClient ec = factory.makePostClient(url); Map map = new HashMap(); map.put("a", "b"); byte[] body = HttpUtil.urlEncode(map); BufferedReader br = ec.doPostUrlEncoded(body); String got = HttpUtil.read(br).trim(); assertEquals("got " + new String(body), got); ec.close(); try { ec.doPostUrlEncoded(body); fail("already closed"); } catch (IllegalStateException e) { } } public void testEasyException() throws Exception { HttpClient c = new BasicHttpClient(new ByteArrayOutputStream(), new ByteArrayInputStream(new byte[0])); MessageHeaders mh = new MessageHeaders(); RequestLine rl = new RequestLine(Method.DELETE, "/", HttpVersion.HTTP11); try { new EasyHttpClient(null, rl, mh); } catch (IllegalArgumentException e) { } try { new EasyHttpClient(c, null, mh); } catch (IllegalArgumentException e) { } try { new EasyHttpClient(c, rl, null); } catch (IllegalArgumentException e) { } } public void testEasyOperation() throws Exception { MyHttpServer server = new MyHttpServer(); server.start(); Socket s = new Socket("127.0.0.1", server.getPort()); URL url = new URL("http://localhost/"); EasyHttpClientFactory2 factory = new EasyHttpClientFactory2(s); EasyHttpClient ec = factory.makePostClient(url); String str = "yo!\n"; ByteArrayInputStream bais = new ByteArrayInputStream(str.getBytes()); InputStream is = ec.doOperation(bais, str.length(), "text/plain"); BufferedReader in = new BufferedReader(new InputStreamReader(is)); String got = HttpUtil.read(in); String fct = server.request.getHeaders().getFieldContent( MessageHeader.FN_CONTENT_TYPE); String fcl = server.request.getHeaders().getFieldContent( MessageHeader.FN_CONTENT_LENGTH); assertEquals("text/plain", fct); assertEquals("4", fcl); assertEquals(("got " + str).trim(), got.trim()); // no length set try { ec.doOperation(null, 10, null); fail("need input stream with length"); } catch (IllegalArgumentException e) { } } public void testGrabBag() throws Exception { MyHttpServer server = new MyHttpServer(); server.doRead = false; server.doPost = false; server.fail = true; server.failAlways = true; Socket s = new Socket("127.0.0.1", server.getPort()); EasyHttpClientFactory2 factory = new EasyHttpClientFactory2(s); URL url = new URL("http://localhost"); EasyHttpClient ec = factory.makeGetClient(url); try { ec.doPostUrlEncoded(null); fail("null urlEncodedData"); } catch (IllegalArgumentException e) { } ec.toString(); try { ec.doPostUrlEncoded(null); fail("null urlEncodedData"); } catch (IllegalArgumentException e) { } } /* * public void testMain() throws Exception { EasyHttpClient.main(new * String[] { }); EasyHttpClient.main(new String[] { * "http://www.example.net" }); EasyHttpClient.main(new String[] { * "http://www.example.net", "a=b" }); } */ public void testGetNoResponse() throws Exception { MyHttpServer server = new MyHttpServer(); server.start(); server.doRead = false; server.doPost = false; server.statusLine = StatusLine.HTTP11_404; Socket s = new Socket("127.0.0.1", server.getPort()); EasyHttpClientFactory2 factory = new EasyHttpClientFactory2(s); URL url = new URL("http://localhost"); EasyHttpClient ec = factory.makeGetClient(url); ec.setCheckStatus(false); BufferedReader br = ec.doGet(); assertTrue("got some sort of reply", br != null); } public void testEasyOperation2() throws Exception { MyHttpServer server = new MyHttpServer(); server.start(); server.doRead = false; server.doPost = false; Socket s = new Socket("127.0.0.1", server.getPort()); URL url = new URL("http://localhost/"); EasyHttpClientFactory2 factory = new EasyHttpClientFactory2(s); EasyHttpClient ec = factory.makeClient(url, Method.DELETE); ec.doOperation(); assertEquals(Method.DELETE, server.request.getRequestLine().getMethod()); // try again, use keep-alive server.doPost = true; ec.doOperation(); ec.close(); server.doPost = false; // try again, this time the server returns empty document s = new Socket("127.0.0.1", server.getPort()); factory = new EasyHttpClientFactory2(s); ec = factory.makeClient(url, Method.DELETE); ec.doOperation(); // server closes connection server.doClose = true; ec.doOperation(); } public void testRetryClientTimeoutBug() throws Exception { MyHttpServer server = new MyHttpServer(); server.start(); server.doRead = false; server.doPost = true; server.sleep = 240 * 1000 * 3; // should cause timeout URL url = new URL("http://localhost:" + server.getPort()); RetryHttpClient client = new RetryHttpClient(url, 3) { protected void setSocketOptions(Socket socket) throws IOException { socket.setSoTimeout(1 * 1000); } protected void retrySendRequest(IOException e, int failures) { super.retrySendRequest(e, failures); System.out.println("Retry " + e + " " + failures); } }; EasyHttpClient ec = new EasyHttpClient(client, url, Method.POST); try { ec.doOperation(); fail("need to time out!"); } catch (SocketTimeoutException e) { } server.interrupt(); System.out.println("should not timeout"); server.sleep = 1; // should not cause timeout ec.doOperation(); server.close(); } public void testMain() throws Exception { EasyHttpClient.main(new String[0]); MyHttpServer server = new MyHttpServer(); server.start(); server.doRead = false; EasyHttpClient.main(new String[] { "http://localhost:" + server.getPort() }); server.close(); } } libexml-java-0.0.20080703.orig/http/src/test/java/net/noderunner/http/MessageHeadersTest.java0000644000175000017500000000514110762067376031517 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.http; import java.net.URL; import junit.framework.TestCase; public class MessageHeadersTest extends TestCase { public void testAppend() { MessageHeaders hl = new MessageHeaders(); MessageHeaders hl2 = new MessageHeaders(); hl.add(MessageHeader.MH_TRANSFER_ENCODING_CHUNKED); hl2.add(MessageHeader.MH_TRANSFER_ENCODING_CHUNKED); assertEquals(1, hl2.count()); hl = new MessageHeaders(); hl2.set(MessageHeader.MH_TRANSFER_ENCODING_CHUNKED); assertEquals("" + hl2, 1, hl2.count()); try { hl.add(null); fail("not valid"); } catch (IllegalArgumentException e) { } } public void testAdd() { MessageHeaders hl = new MessageHeaders(); hl.add(MessageHeader.MH_TRANSFER_ENCODING_CHUNKED); hl.add("trANSFER-enCODING", "boo"); assertEquals(2, hl.asList().size()); assertEquals(true, hl.remove("Transfer-Encoding")); assertEquals(0, hl.asList().size()); assertEquals(false, hl.remove("Transfer-Encoding")); } public void testContains() { MessageHeaders hl = new MessageHeaders(); hl.add(MessageHeader.MH_TRANSFER_ENCODING_CHUNKED); hl.add(MessageHeader.FN_CONTENT_TYPE, "text/xml"); hl.set(MessageHeader.FN_CONTENT_TYPE, "text/xml2"); boolean chunked = hl.contains(MessageHeader.MH_TRANSFER_ENCODING_CHUNKED); assertEquals("got chunked", true, chunked); String val = hl.getFieldContent(MessageHeader.FN_CONTENT_TYPE); assertEquals("got type", "text/xml2", val); String val2 = hl.getFieldContent(MessageHeader.FN_CONTENT_LENGTH); assertEquals("not here", null, val2); } public void testMakeHostHeader() throws Exception { MessageHeader mh; mh = MessageHeader.makeHostHeader(new URL("http://example.com")); assertEquals("example.com", mh.getFieldContent()); mh = MessageHeader.makeHostHeader(new URL("http://example.com:123")); assertEquals("example.com:123", mh.getFieldContent()); } } libexml-java-0.0.20080703.orig/http/src/test/java/net/noderunner/http/ChunkStreamTest.java0000644000175000017500000001776410762067376031101 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.http; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStreamWriter; /** * This class is for unit testing ChunkedOutputStream and ChunkedInputStream. * * @author Elias Ross * @version 1.0 */ public class ChunkStreamTest extends junit.framework.TestCase { public ChunkStreamTest(String name) { super(name); } static final byte stuff[] = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i' }; public void testWriteRead() throws IOException { //System.out.println("testWriteRead"); ByteArrayOutputStream bos = new ByteArrayOutputStream(); ChunkedOutputStream cos = new ChunkedOutputStream(bos); for (int i = 1; i < stuff.length; i++) cos.write(stuff, 0, i); cos.doneOutput(); cos.doneOutput(); // shouldn't matter // read in byte stuffin[] = bos.toByteArray(); InputStream is = new ByteArrayInputStream(stuffin); ChunkedInputStream cis = new ChunkedInputStream(is); for (int i = 1; i < stuff.length; i++) { int len = cis.read(stuffin, 0, i); assertEquals("len", i, len); for (int j = 0; j < len; j++) assertEquals("position", stuff[j], stuffin[j]); } // EOF assertEquals(-1, cis.read()); } public void testWriteRead2() throws IOException { //System.out.println("testWriteRead2"); ByteArrayOutputStream bos = new ByteArrayOutputStream(); ChunkedOutputStream cos = new ChunkedOutputStream(bos); for (int i = 0; i < stuff.length; i++) cos.write(stuff[i]); cos.close(); // read in InputStream is = new ByteArrayInputStream(bos.toByteArray()); ChunkedInputStream cis = new ChunkedInputStream(is); for (int i = 0; i < stuff.length; i++) { int what = cis.read(); assertEquals("what " + i, (char)stuff[i], (char)what); } // EOF assertEquals(-1, cis.read()); assertEquals(-1, cis.read(new byte[1], 0, 1)); } public void testReadBi() throws IOException { //System.out.println("testReadBi"); int ints[] = { 0x0Fe, 1, 45, 7, 55, 1, 0x1ceface1, 0x1234, 0x00001, 0xABCD, 0xEF, 0x12}; ByteArrayOutputStream bos = new ByteArrayOutputStream(); ChunkedOutputStream cos = new ChunkedOutputStream(bos); for (int i = 0; i < ints.length; i++) cos.writeChunkLen(ints[i]); byte buf[] = bos.toByteArray(); cos.close(); // read InputStream is = new ByteArrayInputStream(buf); ChunkedInputStream cis = new ChunkedInputStream(is); for (int i = 0; i < ints.length; i++) { int len = cis.readLengthFromStream(); assertEquals("Read Hex Len", ints[i], len); } // at eof try { cis.readLengthFromStream(); fail("bad length"); } catch (IOException e) { } } public void testReadHex() throws IOException { String hexs[] = { "00Fe", "1234", "000001", "ABCD", "EF" }; int ints[] = { 0x0Fe, 0x1234, 0x00001, 0xABCD, 0xEF }; ByteArrayOutputStream bos = new ByteArrayOutputStream(); OutputStreamWriter osw = new OutputStreamWriter(bos); for (int i = 0; i < hexs.length; i++) { osw.write(hexs[i]); osw.write("\r\n"); } osw.write("\r\n"); osw.write("GHJH\r\n"); osw.close(); byte buf[] = bos.toByteArray(); // read in chunks InputStream is = new ByteArrayInputStream(buf); ChunkedInputStream cis = new ChunkedInputStream(is); for (int i = 0; i < hexs.length; i++) { int len = cis.readLengthFromStream(); assertEquals("Read Hex Len", ints[i], len); } cis.readChunkEnd(); try { //System.out.println("testReadHex readLengthFromStream"); cis.readLengthFromStream(); fail("bad length"); } catch (IOException e) { } cis.close(); } public void testCoverage() throws IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); ChunkedOutputStream cos = new ChunkedOutputStream(bos); cos.toString(); cos.write(new byte[] { 1, 2 } ); byte stuffin[] = bos.toByteArray(); InputStream is = new ByteArrayInputStream(stuffin); ChunkedInputStream cis = new ChunkedInputStream(is); cis.toString(); assertEquals(1, cis.read()); assertEquals(2, cis.read()); } public void testChunkExtension() throws IOException { String s = "01;an extension\r\nx\r\n" + "00\r\nheader: value\r\n\r\n"; InputStream is = new ByteArrayInputStream(s.getBytes()); ChunkedInputStream cis = new ChunkedInputStream(is); assertEquals('x', cis.read()); assertEquals(null, cis.getEntityHeaders()); assertEquals(false, cis.isEndChunk()); assertEquals(-1, cis.read()); assertEquals(true, cis.isEndChunk()); assertEquals("value", cis.getEntityHeaders().getFieldContent("header")); s = "00\r\nheader: val\r\n \r\n"; is = new ByteArrayInputStream(s.getBytes()); cis = new ChunkedInputStream(is); try { cis.read(); fail("no CRLF"); } catch (IOException e) {} s = "01\r\nx\r\n" + "00\r\nan entity-header\r \n\r\n"; is = new ByteArrayInputStream(s.getBytes()); cis = new ChunkedInputStream(is); cis.read(); try { cis.read(); fail("no CRLF"); } catch (IOException e) {} } public void testBadEnd() throws IOException { InputStream is = new ByteArrayInputStream(new byte[] { '1', '\n', '\n'} ); ChunkedInputStream cis = new ChunkedInputStream(is); try { cis.read(); fail("bad seq"); } catch (IOException e) { } is = new ByteArrayInputStream(new byte[] { 'F', '\r', '\n' } ); cis = new ChunkedInputStream(is); assertEquals(-1, cis.read(new byte[100], 0, 100)); is = new ByteArrayInputStream(new byte[] { 'G', '\r', '\n'} ); cis = new ChunkedInputStream(is); try { cis.read(); fail("bad seq"); } catch (IOException e) { } is = new ByteArrayInputStream(new byte[] { 'g', '\r', '\n'} ); cis = new ChunkedInputStream(is); try { cis.read(); fail("bad seq"); } catch (IOException e) { } is = new ByteArrayInputStream("a\r\n01234567890\n\r".getBytes()); cis = new ChunkedInputStream(is); assertEquals('0', cis.read()); is = new ByteArrayInputStream(new byte[] { '1', '\r', '\r'} ); cis = new ChunkedInputStream(is); try { cis.read(); fail("bad seq"); } catch (IOException e) { } is = new ByteArrayInputStream("01\r\nA\n\r".getBytes()); cis = new ChunkedInputStream(is); cis.read(); try { cis.read(); fail("bad seq"); } catch (IOException e) { } is = new ByteArrayInputStream(new byte[] { '1', '\r', '\n', 'a', '\r', '?' } ); cis = new ChunkedInputStream(is); cis.read(); try { cis.read(); fail("bad seq"); } catch (IOException e) { } is = new ByteArrayInputStream(new byte[] { '1', ' ', '\r', '\n', 'a'} ); cis = new ChunkedInputStream(is); assertEquals("Space in length, not in spec, but apache 1.3.29 does it", 'a', cis.read()); } public void testParam() throws IOException { try { new ChunkedInputStream(null); fail("null input"); } catch (IllegalArgumentException e) { } try { new ChunkedOutputStream(null); fail("null input"); } catch (IllegalArgumentException e) { } try { ChunkedOutputStream os = new ChunkedOutputStream(new ByteArrayOutputStream()); os.doneOutput(); os.write('a'); fail("already wrote last chunk"); } catch (IllegalStateException e) { } try { ChunkedOutputStream os = new ChunkedOutputStream(new ByteArrayOutputStream()); os.doneOutput(); os.write(stuff, 0, stuff.length); fail("already wrote last chunk"); } catch (IllegalStateException e) { } } } libexml-java-0.0.20080703.orig/http/src/test/java/net/noderunner/http/servlet/0000755000175000017500000000000011111351351026571 5ustar twernertwerner././@LongLink0000000000000000000000000000015600000000000011567 Lustar rootrootlibexml-java-0.0.20080703.orig/http/src/test/java/net/noderunner/http/servlet/HttpServletRequestImplTest.javalibexml-java-0.0.20080703.orig/http/src/test/java/net/noderunner/http/servlet/HttpServletRequestImpl0000644000175000017500000000735410770533053033217 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.http.servlet; import java.io.ByteArrayInputStream; import java.io.IOException; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.net.Socket; import java.util.Date; import java.util.Locale; import javax.servlet.http.HttpSession; import junit.framework.TestCase; import net.noderunner.http.ContentType; import net.noderunner.http.ServerRequest; public class HttpServletRequestImplTest extends TestCase { HttpServletRequestImpl req; String euro = "\u20AC"; Socket socket; String uri = "/?a=b&c=d"; public void setUp() throws Exception { String s= "GET " + uri + " HTTP/1.1" + "\r\n" + "Content-Length: 3" + "\r\n" + "Content-Type: text/xml; encoding=UTF-8" + "\r\n" + "x-Date: " + new HttpDateFormat().format(new Date()) + "\r\n" + "\r\n" + euro + "\r\n"; ByteArrayInputStream is = new ByteArrayInputStream(s.getBytes("UTF-8")); ServerRequest sreq = new ServerRequest(is); req = new HttpServletRequestImpl(sreq); ServerSocket ss = new ServerSocket(0); req.serverSocket(ss); socket = new Socket("localhost", ss.getLocalPort()); req.remoteAddress((InetSocketAddress)socket.getLocalSocketAddress()); ss.close(); } public void tearDown() throws Exception { socket.close(); } public void testSimple2() throws Exception { assertEquals(null, req.getAuthType()); assertEquals(uri, req.getRequestURI()); assertEquals(uri, req.getRequestURL().toString()); assertEquals(0, req.getCookies().length); assertEquals(3, req.getContentLength()); assertEquals("UTF-8", req.getCharacterEncoding()); assertEquals(euro, req.getReader().readLine()); assertEquals("text", ContentType.parse(req.getContentType()).getType()); req.getLocalAddr(); req.getLocalName(); assertEquals(2, req.getParameterMap().size()); assertEquals("b", req.getParameter("a")); assertEquals(null, req.getParameter("notHere")); req.getParameterNames(); assertEquals("b", req.getParameterValues("a")[0]); req.setAttribute("key", "val"); assertEquals("val", req.getAttribute("key")); assertEquals(true, req.getAttributeNames().hasMoreElements()); req.removeAttribute("key"); assertEquals(null, req.getAttribute("key")); req.setCharacterEncoding("ASCII"); assertEquals(socket.getPort(), req.getServerPort()); assertEquals(Locale.getDefault(), req.getLocale()); assertEquals(Locale.getDefault(), req.getLocales().nextElement()); assertEquals(false, req.isSecure()); assertTrue(req.getDateHeader("x-Date") <= System.currentTimeMillis()); assertEquals("3", req.getHeader("Content-length")); assertEquals(3, req.getIntHeader("Content-length")); assertEquals(true, req.getHeaderNames().hasMoreElements()); assertEquals(false, req.isUserInRole("user")); assertEquals(null, req.getUserPrincipal()); assertEquals(null, req.getSession(false)); HttpSession session = req.getSession(); assertSame(session, req.getSession(false)); assertSame(session, req.getSession(true)); assertEquals(-1, req.getInputStream().read()); } } libexml-java-0.0.20080703.orig/http/src/test/java/net/noderunner/http/servlet/HelloWorldServer.java0000644000175000017500000000250010762067376032721 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.http.servlet; import java.net.ServerSocket; import net.noderunner.http.servlet.ServletServer; /** * Example server. * * @author Elias Ross */ public class HelloWorldServer { public HelloWorldServer(int port) throws Exception { ServerSocket sock = new ServerSocket(port); ServletServer ss = new ServletServer(new HelloServlet(), sock); ss.start(); synchronized (this) { this.wait(); } ss.close(); } public static void main(String s[]) throws Exception { new HelloWorldServer(9090); } } ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootlibexml-java-0.0.20080703.orig/http/src/test/java/net/noderunner/http/servlet/BasicHttpSessionTest.javalibexml-java-0.0.20080703.orig/http/src/test/java/net/noderunner/http/servlet/BasicHttpSessionTest.j0000644000175000017500000000333410762067376033062 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.http.servlet; import junit.framework.TestCase; /** * @author Elias Ross */ public class BasicHttpSessionTest extends TestCase { BasicHttpSession s = new BasicHttpSession(); /** * Test this class. */ public void testThis() { assertEquals(null, s.getAttribute("foo")); assertEquals(false, s.getAttributeNames().hasMoreElements()); assertEquals(true, s.getCreationTime() != 0); assertNotNull(s.getId()); assertEquals(null, s.getServletContext()); assertEquals(null, s.getSessionContext()); assertEquals(null, s.getValue("foo")); assertEquals(0, s.getValueNames().length); s.invalidate(); assertEquals(true, s.isNew()); s.putValue("foo", "bar"); s.removeAttribute("foo"); assertEquals("bar", s.getValue("foo")); assertEquals("foo", s.getValueNames()[0]); s.removeValue("foo"); s.setAttribute("foo", "bar"); assertEquals("bar", s.getAttribute("foo")); s.setMaxInactiveInterval(1000); assertEquals(1000, s.getMaxInactiveInterval()); } } ././@LongLink0000000000000000000000000000015700000000000011570 Lustar rootrootlibexml-java-0.0.20080703.orig/http/src/test/java/net/noderunner/http/servlet/HttpServletResponseImplTest.javalibexml-java-0.0.20080703.orig/http/src/test/java/net/noderunner/http/servlet/HttpServletResponseImp0000644000175000017500000000525310762067376033220 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.http.servlet; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.Date; import java.util.Locale; import net.noderunner.http.ServerResponse; import junit.framework.TestCase; public class HttpServletResponseImplTest extends TestCase { HttpServletResponseImpl res = new HttpServletResponseImpl(); public void testSimple() throws Exception { ServerResponse response = res.createServerResponse(); assertEquals("HTTP/1.1 200 OK", response.getStatusLine().toString()); } public void testSimple2() throws Exception { assertSame(res.getOutputStream(), res.getOutputStream()); assertSame(res.getWriter(), res.getWriter()); res.getOutputStream().write((byte)'!'); res.getWriter().write("Hi"); ServerResponse response = res.createServerResponse(); assertEquals("HTTP/1.1 200 OK", response.getStatusLine().toString()); ByteArrayOutputStream os = new ByteArrayOutputStream(); response.getDataPoster().sendData(os); assertEquals("!Hi", os.toString()); } public void testEnc() throws IOException { res.setContentType("text/xml; encoding=UTF-8"); res.getWriter().append('\u2668'); assertEquals("UTF-8", res.getCharacterEncoding()); } public void testCoverage() throws IOException { res.setLocale(Locale.CANADA); assertEquals(Locale.CANADA, res.getLocale()); assertEquals("ISO-8859-1", res.getCharacterEncoding()); res.setCharacterEncoding("UTF-8"); assertEquals("UTF-8", res.getCharacterEncoding()); res.setBufferSize(100); res.getOutputStream().write(5); res.resetBuffer(); res.getOutputStream().write(5); res.reset(); res.addDateHeader("foo", new Date().getTime()); res.setDateHeader("foo", new Date().getTime()); res.addIntHeader("bar", 5); res.setIntHeader("bar", 5); ByteArrayOutputStream os = new ByteArrayOutputStream(); ServerResponse response = res.createServerResponse(); response.getDataPoster().sendData(os); assertEquals("", os.toString()); } } ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootlibexml-java-0.0.20080703.orig/http/src/test/java/net/noderunner/http/servlet/HttpDateFormatTest.javalibexml-java-0.0.20080703.orig/http/src/test/java/net/noderunner/http/servlet/HttpDateFormatTest.jav0000644000175000017500000000271310762067376033052 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.http.servlet; import java.text.ParseException; import java.util.Date; import junit.framework.TestCase; public class HttpDateFormatTest extends TestCase { HttpDateFormat hdf = new HttpDateFormat(); public void testBasic() throws ParseException { Date parse = hdf.parse("Sun, 06 Nov 1994 08:49:37 GMT"); Date parse2 = hdf.parse("Sunday, 06-Nov-94 08:49:37 GMT"); Date parse3 = hdf.parse("Sun Nov 6 08:49:37 1994"); Date parse4 = hdf.parse("Sun Nov 16 08:49:37 1994"); long at = 784111777000L; assertEquals(at, parse.getTime()); assertEquals(at, parse2.getTime()); assertEquals(at, parse3.getTime()); long day = 1000 * 60 * 60 * 24; assertEquals(at + day * 10, parse4.getTime()); } } libexml-java-0.0.20080703.orig/http/src/test/java/net/noderunner/http/servlet/HelloServlet.java0000644000175000017500000000357210762067376032101 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.http.servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @SuppressWarnings("serial") class HelloServlet extends HttpServlet { boolean fail; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("Get! " + req); resp.setContentType("text/plain"); PrintWriter writer = resp.getWriter(); if (writer != resp.getWriter()) throw new IllegalStateException("not same"); writer.println("Hello, World!"); // not required // writer.flush(); if (fail) throw new ServletException("expected"); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("Post! " + req); resp.setContentType("text/plain"); PrintWriter writer = resp.getWriter(); writer.println("Hello, " + req.getParameter("name") + "!"); writer.flush(); } }././@LongLink0000000000000000000000000000014500000000000011565 Lustar rootrootlibexml-java-0.0.20080703.orig/http/src/test/java/net/noderunner/http/servlet/ServletServerTest.javalibexml-java-0.0.20080703.orig/http/src/test/java/net/noderunner/http/servlet/ServletServerTest.java0000644000175000017500000000451710762067376033144 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.http.servlet; import java.io.BufferedReader; import java.net.ServerSocket; import java.net.URL; import junit.framework.TestCase; import net.noderunner.http.EasyHttpClient; import net.noderunner.http.HttpException; import net.noderunner.http.HttpUtil; import net.noderunner.http.MessageHeader; import net.noderunner.http.MessageHeaders; public class ServletServerTest extends TestCase { HelloServlet servlet = new HelloServlet(); public void testSimple() throws Exception { ServletServer ss = new ServletServer(servlet); ss.start(); URL url = new URL("http://localhost:" + ss.getPort()); EasyHttpClient ehc = new EasyHttpClient(url); BufferedReader reader = ehc.doGet(); MessageHeaders headers = ehc.getLastResponse().getHeaders(); String string = HttpUtil.read(reader); assertEquals("Hello, World!", string.trim()); String content = headers.getFieldContent(MessageHeader.FN_SERVER); assertTrue(content, content.startsWith("ServletServer")); byte[] bs = HttpUtil.urlEncode(new String[] { "name", "Bob" }); reader = ehc.doPostUrlEncoded(bs); string = HttpUtil.read(reader); assertEquals("Hello, Bob!", string.trim()); servlet.fail = true; try { reader = ehc.doGet(); fail("expect fail"); } catch (HttpException e) {} ehc.close(); ss.close(); } public void testSocketConstructor() throws Exception { ServletServer ss = new ServletServer(servlet, new ServerSocket(0)); ss.start(); ss.close(); } } libexml-java-0.0.20080703.orig/http/src/test/java/net/noderunner/http/ByteArrayDataPosterTest.java0000644000175000017500000000402310762067376032526 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.http; import java.io.ByteArrayOutputStream; /** * This class is for unit testing {@link DataPoster} classes. * * @author Elias Ross * @version 1.0 */ public class ByteArrayDataPosterTest extends junit.framework.TestCase { public ByteArrayDataPosterTest(String name) { super(name); } public static void main(String[] args) { junit.textui.TestRunner.run(ByteArrayDataPosterTest.class); } public void testSend() throws Exception { DataPoster poster = new ByteArrayDataPoster(new byte[] { 1, 2, 3}); ByteArrayOutputStream baos = new ByteArrayOutputStream(); poster.sendData(baos); assertEquals(3, baos.size()); assertEquals(1, baos.toByteArray()[0]); } public void testSend2() throws Exception { DataPoster poster = new ByteArrayDataPoster(new byte[] { 1, 2, 3, 4}, 1, 2); ByteArrayOutputStream baos = new ByteArrayOutputStream(); poster.sendData(baos); assertEquals(2, baos.size()); assertEquals(2, baos.toByteArray()[0]); } public void testExceptions() throws Exception { try { new ByteArrayDataPoster(null); fail("null array"); } catch (IllegalArgumentException e) { } DataPoster poster = new ByteArrayDataPoster(new byte[0]); try { poster.sendData(null); fail("null os"); } catch (IllegalArgumentException e) { } } } libexml-java-0.0.20080703.orig/http/src/test/java/net/noderunner/http/ClientServerTest.java0000644000175000017500000005100510762067376031244 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.http; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.net.MalformedURLException; import java.net.Socket; import java.net.URL; import java.util.HashMap; import java.util.Map; /** * This class is for unit testing HttpClient and HttpServer. * * @author Elias Ross * @version 1.0 */ public class ClientServerTest extends junit.framework.TestCase { MessageHeaders mh = new MessageHeaders(); public ClientServerTest(String name) { super(name); } /* public static junit.framework.TestSuite suite() { return new org.hansel.CoverageDecorator(ClientServerTest.class, new Class[] { RetryHttpClient.class }); } public static junit.framework.TestSuite suite() { TestSuite suite = new TestSuite(); suite.addTest(new ClientServerTest("testRedirectBadUrl")); return suite; } */ private static final byte stuff[] = { 1, 2, 3, 4 }; private static final RequestLine requestLine = new RequestLine(Method.GET, "/", HttpVersion.HTTP11); private static final RequestLine requestPost = new RequestLine(Method.POST, "/", HttpVersion.HTTP11); private static final MessageHeaders messageHeaders = new MessageHeaders(); static { messageHeaders.add(MessageHeader.MH_TRANSFER_ENCODING_CHUNKED); } private static final InputStream junkInput = new ByteArrayInputStream(stuff); private static final OutputStream junkOutput = new ByteArrayOutputStream(); private static URL exampleURL = null; static { try { exampleURL = new URL("http://example.com"); } catch (IOException e) { } } public void testServerParam() throws IOException { try { new BasicHttpServer(null, null); fail("null input"); } catch (IllegalArgumentException e) { } try { new BasicHttpServer(new ByteArrayOutputStream(), null); fail("null input"); } catch (IllegalArgumentException e) { } ByteArrayInputStream bais = new ByteArrayInputStream("GET /\r\n\r\n".getBytes()); HttpServer s = new BasicHttpServer(new ByteArrayOutputStream(), bais); s.toString(); s.readRequest(); try { s.writeResponse(null); fail("null ServerResponse"); } catch (IllegalArgumentException e) { } ServerResponse sr = new ServerResponse( StatusLine.HTTP11_200_OK, new MessageHeaders(), new ByteArrayDataPoster("ahou!".getBytes())); s.writeResponse(sr); } public void testServerClose() throws IOException { ByteArrayInputStream bais = new ByteArrayInputStream("1".getBytes()); HttpServer s = new BasicHttpServer(new ByteArrayOutputStream(), bais); s.close(); // to get more code coverage s.close(); MyHttpServer server = new MyHttpServer(); server.start(); server.doRead = false; Socket sock = new Socket("127.0.0.1", server.getPort()); s = new BasicHttpServer(sock); s.close(); // Java 1.4-ism // assertTrue("closed", sock.isClosed()); server.close(); } public void testClientParam() throws IOException { try { new RetryHttpClient(null, 1); fail("null input"); } catch (IllegalArgumentException e) { } try { new RetryHttpClient(exampleURL, -1); fail("bad tries"); } catch (IllegalArgumentException e) { } try { new BasicHttpClient(null, junkInput); fail("null output"); } catch (IllegalArgumentException e) { } try { new BasicHttpClient(junkOutput, null); fail("null input"); } catch (IllegalArgumentException e) { } HttpClient c = new BasicHttpClient(junkOutput, junkInput); c.toString(); try { c.writeRequest(null); fail("null input"); } catch (IllegalArgumentException e) { } } public void testServerState() throws IOException { StatusLine statusLine = StatusLine.HTTP11_200_OK; String head = "GET / HTTP/1.1\r\n\r\n"; InputStream junkInput = new ByteArrayInputStream((head + head + head + head + head + head).getBytes()); try { HttpServer s = new BasicHttpServer(junkOutput, junkInput); s.readRequest(); s.readRequest(); fail("cannot read twice"); } catch (IllegalStateException e) { } try { HttpServer s = new BasicHttpServer(junkOutput, junkInput); s.getOutputStream(); fail("cannot getOutputStream now"); } catch (IllegalStateException e) { } try { HttpServer s = new BasicHttpServer(junkOutput, junkInput); s.readRequest(); s.writeResponse(new ServerResponse(statusLine, messageHeaders)); s.getOutputStream(); s.getOutputStream(); fail("cannot getOutputStream twice"); } catch (IllegalStateException e) { } try { HttpServer s = new BasicHttpServer(junkOutput, junkInput); s.readRequest(); s.writeResponse(new ServerResponse(statusLine, messageHeaders)); s.writeResponse(new ServerResponse(statusLine, messageHeaders)); fail("cannot writeResponse twice"); } catch (IllegalStateException e) { } { HttpServer s = new BasicHttpServer(junkOutput, junkInput); s.readRequest(); s.writeResponse(new ServerResponse(statusLine, messageHeaders)); s.readRequest(); s.writeResponse(new ServerResponse(statusLine, messageHeaders)); // shouldn't fail } } public void testClientState() throws IOException { try { HttpClient c = new BasicHttpClient(junkOutput, junkInput); c.writeRequest(new ClientRequest(requestLine, messageHeaders)); c.writeRequest(new ClientRequest(requestLine, messageHeaders)); fail("cannot write twice"); } catch (IllegalStateException e) { } try { HttpClient c = new BasicHttpClient(junkOutput, junkInput); c.getOutputStream(); fail("cannot getOutputStream now"); } catch (IllegalStateException e) { } try { HttpClient c = new BasicHttpClient(junkOutput, junkInput); c.writeRequest(new ClientRequest(requestLine, messageHeaders)); c.getOutputStream(); c.getOutputStream(); fail("cannot getOutputStream twice"); } catch (IllegalStateException e) { } try { HttpClient c = new BasicHttpClient(junkOutput, junkInput); c.readResponse(); fail("cannot readResponse now"); } catch (IllegalStateException e) { } } public void testClientIn() throws IOException { ByteArrayOutputStream testout = new ByteArrayOutputStream(); String resp = "HTTP/1.1 200 OK" + HttpUtil.CRLF + "Content-Length: 0" + HttpUtil.CRLF + HttpUtil.CRLF; ByteArrayInputStream testin = new ByteArrayInputStream(resp.getBytes()); HttpClient c = new BasicHttpClient(testout, testin); c.writeRequest(new ClientRequest(requestLine, messageHeaders)); ClientResponse r = c.readResponse(); assertEquals("HTTP/1.1", HttpVersion.HTTP11, r.getStatusLine().getHttpVersion()); assertEquals("200", 200, r.getStatusLine().getStatusCode()); assertEquals("OK", "OK", r.getStatusLine().getReasonPhrase()); MessageHeaders headers = r.getHeaders(); assertEquals("One header", 1, headers.count()); assertEquals("0 length", "0", headers.asList().get(0).getFieldContent()); assertEquals("0 remain", 0, testin.available()); InputStream in = r.getInputStream(); assertEquals("empty ", -1, in.read()); String s = new String(testout.toByteArray()); assertTrue("Starts with", s.startsWith("GET / HTTP/1.1")); } private static class MyHttpServer extends ThreadedHttpServer { boolean doRead = true; boolean failException = false; ServerRequest r; public MyHttpServer() throws IOException { super(); } @Override protected void exception(Exception e) { e.printStackTrace(); } /** * Reads one line and then says "got [line]" */ @Override public void handleRequest(Request request) throws IOException { if (failException) throw new RuntimeException("fail"); HttpServer server = request.getServer(); r = server.readRequest(); String result = "got "; InputStream is = r.getInputStream(); is = HttpUtil.wrapInputStream(is, r.getHeaders()); if (doRead) { BufferedReader in = new BufferedReader(new InputStreamReader(is)); String line = in.readLine(); result += line; } MessageHeader mh; mh = new MessageHeader(MessageHeader.FN_CONTENT_LENGTH, "" + result.length()); server.writeResponse(new ServerResponse(StatusLine.HTTP11_200_OK, new MessageHeaders(new MessageHeader[]{ mh }))); PrintWriter out = new PrintWriter(new OutputStreamWriter(server.getOutputStream())); out.println(result); out.flush(); } } public void testEasyGet() throws Exception { MyHttpServer server = new MyHttpServer(); server.start(); server.doRead = false; URL url = new URL("http://localhost:" + server.getPort()); EasyHttpClient ec = new EasyHttpClient(url); BufferedReader br = ec.doGet(); String got = HttpUtil.read(br).trim(); assertEquals("got", got); server.close(); } private class EasyHttpClientFactory2 { EasyHttpClientFactory2() throws IOException { } public EasyHttpClient makePostClient(URL url) { return new EasyHttpClient(url, Method.POST); } } public void testEasyPost() throws Exception { ThreadedHttpServer server = new MyHttpServer(); server.start(); URL url = new URL("http://localhost:" + server.getPort()); EasyHttpClientFactory2 factory = new EasyHttpClientFactory2(); EasyHttpClient ec = factory.makePostClient(url); Map map = new HashMap(); map.put("a", "b"); byte[] body = HttpUtil.urlEncode(map); BufferedReader br = ec.doPostUrlEncoded(body); String got = HttpUtil.read(br).trim(); assertEquals("got " + new String(body), got); ec.close(); server.close(); } public void testClientClose() throws IOException { ThreadedHttpServer server = new MyHttpServer(); Socket s = new Socket("127.0.0.1", server.getPort()); BasicHttpClient client = new BasicHttpClient(s.getOutputStream(), s.getInputStream()); client.close(); try { client.writeRequest(new ClientRequest(requestLine, messageHeaders)); fail("should be closed"); } catch (IllegalStateException e) { } } public void testClientServer() throws IOException { ThreadedHttpServer server = new MyHttpServer(); server.start(); Socket s = new Socket("127.0.0.1", server.getPort()); BasicHttpClient client = new BasicHttpClient(s.getOutputStream(), s.getInputStream()); client.writeRequest(new ClientRequest(requestLine, messageHeaders)); PrintWriter out = new PrintWriter(new OutputStreamWriter(new ChunkedOutputStream(s.getOutputStream()))); String orig = "hello HttpServer"; out.println(orig); out.flush(); ClientResponse r = client.readResponse(); BufferedReader in = new BufferedReader(new InputStreamReader(r.getInputStream())); String line = in.readLine(); assertEquals("we got something", "got " + orig, line); server.close(); } private static class ContinueHttpServer extends ThreadedHttpServer { public ContinueHttpServer() throws IOException { super(); } @Override public void handleRequest(Request request) throws IOException { HttpServer server = request.getServer(); server.readRequest(); MessageHeader mh = new MessageHeader("whatever", "something"); MessageHeaders mhs = new MessageHeaders(); mhs.add(mh); server.writeResponse(new ServerResponse(StatusLine.HTTP11_100, mhs)); StatusLine st = new StatusLine(199); server.writeResponse(new ServerResponse(st, mhs)); server.writeResponse(new ServerResponse(StatusLine.HTTP11_200_OK, mhs)); } } private static class RedirHttpServer extends ThreadedHttpServer { String url; ServerRequest r; boolean sendLocation = true; public RedirHttpServer(String url) throws IOException { this.url = url; } public RedirHttpServer(URL url) throws IOException { super(); this.url = url.toString(); } /** * Reads one line and then redirects to a different location. */ public void handleRequest(Request request) throws IOException { HttpServer server = request.getServer(); // System.out.println("ClientServerTest Reading request " + this); r = server.readRequest(); // System.out.println("ClientServerTest Read request " + r); MessageHeader mh; MessageHeader mh2; r.getInputStream(); String uri = r.getRequestLine().getRequestURI(); if (uri.equals("/")) { mh = new MessageHeader(MessageHeader.FN_LOCATION, url); mh2 = new MessageHeader(MessageHeader.FN_CONTENT_LENGTH, "0"); if (!sendLocation) mh = mh2; server.writeResponse(new ServerResponse(StatusLine.HTTP11_301, new MessageHeader[] { mh, mh2 })); } else { mh = new MessageHeader(MessageHeader.FN_CONTENT_LENGTH, "0"); server.writeResponse(new ServerResponse(StatusLine.HTTP11_200_OK, new MessageHeader[] { mh })); } // System.out.println("ClientServerTest Wrote response " + StatusLine.HTTP11_301); } } private class MyRetryHttpClient extends RetryHttpClient { HttpClient c; URL url; MyRetryHttpClient(HttpClient c) throws MalformedURLException { super(new URL("http://localhost")); this.c = c; } protected HttpClient makeHttpClient(URL url) { this.url = url; return c; } } public void testRedirect() throws Exception { URL url = new URL("http://localhost/someplace"); RedirHttpServer server = new RedirHttpServer(url); server.start(); Socket s = new Socket("localhost", server.getPort()); BasicHttpClient bclient = new BasicHttpClient(s); MyRetryHttpClient client = new MyRetryHttpClient(bclient); client.writeRequest(new ClientRequest(requestLine, new MessageHeaders())); client.readResponse(); String URI = server.r.getRequestLine().getRequestURI(); assertEquals("redir'ed did not change initial url", "http://localhost", client.url.toString()); assertEquals("redir'ed url", "/someplace", URI); } public void testRedirect2() throws Exception { URL url = new URL("http://otherhost/someplace"); RedirHttpServer server = new RedirHttpServer(url); server.start(); MyHttpServer server2 = new MyHttpServer(); server2.start(); Socket s = new Socket("localhost", server.getPort()); BasicHttpClient bclient = new BasicHttpClient(s.getOutputStream(), s.getInputStream()); Socket s2 = new Socket("localhost", server2.getPort()); server2.doRead = false; BasicHttpClient bclient2 = new BasicHttpClient(s2); MyRetryHttpClient client = new MyRetryHttpClient(bclient); client.writeRequest(new ClientRequest(requestLine, messageHeaders)); client.c = bclient2; client.readResponse(); assertTrue("make a request", server.r != null); String URI = server2.r.getRequestLine().getRequestURI(); assertEquals("redir'ed url", "/someplace", URI); server.close(); server2.close(); } public void testRedirectLoop() throws Exception { System.out.println("testRedirectLoop"); URL url = new URL("http://localhost/"); RedirHttpServer server = new RedirHttpServer(url); server.start(); Socket s = new Socket("localhost", server.getPort()); BasicHttpClient bclient = new BasicHttpClient(s); MyRetryHttpClient client = new MyRetryHttpClient(bclient); client.writeRequest(new ClientRequest(requestLine, new MessageHeaders())); try { client.readResponse(); fail("redirect loop"); } catch (HttpException e) { // e.printStackTrace(); } server.close(); } public void testRedirectNoThanks() throws Exception { System.out.println("testRedirectNoThanks"); URL url = new URL("http://localhost/"); RedirHttpServer server = new RedirHttpServer(url); server.start(); URL url2 = new URL("http://localhost:" + server.getPort()); RetryHttpClient client = new RetryHttpClient(url2); client.setFollowRedirects(false); client.writeRequest(new ClientRequest(requestLine, new MessageHeaders())); Response r = client.readResponse(); assertEquals(301, r.getStatusLine().getStatusCode()); server.close(); } public void testRedirectNoLocation() throws Exception { System.out.println("testRedirectNoThanks"); URL url = new URL("http://localhost/"); RedirHttpServer server = new RedirHttpServer(url); server.start(); server.sendLocation = false; URL url2 = new URL("http://localhost:" + server.getPort()); RetryHttpClient client = new RetryHttpClient(url2); client.setFollowRedirects(false); client.writeRequest(new ClientRequest(requestLine, new MessageHeaders())); Response r = client.readResponse(); assertEquals(301, r.getStatusLine().getStatusCode()); server.close(); } public void testRedirectBadUrl() throws Exception { System.out.println("testRedirectBadUrl"); RedirHttpServer server = new RedirHttpServer("bad://URL_here"); server.start(); URL url = new URL("http://localhost:" + server.getPort()); RetryHttpClient client = new RetryHttpClient(url); client.writeRequest(new ClientRequest(requestLine, new MessageHeaders())); try { client.readResponse(); fail("redirect bad URL"); } catch (HttpException e) { System.out.println("HTTP " + e + " " + client); } catch (RuntimeException e) { throw e; } System.out.println(" ETC " + client); client.writeRequest(new ClientRequest(requestLine, new MessageHeaders())); try { client.readResponse(); fail("redirect loop"); } catch (HttpException e) { } } public void testContinue() throws Exception { ContinueHttpServer server = new ContinueHttpServer(); server.start(); Socket s = new Socket("localhost", server.getPort()); BasicHttpClient bclient = new BasicHttpClient(s); MyRetryHttpClient client = new MyRetryHttpClient(bclient); Response r; client.writeRequest(new ClientRequest(requestLine, mh)); r = client.readResponse(); assertEquals(200, r.getStatusLine().getStatusCode()); client.writeRequest(new ClientRequest(requestPost, mh)); r = client.readResponse(); assertEquals(200, r.getStatusLine().getStatusCode()); client.setSkipContinues(false); client.writeRequest(new ClientRequest(requestLine, mh)); r = client.readResponse(); assertEquals(100, r.getStatusLine().getStatusCode()); } public void testClose() throws Exception { MyHttpServer server = new MyHttpServer(); server.start(); server.doRead = false; Socket s; s = new Socket("localhost", server.getPort()); BasicHttpClient bclient; bclient = new BasicHttpClient(s); bclient.writeRequest(new ClientRequest(requestLine, mh)); bclient.readResponse(); try { bclient.readResponse(); fail("closed, cannot write"); } catch (IllegalStateException e) { } bclient.close(); s = new Socket("localhost", server.getPort()); bclient = new BasicHttpClient(s); MyRetryHttpClient rclient = new MyRetryHttpClient(bclient); rclient.writeRequest(new ClientRequest(requestLine, mh)); rclient.close(); try { rclient.readResponse(); fail("closed, cannot read2"); } catch (IllegalStateException e) { } rclient.close(); URL url = new URL("http://localhost:" + server.getPort()); EasyHttpClientFactory2 factory = new EasyHttpClientFactory2(); EasyHttpClient ec = factory.makePostClient(url); ec.close(); server.close(); } public void testFailToConnect() throws Exception { MyHttpServer server = new MyHttpServer(); URL http = new URL("http://localhost:" + (server.getPort() + 10)); RetryHttpClient rhc = new RetryHttpClient(http); try { rhc.writeRequest(new ClientRequest(requestLine, messageHeaders)); fail("protocol"); } catch (IOException e) {} } public void testVariousConstructor() throws Exception { RetryHttpClient rhc; URL ftp = new URL("file:yo"); rhc = new RetryHttpClient(ftp); try { rhc.writeRequest(new ClientRequest(requestLine, messageHeaders)); fail("protocol"); } catch (IOException e) {} rhc.close(); URL https = new URL("https://sourceforge.net"); rhc = new RetryHttpClient(https); rhc.writeRequest(new ClientRequest(requestLine, messageHeaders)); URL http = new URL("http://sourceforge.net"); rhc = new RetryHttpClient(http); rhc.writeRequest(new ClientRequest(requestLine, messageHeaders)); rhc.close(); } public static void main(String s[]) throws Exception { new ClientServerTest("testRedirectBadUrl").testRedirectBadUrl(); } } libexml-java-0.0.20080703.orig/http/src/test/java/net/noderunner/http/HttpVersionTest.java0000644000175000017500000000443310762067376031127 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.http; import java.io.IOException; /** * This class is for unit testing HttpVersionImpl. * * @author Elias Ross * @version 1.0 */ public class HttpVersionTest extends junit.framework.TestCase { public HttpVersionTest(String name) { super(name); } /* public static junit.framework.TestSuite suite() { return new org.hansel.CoverageDecorator(HttpVersionTest.class, new Class[] { HttpVersionImpl.class }); } */ public static void main(String[] args) { junit.textui.TestRunner.run(HttpVersionTest.class); } public void testBad() throws IOException { try { new HttpVersion(null); fail("null argument"); } catch (IllegalArgumentException e) { } try { new HttpVersion("blah"); fail("invalid prefix"); } catch (HttpException e) { } try { new HttpVersion("HTTP/1"); fail("invalid number"); } catch (HttpException e) { } try { new HttpVersion("HTTP/A.B"); fail("invalid integer"); } catch (HttpException e) { } } public void testVersion() throws IOException { String h11 = "HTTP/1.1"; String h12 = "HTTP/1.2"; assertEquals(new HttpVersion(h11), HttpVersion.HTTP11); assertEquals(h11, new HttpVersion(h11).toString()); assertEquals(h12, new HttpVersion(h12).toString()); assertEquals(new HttpVersion("HTTP/1.0"), HttpVersion.HTTP10); assertEquals(new HttpVersion(h12), new HttpVersion(1, 2)); HttpVersion v = HttpVersion.HTTP11; assertEquals(v.hashCode(), new HttpVersion(1,1).hashCode()); } } libexml-java-0.0.20080703.orig/http/src/test/java/net/noderunner/http/MessageHeaderTest.java0000644000175000017500000000706610762067376031344 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.http; import java.io.ByteArrayInputStream; import java.io.IOException; /** * This class is for unit testing HttpClient and HttpServer. * * @author Elias Ross * @version 1.0 */ public class MessageHeaderTest extends junit.framework.TestCase { public MessageHeaderTest(String name) { super(name); } public void testParam() throws IOException { try { MessageHeader.parse(null); fail("null input"); } catch (IllegalArgumentException e) { } try { new MessageHeader(null, "bob"); fail("null input"); } catch (IllegalArgumentException e) { } try { new MessageHeader("bob", null); fail("null input"); } catch (IllegalArgumentException e) { } try { MessageHeader.parse("franky"); fail("no colon"); } catch (HttpException e) { } try { MessageHeader.parse("???:!!!"); fail("bad token: field name"); } catch (HttpException e) { } } public void testHeadersIn() throws IOException { String resp = "Content-Length:0" + HttpUtil.CRLF + "Bob-Length: XYZ " + HttpUtil.CRLF + HttpUtil.CRLF; ByteArrayInputStream testin = new ByteArrayInputStream(resp.getBytes()); MessageHeaders headers = MessageHeaders.readHeaders(testin); assertEquals("Two header", 2, headers.count()); assertEquals("0 in content-length", "0", headers.getFieldContent("content-length")); assertEquals("XYZ in Bob", "XYZ", headers.getFieldContent("bob-length")); MessageHeader bob = new MessageHeader("BoB-LENgth", "XYZ"); MessageHeader bob2 = (MessageHeader) headers.asList().get(1); assertEquals("BOB mixed case", headers.asList().get(1), bob); assertEquals("BOB hash", bob2.hashCode(), bob.hashCode()); assertEquals("BOB string", bob2.toString(), bob.toString()); assertEquals("BOB same", bob, bob); assertTrue("BOB string", !bob.equals("XYZ")); MessageHeader.parse("foo:"); } public void testHeadersCont() throws IOException { String resp = "Foo:" + HttpUtil.CRLF + "\tbar" + HttpUtil.CRLF + " baz" + HttpUtil.CRLF + HttpUtil.CRLF; ByteArrayInputStream testin = new ByteArrayInputStream(resp.getBytes()); MessageHeaders headers = MessageHeaders.readHeaders(testin); assertEquals(1, headers.count()); assertEquals("bar baz", headers.getFieldContent("foo")); resp = " bad header:" + HttpUtil.CRLF + HttpUtil.CRLF; try { testin = new ByteArrayInputStream(resp.getBytes()); MessageHeaders.readHeaders(testin); fail("bad header"); } catch (IOException e) { } resp = "header:" + HttpUtil.CRLF + "cont:a" + HttpUtil.CRLF + " b" + HttpUtil.CRLF + "cont2:z" + HttpUtil.CRLF + HttpUtil.CRLF; testin = new ByteArrayInputStream(resp.getBytes()); headers = MessageHeaders.readHeaders(testin); assertEquals("a b", headers.getFieldContent("cont")); assertEquals("z", headers.getFieldContent("cont2")); } } libexml-java-0.0.20080703.orig/http/src/test/java/net/noderunner/http/LimitStreamTest.java0000644000175000017500000000542410762067376031075 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.http; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; /** * This class is for unit testing LimitedOutputStream and LimitedInputStream. * * @author Elias Ross * @version 1.0 */ public class LimitStreamTest extends junit.framework.TestCase { public LimitStreamTest(String name) { super(name); } public static void main(String[] args) { junit.textui.TestRunner.run(LimitStreamTest.class); } static final byte stuff[] = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i' }; static byte dummy[] = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i' }; public void testLimitSmall() throws IOException { InputStream is = new ByteArrayInputStream(new byte[0]); LimitedInputStream lis = new LimitedInputStream(is, 5); assertEquals(-1, lis.read()); } public void testInLimit() throws IOException { InputStream is = new ByteArrayInputStream(stuff); LimitedInputStream lis = new LimitedInputStream(is, 5); assertEquals(3, lis.read(dummy, 0, 3)); assertEquals('d', lis.read()); assertEquals(1, lis.read(dummy, 0, 2)); assertEquals(-1, lis.read()); assertEquals(-1, lis.read(dummy, 0, 3)); try { new LimitedInputStream(null, 0); fail("IllegalArgumentException"); } catch (IllegalArgumentException e) { } assertEquals(true, lis.markSupported()); lis.mark(0); lis.reset(); lis.toString(); lis.close(); } public void testOutLimit() throws IOException { ByteArrayOutputStream os = new ByteArrayOutputStream(); LimitedOutputStream los = new LimitedOutputStream(os, 5); los.write(stuff, 0, 2); los.write('a'); los.write(stuff, 0, 3); los.write('a'); los.write(stuff, 0, 2); byte result[] = os.toByteArray(); assertEquals("Length ", 5, result.length); assertEquals("Length ", 'a', result[2]); assertEquals("Length ", 'b', result[4]); try { new LimitedOutputStream(null, 0); fail("IllegalArgumentException"); } catch (IllegalArgumentException e) { } los.flush(); los.close(); los.toString(); } } libexml-java-0.0.20080703.orig/http/src/test/java/net/noderunner/http/StatusLineTest.java0000644000175000017500000000304110762067376030727 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.http; import junit.framework.TestCase; public class StatusLineTest extends TestCase { public void testVarious() throws HttpException { try { new StatusLine((String)null); fail("NPE"); } catch (IllegalArgumentException e) {} try { StatusLine.parseStatusLine((String)null); fail("NPE"); } catch (IllegalArgumentException e) {} try { new StatusLine("HTTP/1.1 1000"); fail("NPE"); } catch (HttpException e) {} try { new StatusLine("HTTP/1.1 -404"); fail("NPE"); } catch (HttpException e) {} try { new StatusLine("HTTP/1.1"); fail("NPE"); } catch (HttpException e) {} StatusLine sl = new StatusLine("HTTP/1.2 400 Oh no"); assertEquals(400, sl.getStatusCode()); assertEquals("Oh no", sl.getReasonPhrase()); } } libexml-java-0.0.20080703.orig/http/src/test/java/net/noderunner/http/ContentTypeTest.java0000644000175000017500000000724210762067376031117 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.http; import junit.framework.TestCase; public class ContentTypeTest extends TestCase { public void testIt() { ContentType ct = ContentType.parse("text/plain"); assertEquals("text", ct.getType()); assertEquals("plain", ct.getSubtype()); ct = ContentType.parse("TEXT/plain"); assertEquals("text", ct.getType()); ct = ContentType.parse("x-foo/plain"); assertEquals("x-foo", ct.getType()); assertEquals(null, ct.getParameter("x")); assertEquals(null, ct.getParameterValue("x")); ct = ContentType.parse("X-foo/plain"); assertEquals("x-foo", ct.getType()); } public void testCheck() { ContentType.checkToken("ok"); try { ContentType.checkToken("\b"); fail("invalid"); } catch (IllegalArgumentException e) {} } public void testInvalid() { try { new ContentType(null, null); fail("bad"); } catch (NullPointerException e) {} try { new ContentType("text", null); fail("bad"); } catch (NullPointerException e) {} try { ContentType.parse("bad/plain"); fail("bad"); } catch (IllegalArgumentException e) {} try { ContentType.parse("noslash"); fail("bad"); } catch (IllegalArgumentException e) {} try { ContentType.parse("text/\b"); fail("bad"); } catch (IllegalArgumentException e) {} try { ContentType.parse("text/\u2222"); fail("bad"); } catch (IllegalArgumentException e) {} try { ContentType.parse("text/plain; foo"); fail("bad"); } catch (IllegalArgumentException e) {} try { ContentType.parse("text/plain; \u2222=bar"); fail("bad"); } catch (IllegalArgumentException e) {} try { ContentType.parse("x-\u2222/plain"); fail("bad"); } catch (IllegalArgumentException e) {} try { new ContentType.Parameter(null, null); fail("bad"); } catch (NullPointerException e) {} try { new ContentType.Parameter("x", null); fail("bad"); } catch (NullPointerException e) {} } public void testParams() { ContentType ct; ct = ContentType.parse("text/plain; foo=bar; baz=\"biz\""); assertEquals("text/plain;foo=bar;baz=biz", ct.toString()); ct = ContentType.parse("text/plain; baz=\"b\\\"iz\""); assertEquals("text/plain;baz=\"b\\\"iz\"", ct.toString()); ct = ContentType.parse("texT/plain; baz=\"sp \\ace\""); assertEquals("sp ace", ct.getParameters().get(0).getValue()); ct = ContentType.parse("texT/plain; baz=\";\"; a=b"); assertEquals(";", ct.getParameters().get(0).getValue()); assertEquals("b", ct.getParameters().get(1).getValue()); assertEquals("b", ct.getParameterValue("a")); assertEquals("a=b", ct.getParameter("a").toString()); ContentType.Parameter p = new ContentType.Parameter("x", "\r \t\""); assertEquals("x=\"\r \t\\\"\"", p.toString()); p = new ContentType.Parameter("x", "\";\""); assertEquals("x=\"\\\";\\\"\"", p.toString()); p = new ContentType.Parameter("x", "\\"); assertEquals("\"\\\"", p.getQuoteValue()); } } libexml-java-0.0.20080703.orig/http/src/test/java/net/noderunner/http/PerfTest.java0000644000175000017500000000625010762067376027535 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.http; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Writer; import java.net.URLEncoder; /** * This class is for unit testing HttpClient and HttpServer. * * @author Elias Ross * @version 1.0 */ public class PerfTest extends junit.framework.TestCase { public PerfTest(String name) { super(name); } public static class MyHttpServer extends ThreadedHttpServer { public MyHttpServer() throws IOException { super(); } /** * Writes a couple of lines. */ public void handleRequest(Request req) throws IOException { HttpServer s = req.getServer(); s.readRequest(); String result = "Have a happy day!\n\nTry try again!\n\n"; MessageHeader mh; mh = new MessageHeader(MessageHeader.FN_CONTENT_LENGTH, "" + result.length()); s.writeResponse(new ServerResponse(StatusLine.HTTP11_200_OK, new MessageHeader[] { mh, mh, mh })); Writer out = new OutputStreamWriter(s.getOutputStream()); out.write(result); out.flush(); } } @SuppressWarnings("deprecation") public void testUrlEncode() throws Exception { String k = "key"; String v = "A note from me & \uabcd you."; String nv[] = new String[] { k, v }; int times = 100; long start, end; for (int j = 0; j < 4; j++) { start = System.currentTimeMillis(); for (int i = 0; i < times; i++) { @SuppressWarnings("unused") String str = URLEncoder.encode(k) + "." + URLEncoder.encode(v); } end = System.currentTimeMillis(); System.out.println("java.net.URLEncoder Took " + (end - start) + " MS"); start = System.currentTimeMillis(); for (int i = 0; i < times; i++) { HttpUtil.urlEncode(nv); // String str = new String(b); } end = System.currentTimeMillis(); System.out.println("HttpUtil Took " + (end - start) + " MS"); } } /* public void testEasyGet() throws Exception { MyHttpServer server = new MyHttpServer(); Socket s = new Socket("127.0.0.1", server.getPort()); URL url = new URL("http://localhost/"); EasyHttpClientFactory factory = new EasyHttpClientFactory2(s); EasyHttpClient ec = factory.makeGetClient(url); for (int j = 0; j < 5; j++) { long start = System.currentTimeMillis(); for (int i = 0; i < 1000; i++) { BufferedReader br = ec.doGet(); String str = HttpUtil.read(br); assertTrue("length", str.length() > 0); } long end = System.currentTimeMillis(); System.out.println("Took " + (end - start) + " MS"); } } */ } libexml-java-0.0.20080703.orig/http/src/test/java/net/noderunner/http/HttpUtilTest.java0000644000175000017500000002036010762067376030414 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.http; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.EOFException; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.Arrays; import java.util.HashMap; import java.util.Map; /** * This class is for unit testing TokenUtil and HttpUtil. * * @author Elias Ross * @version 1.0 */ public class HttpUtilTest extends junit.framework.TestCase { public HttpUtilTest(String name) { super(name); } public void testHttpUtil() throws IOException { byte stuff[] = new byte[2048]; java.util.Arrays.fill(stuff, (byte)'a'); InputStream is; is = new ByteArrayInputStream(stuff); try { HttpUtil.readHttpLine(is); fail("Long line"); } catch (HttpException e) { } is = new ByteArrayInputStream(new byte[] { }); try { HttpUtil.readHttpLine(is); fail("EOF line"); } catch (EOFException e) { } is = new ByteArrayInputStream(new byte[] { 'a', 'b', '\r', '\n' }); String line = HttpUtil.readHttpLine(is); assertEquals("AB", "ab", line); is = new ByteArrayInputStream(new byte[] { 'a', 'b', '\r', 'a' }); try { HttpUtil.readHttpLine(is); fail("Expected LN"); } catch (HttpException e) { } is = new ByteArrayInputStream(new byte[] { 'a', 'b', '\n', 'a' }); assertEquals("ab", HttpUtil.readHttpLine(is)); } public void testReadFullyClose() throws IOException { final MessageHeaders mh = new MessageHeaders(); mh.add(MessageHeader.MH_CONNECTION_CLOSE); ClientResponse cr; cr = new ClientResponse() { public StatusLine getStatusLine() { return null; } public MessageHeaders getHeaders() { return mh; } public InputStream getInputStream() { return new ByteArrayInputStream(new byte[1]); } }; assertEquals(0, cr.readFully()); mh.add(new MessageHeader( MessageHeader.FN_CONTENT_LENGTH, "1")); // TODO fix this // assertEquals(1, cr.readFully()); } public void testReadFully() throws IOException { InputStream s; s = new ByteArrayInputStream(new byte[4]); assertEquals(4, HttpUtil.readFully(s)); s = new ByteArrayInputStream(new byte[4000]); assertEquals(4000, HttpUtil.readFully(s)); s = new LimitedInputStream(new ByteArrayInputStream(new byte[4000]), 2000); assertEquals(2000, HttpUtil.readFully(s)); try { HttpUtil.readFully((InputStream)null); fail("cannot read"); } catch (IllegalArgumentException e) { } } public void testWrapInputStream() throws IOException { MessageHeaders headers = new MessageHeaders(); headers.add(MessageHeader.MH_TRANSFER_ENCODING_CHUNKED); headers.add(new MessageHeader(MessageHeader.FN_CONTENT_LENGTH, "10")); InputStream s = new ByteArrayInputStream(new byte[] { } ); assertTrue("chunked input", HttpUtil.wrapInputStream(s, headers) instanceof ChunkedInputStream); headers = new MessageHeaders(); headers.add(new MessageHeader(MessageHeader.FN_CONTENT_LENGTH, "10")); assertTrue("chunked input", HttpUtil.wrapInputStream(s, headers) instanceof LimitedInputStream); headers = new MessageHeaders(); InputStream is = HttpUtil.wrapInputStream(s, headers); assertEquals(s, is); try { headers = new MessageHeaders(); headers.add(new MessageHeader(MessageHeader.FN_CONTENT_LENGTH, "abacaba")); HttpUtil.wrapInputStream(s, headers); fail("bad content-length"); } catch (HttpException e) { } try { HttpUtil.wrapInputStream(null, headers); fail("null"); } catch (IllegalArgumentException e) { } try { HttpUtil.wrapInputStream(s, null); fail("null"); } catch (IllegalArgumentException e) { } } public void testTokenUtil() throws IOException { assertTrue("(", !TokenUtil.isTokenChar('(')); assertTrue("\t", !TokenUtil.isTokenChar('\t')); assertTrue("a", TokenUtil.isTokenChar('a')); assertTrue("bob", TokenUtil.isValidToken("bob")); assertTrue("bob ", !TokenUtil.isValidToken("bob ")); assertTrue("bo:b", !TokenUtil.isValidToken("bo:b")); } public void testEncodeDecode() throws IOException { Map m = new HashMap(); m.put("ab ", "cd"); m.put("ef$", "&&&"); m.put("xy&", "=zy"); byte[] urlEncodedData = HttpUtil.urlEncode(m); Map m2 = HttpUtil.urlDecode(new String(urlEncodedData)); assertEquals("same map", m.keySet(), m2.keySet()); assertEquals("cd", m2.get("ab ")[0]); assertEquals("&&&", m2.get("ef$")[0]); } public void testEncodeDecode2() throws IOException { String s[] = new String[] { "$&", "cd", "k y", "*?" }; byte[] urlEncodedData = HttpUtil.urlEncode(s); String s2[] = HttpUtil.urlDecodeToArray(new String(urlEncodedData)); assertEquals("same length", s.length, s2.length); for (int i = 0; i < s.length; i++) assertEquals("same entry", s[i], s2[i]); } public void testEncodeDecodeStringEncoding() throws IOException { String s[] = new String[] { "foo", "bar" }; byte[] urlEncodedData; try { urlEncodedData = HttpUtil.urlEncode(s, "fuddy-duddy"); fail("fuddy-duddy not valid"); } catch (UnsupportedEncodingException e) { } urlEncodedData = HttpUtil.urlEncode(s, "UTF-8"); String s2[] = HttpUtil.urlDecodeToArray(new String(urlEncodedData)); for (int i = 0; i < s.length; i++) assertEquals("same entry", s[i], s2[i]); } public void testDecode() throws IOException { String urlEncodedData = "apple&banana=&cherry"; Map m = HttpUtil.urlDecode(urlEncodedData); assertTrue(m.containsKey("apple")); assertTrue(m.containsKey("banana")); assertTrue(m.containsKey("cherry")); String urlEncodedData2 = "apple=a&banana=b&cherry=c"; Map m2 = HttpUtil.urlDecode(urlEncodedData2); assertEquals("a", m2.get("apple")[0]); assertEquals("b", m2.get("banana")[0]); assertEquals("c", m2.get("cherry")[0]); } @SuppressWarnings("deprecation") public void testEncodeSpace() throws IOException { String a = " apple "; String s; s = new String(HttpUtil.urlEncode(new String[]{a, a})); assertEquals(URLEncoder.encode(a) + "=" + URLEncoder.encode(a), s); String a2 = "?apple?"; s = new String(HttpUtil.urlEncode(new String[]{a2, a2})); assertEquals(URLEncoder.encode(a2) + "=" + URLEncoder.encode(a2), s); } public void testDecode2() throws IOException { String urlEncodedData = "+apple&ban+ana=+++&cherry"; String s[] = HttpUtil.urlDecodeToArray(urlEncodedData); assertEquals(6, s.length); assertEquals(" apple", s[0]); assertEquals(null, s[1]); assertEquals("ban ana", s[2]); assertEquals(" ", s[3]); assertEquals("cherry", s[4]); assertEquals(null, s[5]); } public void testAdd() { String s[] = new String[] { "ab", "cd" }; String[] strings = HttpUtil.add(s, "ef"); assertEquals("ab", strings[0]); assertEquals("ef", strings[2]); } public void testDiscard() throws IOException { HttpUtil.discard((BufferedReader)null); } public void testDecodeInputStream() throws IOException { String s[] = new String[] { "ab", "cd", "ab", "de" }; byte[] urlEncodedData = HttpUtil.urlEncode(s); Map m = HttpUtil.urlDecode(new ByteArrayInputStream(urlEncodedData)); String sa[] = m.get("ab"); assertEquals("MAP " + m, 2, sa.length); assertEquals("cd", sa[0]); assertEquals("de", sa[1]); String[] s2 = HttpUtil.urlDecodeToArray(new ByteArrayInputStream(urlEncodedData)); assertTrue(Arrays.equals(s, s2)); try { HttpUtil.urlDecodeToArray((String)null); fail(); } catch (RuntimeException e) {} try { HttpUtil.urlDecodeToArray((InputStream)null); fail(); } catch (RuntimeException e) {} } } libexml-java-0.0.20080703.orig/http/src/main/0000755000175000017500000000000011111351351020205 5ustar twernertwernerlibexml-java-0.0.20080703.orig/http/src/main/java/0000755000175000017500000000000011111351351021126 5ustar twernertwernerlibexml-java-0.0.20080703.orig/http/src/main/java/net/0000755000175000017500000000000011111351351021714 5ustar twernertwernerlibexml-java-0.0.20080703.orig/http/src/main/java/net/noderunner/0000755000175000017500000000000011111351351024073 5ustar twernertwernerlibexml-java-0.0.20080703.orig/http/src/main/java/net/noderunner/http/0000755000175000017500000000000011111351352025053 5ustar twernertwernerlibexml-java-0.0.20080703.orig/http/src/main/java/net/noderunner/http/EasyHttpClient.java0000644000175000017500000003503410762067376030650 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.http; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; import java.util.HashMap; import java.util.Map; import java.util.StringTokenizer; /** * An easy-to-use HTTP client that can perform any standard HTTP operation. * Opens a connection that can be used over and over again, unlike the * Java HTTP client. Also allows for streamed data input and output, * and allows for data operations to be performed without the use of * call-backs. * *

* The underlying connection is kept active until {@link #close} is called. * After every operation, the data sent by the HTTP server must be fully read, * otherwise, any following operation on the same connection may not execute * successfully. The character readers returned can be read or discarded * easily with the {@link HttpUtil#read} and {@link HttpUtil#discard} methods. * If the HTTP connection is to be used again, do not call * close on any returned character readers. *

* *

* Example GET usage: (Retrieves the root document) *

 * URL url = new URL("http://example.com");
 * EasyHttpClient client = new EasyHttpClient(url);
 * String document = HttpUtil.read(client.doGet());
 * client.setFile("/somedir/somefile.html");
 * String document2 = HttpUtil.read(client.doGet());
 * client.close();
 * 
*

* *

* Example POST usage: (Posts URL encoded data to the same CGI script) *

 * URL url = new URL("http://example.com/post.cgi");
 * EasyHttpClientFactory factory = new EasyHttpClientFactory();
 * EasyHttpClient client = factory.makePostClient(url);
 * BufferedReader br;
 * java.util.Map map = new HashMap();
 * map.put("name", "Joe");
 * map.put("business", "Bar");
 * br = client.doPostUrlEncoded(HttpUtil.urlEncode(map));
 * EasyHttpClient.discard(br);
 *
 * map.put("name", "Alice");
 * map.put("business", "Foo");
 * br = client.doPostUrlEncoded(HttpUtil.urlEncode(map));
 * EasyHttpClient.discard(br);
 *
 * client.close();
 * 
*

* *

* Example DELETE method usage: (Deletes two remote files) *

 * URL url = new URL("http://example.com/somefile");
 * EasyHttpClientFactory factory = new EasyHttpClientFactory();
 * EasyHttpClient client = factory.makeClient(url, RequestLine.METHOD_DELETE);
 * client.doOperation();
 * client.setFile("/somefile2");
 * client.doOperation();
 * 
*

* *

* Example binary POST method usage: (Posts an image to a CGI script) *

 * URL url = new URL("http://example.com/post.cgi");
 * EasyHttpClientFactory factory = new EasyHttpClientFactory();
 * EasyHttpClient client = factory.makePostClient();
 * InputStream fileIS = new FileInputStream("somefile.jpeg");
 * InputStream resultIS = client.doOperation(fileIS, -1, "image/jpeg");
 * 
 * 

* *

* Design notes: This class is designed as a wrapper, * allowing the underlying {@link HttpClient} behavior to be delegated * in another class. The goal is to provide a lot of functionality * that users will not have to re-implement deal with many of the common * HTTP use-cases. If something significant must be altered in what * HTTP-level functionality is needed, it should be implementable * by extending an existing {@link HttpClient}. The operations * on any {@link HttpClient} can then be simply extended with this wrapper. * *

* @see EasyHttpClientFactory * @see HttpClient */ public class EasyHttpClient { private HttpClient client; private RequestLine requestLine; private MessageHeaders headers; private ClientResponse lastResponse; private boolean checkStatus; private GeneralDataPoster dataPoster; // Constructed if needed /** * Constructs a new HTTP client with a specific wrapped * client, request line, and headers. */ public EasyHttpClient(HttpClient client, RequestLine requestLine, MessageHeaders headers) { if (client == null) throw new IllegalArgumentException("Null client"); if (requestLine == null) throw new IllegalArgumentException("Null requestLine"); if (headers == null) throw new IllegalArgumentException("Null headers"); this.client = client; this.requestLine = requestLine; this.headers = headers; this.checkStatus = true; this.lastResponse = null; } /** * Constructs a new HTTP client. */ public EasyHttpClient(URL url, Method method) { this(makeHttpClient(url), RequestLine.create(url, method), MessageHeaders.defaultHeaders(url)); } /** * Constructs a new HTTP client. */ public EasyHttpClient(HttpClient c, URL url, Method method) { this(c, RequestLine.create(url, method), MessageHeaders.defaultHeaders(url)); } /** * Constructs a new HTTP client. */ public EasyHttpClient(URL url) { this(url, Method.GET); } /** * Creates and returns a new {@link HttpClient}. * By default, returns a new instance of {@link RetryHttpClient}. */ private static HttpClient makeHttpClient(URL url) { return new RetryHttpClient(url); } /** * Allows a subsequent operation to be repeated with a different file on * the same connection. Any previously set headers remain identical. */ public void setFile(String fileName) { requestLine = new RequestLine(requestLine, fileName); } /** * Allows a subsequent operation to be repeated with a different method on * the same connection. Any previously set headers remain identical. */ public void setMethod(Method method) { if (requestLine.getMethod().equals(method)) return; requestLine = new RequestLine(method, requestLine.getRequestURI(), requestLine.getHttpVersion()); } /** * Returns the message headers in use. * These may be modified as required. */ public MessageHeaders getHeaders() { return headers; } /** * Reads the HTTP response, checks the status, and * returns a wrapped input stream based on the headers given. */ private InputStream readResponse2() throws IOException { lastResponse = client.readResponse(); if (checkStatus) { int code = lastResponse.getStatusLine().getStatusCode(); if ((code / 100) != 2) { // Throw away contents lastResponse.readFully(); throw new HttpException("Bad HTTP Status, expected 200 level: " + lastResponse); } } MessageHeaders hl = lastResponse.getHeaders(); return HttpUtil.wrapInputStream(lastResponse.getInputStream(), hl); } private BufferedReader readResponse() throws IOException { InputStream s = readResponse2(); if (s == null) return null; // TODO determine content encoding, and properly wrap that return new BufferedReader(new InputStreamReader(s)); } /** * Sets if the status will automatically be checked for a 200-level * response or whether or not the status will be ignored. By default, status * is checked. */ public void setCheckStatus(boolean checkStatus) { this.checkStatus = checkStatus; } /** * Returns the last HTTP response, including headers, resulting * from the last doPost, doGet, or * doOperation call. * Returns null if no response information exists. */ public Response getLastResponse() { return lastResponse; } /** * Performs a GET operation, * returning a BufferedReader, which can be used to read the * response body. * * @throws HttpException if the input stream could * not be created, or the status was not allowed * @return null if no body was obtained * @see #getLastResponse * @see #setCheckStatus * @see HttpUtil#read * @see HttpUtil#discard */ public BufferedReader doGet() throws IOException { setMethod(Method.GET); client.writeRequest(new ClientRequest(requestLine, headers)); client.getOutputStream(); // does nothing for now return readResponse(); } private void setLenHeader(int len) { String slen = String.valueOf(len); MessageHeader mh = new MessageHeader(MessageHeader.FN_CONTENT_LENGTH, slen); headers.add(mh); } private void setContentType(String contentType) { if (contentType != null) { MessageHeader mh = new MessageHeader(MessageHeader.FN_CONTENT_TYPE, contentType); headers.add(mh); } } private void setChunkedHeader() { headers.add(MessageHeader.MH_TRANSFER_ENCODING_CHUNKED); } /** * Performs a POST operation, returning a * BufferedReader for reading the response body. The data * type to be transferred may be indicated. * * @param data source data array * @param off zero-based offset in source * @param len length of array to send * @param contentType content type to indicate, optionally * null to indicate no content type * * @return null if no body was obtained * @see #getLastResponse * @see #setCheckStatus * @see HttpUtil#read * @see HttpUtil#discard */ public BufferedReader doPost(byte[] data, int off, int len, String contentType) throws IOException { setMethod(Method.POST); setLenHeader(len); setContentType(contentType); DataPoster p = new ByteArrayDataPoster(data, off, len); client.writeRequest(new ClientRequest(requestLine, headers, p)); return readResponse(); } /** * Performs a POST operation, returning a BufferedReader * for reading the response body. The content type header is set * to indicate the x-www-form-urlencoded type. * * @param urlEncodedData data to send (ASCII format) * @see HttpUtil#urlEncode */ public BufferedReader doPostUrlEncoded(byte[] urlEncodedData) throws IOException { if (urlEncodedData == null) throw new IllegalArgumentException("null urlEncodedData"); headers.add(MessageHeader.MH_URL_ENCODED); return doPost(urlEncodedData, 0, urlEncodedData.length, null); } /** * Performs whatever operation was specified in the request line, as * passed into the constructor. Handles no input or output. * This method assumes no data will be returned by the server. * If response data is returned, it is thrown away. * Call the other {@link #doOperation(InputStream, int, String) * doOperation} method to have the data returned. * * @throws HttpException if (unexpectedly) HTTP was obtained */ public void doOperation() throws IOException { doOperation(null, 0, null); lastResponse.readFully(); } /** * Performs whatever operation was specified in the request, as * passed into the constructor. This method can be used to perform * tasks not handled by the basic {@link #doPost doPost} and {@link * #doGet doGet} methods. Utilizes the class {@link GeneralDataPoster} * to do the data posting. * * @param is * data stream to be copied and output over HTTP; * if null, no data is written; if the input stream * supports marking, the post operation may be retried, * if not any retry will throw an HttpException * @param len * if len >= 0, sets the content-length header to this length; * if len < 0, sets the chunked-encoding header * @param contentType if not null, specifies the data content type * in the request * * @return wrapped input stream for reading HTTP server data from * * @throws HttpException if the supplied input stream does not contain * enough data to be sent * @throws IllegalArgumentException if the supplied input stream is null * and a non-zero length was indicated * * @see HttpUtil#readFully */ public InputStream doOperation(InputStream is, int len, String contentType) throws IOException { setContentType(contentType); if (len < 0) setChunkedHeader(); else if (is != null) setLenHeader(len); if (dataPoster == null) dataPoster = new GeneralDataPoster(); dataPoster.init(is, len); client.writeRequest(new ClientRequest(requestLine, headers, dataPoster)); return readResponse2(); } /** * Closes the wrapped HttpClient. */ public void close() throws IOException { client.close(); } /** * Returns debug information. */ public String toString() { return "EasyHttpClient client=[" + client + "]"; } /** * Performs a command-line test. */ public static void main(String args[]) throws Exception { if (args.length == 0) { System.err.println("Usage: EasyHttpClient URL ['post'] [post params]"); System.err.println(" Performs an HTTP GET on the given URL"); System.err.println(" If 'post' is indicated, does an HTTP POST with a string"); System.err.println(" Else, if params are given, does an HTTP POST"); System.err.println(" Post param format: a=b,c=d,e=f"); return; } EasyHttpClient c = null; try { BufferedReader br; if (args.length == 2) { c = new EasyHttpClient(new URL(args[0]), Method.POST); byte pp[]; StringTokenizer st = new StringTokenizer(args[1], "=, "); Map m = new HashMap(); while (st.hasMoreTokens()) { m.put(st.nextToken(), st.nextToken()); } pp = HttpUtil.urlEncode(m); System.err.println("Post body"); System.err.println(new String(pp)); br = c.doPostUrlEncoded(pp); } else if (args.length == 3) { c = new EasyHttpClient(new URL(args[0]), Method.POST); byte pp[]; // PLAIN TEXT pp = args[2].getBytes(); System.err.println("Post body"); System.err.println(new String(pp)); // BAD CHUNKED // c.getHeaders().add("Transfer-Encoding", "Chunked"); br = c.doPost(pp, 0, pp.length, "text/xml"); /* CORRECTLY CHUNKED ByteArrayInputStream is = new ByteArrayInputStream("foobar asdjfklajdsf".getBytes()); InputStream is1 = c.doOperation(is, -1, "text/plain"); br = new BufferedReader(new InputStreamReader(is1)); */ } else { c = new EasyHttpClient(new URL(args[0]), Method.GET); br = c.doGet(); } String s = HttpUtil.read(br); System.out.println(s); c.getLastResponse(); // System.out.println(HttpUtil.read(br)); } catch (Exception e) { System.err.println("Client failed: " + c); e.printStackTrace(); } } } libexml-java-0.0.20080703.orig/http/src/main/java/net/noderunner/http/RequestLine.java0000644000175000017500000000777510762067376030223 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.http; import java.net.URL; import java.util.StringTokenizer; /** * This is a immutable implementation of an HTTP request line. */ public class RequestLine { private Method method; private String requestURI; private HttpVersion version; private String toString; /** * Constructs using a method, a request URI, and the default HTTP/1.1 * version. If the URI is empty, defaults to the file /. */ public RequestLine(Method method, String requestURI) { this(method, requestURI, HttpVersion.HTTP11); } /** * Constructs using all Request-Line parts. */ public RequestLine(Method method, String requestURI, HttpVersion version) { if (method == null) throw new IllegalArgumentException("Null method"); if (requestURI == null) throw new IllegalArgumentException("Null requestURI string"); if (version == null) throw new IllegalArgumentException("Null version"); this.method = method; if (requestURI.length() == 0) requestURI = "/"; this.requestURI = requestURI; this.version = version; } /** * Construct using an unparsed request line. This string should not end in * CRLF. * * @throws HttpException * if an invalid HTTP Request-Line was used in initialization */ public RequestLine(String line) throws HttpException { StringTokenizer st = new StringTokenizer(line, " "); try { method = Method.valueOf(st.nextToken()); requestURI = st.nextToken(); if (st.hasMoreTokens()) version = HttpVersion.parseVersion(st.nextToken()); else version = HttpVersion.HTTP10; } catch (RuntimeException e) { throw new HttpException("Invalid Request-Line: " + line); } } /** * Copy-constructs a new RequestLine using a different requestURI. * @param requestLine existing request line * @param fileName new file name */ public RequestLine(RequestLine requestLine, String requestURI) { this(requestLine.getMethod(), requestURI, requestLine.getHttpVersion()); } /** * Creates and returns a request line based on a URL and method. * For any method, the line consists of the given method, the filename, * and HTTP/1.1 request line. For example, a valid method * is the constant {@link RequestLine#METHOD_GET}. */ public static RequestLine create(URL url, Method method) { if (url == null) throw new IllegalArgumentException("Null url"); if (method == null) throw new IllegalArgumentException("Null method"); return new RequestLine(method, url.getFile()); } /** * Returns the name of the request method. This should be either one of the * constant string methods in this class, or an * extension-method. */ public Method getMethod() { return method; } /** * Returns the URI of this request. */ public String getRequestURI() { return requestURI; } /** * Returns the version of this request. */ public HttpVersion getHttpVersion() { return version; } /** * Returns this RequestLine as: * *
	 * getMethod() + ' ' + getRequestURI() + ' ' + getHttpVersion()
	 * 
* * Note: Does not include CRLF. */ public String toString() { if (toString == null) toString = getMethod().name() + ' ' + getRequestURI() + ' ' + getHttpVersion(); return toString; } } libexml-java-0.0.20080703.orig/http/src/main/java/net/noderunner/http/servlet/0000755000175000017500000000000011111351352026537 5ustar twernertwerner././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootlibexml-java-0.0.20080703.orig/http/src/main/java/net/noderunner/http/servlet/HttpServletRequestImpl.javalibexml-java-0.0.20080703.orig/http/src/main/java/net/noderunner/http/servlet/HttpServletRequestImpl0000644000175000017500000002206410770532150033154 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.http.servlet; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.net.URI; import java.net.URISyntaxException; import java.nio.charset.Charset; import java.security.Principal; import java.text.ParseException; import java.util.Collections; import java.util.Date; import java.util.Enumeration; import java.util.HashMap; import java.util.Locale; import java.util.Map; import javax.servlet.RequestDispatcher; import javax.servlet.ServletInputStream; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import net.noderunner.http.ContentType; import net.noderunner.http.HttpUtil; import net.noderunner.http.MessageHeader; import net.noderunner.http.MessageHeaders; import net.noderunner.http.ServerRequest; /** * Simple HTTP servlet request. * @author Elias Ross */ public class HttpServletRequestImpl implements HttpServletRequest { private ServerRequest request; private BasicHttpSession session; private String encoding; private InputStream inputStream; private String serverName; private int serverPort; private String remoteHost; private int remotePort; private String remoteAddr; private Map parameters = new HashMap(); private Map attributes = new HashMap(); private String localAddr; private String localName; private int localPort; private boolean initParams = false; /** * Constructs a new HttpServletRequestImpl based on a server request. */ public HttpServletRequestImpl(ServerRequest request) throws IOException { this.request = request; this.encoding = getCharacterEncoding0(); try { URI uri = new URI(request.getRequestLine().getRequestURI()); String rq = uri.getRawQuery(); if (rq != null) { parameters.putAll(HttpUtil.urlDecode(uri.getRawQuery())); } } catch (URISyntaxException e) { throw new RuntimeException(e); } inputStream = HttpUtil.wrapInputStream(request.getInputStream(), request.getHeaders()); } void serverSocket(ServerSocket ss) { serverName = ss.getLocalSocketAddress().toString(); localName = ss.getLocalSocketAddress().toString(); localAddr = ss.getLocalSocketAddress().toString(); serverPort = ss.getLocalPort(); localPort = ss.getLocalPort(); } void remoteAddress(InetSocketAddress address) { remoteHost = address.getHostName(); remoteAddr = address.getAddress().getHostAddress(); remotePort = address.getPort(); } public String getAuthType() { return null; } private String getURI() { String uri = request.getRequestLine().getRequestURI(); return uri; } public String getContextPath() { return getURI(); } public Cookie[] getCookies() { return new Cookie[0]; } public long getDateHeader(String fieldName) { try { Date date = new HttpDateFormat().parse(getHeader(fieldName)); return date.getTime(); } catch (ParseException e) { throw new RuntimeException(e); } } public String getHeader(String fieldName) { return request.getHeaders().getFieldContent(fieldName); } public Enumeration getHeaderNames() { return Collections.enumeration(request.getHeaders().getNames()); } public Enumeration getHeaders(String arg0) { throw new UnsupportedOperationException(); } public int getIntHeader(String fieldName) { return Integer.parseInt(getHeader(fieldName)); } public String getMethod() { return request.getRequestLine().getMethod().name(); } public String getPathInfo() { return getURI(); } public String getPathTranslated() { return getURI(); } public String getQueryString() { return getURI(); } public String getRemoteUser() { return null; } public String getRequestURI() { return getURI(); } public StringBuffer getRequestURL() { return new StringBuffer(getURI()); } public String getRequestedSessionId() { return null; } public String getServletPath() { return getURI(); } public HttpSession getSession() { if (session == null) this.session = new BasicHttpSession(); return session; } public HttpSession getSession(boolean create) { if (!create) return session; return getSession(); } public Principal getUserPrincipal() { return null; } public boolean isRequestedSessionIdFromCookie() { return false; } public boolean isRequestedSessionIdFromURL() { return false; } public boolean isRequestedSessionIdFromUrl() { return false; } public boolean isRequestedSessionIdValid() { return false; } public boolean isUserInRole(String arg0) { return false; } public Object getAttribute(String key) { return attributes.get(key); } public Enumeration getAttributeNames() { return Collections.enumeration(attributes.keySet()); } private String getCharacterEncoding0() { String ct = getHeader("content-type"); if (ct == null) return null; String enc = ContentType.parse(ct).getParameterValue("encoding"); return enc; } public String getCharacterEncoding() { return encoding; } public int getContentLength() { String cl = getHeader("content-length"); if (cl == null) return -1; return Integer.parseInt(cl); } public String getContentType() { return getHeader("content-type"); } public ServletInputStream getInputStream() throws IOException { return new ServletInputStream() { @Override public int read(byte[] b, int off, int len) throws IOException { return inputStream.read(b, off, len); } @Override public int read() throws IOException { return inputStream.read(); } }; } public String getLocalAddr() { return localAddr; } public String getLocalName() { return localName; } public int getLocalPort() { return localPort; } public Locale getLocale() { return Locale.getDefault(); } public Enumeration getLocales() { return Collections.enumeration(Collections.singleton(getLocale())); } public String getParameter(String key) { initParams(); String[] sa = parameters.get(key); if (sa == null) return null; return sa[0]; } public Map getParameterMap() { initParams(); return parameters; } public Enumeration getParameterNames() { initParams(); return Collections.enumeration(parameters.keySet()); } private void initParams() { if (initParams) return; MessageHeaders headers = request.getHeaders(); // TODO decide of headers should be read or not if (headers.contains(MessageHeader.MH_URL_ENCODED)) { try { parameters.putAll(HttpUtil.urlDecode(inputStream)); } catch (IOException e) { throw new RuntimeException(e); } } initParams = true; } public String[] getParameterValues(String key) { return parameters.get(key); } public String getProtocol() { return "http"; } public BufferedReader getReader() throws IOException { InputStreamReader isr = new InputStreamReader(inputStream, encoding); return new BufferedReader(isr); } public String getRealPath(String arg0) { return getURI(); } public String getRemoteAddr() { return remoteAddr; } public String getRemoteHost() { return remoteHost; } public int getRemotePort() { return remotePort; } public RequestDispatcher getRequestDispatcher(String arg0) { throw new UnsupportedOperationException(); } public String getScheme() { return "http"; } public String getServerName() { return serverName; } public int getServerPort() { return serverPort; } public boolean isSecure() { return false; } public void removeAttribute(String key) { attributes.remove(key); } public void setAttribute(String key, Object value) { attributes.put(key, value); } public void setCharacterEncoding(String encoding) throws UnsupportedEncodingException { Charset.forName(encoding); this.encoding = encoding; } public String toString() { return super.toString() + " p=" + parameters; } } libexml-java-0.0.20080703.orig/http/src/main/java/net/noderunner/http/servlet/BasicHttpSession.java0000644000175000017500000000656110762067376032664 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.http.servlet; import java.util.Collections; import java.util.Enumeration; import java.util.HashMap; import java.util.Map; import javax.servlet.ServletContext; import javax.servlet.http.HttpSession; import javax.servlet.http.HttpSessionContext; /** * Basic (mostly dummy) implementation of HTTP session. * * @author Elias Ross */ @SuppressWarnings("deprecation") public class BasicHttpSession implements HttpSession { private Map attributes = new HashMap(); private Map values = new HashMap(); private long time = System.currentTimeMillis(); private String id = Long.toHexString(time); private int inactiveInterval = 0; /** * Returns attribute value by name. */ public Object getAttribute(String name) { return attributes.get(name); } /** * Returns attribute enumeration. */ public Enumeration getAttributeNames() { return Collections.enumeration(attributes.keySet()); } /** * Returns time this object was created. */ public long getCreationTime() { return time; } /** * Returns ID based on timestamp. */ public String getId() { return id; } /** * Returns zero. */ public long getLastAccessedTime() { return 0; } /** * Returns zero. */ public int getMaxInactiveInterval() { return inactiveInterval; } /** * Returns null. */ public ServletContext getServletContext() { return null; } /** * Returns null. */ public HttpSessionContext getSessionContext() { return null; } /** * Returns the value of the attribute. */ public Object getValue(String name) { return values.get(name); } /** * Returns the value names. */ public String[] getValueNames() { return values.keySet().toArray(new String[0]); } /** * Clears attributes. */ public void invalidate() { attributes.clear(); } /** * Returns true. */ public boolean isNew() { return true; } /** * Puts the value. */ public void putValue(String name, Object value) { values.put(name, value); } /** * Removes an attribute by name. */ public void removeAttribute(String name) { attributes.remove(name); } /** * Removes a value by name. */ public void removeValue(String name) { values.remove(name); } /** * Sets an attribute. */ public void setAttribute(String name, Object arg1) { attributes.put(name, arg1); } /** * Sets inactive interval. */ public void setMaxInactiveInterval(int arg0) { this.inactiveInterval = arg0; } } ././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootlibexml-java-0.0.20080703.orig/http/src/main/java/net/noderunner/http/servlet/HttpServletResponseImpl.javalibexml-java-0.0.20080703.orig/http/src/main/java/net/noderunner/http/servlet/HttpServletResponseImp0000644000175000017500000001353110762067376033163 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.http.servlet; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.Writer; import java.util.Date; import java.util.Locale; import javax.servlet.ServletOutputStream; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletResponse; import net.noderunner.http.ByteArrayDataPoster; import net.noderunner.http.ContentType; import net.noderunner.http.DataPoster; import net.noderunner.http.MessageHeader; import net.noderunner.http.MessageHeaders; import net.noderunner.http.ServerResponse; import net.noderunner.http.StatusLine; /** * Internal implementation. * Currently does not support streaming. * * @author Elias Ross */ public class HttpServletResponseImpl implements HttpServletResponse { private MessageHeaders headers; private ByteArrayOutputStream baos; private int statusCode; private String statusReason; private String encoding = "ISO-8859-1"; private Locale locale = Locale.getDefault(); private PrintWriter pw; private ServletOutputStream sos; public HttpServletResponseImpl() { reset(); } public void addCookie(Cookie c) { throw new UnsupportedOperationException(); } public void addDateHeader(String name, long d) { String string = new HttpDateFormat().format(new Date(d)); headers.add(name, string); } public void addHeader(String name, String value) { headers.add(name, value); } public void addIntHeader(String name, int value) { headers.add(name, String.valueOf(value)); } public boolean containsHeader(String name) { return headers.getNames().contains(name); } public String encodeRedirectURL(String url) { return url; } public String encodeRedirectUrl(String url) { return url; } public String encodeURL(String url) { return url; } public String encodeUrl(String url) { return url; } public void sendError(int error) throws IOException { statusCode = error; } public void sendError(int error, String reason) throws IOException { statusCode = error; statusReason = reason; } public void sendRedirect(String arg0) throws IOException { throw new UnsupportedOperationException(); } public void setDateHeader(String name, long value) { headers.remove(name); addDateHeader(name, value); } public void setHeader(String name, String value) { headers.remove(name); addHeader(name, value); } public void setIntHeader(String name, int value) { headers.remove(name); addIntHeader(name, value); } public void setStatus(int error) { statusCode = error; } public void setStatus(int error, String reason) { statusCode = error; statusReason = reason; } public void flushBuffer() throws IOException { if (pw != null) pw.flush(); } public int getBufferSize() { return baos.size(); } public String getCharacterEncoding() { return encoding; } public String getContentType() { return getHeader(MessageHeader.FN_CONTENT_TYPE); } private String getHeader(String header) { return headers.getFieldContent(header); } public Locale getLocale() { return locale; } public ServletOutputStream getOutputStream() throws IOException { if (sos != null) return sos; return sos = new ServletOutputStream() { @Override public void write(int c) throws IOException { baos.write(c); } @Override public void write(byte[] b, int off, int len) throws IOException { baos.write(b, off, len); } }; } public PrintWriter getWriter() throws IOException { if (pw != null) return pw; Writer w = new OutputStreamWriter(baos, encoding); pw = new PrintWriter(w); return pw; } public boolean isCommitted() { return false; } public void reset() { baos = new ByteArrayOutputStream(); headers = new MessageHeaders(); statusCode = StatusLine.HTTP11_200_OK.getStatusCode(); statusReason = StatusLine.HTTP11_200_OK.getReasonPhrase(); } public void resetBuffer() { baos.reset(); } public void setBufferSize(int size) { } public void setCharacterEncoding(String encoding) { if (encoding == null) throw new IllegalArgumentException(); this.encoding = encoding; } public void setContentLength(int len) { setIntHeader(MessageHeader.FN_CONTENT_LENGTH, len); } public void setContentType(String type) { if (type == null) throw new NullPointerException(); String enc = ContentType.parse(type).getParameterValue("encoding"); if (enc != null) setCharacterEncoding(enc); setHeader(MessageHeader.FN_CONTENT_TYPE, type); } public void setLocale(Locale locale) { this.locale = locale; } ServerResponse createServerResponse() throws IOException { flushBuffer(); if (pw != null) pw.close(); setContentLength(baos.size()); StatusLine sl = new StatusLine(statusCode, statusReason); DataPoster dp = new ByteArrayDataPoster(baos.toByteArray()); ServerResponse sr = new ServerResponse(sl, headers, dp); return sr; } } libexml-java-0.0.20080703.orig/http/src/main/java/net/noderunner/http/servlet/HttpDateFormat.java0000644000175000017500000000434510762067376032323 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.http.servlet; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.TimeZone; /** * Parses three possible date formats: RFC 1123, RFC 1036, and ANSI C asctime(). * Formats in RFC 1123 only. * * @author Elias Ross */ public class HttpDateFormat extends SimpleDateFormat { private static final long serialVersionUID = -8265246501291690430L; private static final String RFC_1123 = "EEE', 'dd MMM yyyy HH:mm:ss 'GMT'"; private static final String RFC_1036 = "EEEE', 'dd'-'MMM'-'yy HH:mm:ss 'GMT'"; private static final TimeZone GMT = TimeZone.getTimeZone("GMT"); /** * ANSI C asctime(). * Note: dd is used as the date format. */ private static final String asctime = "EEE MMM dd HH:mm:ss yyyy"; /** * Constructs a new HttpDateFormat using RFC 1123 as output. */ public HttpDateFormat() { super(RFC_1123); setTimeZone(GMT); } /** * Parses an HTTP date. */ @Override public Date parse(String s) throws ParseException { if (s == null) throw new NullPointerException(); int comma = s.indexOf(','); if (comma == 3) return super.parse(s); if (comma == -1) return parse0(asctime, s); else return parse0(RFC_1036, s); } private Date parse0(String df, String s) throws ParseException { SimpleDateFormat sdf = new SimpleDateFormat(df); sdf.setLenient(true); sdf.setTimeZone(GMT); return sdf.parse(s); } } libexml-java-0.0.20080703.orig/http/src/main/java/net/noderunner/http/servlet/ServletServer.java0000644000175000017500000000600210762067376032240 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.http.servlet; import java.io.IOException; import java.io.PrintWriter; import java.net.ServerSocket; import javax.servlet.http.HttpServlet; import net.noderunner.http.MessageHeader; import net.noderunner.http.ServerRequest; import net.noderunner.http.ServerResponse; import net.noderunner.http.ThreadedHttpServer; /** * Extends the threaded HTTP server by sending requests to a single servlet. * * Currently does not support streamed requests or responses, though this * feature may likely be supported in the future. * * @author Elias Ross */ public class ServletServer extends ThreadedHttpServer { private HttpServlet servlet; /** * Constructs a new ServletServer. * * @param servlet pre-initialized HTTP servlet to use * @throws IOException */ public ServletServer(HttpServlet servlet) throws IOException { super(); this.servlet = servlet; } /** * Constructs a new ServletServer. * * @param servlet pre-initialized HTTP servlet to use * @param ss server socket */ public ServletServer(HttpServlet servlet, ServerSocket ss) { super(ss); this.servlet = servlet; } /** * Constructs a new ServletServer for this local port. * * @param servlet pre-initialized HTTP servlet to use * @param port TCP/IP port number */ public ServletServer(HttpServlet servlet, int port) throws IOException { this(servlet, new ServerSocket(port)); } @Override protected void handleRequest(Request r) throws IOException { ServerRequest request = r.getServer().readRequest(); HttpServletRequestImpl sreq = new HttpServletRequestImpl(request); HttpServletResponseImpl sres = new HttpServletResponseImpl(); sres.setHeader(MessageHeader.FN_SERVER, "ServletServer_" + servlet.getClass().getSimpleName()); if (ss != null) { sreq.serverSocket(ss); } sreq.remoteAddress(r.getRemoteAddress()); try { servlet.service(sreq, sres); } catch (Exception e) { PrintWriter pw = sres.getWriter(); pw.println("Failure to process request:"); e.printStackTrace(pw); pw.flush(); sres.setStatus(500, sres.toString()); exception(e); } ServerResponse response = sres.createServerResponse(); r.getServer().writeResponse(response); } } libexml-java-0.0.20080703.orig/http/src/main/java/net/noderunner/http/servlet/package.html0000644000175000017500000000036210676367451031047 0ustar twernertwerner

**EXPERIMENTAL** HttpServlet server library. See the examples and test cases.

libexml-java-0.0.20080703.orig/http/src/main/java/net/noderunner/http/Method.java0000644000175000017500000000172310762067376027166 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.http; /** * Standard HTTP methods. * Defined in RFC 2616 section 9. * * @author Elias Ross */ public enum Method { OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT } libexml-java-0.0.20080703.orig/http/src/main/java/net/noderunner/http/GeneralDataPoster.java0000644000175000017500000000757110762067376031321 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.http; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; /** * A utility class for sending binary data to an HTTP server or client. * Example usage: *
 * HttpClient client = new RetryHttpClient("http://example.net");
 * InputStream fileIS = new FileInputStream("somefile.jpeg");
 * DataPoster dataPoster = new GeneralDataPoster(fileIS, -1);
 * RequestLine rl = new RequestLineImpl( ... );
 * ClientRequest request = new ClientRequestImpl(rl, dataPoster);
 *
 * client.writeRequest(request);
 * ClientResponse response = client.readResponse();
 * 
*/ public class GeneralDataPoster implements DataPoster { /** * Default copy buffer size to create upon * initialization. Default size is 1024 bytes. */ protected int DEFAULT_BUFFER_SIZE = 1024; private InputStream is; private int len; private byte buf[]; private boolean sentOnce; /** * Constructs a new, uninitialized GeneralDataPoster. * The {@link #init init} method must be called before * this object can be used. */ public GeneralDataPoster() { } /** * Constructs a new GeneralDataPoster that outputs data * from the specified stream. Calls {@link #init init}. */ public GeneralDataPoster(InputStream is, int len) { init(is, len); } /** * Sets the input stream to use and the number of bytes to send. * * @param is input stream to read for output * @param len if zero, we do nothing, if < 0, we send * chunked data, if > 0 we sent only len number of * bytes */ public void init(InputStream is, int len) { if (is == null && len != 0) throw new IllegalArgumentException("Null InputStream with non-zero length"); this.is = is; this.len = len; if (buf == null) buf = new byte[DEFAULT_BUFFER_SIZE]; } /** * Copies our input stream data to the supplied output stream. * Does nothing if the number of bytes to send is zero. * * @throws IllegalHttpStateException if the input stream was never * set * @throws HttpException if the data was already read from our * stream, and the input stream cannot be reset */ public void sendData(OutputStream os) throws IOException { if (os == null) throw new IllegalArgumentException("OutputStream is null"); if (len == 0) return; if (sentOnce) { if (!is.markSupported()) throw new HttpException("Cannot re-post data"); is.reset(); } sentOnce = true; if (is.markSupported()) { is.mark(len > 0 ? len : Integer.MAX_VALUE); } InputStream is2 = is; if (len < 0) os = new ChunkedOutputStream(os); else // we don't have to count anything is2 = new LimitedInputStream(is, len); int sent = 0; while (true) { int got = is2.read(buf); if (got == -1) break; os.write(buf, 0, got); sent += got; } os.flush(); if (os instanceof ChunkedOutputStream) ((ChunkedOutputStream)os).doneOutput(); if (len > 0 && sent != len) throw new HttpException("Expected " + len + " bytes, could send only " + sent); } /** * Returns a debug string. */ public String toString() { return "GeneralDataPoster is=" + is + " len=" + len; } } libexml-java-0.0.20080703.orig/http/src/main/java/net/noderunner/http/MessageHeaders.java0000644000175000017500000001462710762067376030635 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.http; import java.io.IOException; import java.io.InputStream; import java.io.Writer; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Locale; /** * Contains a list of message headers. * * @author Elias Ross */ public class MessageHeaders { private List headers; /** * Constructs a new MessageHeaders. * @param h array of headers */ public MessageHeaders(MessageHeader h[]) { this(new LinkedList(Arrays.asList(h))); } /** * Constructs a new MessageHeaders. * @param headers list of headers */ public MessageHeaders(List headers) { if (headers == null) throw new IllegalArgumentException("null headers"); this.headers = headers; } /** * Constructs a new MessageHeaders with no headers. */ public MessageHeaders() { this(new ArrayList()); } /** * Creates and returns default HTTP headers based on a URL. * By default, there are only two headers. * The first is the host header, the second is a * connection keep-alive header. * * @see MessageHeader#makeHostHeader * @see MessageHeader#MH_CONNECTION_KEEP_ALIVE */ public static MessageHeaders defaultHeaders(URL url) { MessageHeaders mh = new MessageHeaders(); mh.add(MessageHeader.MH_USER_AGENT); mh.add(MessageHeader.makeHostHeader(url)); mh.add(MessageHeader.MH_CONNECTION_KEEP_ALIVE); return mh; } private static boolean lws(char c) { return c == ' ' || c == '\t'; } /** * Returns a list of headers from a binary input stream. * For every line read, until a blank line is reached, * a new MessageHeader instance is created. * * @throws HttpException if invalid HTTP message header data was found */ public static MessageHeaders readHeaders(InputStream is) throws IOException { List hl = new ArrayList(); String curhead = null; while (true) { String line = HttpUtil.readHttpLine(is); if (line.length() == 0) break; if (lws(line.charAt(0))) { // continuation if (curhead == null) throw new IOException("Malformed header: " + line); curhead = curhead + line; } else { if (curhead != null) hl.add(MessageHeader.parse(curhead)); curhead = line; } } if (curhead != null) hl.add(MessageHeader.parse(curhead)); return new MessageHeaders(hl); } /** * Sets a new header to the existing list array. * If the field-name of newHeader already exists, * the existing field-value is replaced. */ public void set(MessageHeader newHeader) { if (newHeader == null) throw new IllegalArgumentException("null newHeader"); for (Iterator i = headers.iterator(); i.hasNext(); ) { MessageHeader h = i.next(); if (h.getFieldName().equals(newHeader.getFieldName())) { i.remove(); } } headers.add(newHeader); } /** * Adds a new header to the existing list array. * If the field-name of newHeader already exists, * the existing field-value is replaced. */ public void add(MessageHeader newHeader) { if (newHeader == null) throw new IllegalArgumentException("null newHeader"); headers.add(newHeader); } /** * Adds a new header to the existing list array. */ public void add(String field, String value) { add(new MessageHeader(field, value)); } /** * Sets a new header in the existing list array. * If the field-name of field already exists, * the existing field-value is replaced. */ public void set(String field, String value) { set(new MessageHeader(field, value)); } /** * Removes a header by field name. * Returns true if the field name was found. */ public boolean remove(String fieldName) { fieldName = fieldName.toLowerCase(Locale.ENGLISH); boolean removed = false; for (Iterator i = headers.iterator(); i.hasNext(); ) { MessageHeader h = i.next(); if (h.getFieldName().equals(fieldName)) { i.remove(); removed = true; } } return removed; } /** * Returns true if header is within the headers. */ public boolean contains(MessageHeader header) { return headers.contains(header); } /** * Returns the field content of the first header matching * a given field name. */ public String getFieldContent(String fieldName) { fieldName = fieldName.toLowerCase(Locale.ENGLISH); for (int i = 0; i < headers.size(); i++) { MessageHeader h = headers.get(i); if (h.getFieldName().equals(fieldName)) return h.getFieldContent(); } return null; } /** * Writes these headers to output. * @throws IOException if writing fails */ public void write(Writer writer) throws IOException { for (int i = 0; i < headers.size(); i++) { MessageHeader h = headers.get(i); writer.write(h.toString()); writer.write(HttpUtil.CRLF); } } /** * Returns the number of headers. */ public int count() { return headers.size(); } /** * Returns the headers as a read-only list. */ public List asList() { return Collections.unmodifiableList(headers); } /** * Returns a list of field names, read-only. */ public List getNames() { List nl = new ArrayList(headers.size()); for (MessageHeader h : headers) nl.add(h.getFieldName()); return Collections.unmodifiableList(nl); } /** * Returns a debug string. */ public String toString() { return headers.toString(); } } libexml-java-0.0.20080703.orig/http/src/main/java/net/noderunner/http/HttpServer.java0000644000175000017500000000421510762067376030053 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.http; import java.io.IOException; import java.io.OutputStream; /** * Specifies methods for an HTTP server, which is * handling a single request from an HTTP client. * Methods must be called in specific order for a successful HTTP * exchange to take place. The order of calls that must be made is: *
    *
  • {@link #readRequest}
  • *
  • {@link #writeResponse}
  • *
  • {@link #getOutputStream}
  • *
*/ public interface HttpServer { /** * Reads the HTTP Request information. * * @throws IllegalHttpStateException if the request was already read */ ServerRequest readRequest() throws IOException; /** * Sends response data to the HTTP client. * * @throws IllegalHttpStateException if the request was not yet read * or the response was already sent * @throws HttpException if the server returned an invalid HTTP * response */ void writeResponse(ServerResponse response) throws IOException; /** * Returns a stream for writing data to, if data is to be sent to the * client. * * @throws IllegalHttpStateException if the request was not yet read, * or the response was already sent, or data was sent by a * DataPoster, or this method was already called */ OutputStream getOutputStream(); /** * Closes and releases any open connections or resources * used by this server. */ void close() throws IOException; } libexml-java-0.0.20080703.orig/http/src/main/java/net/noderunner/http/ContentType.java0000644000175000017500000001737710762067376030236 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.http; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Locale; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Content type field value class, see RFC 2045 section 5.1 on this. * Immutable class. * * @author Elias Ross */ public final class ContentType { /** * Standard content types. */ public enum StandardType { application, audio, image, message, multipart, text, video; } private StandardType stype; private String xtype; private String subtype; private List parameters = Collections. emptyList(); private static final char QUOTE = '"'; private static final char BS = '\\'; private static final String TSPECIAL = "()<>@,;:\\\"/[]?="; private static final String TC = "[\\p{ASCII}&&[^\\p{Cntrl}" + Pattern.quote(TSPECIAL) + "]]"; /* * private static final String TC = "[\\p{ASCII}&&[^X]]"; */ private static final Pattern TOKEN = Pattern.compile(TC + "+"); /** * Constructs a new ContentType. */ public ContentType(String type, String subtype) { this(type, subtype, null); } /** * Constructs a new ContentType. * * @param type * non-null type * @param subtype * non-null subtype * @param param * list of parameters, optionally null */ public ContentType(String type, String subtype, List param) { if (type == null) throw new NullPointerException("type"); if (subtype == null) throw new NullPointerException("type"); type = lc(type); if (type.startsWith("x-")) { checkToken(type); this.xtype = type; } else { stype = StandardType.valueOf(type); } checkToken(subtype); this.subtype = subtype; if (param != null) this.parameters = new ArrayList(param); } private static class ParseState { int at; } /** * Factory method, parsing a content type line and generating a content type * object. * * @return newly created content type object */ public static ContentType parse(String string) { int slash = string.indexOf('/'); if (slash == -1) throw new IllegalArgumentException("No / found: " + string); String type = string.substring(0, slash); String subtype = null; int semi = string.indexOf((char) ';'); if (semi == -1) { subtype = string.substring(slash + 1).trim(); return new ContentType(type, subtype); } ArrayList p = new ArrayList(); ParseState state = new ParseState(); state.at = semi; while (state.at < string.length()) { if (subtype == null) subtype = string.substring(slash + 1, state.at).trim(); int eq = string.indexOf('=', state.at); if (eq == -1) throw new IllegalArgumentException("Expected = in: " + string + " at " + state.at); String name = string.substring(state.at + 1, eq).trim(); state.at = eq + 1; String value = value(string, state); p.add(new Parameter(name, value)); } return new ContentType(type, subtype, p); } private static String value(String string, ParseState state) { boolean quoted = false; // value is quoted boolean bs = false; // last character backslash boolean first = true; // true for first character StringBuilder sb = new StringBuilder(); // result while (state.at < string.length()) { char c = string.charAt(state.at++); if (c == BS && quoted) { bs = true; continue; } if (c == QUOTE) { if (bs) { bs = false; sb.append(QUOTE); continue; } if (first) { quoted = true; } else { return sb.toString(); } } else if (c == ';' && !quoted) { return sb.toString(); } else { sb.append(c); bs = false; first = false; } } return sb.toString(); } /** * Checks a token syntax. * * @throws IllegalArgumentException * if token is invalid */ public static void checkToken(String t) { Matcher matcher = TOKEN.matcher(t); if (!matcher.matches()) throw new IllegalArgumentException("Invalid token: '" + t + "'"); } /** * Content type parameter, see parameter definition in RFC 2045. * Immutable class. * * @author Elias Ross */ public final static class Parameter { private String attribute; private String value; /** * Lazily created. */ private String quoteValue; /** * Constructs a new Parameter. * * @param attribute valid attribute token * @param value unquoted, raw value * * @throws IllegalArgumentException if attribute or value is invalid */ public Parameter(String attribute, String value) { if (attribute == null) throw new NullPointerException(); if (value == null) throw new NullPointerException(); checkToken(attribute); this.attribute = attribute; this.value = value; } private void quoteValue() { StringBuilder sb = new StringBuilder(); sb.append(QUOTE); boolean quote = false; for (int i = 0; i < value.length(); i++) { char c = value.charAt(i); if (c > 127) throw new IllegalArgumentException("Not ASCII " + value); if (c == QUOTE) { quote = true; sb.append('\\'); } else if (c == '\r' || c == ' ' || c == '\t') { quote = true; } else if (TSPECIAL.indexOf(c) != -1) { quote = true; } sb.append(c); } if (quote) quoteValue = sb.append(QUOTE).toString(); else quoteValue = value; } /** * Returns attribute. */ public String getAttribute() { return attribute; } /** * Returns value, unquoted. */ public String getValue() { return value; } /** * Returns the quoted value of this parameter. */ public String getQuoteValue() { if (quoteValue == null) quoteValue(); return quoteValue; } /** * Returns a formatted attribute=value string. */ public String toString() { return getAttribute() + "=" + getQuoteValue(); } } /** * Returns type. */ public String getType() { if (stype != null) return stype.name(); return xtype; } /** * Returns content sub type. */ public String getSubtype() { return subtype; } /** * Returns parameters, unmodifiable. */ public List getParameters() { return Collections.unmodifiableList(parameters); } /** * Returns the first parameter matching this attribute string. * Returns null if not found. */ public Parameter getParameter(String attribute) { attribute = lc(attribute); for (Parameter p : parameters) if (p.getAttribute().equals(attribute)) return p; return null; } /** * Returns the first parameter value matching this attribute string. * Returns null if not found. */ public String getParameterValue(String attribute) { Parameter parameter = getParameter(attribute); if (parameter == null) return null; return parameter.getValue(); } public String toString() { StringBuilder sb = new StringBuilder(getType()); sb.append('/').append(subtype); for (Parameter p : parameters) sb.append(';').append(p); return sb.toString(); } private static String lc(String s) { return s.toLowerCase(Locale.ENGLISH); } }libexml-java-0.0.20080703.orig/http/src/main/java/net/noderunner/http/ThreadedHttpServer.java0000644000175000017500000001034710762067376031517 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.http; import java.io.IOException; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.net.Socket; /** * This class is for unit testing. It accepts one request at a time in a single thread. * Override the handleRequest method to do something interesting. * * @author Elias Ross * @version 1.0 */ public abstract class ThreadedHttpServer implements Runnable { protected ServerSocket ss; private Thread t; private volatile boolean run = true; /** * Constructs a new SingleHttpServer, initialized with a server socket. * @param ss server socket to listen with */ public ThreadedHttpServer(ServerSocket ss) { this.ss = ss; } public ThreadedHttpServer() throws IOException { ss = new ServerSocket(0); } /** * Starts listening in a new thread. */ public void start() { t = new Thread(this); t.setName("listen-" + ss.getLocalSocketAddress()); t.setDaemon(true); t.start(); } public int getPort() { return ss.getLocalPort(); } /** * Inner class for handling a single HTTP server request. */ public class Request { private HttpServer server; private InetSocketAddress address; /** * Constructs a new Request. * @param server * @param address */ public Request(HttpServer server, InetSocketAddress address) { this.server = server; this.address = address; } /** * Returns address. */ public InetSocketAddress getRemoteAddress() { return address; } /** * Returns server. */ public HttpServer getServer() { return server; } } /** * Override this method to handle the request. * You may optionally process this request asynchronously. * @param s server request * @param address address of request * @throws IOException */ protected abstract void handleRequest(Request request) throws IOException; /** * Called when an exception occurs when listening; does nothing now. */ protected void exception(Exception e) { } public final void run() { while (run) { Socket socket = null; try { socket = ss.accept(); socket.setTcpNoDelay(true); new SocketHandler(socket).start(); } catch (IOException e) { if (socket != null) { try { socket.close(); } catch (IOException e2) { } } if (run) exception(e); } } } private class SocketHandler extends Thread { private Socket socket; /** * Constructs a new SocketHandler. * @param socket */ public SocketHandler(Socket socket) { this.socket = socket; setName("handle-" + socket.getInetAddress()); } public final void run() { try { HttpServer server = new BasicHttpServer(socket); while (true) { Request request = new Request(server, (InetSocketAddress)socket.getRemoteSocketAddress()); handleRequest(request); } } catch (IOException e) { exception(e); } finally { try { socket.close(); } catch (IOException e) { exception(e); } } } } /** * Closes as soon as possible. */ public void close() throws IOException { run = false; if (ss != null) ss.close(); ss = null; if (t == null) return; t.interrupt(); try { t.join(); } catch (InterruptedException e) { exception(e); Thread.currentThread().interrupt(); } } /** * Interrupts processing. */ void interrupt() throws IOException { t.interrupt(); } /** * Returns a debug string. */ public String toString() { return "SingleHttpServer ss=" + ss; } } libexml-java-0.0.20080703.orig/http/src/main/java/net/noderunner/http/HttpUtil.java0000644000175000017500000003133310762067376027523 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.http; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.EOFException; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.util.BitSet; import java.util.HashMap; import java.util.Map; import java.util.StringTokenizer; /** * Contains utility functions for common HTTP I/O tasks. */ public class HttpUtil { static String CRLF = "\r\n"; private static byte junk[] = null; private static BitSet noencode; private static final byte hex[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; static { noencode = new BitSet(256); for (int i = 'a'; i <= 'z'; i++) noencode.set(i); for (int i = 'A'; i <= 'Z'; i++) noencode.set(i); for (int i = '0'; i <= '9'; i++) noencode.set(i); noencode.set('-'); noencode.set('_'); noencode.set('.'); noencode.set('*'); } /** * Cannot be instantiated. */ private HttpUtil() { } /** * Reads an input stream until EOF. * Returns the number of bytes read. */ public static int readFully(InputStream stream) throws IOException { if (stream == null) throw new IllegalArgumentException("Null stream"); // not synchronized, but not a big deal if (junk == null) junk = new byte[1024]; int total = 0; int got = 0; while (true) { got = stream.read(junk, 0, junk.length); if (got == -1) return total; total += got; } } /** * Reads an input stream until EOF. * Returns the bytes read. */ public static byte[] read(InputStream stream) throws IOException { byte b[] = new byte[128]; ByteArrayOutputStream bo = new ByteArrayOutputStream(); int got = 0; while (true) { got = stream.read(b, 0, b.length); if (got == -1) return bo.toByteArray(); bo.write(b, 0, got); } } /** * Returns a character reader for reading HTTP data. * Returns either an InputStreamReader, wrapping * either a {@link ChunkedInputStream} or * {@link LimitedInputStream}, based on the supplied headers. * If the headers did not indicate data was being sent, returns * an input stream for reading the rest of the document. */ public static InputStream wrapInputStream(InputStream stream, MessageHeaders hl) throws IOException { if (stream == null) throw new IllegalArgumentException("Null stream"); if (hl == null) throw new IllegalArgumentException("Null headers"); boolean chunked = hl.contains(MessageHeader.MH_TRANSFER_ENCODING_CHUNKED); if (chunked) return new ChunkedInputStream(stream); String s = hl.getFieldContent(MessageHeader.FN_CONTENT_LENGTH); if (s == null) return stream; try { int length = Integer.parseInt(s); return new LimitedInputStream(stream, length); } catch (NumberFormatException e) { throw new HttpException("content-length not a number:" + s); } } /** * Returns a single line from a 8-bit InputStream * (which is assumed to be ASCII). */ public static String readHttpLine(InputStream in) throws IOException { StringBuilder sb = new StringBuilder(); int c = 0; while (true) { c = in.read(); if (c == -1) throw new EOFException("EOF processing HTTP request"); if (c == '\n') break; if (c == '\r') { c = in.read(); if (c != '\n') throw new HttpException("Expected LN character reading HTTP information"); break; } sb.append((char)c); if (sb.length() > 1024) throw new HttpException("Header line too long"); } return sb.toString(); } /** * URL encodes a series of parameters. * Names are followed by their value in the array. For example: *
	 * byte[] buf;
	 * buf = HttpUtil.urlEncode(new String[] { "name1", "value1", "name2", "value2" }); 
	 * 
* results in the byte array: *
	 * "name1=value1&name2=value2"
	 * 
* Strings are converted to bytes using the given encoding. * @param nvPairs array of name-value pairs, must be * even in length * @param encoding Java encoding, or null to use the default encoding * @return a byte array which can be used in {@link EasyHttpClient#doPostUrlEncoded} * @throws UnsupportedEncodingException if the encoding is invalid */ public static byte[] urlEncode(String[] nvPairs, String encoding) throws UnsupportedEncodingException { if (nvPairs == null) throw new IllegalArgumentException("Null array"); if (nvPairs.length % 2 != 0) throw new IllegalArgumentException("Odd length array"); ByteArrayOutputStream bb; bb = new ByteArrayOutputStream(16 * nvPairs.length); for (int i = 0; i < nvPairs.length; i += 2) appendNV(bb, nvPairs[i], nvPairs[i + 1], encoding); return bb.toByteArray(); } /** * URL encodes a series of parameters, using the * Strings are converted to the default platform encoding. */ public static byte[] urlEncode(String[] nvPairs) { try { return urlEncode(nvPairs, null); } catch (UnsupportedEncodingException e) { throw new Error("should not be here"); } } /** * URL encodes a single value, writing its value to * an output stream. */ public static void urlEncode(ByteArrayOutputStream os, byte[] buf) { for (int i = 0; i < buf.length; i++) { byte b = buf[i]; if (noencode.get(b)) { os.write(b); } else if (b == ' ') { os.write((byte)'+'); } else { os.write((byte)'%'); int low = (int) (b & 0x0f); int high = (int) ((b & 0xf0) >> 4); os.write(hex[high]); os.write(hex[low]); } } } /** * Appends a key-value pair to an output stream buffer. */ private static void appendNV(ByteArrayOutputStream os, String n, String v, String enc) throws java.io.UnsupportedEncodingException { if (os.size() > 0) os.write((byte)'&'); if (enc == null) urlEncode(os, n.getBytes()); else urlEncode(os, n.getBytes(enc)); if (v != null) { os.write((byte)'='); if (enc == null) urlEncode(os, v.getBytes()); else urlEncode(os, v.getBytes(enc)); } } /** * URL encodes a Map. * @param map a name-value map of entries to encode * @param encoding Java encoding, or null to use the default encoding * @return a byte buffer which can be used in {@link EasyHttpClient#doPostUrlEncoded} * @throws UnsupportedEncodingException if the encoding is invalid */ public static byte[] urlEncode(Map map, String encoding) throws UnsupportedEncodingException { if (map == null) throw new IllegalArgumentException("Null map"); ByteArrayOutputStream os = new ByteArrayOutputStream(); for (Map.Entry me : map.entrySet()) { appendNV(os, me.getKey(), me.getValue(), encoding); } return os.toByteArray(); } /** * URL encodes a Map. * @param map a name-value map of entries to encode * @return a byte buffer which can be used in {@link EasyHttpClient#doPostUrlEncoded} * Strings are converted to the default platform encoding. */ public static byte[] urlEncode(Map map) { try { return urlEncode(map, null); } catch (UnsupportedEncodingException e) { throw new Error("should not be here"); } } /** * URL decodes a string. */ @SuppressWarnings("deprecation") private static String decode(String s) { return URLDecoder.decode(s); } /** * Returns the number of times a character appears in a string. */ private static int count(String s, char c) { int count = 0; for (int i = 0; i < s.length(); i++) if (s.charAt(i) == c) count++; return count; } /** * Creates and returns a new array one entry longer, with a new value at the end. * @param sa existing array * @param s new value * @return new array */ public static String[] add(String sa[], String s) { String sa2[] = new String[sa.length + 1]; System.arraycopy(sa, 0, sa2, 0, sa.length); sa2[sa.length] = s; return sa2; } private static void put(Map map, String n, String v) { String[] sa = map.get(n); if (sa == null) map.put(n, new String[] { v }); else map.put(n, add(sa, v)); } /** * URL decodes a string into a Map. * Names without values are placed in the map, but given a * null value. For example: *
	 * foo&bar=&baz
	 * 
* results in a map with keys foo, bar, * baz mapped to "". * If the same key appears more than once, it is added to the array. * This method will not throw exceptions * even if the data is irregular. * * @param urlEncodedData data in the URL encoded format * @return a map containing the decoded name-value pairs * @throws IllegalArgumentException if null data is passed in * @see #urlEncode */ public static Map urlDecode(String urlEncodedData) { if (urlEncodedData == null) throw new IllegalArgumentException("Null urlEncodedData"); urlEncodedData = urlEncodedData.trim(); StringTokenizer st = new StringTokenizer(urlEncodedData, "&=", true); Map map = new HashMap(); String n; String eq; String v; while (st.hasMoreTokens()) { n = st.nextToken(); if (!st.hasMoreTokens()) { put(map, decode(n), ""); break; } eq = st.nextToken(); if (!st.hasMoreTokens()) { put(map, decode(n), ""); break; } if (eq.equals("&")) { put(map, decode(n), ""); continue; } v = st.nextToken(); if (!v.equals("&")) { String dn = decode(n); String dv = decode(v); put(map, dn, dv); } else { put(map, decode(n), ""); continue; } if (st.hasMoreTokens()) st.nextToken(); // & } return map; } /** * URL decodes an input stream. * @return mapping of name value pairs */ public static Map urlDecode(InputStream is) throws IOException { byte[] bs = HttpUtil.read(is); return urlDecode(new String(bs, "ASCII")); } /** * URL decodes an input stream. * @return array of name value pairs */ public static String[] urlDecodeToArray(InputStream is) throws IOException { byte[] bs = HttpUtil.read(is); return urlDecodeToArray(new String(bs, "ASCII")); } /** * Performs the same operation as {@link #urlDecode}, except the * returned data is in an ordered array. * * @see #urlEncode */ public static String[] urlDecodeToArray(String urlEncodedData) { if (urlEncodedData == null) throw new IllegalArgumentException("Null urlEncodedData"); urlEncodedData = urlEncodedData.trim(); StringTokenizer st = new StringTokenizer(urlEncodedData, "&=", true); int amps = count(urlEncodedData, '&'); String array[] = new String[(amps + 1) * 2]; String n; String eq; String v; int i = -2; while (st.hasMoreTokens()) { i += 2; n = st.nextToken(); array[i] = decode(n); if (!st.hasMoreTokens()) break; eq = st.nextToken(); if (!st.hasMoreTokens()) break; if (eq.equals("&")) continue; v = st.nextToken(); if (!v.equals("&")) array[i + 1] = decode(v); else continue; if (st.hasMoreTokens()) st.nextToken(); // & } return array; } /** * Discards the contents of a BufferedReader. * If the reader is null, does nothing: * This is to facilitate the coding of cases when the data is of * no use to the client. */ public static void discard(BufferedReader r) throws IOException { if (r == null) return; while (r.readLine() != null); } /** * Returns the contents of a BufferedReader as a String. * By default, each line is appended with * System.getProperty("line.separator"). * This may or may not be the original line termination character used. * * @throws IllegalArgumentException if the reader is null */ public static String read(BufferedReader r) throws IOException { if (r == null) throw new IllegalArgumentException("null reader"); String sep = System.getProperty("line.separator", "\n"); StringBuilder sb = new StringBuilder(128); String line; while ((line = r.readLine()) != null) { sb.append(line).append(sep); } return sb.toString(); } } libexml-java-0.0.20080703.orig/http/src/main/java/net/noderunner/http/ChunkedInputStream.java0000644000175000017500000001254510762067376031527 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.http; import java.io.EOFException; import java.io.IOException; import java.io.InputStream; /** * An InputStream wrapper supporting the chunked transfer encoding. * * @author Elias Ross * * @see ChunkedOutputStream * */ public class ChunkedInputStream extends InputStream { /** * True if the final chunk was found. */ private boolean endChunk; /** * Current chunk length. */ private int chunkLength; /** * Current chunk buffer position. */ private int chunkPos; /** * The underlying input stream. */ private InputStream stream; /** * Trailer headers. */ private MessageHeaders entityHeaders; /** * Constructs a chunked input stream wrapping input. * * @param stream Must be non-null. * */ public ChunkedInputStream(InputStream stream) { if (stream == null) { throw new IllegalArgumentException("InputStream parameter is null"); } endChunk = false; chunkLength = 0; chunkPos = 0; this.stream = stream; } /** * Closes the underlying input stream. */ public void close() throws IOException { stream.close(); } /** * Reads up to len bytes of data from the input stream * into an array of bytes. An attempt is made to read as many as * len bytes, but a smaller number may be read, * possibly zero. The number of bytes actually read is returned as * an integer. * * @param b The buffer into which the data is read * @param off The start offset into array b at which * the data is written * @param len The maximum number of bytes to read * * @exception IOException if an input/output error occurs */ public int read(byte b[], int off, int len) throws IOException { if (endChunk) return -1; if (chunkLength == chunkPos) { if (chunkLength > 0) // finishes previous chunk readChunkEnd(); chunkLength = readLengthFromStream(); chunkPos = 0; if (chunkLength == 0) { readChunkTrailer(); // trailer endChunk = true; return -1; } } int want = Math.min(len, chunkLength - chunkPos); int got = stream.read(b, off, want); if (got == -1) return -1; chunkPos += got; return got; } /* // Not supported public int available() throws IOException { return stream.available(); } public boolean markSupported() { return stream.markSupported(); } public void reset() throws IOException { stream.reset(); } public void mark(int readlimit) { stream.mark(readlimit); } */ /** * Reads and return a single byte from this input stream, or -1 if end of * file has been encountered. * * @exception IOException if an input/output error occurs */ public int read() throws IOException { byte oneChar[] = new byte[1]; int c = read(oneChar, 0, 1); if (c == -1) return -1; return oneChar[0]; } int readLengthFromStream() throws IOException { int ch; int total = 0; boolean extension = false; while (true) { ch = stream.read(); if (ch == -1) throw new EOFException(); if (ch == '\r') break; if (ch == ';') extension = true; if (ch == ' ') // This is not in the spec, but allowed anyway continue; if (extension) continue; total <<= 4; if (ch >= '0' && ch <= '9') total += ch - '0'; else if (ch >= 'a' && ch <= 'f') total += ch - 'a' + 10; else if (ch >= 'A' && ch <= 'F') total += ch - 'A' + 10; else throw new IOException("Bad length character in stream: " + ch); } ch = stream.read(); if (ch != '\n') throw new IOException("Expected LF character in stream: " + ch); return total; } /** * Returns "trailer" entity headers, which appear at the end of * a chunked encoding request. Returns null if not at the end of input. * These will only appear when {@link #isEndChunk()} returns true. * * See: http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.6.1 */ public MessageHeaders getEntityHeaders() { return entityHeaders; } /** * Returns true if the end chunk was read. */ public boolean isEndChunk() { return endChunk; } /** * Reads CR NL. */ void readChunkEnd() throws IOException { int ch = stream.read(); if (ch != '\r') throw new IOException("Expected CR in end chunk " + (char)ch); ch = stream.read(); if (ch != '\n') throw new IOException("Expected LN in end chunk"); } /** * Reads chunk trailer. */ void readChunkTrailer() throws IOException { entityHeaders = MessageHeaders.readHeaders(stream); } /** * Returns a debug string. */ public String toString() { return "ChunkedInputStream " + " stream=" + stream + " chunkLength=" + chunkLength + " chunkPos=" + chunkPos; } } libexml-java-0.0.20080703.orig/http/src/main/java/net/noderunner/http/TokenUtil.java0000644000175000017500000000246710762067376027672 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.http; class TokenUtil { private static final char separators[] = { '(' , ')' , '<' , '>' , '@', ',' , ';' , ':' , '\\' , '<', '>', '/' , '[' , ']' , '?' , '=', '{' , '}' , ' ' , '\t' }; public static final boolean isTokenChar(char c) { if (c < 31 || c == 127) return false; for (int i = 0; i < separators.length; i++) if (c == separators[i]) return false; return true; } public static boolean isValidToken(String s) { for (int i = 0; i < s.length(); i++) if (!isTokenChar(s.charAt(i))) return false; return true; } } libexml-java-0.0.20080703.orig/http/src/main/java/net/noderunner/http/ChunkedOutputStream.java0000644000175000017500000001007310762067376031722 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.http; import java.io.IOException; import java.io.OutputStream; /** * An OutputStream wrapper that supports the chunked transfer encoding. * * @author Elias Ross * * @see ChunkedInputStream */ public class ChunkedOutputStream extends OutputStream { /** * The underlying output stream to which we will write data. */ private OutputStream stream; /** * True if done chunking. */ private boolean doneChunking; /** * Re-useable length encoding array. */ private byte lenEnc[] = {'0', '0', '0', '0', 13, 10}; /** * Conversion symbols. */ private static final byte hex[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; /** * Constructs an output stream wrapping the given stream. * * @param stream wrapped output stream. Must be non-null. */ public ChunkedOutputStream(OutputStream stream) { if (stream == null) throw new IllegalArgumentException("Stream parameter is null"); this.stream = stream; this.doneChunking = false; } /** * Writes the specified byte to the output stream. * Note: Of course, this isn't very efficient, as we have to send * seven bytes of header data as well. * * @param b The byte to be written * @exception IOException if an input/output error occurs */ public void write(int b) throws IOException { if (doneChunking) throw new IllegalHttpStateException("Already wrote last chunk"); writeChunkLen(1); stream.write(b); writeEndChunk(); } /** * Writes the specified byte array. */ public void write(byte[] b) throws IOException { write(b, 0, b.length); } /** * Writes the specified byte array. */ public void write(byte[] b, int off, int len) throws IOException { if (doneChunking) throw new IllegalHttpStateException("Already wrote last chunk"); writeChunkLen(len); stream.write(b, off, len); writeEndChunk(); } /** * Writes integer length and CR LR to the stream. */ void writeChunkLen(int len) throws IOException { if (len > 0xffff) { lenEnc[0] = hex[(len >> 28 ) & 0x0f]; lenEnc[1] = hex[(len >> 24 ) & 0x0f]; lenEnc[2] = hex[(len >> 20 ) & 0x0f]; lenEnc[3] = hex[(len >> 16 ) & 0x0f]; stream.write(lenEnc, 0, 4); } lenEnc[0] = hex[(len >> 12) & 0x0f]; lenEnc[1] = hex[(len >> 8) & 0x0f]; lenEnc[2] = hex[(len >> 4 ) & 0x0f]; lenEnc[3] = hex[len & 0x0f]; stream.write(lenEnc, 0, 6); } /** * Writes CR LF to the stream. */ private void writeEndChunk() throws IOException { stream.write(lenEnc, 4, 2); } /** * Flushes this output stream. */ public void flush() throws IOException { stream.flush(); } /** * This method differs from close as it merely writes the * final chunk and does not close the underlying output stream. * This has no effect if this method was called already. */ public void doneOutput() throws IOException { if (!doneChunking) { // Write the final chunk. writeChunkLen(0); writeEndChunk(); // required extra CRLF doneChunking = true; flush(); } } /** * Closes this output stream, calling doneOutput once before closing. */ public void close() throws IOException { doneOutput(); stream.close(); } public String toString() { return "ChunkedOutputStream " + "stream=" + stream + "doneChunking=" + doneChunking; } } libexml-java-0.0.20080703.orig/http/src/main/java/net/noderunner/http/BasicHttpClient.java0000644000175000017500000000747410762067376030777 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.http; import java.io.BufferedInputStream; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Writer; import java.net.Socket; /** * A very basic HTTP client implementation. */ public class BasicHttpClient implements HttpClient { enum State { INITIAL, SENT_REQUEST, GOT_INPUT, CONTINUE, CLOSED, }; private InputStream is; private OutputStream os; private Socket socket; private Writer writer; private State state; /** * Constructs a BasicHttpClient that communicates over * a socket. By default, wraps the input stream created * in a BufferedInputStream. The output stream is unbuffered. */ public BasicHttpClient(Socket socket) throws IOException { this(socket.getOutputStream(), new BufferedInputStream(socket.getInputStream())); this.socket = socket; } /** * Constructs a BasicHttpClient that communicates over * input and output streams. */ public BasicHttpClient(OutputStream os, InputStream is) { if (os == null) throw new IllegalArgumentException("Null OutputStream"); if (is == null) throw new IllegalArgumentException("Null InputStream"); this.os = os; this.writer = new BufferedWriter(new OutputStreamWriter(os)); this.is = is; this.state = State.INITIAL; } public void writeRequest(ClientRequest request) throws IOException { if (state != State.INITIAL) throw new IllegalHttpStateException("Invalid HTTP state: " + this); if (request == null) throw new IllegalArgumentException("Null ClientRequest"); writer.write(request.getRequestLine().toString()); writer.write(HttpUtil.CRLF); request.getHeaders().write(writer); writer.write(HttpUtil.CRLF); writer.flush(); state = State.SENT_REQUEST; if (request.getDataPoster() != null) { request.getDataPoster().sendData(getOutputStream()); // This is forbidden by the specification // writer.write(HttpUtil.CRLF); writer.flush(); } } public OutputStream getOutputStream() { if (state != State.SENT_REQUEST) throw new IllegalHttpStateException("Invalid HTTP state"); state = State.GOT_INPUT; return os; } public ClientResponse readResponse() throws IOException { if (state != State.SENT_REQUEST && state != State.GOT_INPUT && state != State.CONTINUE) throw new IllegalHttpStateException("Invalid HTTP state: " + state); if (state == State.GOT_INPUT) { os.flush(); } State done = State.INITIAL; // READ_RESPONSE; try { ClientResponse response = new ClientResponse(is); if (response.isContinue()) done = State.CONTINUE; return response; } finally { state = done; } } /** * Closes the underlying input and output streams. */ public void close() throws IOException { state = State.CLOSED; if (socket != null) socket.close(); if (os != null) os.close(); if (is != null) is.close(); socket = null; os = null; is = null; } /** * Returns debug information. */ public String toString() { return "BasicHttpClient state=" + state + " socket=" + socket; } } libexml-java-0.0.20080703.orig/http/src/main/java/net/noderunner/http/LimitedInputStream.java0000644000175000017500000000602110762067376031525 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.http; import java.io.IOException; import java.io.InputStream; /** * An InputStream wrapper which allows only a certain number of bytes to be * read. This is used in conjunction reading from HTTP requests or responses * with supplied Content-Length headers. This stream is * unsynchronized. * * @author Elias Ross * * @see LimitedOutputStream * */ public class LimitedInputStream extends InputStream { /** * Number of bytes that can be read. */ private int remaining; /** * The underlying input stream. */ private InputStream stream; /** * Constructs a limited input stream. * * @param stream * Must be non-null. * @param lengthLimit * limit of bytes of input. */ public LimitedInputStream(InputStream stream, int lengthLimit) { if (stream == null) throw new IllegalArgumentException("InputStream parameter is null"); this.stream = stream; this.remaining = lengthLimit; } /** * Closes the underlying input stream. */ public void close() throws IOException { stream.close(); } /** * Reads up to len bytes of data from the input stream into * an array of bytes, possibly less if the read limit is reached. */ public int read(byte b[], int off, int len) throws IOException { if (remaining == 0) return -1; if (len > remaining) len = remaining; int got = stream.read(b, off, len); if (got != -1) remaining -= got; return got; } /** Calls the wrapped stream. */ public int available() throws IOException { return stream.available(); } /** Calls the wrapped stream. */ public boolean markSupported() { return stream.markSupported(); } /** Calls the wrapped stream. */ public void reset() throws IOException { stream.reset(); } /** Calls the wrapped stream. */ public void mark(int readlimit) { stream.mark(readlimit); } /** * Reads and returns a single byte from this input stream, or -1 if end of * file or the read limit has been encountered. */ public int read() throws IOException { if (remaining == 0) return -1; int r = stream.read(); if (r != -1) remaining--; return r; } /** * Returns a debug string. */ public String toString() { return "LimitedInputStream " + " stream=" + stream + " remaining=" + remaining; } } libexml-java-0.0.20080703.orig/http/src/main/java/net/noderunner/http/LimitedOutputStream.java0000644000175000017500000000517710762067376031741 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.http; import java.io.IOException; import java.io.OutputStream; /** * An OutputStream wrapper which allows only a certain number of bytes to be * output. This is used in conjunction writing HTTP requests or responses * with supplied Content-Length headers. This stream is * unsynchronized. * * @author Elias Ross * * @see LimitedInputStream * */ public class LimitedOutputStream extends OutputStream { /** * Number of bytes that can be output. */ private int remaining; /** * The underlying output stream. */ private OutputStream stream; /** * Constructs a limited output stream. * * @param stream must be non-null. * @param lengthLimit limit of bytes of output. * */ public LimitedOutputStream(OutputStream stream, int lengthLimit) { if (stream == null) throw new IllegalArgumentException("OutputStream parameter is null"); this.stream = stream; this.remaining = lengthLimit; } /** * Closes the underlying output stream. */ public void close() throws IOException { stream.close(); } /** * Flushes the underlying output stream. */ public void flush() throws IOException { stream.flush(); } /** * Writes up to len bytes of data to the output stream, * possibly less if the write limit is reached. */ public void write(byte b[], int off, int len) throws IOException { if (remaining == 0) return; if (len > remaining) len = remaining; stream.write(b, off, len); remaining -= len; } /** * Writes a byte of data to the output stream, * possibly does nothing if the write limit is reached. */ public void write(int b) throws IOException { if (remaining == 0) return; stream.write(b); remaining--; } /** * Returns a debug string. */ public String toString() { return "LimitedOutputStream " + " stream=" + stream + " remaining=" + remaining; } } libexml-java-0.0.20080703.orig/http/src/main/java/net/noderunner/http/ClientRequest.java0000644000175000017500000000335710762067376030542 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.http; /** * Contains an HTTP client request. */ public class ClientRequest extends Request { DataPoster dataPoster; /** * Constructs a ClientRequestImpl by parts. */ public ClientRequest(RequestLine requestLine, MessageHeaders headers) { super(requestLine, headers); } /** * Constructs a ClientRequestImpl by parts. * @param dataPoster may be null */ public ClientRequest(RequestLine requestLine, MessageHeaders headers, DataPoster dataPoster) { super(requestLine, headers); this.dataPoster = dataPoster; } /** * Returns an optional call-back interface for sending * HTTP data to the server. May return null, in which case, data may * be instead sent by via the output stream obtained by calling {@link * HttpClient#getOutputStream}. */ public DataPoster getDataPoster() { return dataPoster; } /** * Returns a debug string. */ public String toString() { return super.toString() + " dataPoster=" + dataPoster; } } libexml-java-0.0.20080703.orig/http/src/main/java/net/noderunner/http/ClientResponse.java0000644000175000017500000000427510762067376030710 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.http; import java.io.IOException; import java.io.InputStream; /** * Contains the contents of an HTTP response message. * In RFC 2616 terms, this object represents data found in the * Response body. */ public class ClientResponse extends Response { InputStream is; /** * Package-private constructor */ ClientResponse() { } /** * Constructs a ClientResponseImpl by parsing an input stream. */ public ClientResponse(InputStream is) throws IOException { String line; do { line = HttpUtil.readHttpLine(is); } while (line.length() == 0); this.statusLine = StatusLine.parseStatusLine(line); this.headers = MessageHeaders.readHeaders(is); this.is = is; } /** * Returns a stream for reading data from the HTTP server. */ public InputStream getInputStream() { return is; } /** * Reads a response's input stream until EOF. * Returns the number of bytes read. * If the server indicates the connection was closed, does nothing. */ public int readFully() throws IOException { InputStream s = HttpUtil.wrapInputStream(getInputStream(), getHeaders()); if (s != null) { boolean close = getHeaders().contains(MessageHeader.MH_CONNECTION_CLOSE); if (!close) return HttpUtil.readFully(s); } return 0; } /** * Returns a debug string showing the response information contained * within. */ public String toString() { return super.toString() + " is=" + is; } } libexml-java-0.0.20080703.orig/http/src/main/java/net/noderunner/http/Response.java0000644000175000017500000000356310762067376027550 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.http; /** * Contains the contents of an HTTP response message. * In RFC 2616 terms, this object represents data found in the * Response body. */ public class Response { StatusLine statusLine; MessageHeaders headers; /** * Package-private default constructor. */ Response() { } /** * Constructs a Response object by parts. */ public Response(StatusLine statusLine, MessageHeaders headers) { this.headers = headers; this.statusLine = statusLine; } public StatusLine getStatusLine() { return statusLine; } public MessageHeaders getHeaders() { return headers; } /** * Returns true if the response should be continued. */ public boolean isContinue() { int code = getStatusLine().getStatusCode(); return (code >= 100) && (code < 200); } /** * Returns a debug string showing the response information contained * within. */ public String toString() { StringBuffer sb = new StringBuffer(); sb.append("ResponseImpl status=").append(getStatusLine()).append(" headers=[ "); sb.append(headers).append(' '); sb.append(']'); return sb.toString(); } } libexml-java-0.0.20080703.orig/http/src/main/java/net/noderunner/http/RetryHttpClient.java0000644000175000017500000002453710762067376031062 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.http; import java.io.IOException; import java.io.OutputStream; import java.net.MalformedURLException; import java.net.Socket; import java.net.URL; import javax.net.SocketFactory; import javax.net.ssl.SSLSocketFactory; /** * A HttpClient implementation that retries contacting a remote URL and * allows for persistant connections. For each retry, this client waits an * additional second before attempting a new connection. Note that if a * failure occurs reading the server response, retries may or may not be made * only for non-POST and PUT methods. Refer to * {@link #readResponse readResponse} on this is handled. *

* Also, this client handles most redirects, on either the same host or * different host. By default, note that redirects will only be followed for * non-POST and PUT methods. * Refer to {@link #setFollowRedirects setFollowRedirects} on this. *

*

* HTTPS (HTTP over SSL) relies on the javax.net.ssl library, and * may require com.sun.net.ssl.internal.ssl.Provider to be * installed using the java.security.Security.addProvider method. *

*

* Many of the protected methods may be overriden * to supply specific functionality. For example, by default * the underlying HttpClient is the {@link BasicHttpClient}, * this can be easily changed. *

*/ public class RetryHttpClient implements HttpClient { /** * Default number of tries. */ public static final int DEFAULT_MAX_TRIES = 3; /** * Lazy-constructed. */ private static SocketFactory sslSocketFactory; private URL url; private int maxTries; private boolean open; private HttpClient client; private ClientRequest request; private boolean followRedirects; private boolean skipContinues; /** * Constructs a RetryHttpClient that retries a number of times. * @param maxTries must be greater than zero */ public RetryHttpClient(URL url, int maxTries) { if (url == null) throw new IllegalArgumentException("Null URL"); if (maxTries < 1) throw new IllegalArgumentException("Invalid number of retries"); this.url = url; this.maxTries = maxTries; this.followRedirects = true; this.skipContinues = true; } /** * Constructs a RetryHttpClient that retries 3 times. */ public RetryHttpClient(URL url) { this(url, DEFAULT_MAX_TRIES); } /** * Callback that indicates the connection failed and will be retried. The * default implementation simply closes the connection. * @param failures number of failures (counting from 0) */ protected void retrySendRequest(IOException e, int failures) { try { close(); } catch (IOException ex2) { } } /** * Returns a newly constructed socket for a given URL. * By default, the HTTP port to use will be 80. */ protected Socket makeSocket(URL url) throws IOException { int port = url.getPort(); if (port == -1) port = 80; Socket s = new Socket(url.getHost(), port); s.setSoTimeout(30 * 1000); return s; } /** * Returns a newly constructed SSL socket for a given URL. * By default, the HTTPS port to use will be 443. */ protected Socket makeSSLSocket(URL url) throws IOException { int port = url.getPort(); if (port == -1) port = 443; if (sslSocketFactory == null) sslSocketFactory = SSLSocketFactory.getDefault(); return sslSocketFactory.createSocket(url.getHost(), 443); } /** * Sets the socket options to use. * By default, sets the read timeout to 30 seconds. */ protected void setSocketOptions(Socket socket) throws IOException { socket.setSoTimeout(30 * 1000); } /** * Returns a newly constructed HTTP client for a given URL. * Calls {@link #makeSocket} to construct a network socket * for HTTP, {@link #makeSSLSocket} for HTTPS. * Calls {@link #setSocketOptions} to set socket options. */ protected HttpClient makeHttpClient(URL url) throws IOException { Socket socket; String p = url.getProtocol(); if ("http".equals(p)) socket = makeSocket(url); else if ("https".equals(p)) socket = makeSSLSocket(url); else throw new IOException("Unknown protocol: " + url); setSocketOptions(socket); return new BasicHttpClient(socket); } /** * Attempts to send an HTTP request, and may retry to send a certain * number of times. * Calls {@link #makeHttpClient} to construct a new client. */ public void writeRequest(ClientRequest request) throws IOException { this.request = request; IOException lastException = null; int tries = 0; do { if (!open) client = makeHttpClient(url); try { client.writeRequest(request); open = true; return; } catch (IOException e) { lastException = e; retrySendRequest(e, tries); } } while (tries++ < maxTries); throw lastException; } /** * Returns a stream for writing data to, if data is to be sent to the * server. */ public OutputStream getOutputStream() { if (!open) throw new IllegalHttpStateException("Client not open"); return client.getOutputStream(); } private boolean differentHost(URL newUrl) { return (!newUrl.getHost().equals(url.getHost()) || newUrl.getPort() != url.getPort()); } /** * Kind of convoluted way of making a new request. */ private void setupClientRequest(URL newUrl) { MessageHeaders headers = request.getHeaders(); if (differentHost(newUrl)) { MessageHeader hh = MessageHeader.makeHostHeader(newUrl); headers.add(hh); } RequestLine rl = new RequestLine(request.getRequestLine().getMethod(), newUrl.getFile()); this.request = new ClientRequest(rl, headers, request.getDataPoster()); this.url = newUrl; } /** * Returns true if the response is a 100 continue code. * Ignores 100 to 199 status codes. */ private boolean doingContinue(ClientResponse r) { if (!skipContinues) return false; return r.isContinue(); } /** * Returns true, if the response is a redirect and we should follow. * Follows 301, 302, and 307 status codes. * If we're redirecting to a different host, the old request is closed. * Doesn't really follow the official redirection guidelines in the * RFC. */ private boolean doingRedirect(ClientResponse r) throws IOException { if (!followRedirects) return false; int code = r.getStatusLine().getStatusCode(); if (code != 301 && code != 302 && code != 303 && code != 307) return false; String location = r.getHeaders().getFieldContent(MessageHeader.FN_LOCATION); if (location == null) throw new HttpException("No location header in HTTP redirect"); location = location.trim(); URL newUrl; try { // build new URL from the old newUrl = new URL(url, location); } catch (MalformedURLException e) { throw new HttpException("Location header has invalid URL: " + location); } if (differentHost(newUrl)) close(); else r.readFully(); setupClientRequest(newUrl); return true; } private boolean closeConnection(ClientResponse r) { return r.getHeaders().contains(MessageHeader.MH_CONNECTION_CLOSE); } /** * Reads the response data from the HTTP server. *

* If the response data cannot be read, then the connection will be * closed, and {@link #writeRequest writeRequest} will be called * up to the maximum of retries as previously set. * The original request will not retried if the request method was * PUT or POST and {@link * ClientRequest#getDataPoster} returns null. *

*

* If a redirection response was read, it is followed only if redirection * is enabled. *

*/ public ClientResponse readResponse() throws IOException { if (!open) throw new IllegalHttpStateException("Client not open"); int tries = 0; IOException lastException = null; do { if (!open) writeRequest(request); try { ClientResponse r = client.readResponse(); this.open = !closeConnection(r); // Check for continue if (doingContinue(r)) { continue; } // Can't (always) redirect if we are posting ... if (request.getDataPoster() == null) { Method m = request.getRequestLine().getMethod(); if (m == Method.POST || m == Method.PUT) return r; } // Check redirect if (!doingRedirect(r)) return r; else writeRequest(request); } catch (IOException e) { lastException = e; retrySendRequest(e, tries); } } while (tries++ < maxTries); if (lastException == null) // must be redirect failed throw new HttpException("Redirected too many times: " + maxTries); throw lastException; } /** * Closes the wrapped {@link HttpClient}. * The underlying client may not be re-used. */ public void close() throws IOException { if (open) client.close(); open = false; } /** * Sets whether HTTP redirects should be followed. * These are 300-level response codes. By default, redirects are followed. * The max number of redirects followed is equal to the number of * retries, as was set in the constructor. */ public void setFollowRedirects(boolean followRedirects) { this.followRedirects = followRedirects; } /** * Sets whether HTTP continue responses should be skipped. * These are 100-level response codes. By default, continue responses are ignored. * There is no limit to the number of these that will be read. */ public void setSkipContinues(boolean skipContinues) { this.skipContinues = skipContinues; } /** * Returns debug information. */ public String toString() { return super.toString() + " maxTries=" + maxTries + " client=[" + client + "] url=" + url + " open=" + open; } } libexml-java-0.0.20080703.orig/http/src/main/java/net/noderunner/http/DataPoster.java0000644000175000017500000000237210762067376030015 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.http; import java.io.IOException; import java.io.OutputStream; /** * Interface for sending data during an HTTP POST or PUT operation. * * @see HttpClient#writeRequest * @see ClientRequest#getDataPoster */ public interface DataPoster { /** * Sends data to the remote host. * Invoked after the request line and headers have been sent. * @param os output stream to send data to * @throws IOException if data could not be written */ void sendData(OutputStream os) throws IOException; } libexml-java-0.0.20080703.orig/http/src/main/java/net/noderunner/http/BasicHttpServer.java0000644000175000017500000000712210762067376031015 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.http; import java.io.BufferedInputStream; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Writer; import java.net.Socket; /** * A very basic HTTP server implementation. * * @see BasicHttpClient */ public class BasicHttpServer implements HttpServer { enum State { INITIAL, READ_REQUEST, WROTE_RESPONSE, WROTE_CONTINUE, // GOT_OUTPUT = INITIAL; CLOSED } private OutputStream os; private Writer writer; private InputStream is; private Socket socket; private State state; /** * Constructs a BasicHttpServer that communicates over * a socket. The input stream is wrapped in a buffered * input stream. */ public BasicHttpServer(Socket socket) throws IOException { this(socket.getOutputStream(), new BufferedInputStream(socket.getInputStream())); this.socket = socket; } /** * Constructs a BasicHttpServer that communicates over * an input and output stream. */ public BasicHttpServer(OutputStream os, InputStream is) { if (os == null) throw new IllegalArgumentException("Null OutputStream"); if (is == null) throw new IllegalArgumentException("Null InputStream"); this.os = os; this.writer = new BufferedWriter(new OutputStreamWriter(os)); this.is = is; this.state = State.INITIAL; } public ServerRequest readRequest() throws IOException { if (state != State.INITIAL && state != State.WROTE_RESPONSE) throw new IllegalHttpStateException("Invalid HTTP state"); state = State.READ_REQUEST; return new ServerRequest(is); } public void writeResponse(ServerResponse response) throws IOException { if (state != State.READ_REQUEST && state != State.WROTE_CONTINUE) throw new IllegalHttpStateException("Invalid HTTP state"); if (response == null) throw new IllegalArgumentException("Null ServerResponse"); state = response.isContinue() ? State.WROTE_CONTINUE : State.WROTE_RESPONSE; writer.write(response.getStatusLine().toString()); writer.write(HttpUtil.CRLF); response.getHeaders().write(writer); writer.write(HttpUtil.CRLF); writer.flush(); if (response.getDataPoster() != null) { response.getDataPoster().sendData(getOutputStream()); } } public OutputStream getOutputStream() { if (state != State.WROTE_RESPONSE) throw new IllegalHttpStateException("Invalid HTTP state " + state); state = State.INITIAL; return os; } /** * Closes the underlying input and output streams. */ public void close() throws IOException { state = State.CLOSED; if (socket != null) socket.close(); if (os != null) os.close(); if (is != null) is.close(); os = null; is = null; } /** * Returns debug information. */ public String toString() { return "BasicHttpServer state=" + state + " socket=" + socket; } } libexml-java-0.0.20080703.orig/http/src/main/java/net/noderunner/http/HttpClient.java0000644000175000017500000000573310762067376030031 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.http; import java.io.IOException; import java.io.OutputStream; /** * Specifies methods for an HTTP client. * Methods must be called in specific order for a successful HTTP * exchange to take place. The order of calls that must be made: *
    *
  • {@link #writeRequest}
  • *
  • {@link #getOutputStream}
  • *
  • {@link #readResponse}
  • *
* If the HTTP server and client are HTTP/1.1, then * of course the same output and input stream can be re-used. */ public interface HttpClient { /** * Sends the first part of a Request message, * consisting of a request line and headers. * The message body may be sent in one of two ways: *
    *
  1. By returning a {@link DataPoster} in the client request * object. *
  2. Or, by using the stream returned by {@link #getOutputStream}. *
* * @throws IllegalHttpStateException if the request was already sent * and the response was not yet read */ void writeRequest(ClientRequest request) throws IOException; /** * Returns a stream for writing data to, if data is to be sent to the * server. For some HTTP methods, like GET, calling this * method of course makes little sense. Data must be sent if * content-length or transfer encoding headers were sent. * This stream should be wrapped to control output based on the * headers specified in the request. * * @throws IllegalHttpStateException if the request was not yet sent * or the response was already read, data was sent with a * DataPoster, or this method was already called */ OutputStream getOutputStream(); /** * Reads the response data from the HTTP server. * This commits the output stream and reads the response from the input * stream. If data is being sent by the HTTP server, it must be * read fully before another request can be accepted. * * @throws IllegalHttpStateException if the request was not yet sent * @throws HttpException if the server returned an invalid HTTP * response */ ClientResponse readResponse() throws IOException; /** * Closes any underlying sockets or streams. * May optionally release other sorts of allocated resources. */ void close() throws IOException; } libexml-java-0.0.20080703.orig/http/src/main/java/net/noderunner/http/package.html0000644000175000017500000000033510676367451027363 0ustar twernertwerner

Provides classes for sending and receiving data over HTTP.

libexml-java-0.0.20080703.orig/http/src/main/java/net/noderunner/http/ServerRequest.java0000644000175000017500000000373010762067376030565 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.http; import java.io.IOException; import java.io.InputStream; /** * Specifies an HTTP request. * In RFC 2616 terms, this object represents data found in the * Request body. */ public class ServerRequest extends Request { private InputStream is; /** * Constructs a ServerRequest by parsing an input stream. */ public ServerRequest(InputStream is) throws IOException { String line; do { line = HttpUtil.readHttpLine(is); } while (line.length() == 0); this.requestLine = new RequestLine(line); this.headers = MessageHeaders.readHeaders(is); this.is = is; } public InputStream getInputStream() { return is; } /** * Reads a response's input stream until EOF. * Returns the number of bytes read. * If the server indicates the connection was closed, does nothing. */ public int readFully() throws IOException { InputStream s = HttpUtil.wrapInputStream(getInputStream(), getHeaders()); if (s != null) { boolean close = getHeaders().contains(MessageHeader.MH_CONNECTION_CLOSE); if (!close) return HttpUtil.readFully(s); } return 0; } /** * Returns a debug string. */ public String toString() { return super.toString() + " is=" + is; } } libexml-java-0.0.20080703.orig/http/src/main/java/net/noderunner/http/HttpVersion.java0000644000175000017500000000714110762067376030233 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.http; import java.util.NoSuchElementException; import java.util.StringTokenizer; /** * This represents an HTTP-Version data object, as found in RFC * 2616. It is immutable. */ public class HttpVersion { private int major; private int minor; private String toString; /** * Represents HTTP version 1.1 */ public static final HttpVersion HTTP11 = new HttpVersion(1, 1); /** * Represents HTTP version 1.0 */ public static final HttpVersion HTTP10 = new HttpVersion(1, 0); /** * The string HTTP/. */ public static final String HTTP_VERSION_BEGIN = "HTTP/"; /** * Constructs a HttpVersionImpl out of a parsable String. */ public HttpVersion(String line) throws HttpException { if (line == null) throw new IllegalArgumentException("Null HTTP version line"); if (!line.startsWith(HTTP_VERSION_BEGIN)) throw new HttpException("HTTP Version prefix invalid: " + line); StringTokenizer st = new StringTokenizer(line, "/."); try { st.nextToken(); major = Integer.parseInt(st.nextToken()); minor = Integer.parseInt(st.nextToken()); } catch (NoSuchElementException e) { throw new HttpException("HTTP version invalid syntax"); } catch (NumberFormatException e) { throw new HttpException("HTTP version invalid number"); } this.toString = HTTP_VERSION_BEGIN + getMajorVersion() + '.' + getMinorVersion(); } /** * Based on the string supplied, returns either * HttpVersion.HTTP10 or HttpVersion.HTTP11 or * a newly constructed HttpVersion instance. */ public static HttpVersion parseVersion(String version) throws HttpException { if (version.equals(HTTP10.toString())) return HTTP10; if (version.equals(HTTP11.toString())) return HTTP11; return new HttpVersion(version); } /** * Constructs a HttpVersionImpl out of version number parts. */ public HttpVersion(int major, int minor) { this.major = major; this.minor = minor; this.toString = HTTP_VERSION_BEGIN + getMinorVersion() + '.' + getMajorVersion(); } /** * Returns the minor version number in use. */ public int getMinorVersion() { return minor; } /** * Returns the major version number in use. */ public int getMajorVersion() { return major; } /** * Returns
HTTP_VERSION_BEGIN + getMinorVersion() + '.' + getMajorVersion()
*/ public String toString() { return toString; } /** * Returns true if the other object is an HttpVersion with the same minor * and major versions. */ public boolean equals(Object other) { if (!(other instanceof HttpVersion)) return false; HttpVersion v = (HttpVersion) other; return v.getMinorVersion() == getMinorVersion() && v.getMajorVersion() == getMajorVersion(); } /** * Returns the hashcode. */ public int hashCode() { return major * 10 + minor; } } libexml-java-0.0.20080703.orig/http/src/main/java/net/noderunner/http/ServerResponse.java0000644000175000017500000000352610762067376030736 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.http; /** * Contains the contents of an HTTP response message. * In RFC 2616 terms, this object represents data found in the * Response body. */ public class ServerResponse extends Response { DataPoster dataPoster; /** * Constructs a ServerResponseImpl by parts, * with no data poster. */ public ServerResponse(StatusLine line, MessageHeaders headers) { super(line, headers); } /** * Constructs a ServerResponseImpl by parts. * @param dataPoster may be null */ public ServerResponse(StatusLine line, MessageHeaders headers, DataPoster dataPoster) { super(line, headers); this.dataPoster = dataPoster; } /** * Constructs a ServerResponseImpl by parts. */ public ServerResponse(StatusLine line, MessageHeader[] headers) { this(line, new MessageHeaders(headers)); } public DataPoster getDataPoster() { return dataPoster; } /** * Returns a debug string showing the response information contained * within. */ public String toString() { return super.toString() + " dataPoster=" + dataPoster; } } libexml-java-0.0.20080703.orig/http/src/main/java/net/noderunner/http/Request.java0000644000175000017500000000312610762067376027375 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.http; /** * Contains an HTTP request. * In RFC 2616 terms, this object represents data found in the * Request body. */ public class Request { RequestLine requestLine; MessageHeaders headers; /** * Package-private constructor. */ Request() { } /** * Constructs a RequestImpl by parts. */ public Request(RequestLine requestLine, MessageHeaders headers) { this.requestLine = requestLine; this.headers = headers; } /** * Returns the request line. */ public RequestLine getRequestLine() { return requestLine; } /** * Returns headers from the HTTP request. */ public MessageHeaders getHeaders() { return headers; } /** * Returns a debug string. */ public String toString() { String s = "Request line=[" + requestLine + "] headers="; s += headers + " "; return s; } } libexml-java-0.0.20080703.orig/http/src/main/java/net/noderunner/http/ByteArrayDataPoster.java0000644000175000017500000000474110762067376031642 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.http; import java.io.IOException; import java.io.OutputStream; /** * A utility class for sending an array of bytes to an HTTP server or client. * Example usage: *
 * HttpClient client = new RetryHttpClient("http://example.net");
 * byte buf[] = "This is only a test".getBytes();
 * DataPoster dataPoster = new ByteArrayDataPoster(buf);
 * RequestLine rl = new RequestLineImpl( ... );
 * ClientRequest request = new ClientRequestImpl(rl, dataPoster);
 *
 * client.writeRequest(request);
 * ClientResponse response = client.readResponse();
 * 
*/ public class ByteArrayDataPoster implements DataPoster { private byte data[]; private int len; private int off; /** * Constructs a ByteArrayDataPoster, * which will send an entire byte array. */ public ByteArrayDataPoster(byte[] data) { if (data == null) throw new IllegalArgumentException("Null byte[]"); this.data = data; this.off = 0; this.len = data.length; } /** * Constructs a ByteArrayDataPoster * which will send part of a byte array. * * @param data source data array * @param off zero-based offset in source * @param len length of array to send */ public ByteArrayDataPoster(byte[] data, int off, int len) { if (data == null) throw new IllegalArgumentException("Null byte[]"); this.data = data; this.off = off; this.len = len; } /** * Writes the byte array to the supplied output stream. */ public void sendData(OutputStream os) throws IOException { if (os == null) throw new IllegalArgumentException("OutputStream is null"); os.write(data, off, len); os.flush(); } public String toString() { return "ByteArrayDataPoster data=" + data.length + " off=" + off + " len=" + len; } } libexml-java-0.0.20080703.orig/http/src/main/java/net/noderunner/http/StatusLine.java0000644000175000017500000001153410762067376030042 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.http; import java.util.NoSuchElementException; import java.util.StringTokenizer; /** * This is a immutable implementation of the StatusLine interface. */ public class StatusLine { /** * Basic Continue message from an HTTP/1.1 server. */ public static final StatusLine HTTP11_100 = new StatusLine(HttpVersion.HTTP11, 100, "Continue"); /** * Basic OK message from an HTTP/1.1 server. */ public static final StatusLine HTTP11_200_OK = new StatusLine(HttpVersion.HTTP11, 200, "OK"); /** * Basic 204 message from an HTTP/1.1 server. */ public static final StatusLine HTTP11_204 = new StatusLine(HttpVersion.HTTP11, 204, "No Content"); /** * Basic 301 message from an HTTP/1.1 server. */ public static final StatusLine HTTP11_301 = new StatusLine(HttpVersion.HTTP11, 301, "Moved Permanently"); /** * Basic 404 message from an HTTP/1.1 server. */ public static final StatusLine HTTP11_404 = new StatusLine(HttpVersion.HTTP11, 404, "Not Found"); private HttpVersion version; private int statusCode; private String reasonPhrase; /** Cached string value for this object */ private String toString; /** * Constructs this object using a status code, HTTP version 1.1, and blank reason. * @param statusCode must be in the range 0 to 999 */ public StatusLine(int statusCode) { this(HttpVersion.HTTP11, statusCode, ""); } /** * Constructs this object using Status-Line parts. * @param version may not be null * @param statusCode must be in the range 0 to 999 * @param reasonPhrase may not be null */ public StatusLine(HttpVersion version, int statusCode, String reasonPhrase) { if (version == null) throw new IllegalArgumentException("Null version"); if (reasonPhrase == null) throw new IllegalArgumentException("Null reason"); if (statusCode < 0 || statusCode > 999) throw new IllegalArgumentException("Invalid range for status code"); this.version = version; this.statusCode = statusCode; this.reasonPhrase = reasonPhrase; } /** * Constructs a StatusLineImpl using an unparsed request * line. This string should not end in CRLF. * @throws HttpException if an invalid HTTP Request-Line was used * in initialization */ public StatusLine(String line) throws HttpException { if (line == null) throw new IllegalArgumentException("Null status line"); StringTokenizer st = new StringTokenizer(line, " "); try { version = HttpVersion.parseVersion(st.nextToken()); statusCode = Integer.parseInt(st.nextToken()); if (statusCode < 0 || statusCode > 999) throw new HttpException("Invalid status number: " + statusCode); reasonPhrase = st.nextToken("").trim(); } catch (NoSuchElementException e) { throw new HttpException("Invalid status line: " + line); } } /** * Constructs this object using Status-Line parts. * @param statusCode must be in the range 0 to 999 * @param reasonPhrase may not be null */ public StatusLine(int statusCode, String statusReason) { this(HttpVersion.HTTP11, statusCode, statusReason); } /** * Returns either {@link StatusLine#HTTP11_200_OK} or a newly * constructed StatusLine object. */ public static StatusLine parseStatusLine(String line) throws HttpException { if (line == null) throw new IllegalArgumentException("Null status line"); if (line.equals(HTTP11_200_OK.toString())) return HTTP11_200_OK; return new StatusLine(line); } /** * Returns the status' HTTP version. */ public HttpVersion getHttpVersion() { return version; } /** * Returns the three-digit status code. */ public int getStatusCode() { return statusCode; } /** * Returns the status reason phrase. */ public String getReasonPhrase() { return reasonPhrase; } /** * Returns this StatusLine as: *
	 * getHttpVersion() + ' ' + getStatusCode() + ' ' + getReasonPhrase()
	 * 
* Note: Does not include CRLF. */ public String toString() { if (toString == null) toString = getHttpVersion().toString() + ' ' + getStatusCode() + ' ' + getReasonPhrase(); return toString; } } ././@LongLink0000000000000000000000000000014500000000000011565 Lustar rootrootlibexml-java-0.0.20080703.orig/http/src/main/java/net/noderunner/http/IllegalHttpStateException.javalibexml-java-0.0.20080703.orig/http/src/main/java/net/noderunner/http/IllegalHttpStateException.java0000644000175000017500000000254210762067376033037 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.http; /** * Unchecked exception used to indicate the use of the HTTP * library (such as call order) was incorrectly made. */ public class IllegalHttpStateException extends IllegalStateException { private static final long serialVersionUID = -6481927370224466490L; /** * Constructs a new IllegalHttpStateException with a message. * @param message explaination */ public IllegalHttpStateException(String message) { super(message); } /** * Constructs a new IllegalHttpStateException with no message. */ public IllegalHttpStateException() { super(); } } libexml-java-0.0.20080703.orig/http/src/main/java/net/noderunner/http/MessageHeader.java0000644000175000017500000001345010762067376030443 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.http; import java.net.URL; import java.util.Locale; /** * This is an immutable implementation of the MessageHeader interface. */ public class MessageHeader { /** * Field name for the host header. */ public static final String FN_HOST = "host"; /** * Field name for the connection header. */ public static final String FN_CONNECTION = "connection"; /** * Field name for the content-length header. */ public static final String FN_CONTENT_LENGTH = "content-length"; /** * Field name for the content-type header. */ public static final String FN_CONTENT_TYPE = "content-type"; /** * Field name for the location header. * Typically used in redirects. */ public static final String FN_LOCATION = "location"; /** * Field name for the referer header. */ public static final String FN_REFERER = "referer"; /** * Field name for the user agent header. */ public static final String FN_TRANSFER_ENCODING = "transfer-encoding"; /** * Field name for the user agent header. */ public static final String FN_USER_AGENT = "user-agent"; /** * Field name for the server header. */ public static final String FN_SERVER = "server"; /** * Use this MessageHeader for sending chunked data. */ public static final MessageHeader MH_TRANSFER_ENCODING_CHUNKED = new MessageHeader(FN_TRANSFER_ENCODING, "chunked"); /** * Use this MessageHeader for indicating a keep-alive * connection. */ public static final MessageHeader MH_CONNECTION_KEEP_ALIVE = new MessageHeader(FN_CONNECTION, "Keep-Alive"); /** * Use this MessageHeader for indicating connection close. */ public static final MessageHeader MH_CONNECTION_CLOSE = new MessageHeader(FN_CONNECTION, "close"); /** * Use this MessageHeader for indicating a URL encoded * content type. */ public static final MessageHeader MH_URL_ENCODED = new MessageHeader(FN_CONTENT_TYPE, "application/x-www-form-urlencoded"); /** * Default user agent string for this library. */ public static final MessageHeader MH_USER_AGENT = new MessageHeader(FN_USER_AGENT, "ehttp/1.0"); private String fieldName; private String fieldContent; private String toString; /** * Parse using a message-header string. * @throws HttpException if invalid HTTP message header data was used * in initialization */ public static MessageHeader parse(String messageHeader) throws HttpException { if (messageHeader == null) throw new IllegalArgumentException("Null messageHeader string"); int colonAt = messageHeader.indexOf(':'); if (colonAt == -1) throw new HttpException("No message-header colon found"); String fieldName = messageHeader.substring(0, colonAt).toLowerCase(); String fieldValue; if (colonAt + 1 < messageHeader.length()) fieldValue = messageHeader.substring(colonAt + 1).trim(); else fieldValue = ""; try { return new MessageHeader(fieldName, fieldValue); } catch (RuntimeException e) { throw new HttpException(e); } } private void init(String fieldName, String fieldValue) { if (fieldName == null) throw new IllegalArgumentException("Null fieldName"); if (fieldValue == null) throw new IllegalArgumentException("Null fieldValue"); this.fieldName = fieldName.toLowerCase(Locale.ENGLISH); fieldContent = fieldValue.trim(); if (!TokenUtil.isValidToken(fieldName)) throw new IllegalArgumentException("Invalid characters in field-name " + fieldName); } /** * Initialize using a field-name and field-value. */ public MessageHeader(String fieldName, String fieldValue) { init(fieldName, fieldValue); } public boolean equals(Object other) { if (this == other) return true; if (!(other instanceof MessageHeader)) return false; MessageHeader h = (MessageHeader)other; return h.getFieldName().equals(getFieldName()) && h.getFieldContent().equals(getFieldContent()); } /** * Returns the name of the header, which for consistency is in * lower-case form. */ public String getFieldName() { return fieldName; } /** * Returns the value of this header. * In terms of RFC 2616, this is the header's field-content, * which excludes trailing and following white-space. */ public String getFieldContent() { return fieldContent; } /** * Returns the hashcode. */ public int hashCode() { return fieldName.hashCode() ^ fieldContent.hashCode(); } /** * Returns a new Host header, appropriate to the * given URL. */ public static MessageHeader makeHostHeader(URL url) { if (url == null) throw new IllegalArgumentException("Null url"); int port = url.getPort(); String s; if (port == -1) s = url.getHost(); else s = url.getHost() + ":" + port; return new MessageHeader(MessageHeader.FN_HOST, s); } /** * Should return this MessageHeader as: *
	 * getFieldName() + ':' + getFieldContent();
	 * 
*/ public String toString() { if (toString == null) toString = getFieldName() + ':' + getFieldContent(); return toString; } } libexml-java-0.0.20080703.orig/http/src/main/java/net/noderunner/http/HttpException.java0000644000175000017500000000256010762067376030544 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.http; import java.io.IOException; /** * This exception is used to indicate the use of the HTTP protocol was * incorrect. */ public class HttpException extends IOException { private static final long serialVersionUID = 3976891853888098317L; /** * Construct a new HttpException with a message. * @param message explaination */ public HttpException(String message) { super(message); } /** * Construct a new HttpException with no message. */ public HttpException() { super(); } /** * Construct a new HttpException with cause. */ public HttpException(Exception e) { initCause(e); } } libexml-java-0.0.20080703.orig/http/.classpath0000644000175000017500000000064510731326000020462 0ustar twernertwerner libexml-java-0.0.20080703.orig/http/.project0000644000175000017500000000105610731326000020143 0ustar twernertwerner http org.eclipse.jdt.core.javabuilder org.maven.ide.eclipse.maven2Builder org.eclipse.jdt.core.javanature org.maven.ide.eclipse.maven2Nature libexml-java-0.0.20080703.orig/http/pom.xml0000644000175000017500000000365010770533053020026 0ustar twernertwerner 4.0.0 net.noderunner http HTTP server and client library HTTP client and server classes 1.0.2 http://e-xml.sourceforge.net maven-compiler-plugin 1.5 1.5 org.codehaus.mojo cobertura-maven-plugin org.apache.maven.wagon wagon-ssh-external 1.0-beta-2 e-xml.sourceforge.net http://e-xml.sourceforge.net/maven2/repository e-xml.sourceforge.net scp://e-xml.sourceforge.net/home/users/g/ge/genman/htdocs/maven2/repository junit junit 3.8.1 test javax.servlet servlet-api 2.5 provided libexml-java-0.0.20080703.orig/e-xml/0000755000175000017500000000000011111351372016540 5ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/0000755000175000017500000000000011111351372017327 5ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/0000755000175000017500000000000011111351354020306 5ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/java/0000755000175000017500000000000011111351353021226 5ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/java/net/0000755000175000017500000000000011111351353022014 5ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/java/net/noderunner/0000755000175000017500000000000011111351353024173 5ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/java/net/noderunner/exml/0000755000175000017500000000000011111351354025141 5ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/java/net/noderunner/exml/DefaultResolverTest.java0000644000175000017500000000417010762067376031777 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.exml; import java.io.BufferedReader; import java.io.IOException; import java.io.Reader; /** * This is used to test the DefaultResolver class. */ public class DefaultResolverTest extends junit.framework.TestCase { public DefaultResolverTest(String name) { super(name); } public static void main(String[] args) { junit.textui.TestRunner.run(DefaultResolverTest.class); if (args.length == 0) { System.err.println("Usage: DefaultResolver [path path2] item"); return; } // DefaultResolver r = new DefaultResolver(); for (int i = 0; i < args.length - 1; i++) { r.addSearchPath(args[i]); } try { Reader in = r.resolve(args[args.length - 1]); BufferedReader br = new BufferedReader(in); String line; while ((line = br.readLine()) != null) System.out.println(line); } catch (Exception e) { e.printStackTrace(); } } public void testWhatever() throws Exception { DefaultResolver r = new DefaultResolver(); try { r.resolve(null); fail("no null"); } catch (IllegalArgumentException e) { } try { r.addSearchPath(null); fail("no null"); } catch (IllegalArgumentException e) { } r.addSearchPath("http://example.com/"); r.addSearchPath("http://example.org/"); r.addSearchPath("http://example.net/"); try { r.resolve("barney.xml"); fail("should not be able to find barney"); } catch (IOException e) { } } } libexml-java-0.0.20080703.orig/e-xml/src/test/java/net/noderunner/exml/XmlSParserTest.java0000644000175000017500000007345410762067376030744 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.exml; import java.io.BufferedWriter; import java.io.FileInputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.io.StringReader; import java.io.StringWriter; /** * This class is for unit testing the XmlSParser class. * * @see XmlSParser * @author Elias Ross * @version 1.0 */ public class XmlSParserTest extends junit.framework.TestCase { public XmlSParserTest(String name) { super(name); } /* public static junit.framework.TestSuite suite() { return new org.hansel.CoverageDecorator(XmlSParserTest.class, new Class[] { XmlSParser.class }); } */ static String testDoc = "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "stuff\n" + "\n" + "&'"<>\n" + "\n" + "\n"; // don't ignore whitespace and repeat text events static int testDocEvents2[] = { XmlEvent.XML_DECL, XmlEvent.CHARDATA, XmlEvent.DOCTYPE_DECL, XmlEvent.CHARDATA, XmlEvent.STAG, XmlEvent.CHARDATA, XmlEvent.STAG, XmlEvent.ETAG, XmlEvent.CHARDATA, XmlEvent.COMMENT, XmlEvent.CHARDATA, XmlEvent.COMMENT, XmlEvent.CHARDATA, XmlEvent.PI, XmlEvent.CHARDATA, XmlEvent.CDSECT, XmlEvent.CHARDATA, XmlEvent.CDSECT, XmlEvent.CHARDATA, XmlEvent.ENTITY_DECL, XmlEvent.CHARDATA, XmlEvent.ELEMENT_DECL, XmlEvent.CHARDATA, XmlEvent.ATTLIST_DECL, XmlEvent.CHARDATA, XmlEvent.CONDITIONAL_SECT, XmlEvent.CHARDATA, XmlEvent.CONDITIONAL_SECT, XmlEvent.CHARDATA, XmlEvent.NOTATATION_DECL, XmlEvent.CHARDATA, XmlEvent.REFERENCE, XmlEvent.REFERENCE, XmlEvent.REFERENCE, XmlEvent.REFERENCE, XmlEvent.REFERENCE, XmlEvent.CHARDATA, XmlEvent.STAG, XmlEvent.ETAG, XmlEvent.CHARDATA, XmlEvent.ETAG, XmlEvent.EOD }; static int testDocEvents[] = { XmlEvent.XML_DECL, // 0 XmlEvent.DOCTYPE_DECL, // 1 XmlEvent.STAG, // 2 XmlEvent.STAG, XmlEvent.ETAG, // 3 XmlEvent.COMMENT, // 4 XmlEvent.COMMENT, // 5 XmlEvent.PI, // 6 XmlEvent.CDSECT, // 7 // XmlEvent.CDSECT, XmlEvent.ENTITY_DECL, // 8 XmlEvent.ELEMENT_DECL, // 9 XmlEvent.ATTLIST_DECL, // 10 XmlEvent.CONDITIONAL_SECT, // 11 XmlEvent.CONDITIONAL_SECT, // 12 XmlEvent.CHARDATA, // 13 XmlEvent.NOTATATION_DECL, // 14 XmlEvent.REFERENCE, // 15 // XmlEvent.REFERENCE, // XmlEvent.REFERENCE, // XmlEvent.REFERENCE, // XmlEvent.REFERENCE, XmlEvent.STAG, XmlEvent.ETAG, XmlEvent.ETAG, XmlEvent.EOD }; public void testEventStream() throws Exception { XmlSParser parser; Reader r; r = new StringReader(testDoc); parser = new XmlSParser(new XmlReader(r), XmlEvent.ALL_EVENTS); int i = 0; while (parser.hasNext()) { int event = parser.next(); assertTrue("not match " + parser, !parser.matches("XXX".toCharArray())); assertEquals("Expect event " + i, testDocEvents[i++], event); } } public void testEventStreamReset() throws Exception { XmlSParser parser; parser = new XmlSParser(new XmlReader(), XmlEvent.ALL_EVENTS); for (int j = 0; j < 2; j++) { parser.setReadString(testDoc); for (int i = 0; i < testDocEvents.length - 4; i++) { int event = parser.next(); assertEquals("Expect event " + i, testDocEvents[i], event); } } } public void testEventStreamNoSkip() throws Exception { XmlSParser parser; Reader r; r = new StringReader(testDoc); parser = new XmlSParser(new XmlReader(r), XmlEvent.ALL_EVENTS); parser.setSkipWS(false); parser.setSkipRepeatTextEvents(false); int i = 0; while (parser.hasNext()) { int event = parser.next(); assertEquals("Expect event " + i, testDocEvents2[i++], event); } } public void testFilteredEventStream() throws Exception { XmlSParser parser; Reader r; for (int i = 0; i < 14; i++) { int found = 0; int retEvent = 1< 0); } } public static void main(String[] args) { if (args.length > 0) { try { for (int i = 0; i < args.length; i++) { InputStream fis = new FileInputStream(args[i]); Reader r = new InputStreamReader(fis); XmlSParser parser; parser = new XmlSParser(new XmlReader(r), XmlEvent.ALL_EVENTS); parser.setSkipWS(false); parser.setSkipRepeatTextEvents(false); int event; while (parser.hasNext()) { event = parser.next(); System.out.println("Event " + XmlSParser.eventToString(event)); if (event == XmlEvent.TEXT) { System.out.println("Got text " + parser.getText().trim()); } } } } catch (Exception e) { e.printStackTrace(); } } junit.textui.TestRunner.run(XmlSParserTest.class); } public void testNoContent() throws Exception { XmlSParser parser; Reader r; r = new StringReader(""); parser = new XmlSParser(new XmlReader(r)); assertTrue("no data", parser.isEvent(XmlEvent.NONE)); } public static final String D_CONTENT = "D's content here"; /** * Create a new parser for testing. Also checks that XmlWriter is * creating valid Xml. */ public static XmlSParser newParser() throws Exception { XmlWriter writer; StringWriter sw = new StringWriter(); writer = new XmlWriter(new BufferedWriter(sw)); writer.writeHeader("UTF-8"); Element root = new Element("test"); Element a = new Element("a"); Element b = new Element("b"); Element b2 = new Element("b2"); Element c = new Element("c"); Element d = new Element("d"); writer.startElement(root); writer.startElement(a); writer.startElement(b); writer.emptyElement(c); writer.startElement(d); writer.writeCData(D_CONTENT); writer.endElement(); writer.endElement(); writer.startElement(b2); writer.endElement(); writer.endElement(); writer.endElement(); writer.flush(); String in = sw.getBuffer().toString(); ElementRule rule; rule = new ElementRule(); Dtd dtd = new Dtd(); dtd.addElementRule(root, rule); dtd.addElementRule(a, rule); dtd.addElementRule(b, rule); dtd.addElementRule(b2, rule); dtd.addElementRule(c, rule); rule = new ElementRule(); rule.setAllowPCData(true); dtd.addElementRule(d, rule); XmlReader reader = new XmlReader(new StringReader(in), dtd); return new XmlSParser(reader); } public void testBasicDoc() throws Exception { Dtd dtd = new Dtd(); ElementRule rule = new ElementRule(); dtd.addElementRule("root", rule); String in = " "; XmlReader reader = new XmlReader(new StringReader(in), dtd); XmlSParser parser = new XmlSParser(reader); // do stuff Element e = parser.startTag(); assertEquals("root", e.getName()); Element end = parser.endTag(); assertEquals("root null", null, end); assertTrue("root", !e.isOpen()); assertTrue("more data true", reader.hasMoreData()); // try another doc Element st = parser.startTag(); assertEquals("root", st.getName()); parser.getContent(st); Element a = (Element)st.getChild(0); assertTrue("closed a", !a.isOpen()); parser.up(0); assertTrue("more data false", !reader.hasMoreData()); } // tests up() method public void testParserUp() throws Exception { XmlSParser parser = newParser(); parser.next(); assertEquals("test", parser.startTag().getName()); assertEquals("a", parser.startTag().getName()); int depth = parser.getDepth(); assertEquals("b", parser.startTag().getName()); assertEquals("c", parser.startTag().getName()); parser.up(depth); assertEquals("b2", parser.startTag().getName()); assertEquals("b2", parser.endTag().getName()); assertEquals("a", parser.endTag().getName()); assertEquals("test", parser.endTag().getName()); assertEquals(null, parser.endTag()); } /** * Tests whole tree parsing. */ public void testWholeTreeParsing() throws Exception { XmlSParser parser = newParser(); parser.next(); assertEquals(parser.startTag().getName(), "test"); assertEquals(parser.startTag().getName(), "a"); assertEquals(parser.startTag().getName(), "b"); assertEquals(parser.startTag().getName(), "c"); assertEquals(parser.endTag().getName(), "c"); Element e = parser.startTag(); assertEquals(e.getName(), "d"); parser.getContent(e); assertEquals(e.getName(), "d"); assertEquals(parser.endTag().getName(), "d"); assertEquals(parser.endTag().getName(), "b"); assertEquals(parser.startTag().getName(), "b2"); parser.close(); } public void testGetAttNameEOF() throws Exception { Reader r = new StringReader(" blah"); XmlReader xr = new XmlReader(r); XmlSParser p = new XmlSParser(xr); p.next(); try { p.copyContent(NullWriter.getInstance()); fail("EOF in copyContent"); } catch (XmlException e) { } } public void testCopyKnownEntity() throws Exception { Reader r = new StringReader("the &known; here"); XmlReader xr = new XmlReader(r); xr.getDtd().addEntity("known", new Entity("value")); XmlSParser p = new XmlSParser(xr); p.next(); p.next(); String s = p.getText(); assertEquals("the value here", s); } public void testGetAttNameBad() throws Exception { Reader r = new StringReader("text"); XmlSParser p = new XmlSParser(new XmlReader(r)); assertEquals("STAG", XmlEvent.STAG, p.next()); String foo = p.getTagName(); assertEquals("foo", foo); String versionn = p.getAttName(); assertEquals("version", versionn); String versionv = p.getAttValue(null); assertEquals("version", "1.0", versionv); String ref = p.getAttValue(null); assertEquals("ref", "/bar/", ref); String dflt = "whatever"; String notHere; notHere = p.getAttValue(dflt); assertEquals("dflt", notHere, dflt); notHere = p.getAttValue(dflt); assertEquals("dflt", notHere, dflt); // hmm assertEquals("PI" + p, XmlEvent.CHARDATA, p.next()); assertEquals("text", p.getText()); } public void testGetText() throws Exception { // we want to make sure we can get really long strings StringBuffer sb = new StringBuffer(); for (int i = 0; i < 256; i++) sb.append("stuff"); String doc = "" + sb + ""; XmlSParser p = new XmlSParser(new XmlReader()); p.setReadString(doc); p.next(); // stag p.next(); // chardata assertEquals("text", sb.toString(), p.getText()); p.setReadString(doc); p.next(); p.next(); assertEquals("text", sb.toString(), p.getText()); } public void testSmartGetText() throws Exception { String doc = "texttext2text3"; XmlSParser p = new XmlSParser(); p.setReadString(doc); p.setEvents(XmlEvent.STAG); p.setReadString(doc); p.next(); assertEquals("text", p.getText()); p.next(XmlEvent.STAG); assertEquals("text2", p.getText()); p.next(XmlEvent.ETAG); assertEquals("text3", p.getText()); } public void testNext2() throws Exception { String doc = "text3"; XmlSParser p = new XmlSParser(); p.setReadString(doc); p.setEvents(XmlEvent.COMMENT); assertEquals("STAG", XmlEvent.ETAG, p.next(XmlEvent.ETAG)); assertEquals("TEXT", XmlEvent.CHARDATA, p.next(XmlEvent.TEXT)); assertEquals("STAG", XmlEvent.EOD, p.next(XmlEvent.EOD)); } public void testGetAtty() throws Exception { Reader r = new StringReader(""); XmlSParser p = new XmlSParser(new XmlReader(r)); try { p.getAttName(); fail("Must be on STAG"); } catch (IllegalStateException e) { } p.next(); String versionn = p.getAttName(); assertEquals("version", versionn); p.getAttValue(null); String refn = p.getAttName(); assertEquals("ref", refn); p.next(); } public void testGetAtty2() throws Exception { Reader r = new StringReader(""); XmlSParser p = new XmlSParser(new XmlReader(r)); p.next(); String crap = p.getAttName(); assertEquals("crap", null, crap); String crap2 = p.getAttName(); assertEquals("crap2", null, crap2); String crap3 = p.getAttValue(); assertEquals("crap3", null, crap3); String crap4 = p.getAttName(); assertEquals("crap4", null, crap4); } public void testGetAttValue2() throws Exception { Reader r = new StringReader(""); XmlSParser p = new XmlSParser(new XmlReader(r)); assertEquals("STAG", XmlEvent.STAG, p.next()); String version = p.getAttValue(null); assertEquals("version", "1/0", version); p.getAttValue(null); p.getAttValue(null); assertEquals("fake ETAG" + p, XmlEvent.ETAG, p.next()); } public void testMatches() throws Exception { final char foo[] = "foo".toCharArray(); final char bar[] = "bar".toCharArray(); Reader r = new StringReader( "bar"); XmlSParser p = new XmlSParser(new XmlReader(r), XmlEvent.ALL_EVENTS); assertEquals("STAG", XmlEvent.STAG, p.next()); assertTrue("foo", p.matches(foo)); assertTrue("foobar", !p.matches(bar)); assertEquals("ETAG", XmlEvent.ETAG, p.next()); assertEquals("CHARDATA", XmlEvent.CHARDATA, p.next()); assertTrue("bar", p.matches(bar)); assertEquals("PI", XmlEvent.PI, p.next()); assertTrue("foo pi", p.matches(foo)); assertEquals("COMMENT", XmlEvent.COMMENT, p.next()); assertTrue("bar", p.matches(bar)); } public void testExample() throws Exception { String document = "\n" + "\n" + "\n" + "\n" + "Hello world!\n" + "\n"; java.io.Reader r = new java.io.StringReader(document); XmlSParser parser = new XmlSParser(new XmlReader(r)); parser.next(); // returns XmlEvent.STAG for 'doc' tag assertEquals(0, parser.getDepth()); parser.next(); // returns XmlEvent.STAG for empty1 tag assertEquals(1, parser.getDepth()); Element e = parser.startTag(); String v1 = e.getAttValue("attr"); // returns 'value1' attribute value from empty1 assertTrue("not null", v1 != null); parser.next(); // returns XmlEvent.ETAG for empty1 tag parser.next(); // returns XmlEvent.STAG for empty2 tag assertEquals(1, parser.getDepth()); String v2 = parser.getAttValue(); // returns 'value2' attribute value from empty2 assertTrue("not null", v2 != null); parser.next(); // returns XmlEvent.ETAG for empty2 tag parser.next(); // returns XmlEvent.STAG for para tag assertEquals(1, parser.getDepth()); parser.next(); // returns XmlEvent.CHARDATA for text assertEquals(2, parser.getDepth()); String text = parser.getText(); // returns 'Hello world!' assertEquals("hello", "Hello world!", text); parser.next(); // returns XmlEvent.ETAG for para tag assertEquals(2, parser.getDepth()); parser.next(); // returns XmlEvent.ETAG for 'doc' tag assertEquals(1, parser.getDepth()); parser.next(); // returns XmlEvent.EOD assertEquals(0, parser.getDepth()); } public void testExample2() throws Exception { String document = "\n" + "\n" + "\n" + "text\n"+ "\n" + "\n"+ "\n" + "\n"; java.io.Reader r = new java.io.StringReader(document); XmlSParser parser = new XmlSParser(new XmlReader(r)); parser.next(); // returns XmlEvent.STAG for 'doc' tag assertEquals(0, parser.getDepth()); parser.next(); // returns XmlEvent.STAG for empty1 tag parser.getElementTree(); assertEquals(XmlEvent.CHARDATA, parser.next()); assertEquals(XmlEvent.STAG, parser.next()); parser.getElementTree(); assertEquals(XmlEvent.STAG, parser.next()); assertEquals(XmlEvent.ETAG, parser.next()); assertEquals(XmlEvent.STAG, parser.next()); parser.getElementTree(); parser.next(); // returns XmlEvent.ETAG for doc tag assertEquals(1, parser.getDepth()); parser.next(); // returns XmlEvent.EOD assertEquals(0, parser.getDepth()); } public void testExample3() throws Exception { String document = "\n" + "\n" + "\n" + "\n"+ "\n"; java.io.Reader r = new java.io.StringReader(document); XmlSParser parser = new XmlSParser(new XmlReader(r)); assertEquals(XmlEvent.STAG, parser.next()); assertEquals(XmlEvent.STAG, parser.next()); assertEquals(XmlEvent.ETAG, parser.next()); Element e; e = parser.endTag(); assertEquals("empty1", e.getName()); assertEquals(XmlEvent.STAG, parser.next()); assertEquals(XmlEvent.ETAG, parser.next()); e = parser.endTag(); assertEquals(XmlEvent.ETAG, parser.next()); assertEquals(XmlEvent.EOD, parser.next()); assertEquals(0, parser.getDepth()); } public void testRef() throws Exception { Reader r = new StringReader("<>"); XmlSParser parser = new XmlSParser(new XmlReader(r)); assertEquals(XmlEvent.STAG, parser.next()); assertEquals(XmlEvent.REFERENCE, parser.next()); String s = parser.getText(); assertEquals("references in body", "<>", s); } public void testReadTagName() throws Exception { XmlReader xr = new XmlReader(); XmlSParser parser = new XmlSParser(xr); // this is NOT valid XML parser.setReadString(""); NamespaceImpl ns = new NamespaceImpl(); parser.next(); parser.readTagName(ns); assertEquals(null, ns.getNamespaceURI()); assertEquals("a", ns.getPrefix()); assertEquals("b", ns.getLocalName()); assertEquals("a:b", ns.getName()); parser.next(); parser.readTagName(ns); assertEquals(null, ns.getNamespaceURI()); assertEquals(null, ns.getPrefix()); assertEquals(null, ns.getLocalName()); assertEquals("c", ns.getName()); String URI = "http://example.net/xmlns"; xr.getScanner().setUriMap(new UriMap()); xr.getScanner().getUriMap().put("a", URI); parser.setReadString(""); parser.next(); parser.readTagName(ns); assertEquals(URI, ns.getNamespaceURI()); assertEquals("a", ns.getPrefix()); assertEquals("b", ns.getLocalName()); assertEquals("a:b", ns.getName()); } public void testReadAttNameExample() throws Exception { java.io.Reader r = new java.io.StringReader(""); XmlSParser p = new XmlSParser(new XmlReader(r)); assertEquals(XmlEvent.STAG, p.next()); assertEquals("version", p.getAttName()); assertEquals("ref", p.getAttName()); assertEquals(null, p.getAttName()); assertEquals(null, p.getAttName()); } public void testReadAttName() throws Exception { XmlSParser parser = new XmlSParser(new XmlReader()); parser.setReadString(""); NamespaceImpl ns = new NamespaceImpl(); parser.next(); parser.readAttName(ns); assertEquals(null, ns.getNamespaceURI()); assertEquals("c", ns.getPrefix()); assertEquals("d", ns.getLocalName()); assertEquals("c:d", ns.getName()); parser.readAttName(ns); assertEquals(null, ns.getNamespaceURI()); assertEquals(null, ns.getPrefix()); assertEquals(null, ns.getLocalName()); assertEquals("" + parser, "g", ns.getName()); parser.readAttName(ns); assertTrue("clear ns", ns.isClear()); } public void testReadPlain() throws Exception { XmlSParser parser = new XmlSParser(new XmlReader()); // EOD will happen parser.setEvents(XmlEvent.CHARDATA | XmlEvent.STAG | XmlEvent.ETAG); parser.setReadString("apple banana cherry"); assertEquals(XmlEvent.CHARDATA, parser.next()); assertEquals(XmlEvent.STAG, parser.next()); assertEquals(XmlEvent.CHARDATA, parser.next()); assertEquals(XmlEvent.ETAG, parser.next()); assertEquals(XmlEvent.CHARDATA, parser.next()); } public void testCopy0() throws Exception { XmlSParser parser = new XmlSParser(new XmlReader()); String s = " a document here "; parser.setReadString("" + s + "" + s + ""); XmlCharArrayWriter caw = new XmlCharArrayWriter(); assertEquals(XmlEvent.STAG, parser.next()); assertEquals(XmlEvent.STAG, parser.next()); parser.copyContent(caw); assertEquals(s, caw.toString()); assertEquals(XmlEvent.ETAG, parser.next()); assertEquals(XmlEvent.STAG, parser.next()); caw.reset(); parser.copyContent(caw); assertEquals(s, caw.toString()); assertEquals(XmlEvent.ETAG, parser.next()); assertEquals(XmlEvent.ETAG, parser.next()); } public void testCopy() throws Exception { XmlSParser parser = new XmlSParser(new XmlReader()); String s = " a document was definately here "; parser.setReadString("" + s + ""); XmlCharArrayWriter caw = new XmlCharArrayWriter(); try { parser.copyContent(caw); fail("not on STAG"); } catch (IllegalStateException e) { } assertEquals(XmlEvent.STAG, parser.next()); parser.copyContent(caw); assertEquals(XmlEvent.ETAG, parser.next()); } public void testCopy2() throws Exception { XmlSParser parser = new XmlSParser(new XmlReader()); String s = "I was definately e]]>"; // String s = "I was definately here "; parser.setReadString("" + s + ""); XmlCharArrayWriter caw = new XmlCharArrayWriter(); assertEquals(XmlEvent.STAG, parser.next()); parser.copyContent(caw); assertEquals(s, caw.toString()); assertEquals(XmlEvent.ETAG, parser.next()); assertEquals("" + parser, XmlEvent.EOD, parser.next()); assertEquals("" + parser, XmlEvent.STAG, parser.next()); assertEquals("" + parser, XmlEvent.ETAG, parser.next()); } public void testCopy3() throws Exception { XmlSParser parser = new XmlSParser(new XmlReader()); String s = "I was definately "; parser.setReadString("" + s + ""); assertEquals(XmlEvent.STAG, parser.next()); XmlCharArrayWriter caw = new XmlCharArrayWriter(); parser.copyContent(caw); assertEquals(s, caw.toString()); } public void testCopyNull() throws Exception { XmlSParser parser = new XmlSParser(new XmlReader()); parser.setReadString(" "); assertEquals(XmlEvent.STAG, parser.next()); // should be able to get stuff parser.getTagName(); parser.getAttValue(); parser.getAttName(); XmlCharArrayWriter caw = new XmlCharArrayWriter(); parser.copyContent(caw); assertEquals("", caw.toString()); assertEquals("empty tag returns 'fake' ETAG", XmlEvent.ETAG, parser.next()); // white space was eaten assertEquals(XmlEvent.STAG, parser.next()); } public void testName() throws Exception { XmlSParser parser = new XmlSParser(new XmlReader()); parser.setReadString(""); try { assertEquals("something", parser.getAttName()); fail("need a space!"); } catch (IllegalStateException e) { } } public void testEmptyDoc() throws Exception { XmlSParser parser = new XmlSParser(); assertEquals(XmlEvent.EOD, parser.next()); } public void testExtractComments() throws Exception { XmlSParser parser = new XmlSParser(); parser.setReadString(" "); parser.setEvents(XmlEvent.COMMENT | XmlEvent.EOD); while (parser.next() != XmlEvent.EOD) { parser.getComment(); // System.out.println("comment " + c); } } public void testBadComment() throws Exception { XmlSParser parser = new XmlSParser(); parser.setReadString(""); try { parser.next(); fail("-- in comment"); } catch (XmlException e) { } } public void testForCodeCoverage2() throws Exception { XmlSParser parser = new XmlSParser(); parser.setReader(new StringReader(" ")); parser.setSkipWS(false); parser.next(); assertEquals(XmlEvent.STAG, parser.next()); StringWriter sw = new StringWriter(); // don't touch space parser.copyContent(sw); assertEquals("", sw.toString()); assertEquals(XmlEvent.ETAG, parser.next()); assertEquals(XmlEvent.CHARDATA, parser.next()); assertEquals(XmlEvent.ETAG, parser.next()); // don't touch space parser.setReader(new StringReader(" ")); parser.setSkipWS(false); parser.next(); assertEquals(XmlEvent.STAG, parser.next()); Element elem = parser.startTag(); assertEquals("a", elem.getName()); assertEquals(XmlEvent.ETAG, parser.next()); assertEquals(XmlEvent.CHARDATA, parser.next()); parser.setReader(new StringReader("")); try { parser.next(); fail("Unknown token"); } catch (XmlException e) { } parser.setReader(new StringReader("")); parser.setEvents(XmlEvent.PI); parser.next(); PI pi = parser.getPI(); assertEquals("PI", pi.getName()); assertEquals("x", pi.getData()); } public void testSkip() throws Exception { XmlSParser parser = new XmlSParser(); parser.setReadString(" a &ent; b "); parser.next(); parser.next(); assertEquals(XmlEvent.ETAG, parser.next()); } public void testForCodeCoverage() throws Exception { XmlSParser parser = new XmlSParser(); XmlSParser.eventToString(XmlEvent.ALL_EVENTS); XmlSParser.eventToString(XmlEvent.NONE); XmlSParser.eventToString(XmlEvent.TEXT); XmlSParser.eventToString(333333); XmlSParser.eventToString(XmlEvent.EOD); parser.setReader(new StringReader("")); parser.next(); parser.setReader(new StringReader("]>] ]]>")); parser.next(); assertEquals(XmlEvent.CDSECT, parser.next()); assertEquals(XmlEvent.ETAG, parser.next()); parser.setReader(new StringReader("")); parser.setEvents(XmlEvent.STAG | XmlEvent.ETAG | XmlEvent.TEXT | XmlEvent.COMMENT); assertEquals(XmlEvent.STAG, parser.next()); parser.next(); assertTrue(parser.isEvent(XmlEvent.COMMENT)); assertNull(parser.startTag()); parser.next(); assertTrue(parser.isEvent(XmlEvent.ETAG)); parser.setReader(new StringReader(" &")); parser.setSkipWS(false); parser.setSkipRepeatTextEvents(false); parser.next(); assertTrue(parser.startTag() != null); assertEquals(XmlEvent.CHARDATA, parser.next()); try { parser.getTagName(); fail("cannot copy from reference"); } catch (IllegalXmlParserStateException e) { } assertEquals(XmlEvent.REFERENCE, parser.next()); assertEquals(XmlEvent.CDSECT, parser.next()); StringWriter sw = new StringWriter(); parser.copyText(sw); assertEquals("k", sw.toString()); // assertEquals(XmlEvent.CHARDATA, parser.next()); parser.next(); assertEquals("a", parser.getTagName()); } public void testCanonicalText() throws Exception { XmlSParser xs = new XmlSParser(new XmlReader(), XmlEvent.CHARDATA); xs.setReadString("Fo'oFo'o"); xs.next(); String foo1 = xs.getCanonicalText(); xs.next(); String foo2 = xs.getCanonicalText(); assertTrue(foo1.equals("Fo'o")); assertTrue(foo1 == foo2); } public void testStringCtr() throws Exception { XmlSParser xs = new XmlSParser(); xs.setReadString("test"); xs.next(); assertEquals("test", xs.getText()); } public void testCanonicalText2() throws Exception { XmlReader xr = new XmlReader(); StringPool sp = xr.getStringPool(); XmlSParser xs = new XmlSParser(xr, XmlEvent.CHARDATA); xs.setReadString("Fo'oFo'o"); xs.next(); String foo1 = sp.intern(xs.getText()); xs.next(); String foo2 = sp.intern(xs.getText()); assertTrue(foo1.equals("Fo'o")); assertTrue(foo1 == foo2); } /* public void testTooManyETAG() throws Exception { Reader r = new StringReader(""); XmlSParser p = new XmlSParser(new XmlReader(r), XmlEvent.STAG | XmlEvent.ETAG); assertEquals("" + p, XmlEvent.STAG, p.next()); assertEquals("" + p, XmlEvent.ETAG, p.next()); try { p.next(); // EOD p.next(); // ETAG p.next(); // FAIL! fail("Should get too many end tags"); } catch (XmlException e) { } } */ } libexml-java-0.0.20080703.orig/e-xml/src/test/java/net/noderunner/exml/ObjectPoolTest.java0000644000175000017500000000506010762067376030730 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.exml; public class ObjectPoolTest extends junit.framework.TestCase { public ObjectPoolTest(String name) { super(name); } public void testBasic() { ObjectPool pool = new ObjectPool(StringBuffer.class, 16); for (int i = 0; i < 1024; i++) pool.checkOut(); System.out.println("pool " + pool); for (int i = 0; i < 1024; i++) pool.checkIn(); System.out.println("pool " + pool); StringBuffer sb; StringBuffer sb2; sb = (StringBuffer)pool.checkOut(); sb.append("haha"); pool.checkIn(); sb2 = (StringBuffer)pool.checkOut(); assertEquals("same haha", sb, sb2); } public abstract class Bogus { public Bogus() { } abstract void something(); } public void testExceptions() { try { new ObjectPool(StringBuffer.class, 0); fail("Must not create zero sized stack"); } catch (IllegalArgumentException e) { } try { new ObjectPool(Bogus.class, 0); fail("Must not create bogus class"); } catch (IllegalArgumentException e) { } try { new ObjectPool(null, 1); fail("Must not create null prototype"); } catch (IllegalArgumentException e) { } try { new ObjectPool(Integer.class, 1); fail("Must not create bogus prototype"); } catch (IllegalArgumentException e) { } try { ObjectPool pool = new ObjectPool(StringBuffer.class, 1); pool.checkIn(); fail("Must not checkIn() excessively"); } catch (IllegalStateException e) { } try { ObjectPool pool = new ObjectPool(StringBuffer.class, 1); pool.checkOut(); pool.checkIn(); pool.checkIn(); fail("Must not checkIn() excessively"); } catch (IllegalStateException e) { } } public void testIt() { ObjectPool pool = new ObjectPool(Object.class, 5); Object o1 = pool.checkOut(); assertSame(o1, pool.checkIn()); Object o2 = pool.checkOut(); assertSame(o2, pool.checkIn()); } } libexml-java-0.0.20080703.orig/e-xml/src/test/java/net/noderunner/exml/StringPoolTest.java0000644000175000017500000001354110762067376030773 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.exml; import java.util.Collection; import java.util.Iterator; public class StringPoolTest extends junit.framework.TestCase { static boolean runSoftTest = false; public static void main(String[] args) { if (args.length > 0) runSoftTest = true; junit.textui.TestRunner.run(StringPoolTest.class); } public StringPoolTest(String name) { super(name); } public void testCollection() { Collection c = new StringPool(); assertTrue("empty", c.isEmpty()); assertEquals("size 0", 0, c.size()); Collection c2 = new StringPool(); assertEquals("same", c, c2); Iterator i = c.iterator(); assertEquals("hasNext false", false, i.hasNext()); try { i.remove(); fail("UnsupportedOperationException expected"); } catch (UnsupportedOperationException e) { } } public void testCollection3() { StringPool sp = new StringPool(16); sp.intern("a"); sp.intern("b"); sp.intern("c"); Iterator i = sp.iterator(); while (i.hasNext()) { i.next(); } } public void testCollection2() { StringPool sp = new StringPool(16); String h = "hello"; String h2 = "hello2"; sp.intern(h); sp.intern(h2); assertTrue("contains h", sp.contains(h)); assertTrue("contains h2", sp.contains(h2)); StringPool sp2 = new StringPool(17); sp2.intern(h); sp2.intern(h2); assertTrue("containsAll 1", sp.containsAll(sp2)); assertTrue("containsAll 2", sp2.containsAll(sp)); assertEquals("same contents", sp, sp2); } public void testIntern() { StringPool sp = new StringPool(); String h1 = sp.intern("hello"); String h2 = sp.intern("hello"); assertTrue("internally same", h1 == h2); assertEquals("size 1", 1, sp.size()); } public void testHashCode() { String abc = "abcd1234!@#$"; int code = StringPool.hashCode(abc.toCharArray(), 0, abc.length()); int code2 = abc.hashCode(); assertEquals("hash codes the same", code, code2); } public void testRemove() { StringPool sp = new StringPool(16); String h = "hello"; String h2 = "hello2"; sp.add(h); sp.add(h2); sp.add(h); assertEquals("size 2", 2, sp.size()); assertTrue("contains h", sp.contains(h)); sp.remove(h); assertTrue("no contains h", !sp.contains(h)); sp.remove(h); assertTrue("no contains h", !sp.contains(h)); sp.remove(h2); assertTrue("no contains h2", !sp.contains(h2)); assertEquals("size empty", 0, sp.size()); } // This takes a long time to automatically run public void testSoftPool() { if (!runSoftTest) return; StringPool sp = new StringPool(16); StringBuffer sb = new StringBuffer(); for (int i = 0; i < 3000; i++) sb.append("abcdefghijklmnopqrstuvwxyz"); String s = sb.toString(); String special = "how special!"; sp.add(special); System.out.println("contents " + sp.size()); for (int i = 0; i < 1000; i++) { s = "" + sb + i % 5000; String iterned = sp.intern(s); String iterned2 = sp.intern(s.toCharArray(), 0, s.length()); assertTrue("string not null", iterned != null); assertTrue("itern equal", s == iterned); assertTrue("itern2 equal", s == iterned2); if (i % 1000 == 0) System.out.println("I is " + i / 1000 + " buckets " + sp.buckets()); } assertTrue("special here", sp.contains(special)); System.out.println("contents " + sp.size()); } public void testIntern2() { StringPool sp = new StringPool(); String h1 = sp.intern("hello"); char c[] = "hello".toCharArray(); String h2 = sp.intern(c, 0, c.length); assertTrue("internally same", h1 == h2); assertEquals("size 1", 1, sp.size()); // try some more char c2[] = " hello ".toCharArray(); String h3 = sp.intern(c2, 1, 5); assertEquals("size 1" + sp, 1, sp.size()); assertEquals("hello", h3); assertTrue("internally same" + sp, h1 == h3); } /* This is slow, so only run if recreate() has changed public void testRecreate() { String s = "message"; StringPool sp = new StringPool(4); int c = 100000; for (int j = 0; j < 10; j++) { for (int i = 0; i < c; i++) { sp.intern(s + i); Thread.yield(); } System.gc(); } System.out.println(sp.toString().length()); System.gc(); for (int i = 0; i < c; i++) { assertEquals(s + i, sp.intern(s + i)); } } */ public void testAddLots() { StringPool sp = new StringPool(4); for (int i = 0; i < 128; i++) { String s = "number " + i; String a = sp.intern(s); String b = sp.intern(s); assertTrue("intern equality", a == b); } assertEquals("size 128", 128, sp.size()); for (int i = 0; i < 128; i++) { String s = "number " + i; assertTrue("contains it " + sp, sp.contains(s)); } assertEquals("size 128", 128, sp.size()); Iterator i = sp.iterator(); assertEquals("hasNext true", true, i.hasNext()); } public void testIntern3() { String a = "a"; StringPool sp = new StringPool(4); String a2 = sp.intern(new char[] { 'a' }, 0, 1); assertTrue("object equals", a == a2); String a3 = sp.intern(new char[] { 'a' }, 0, 1); assertTrue("object equals", a2 == a3); String a0 = new StringBuffer().append('a').toString(); assertTrue("object equals", a == sp.intern(a0)); } } libexml-java-0.0.20080703.orig/e-xml/src/test/java/net/noderunner/exml/CommentTest.java0000644000175000017500000000233510762067376030274 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.exml; /** * This class is for unit testing the comment class. * * @see Comment * @author Elias Ross * @version 1.0 */ public class CommentTest extends junit.framework.TestCase { public CommentTest(String name) { super(name); } public static void main(String[] args) { junit.textui.TestRunner.run(CommentTest.class); } public void testInit() { Comment c = new Comment(); assertEquals("type is COMMENT_NODE", Node.COMMENT_NODE, c.getNodeType()); } } libexml-java-0.0.20080703.orig/e-xml/src/test/java/net/noderunner/exml/AttributeTest.java0000644000175000017500000000237010762067376030634 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.exml; /** * This class is for unit testing the Attribute class. * * @see Attribute * @author Elias Ross * @version 1.0 */ public class AttributeTest extends junit.framework.TestCase { public AttributeTest(String name) { super(name); } public static void main(String[] args) { junit.textui.TestRunner.run(CommentTest.class); } public void testInit() { Attribute a = new Attribute("name", "value"); assertEquals("name", a.getName()); assertEquals("value", a.getValue()); } } libexml-java-0.0.20080703.orig/e-xml/src/test/java/net/noderunner/exml/ArrayStackTest.java0000644000175000017500000001060111014421656030713 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.exml; import java.util.Collection; import java.util.Iterator; import java.util.NoSuchElementException; public class ArrayStackTest extends junit.framework.TestCase { public ArrayStackTest(String name) { super(name); } public static ArrayStack newStack(int size) { ArrayStack stack = new ArrayStack(1); for (int i = 0; i < size; i++) stack.add(new Integer(i)); return stack; } public void testBasic() { ArrayStack stack = new ArrayStack(1); Object o = new Object(); Object o2 = new Object(); assertEquals("is empty", true, stack.isEmpty()); stack.push(o); stack.push(o2); assertEquals("is empty", false, stack.isEmpty()); assertEquals("size", 2, stack.size()); assertEquals("same stuff", o2, stack.peek()); assertEquals("same stuff", o2, stack.pop()); assertEquals("same stuff", o, stack.peek()); assertEquals("same stuff", o, stack.pop()); stack.push(o); stack.clear(); assertEquals("is empty", true, stack.isEmpty()); stack.push(o); assertEquals("toString", "[" + o + "]", stack.toString()); } public void testShrink() { final int size = 1024; ArrayStack stack = newStack(size); stack.clear(); assertEquals("capacity shrunk again", 1, stack.capacity()); } public void testIterate() { final int size = 10; ArrayStack stack = newStack(size); Iterator iterator = stack.iterator(); // 9 8 7 6 5 4 3 2 1 0 for (int i = size - 1; i >= 0; i--) { Integer n = (Integer)iterator.next(); assertEquals("count " + i, i, n.intValue()); } // System.out.println(stack); } public void testCoverage() { new ArrayStack(); ArrayStack stack2 = new ArrayStack(4); for (int i = 0; i < 1000; i++) { stack2.add(""); stack2.add(""); stack2.pop(); } for (int i = 0; i < 1000; i++) stack2.pop(); } public void testRemove() { ArrayStack stack = new ArrayStack(); stack.add("a"); Iterator i = stack.iterator(); assertTrue(i.hasNext()); i.next(); i.remove(); assertTrue("at end", !i.hasNext()); } public void testExceptions() { try { new ArrayStack(-1); fail("Must not create negative sized stack"); } catch (IllegalArgumentException e) { } try { new ArrayStack(0); fail("Must not create zero sized stack"); } catch (IllegalArgumentException e) { } try { ArrayStack stack = new ArrayStack(1); stack.pop(); fail("Must not pop from empty stack"); } catch (NoSuchElementException e) { } try { ArrayStack stack = new ArrayStack(10); stack.peek(); fail("Must not peek from empty stack"); } catch (NoSuchElementException e) { } try { Collection stack = new ArrayStack(10); Iterator i = stack.iterator(); assertTrue("Iterator empty ", !i.hasNext()); assertTrue("Iterator empty 2", !i.hasNext()); i.next(); fail("Must not next() from empty iterator"); } catch (NoSuchElementException e) { } try { Collection stack = newStack(10); stack.add(""); Iterator i = stack.iterator(); i.remove(); fail("Must call next() before remove()"); } catch (UnsupportedOperationException e) { } try { Collection stack = newStack(10); stack.add(null); stack.add(null); Iterator i = stack.iterator(); i.next(); i.next(); i.remove(); fail("Must call remove() from non-top"); } catch (UnsupportedOperationException e) { } } /* public static junit.framework.TestSuite suite() { return new org.hansel.CoverageDecorator(ArrayStackTest.class, new Class[] { ArrayStack.class }); } */ public static void main(String[] args) { junit.textui.TestRunner.run(ArrayStackTest.class); } } libexml-java-0.0.20080703.orig/e-xml/src/test/java/net/noderunner/exml/XmlCharArrayWriterTest.java0000644000175000017500000000767110762067376032434 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.exml; import java.io.StringWriter; /** * This class is for unit testing the XmlCharArrayWriter class. * * @see XmlCharArrayWriter * @author Elias Ross * @version 1.0 */ public class XmlCharArrayWriterTest extends junit.framework.TestCase { public XmlCharArrayWriterTest(String name) { super(name); } /* public static junit.framework.TestSuite suite() { return new org.hansel.CoverageDecorator(XmlCharArrayWriterTest.class, new Class[] { XmlCharArrayWriter.class }); } */ public static void main(String[] args) { junit.textui.TestRunner.run(XmlCharArrayWriterTest.class); } public void testAppendString() throws Exception { XmlCharArrayWriter w = new XmlCharArrayWriter(10); XmlCharArrayWriter w2 = new XmlCharArrayWriter(10); StringBuffer sb = new StringBuffer(); String X = "all your base are belong to us."; char X2[] = X.toCharArray(); for (int i = 0; i < 10; i++) { w.write(X); sb.append(X); w2.write(X2); } assertEquals("Both the same", w.toString(), sb.toString()); assertEquals("Both the same2", w2.toString(), sb.toString()); } public void testAppendString2() throws Exception { XmlCharArrayWriter w = new XmlCharArrayWriter(); String X = "all your base are belong to us."; w.write(X, 4, 4); assertEquals("Both the same", "your", w.toString()); } public void testAppendString3() throws Exception { XmlCharArrayWriter w = new XmlCharArrayWriter(); String X = "all your base are belong to us."; w.write(X); w.write(X); assertEquals("Both the same", X + X, w.toString()); } public void testReset() throws Exception { XmlCharArrayWriter w = new XmlCharArrayWriter(); String X = "all your base are belong to us."; w.write(X); assertEquals("Something", X.length(), w.size()); w.reset(); assertEquals("Zero", 0, w.size()); } public void testMisc() throws Exception { XmlCharArrayWriter w = new XmlCharArrayWriter(0); w.write('a'); w.write("bc"); assertEquals('a', w.getBuffer()[0]); assertEquals('b', w.getBuffer()[1]); assertEquals('c', w.getBuffer()[2]); w.flush(); w.close(); w.write(new char[] { }, 0, 0); } public void testEmpty() throws Exception { XmlCharArrayWriter w = new XmlCharArrayWriter(); assertEquals(w.toString(), ""); } public void testEscape() throws Exception { XmlCharArrayWriter w = new XmlCharArrayWriter(); StringBuffer sb = new StringBuffer(); StringWriter sw = new StringWriter(); w.write('<'); w.write('>'); w.write('\"'); w.write('\''); w.write('&'); w.write('a'); w.writeEscapedTo(sb); w.writeEscapedTo(sw); String esc = "<>"'&a"; assertEquals("Both the same", sb.toString(), sw.toString()); assertEquals("Escaped", esc, sb.toString()); sw = new StringWriter(); w.writeTo(sw); assertEquals("Write to the same", w.toString(), sw.toString()); } public void testException() throws Exception { try { new XmlCharArrayWriter(-1); fail("negative size"); } catch (IllegalArgumentException e) { } XmlCharArrayWriter w = new XmlCharArrayWriter(); char s[] = "your".toCharArray(); try { w.write(s, -1, 1); fail("negative size"); } catch (java.lang.ArrayIndexOutOfBoundsException e) { } } } libexml-java-0.0.20080703.orig/e-xml/src/test/java/net/noderunner/exml/ElementToSAXTest.java0000644000175000017500000000517710762067376031151 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.exml; import java.util.ArrayList; import org.xml.sax.Attributes; import org.xml.sax.helpers.DefaultHandler; /** * This class is for unit testing the ElementToSAX class. * * @see ElementToSAX * @author Elias Ross * @version 1.0 */ public class ElementToSAXTest extends junit.framework.TestCase { public ElementToSAXTest(String name) { super(name); } public static void main(String[] args) { junit.textui.TestRunner.run(ElementToSAXTest.class); } public void testInit() { } class TestHandler extends DefaultHandler { StringBuffer sb = new StringBuffer(); public void startElement(String uri, String localName, String qName, Attributes a) { sb.append('<').append(localName).append(a).append('>'); } public void endElement(String uri, String localName, String qName) { sb.append(""); } public void characters(char cbuf[], int off, int len) { sb.append(cbuf, off, len); } public String toString() { return sb.toString(); } } public void testEasy() throws Exception { Element a = new Element("a"); TestHandler handler = new TestHandler(); ElementToSAX.pipe(a, handler); assertEquals("handler data and element", a.toString(), handler.toString()); } public void testHarder() throws Exception { ArrayList al = new ArrayList(); al.add(new Attribute("name", "value")); al.add(new Attribute("name2", "value2")); Element a = new Element("a", al, true); Element b = new Element("b"); CharacterData data = new CharacterData(); data.getWriter().write("hello"); a.appendChild(b); a.appendChild(data); a.appendChild(b); b.appendChild(data); TestHandler handler = new TestHandler(); ElementToSAX.pipe(a, handler); // Note: XmlWriter uses \n at the end of lines, but // if this changes, change TestHandler code too assertEquals("handler data and element", a.toString(), handler.toString()); } } libexml-java-0.0.20080703.orig/e-xml/src/test/java/net/noderunner/exml/PITest.java0000644000175000017500000000237310762067376027204 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.exml; /** * This class is for unit testing the PI class. * * @see PI * @author Elias Ross * @version 1.0 */ public class PITest extends junit.framework.TestCase { public PITest(String name) { super(name); } public static void main(String[] args) { junit.textui.TestRunner.run(PITest.class); } public void testInit() { String name = "name"; PI pi = new PI(name); assertEquals("type is PI_NODE", Node.PI_NODE, pi.getNodeType()); assertEquals("name ", name, pi.getName()); } } libexml-java-0.0.20080703.orig/e-xml/src/test/java/net/noderunner/exml/XmlScannerTest.java0000644000175000017500000004545510762067376030756 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.exml; import java.io.IOException; import java.io.Reader; import java.io.StringReader; import java.io.StringWriter; /** * This class is for unit testing the XmlScanner class. * * @author Elias Ross * @version 1.0 */ public class XmlScannerTest extends junit.framework.TestCase { public XmlScannerTest(String name) { super(name); } /* public static junit.framework.TestSuite suite() { return new org.hansel.CoverageDecorator(XmlScannerTest.class, new Class[] { XmlScanner.class }); } */ public static void main(String[] args) { junit.textui.TestRunner.run(XmlScannerTest.class); } public void testEOFCondition() throws Exception { final int size = 128; char buf2[] = new char[size]; StringReader sr; XmlScanner pr; String s = "abcdefghi"; sr = new StringReader(s); pr = new XmlScanner(sr, size); assertEquals("First read", s.length(), pr.read(buf2, 0, size)); pr.unread(buf2, 0, s.length()); // we should be at EOF assertEquals("Second read", s.length(), pr.read(buf2, 0, size)); } public void testReadAvailable() throws Exception { final int size = 128; char buf2[] = new char[size]; StringReader sr; XmlScanner pr; String s = "abcdefghi"; sr = new StringReader(s); pr = new XmlScanner(sr, size); assertEquals(pr.read(buf2, 0, size), s.length()); // assertEquals(0, pr.available); pr.unread(buf2, 0, 2); assertEquals(2, pr.read(buf2, 0, size)); // assertEquals(0, pr.available); assertEquals('a', buf2[0]); assertEquals('b', buf2[1]); } public void testUnread() throws Exception { final int size = 7; char buf2[] = new char[size]; int got; StringReader sr; XmlScanner pr; String s = "ABCDEF"; sr = new StringReader(s); pr = new XmlScanner(sr, size, 0); got = pr.read(buf2, 0, s.length() - 2); assertEquals(s.length() - 2, got); pr.unread(buf2, 0, s.length() - 2); got = pr.read(buf2, 0, s.length()); assertEquals(s.length(), got); String s2 = new String(buf2, 0, s.length()); assertEquals(s, s2); pr.unread(0); try { pr.unread(-1); fail("shouldn't unread -1"); } catch (IllegalArgumentException e) { } } public void testFour() throws Exception { final int size = 10; char buf2[] = new char[size]; int got; StringReader sr; XmlScanner pr; sr = new StringReader("eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"); pr = new XmlScanner(sr, size, 5); pr.unread('a'); pr.unread('b'); pr.unread('c'); pr.unread('d'); assertEquals("D", 'd', pr.read()); assertEquals("C", 'c', pr.read()); assertEquals("B", 'b', pr.read()); assertEquals("A", 'a', pr.read()); pr.unread('a'); pr.unread('b'); pr.read(); pr.read(); pr.read(); pr = new XmlScanner(sr, size, 5); for (int i = 0; i < 10; i++) { pr.unread(new char[] {'a', 'b', 'c', 'd'}, 0, 4); assertEquals("PEEKED ONE", 'a', pr.peek()); got = pr.peek(buf2, 0, 5); assertEquals("GOT PEEK", 5, got); assertEquals("PEEKED A", 'a', buf2[0]); assertEquals("PEEKED B", 'b', buf2[1]); assertEquals("PEEKED E", 'e', buf2[4]); // System.out.println(" " + i + " " + pr); got = pr.read(buf2, 0, 3); assertEquals("A2 " + pr, 'a', buf2[0]); assertEquals("B2", 'b', buf2[1]); assertEquals("C2", 'c', buf2[2]); assertEquals("D2", 'd', pr.read()); assertEquals("E2", 'e', pr.read()); // System.out.println(" " + i + " " + pr); assertEquals("E3", 'e', pr.read()); // System.out.println(" " + i + " " + pr); } } public void testUnreadEasy() throws Exception { final int size = 128; char buf2[] = new char[size]; int got; StringReader sr; XmlScanner pr; String s = "abcdefghijkl"; sr = new StringReader(s); pr = new XmlScanner(sr, size); got = pr.read(buf2, 0, size); assertEquals(s.length(), got); // assertEquals(0, pr.available); got = pr.read(buf2, 0, size); assertEquals("Should get EOF", -1, got); sr = new StringReader(s); pr = new XmlScanner(sr, size); got = pr.read(buf2, 0, 4); pr.unread(buf2, 0, 3); pr.read(); got = pr.read(); // assertEquals(1, pr.available); pr.unread(got); // assertEquals(2, pr.available); } public void testCopyUntil() throws Exception { String abc = "abcdefgh"; String s = abc + "#" + abc + "@" + abc + "#"; StringReader sr = new StringReader(s); XmlScanner pr = new XmlScanner(sr, 4, 2); StringWriter sw; sw = new StringWriter(); int c = pr.copyUntil(sw, '#', '?'); assertTrue("ABC 1", sw.toString().equals(abc)); assertEquals("ABC 1L", c, '#'); assertEquals("ABC 1", '#', pr.read()); sw = new StringWriter(); pr.copyUntil(sw, '?', '@'); assertTrue("ABC 2 " + sw, sw.toString().equals(abc)); assertEquals("ABC 2", '@', pr.read()); sw = new StringWriter(); pr.copyUntil(sw, '#', '#'); assertTrue("ABC 3", sw.toString().equals(abc)); assertEquals("ABC 3", '#', pr.read()); assertEquals("ABC 3", -1, pr.read()); } public void testCopyUntil2() throws Exception { StringWriter sw; int c; String abc = "abcdefgh"; String s = abc + "#" + abc + "@" + abc + "#"; StringReader sr = new StringReader(s); XmlScanner pr = new XmlScanner(sr, 4, 2); sw = new StringWriter(); c = pr.copyUntil(sw, '#'); assertEquals('#', c); assertTrue("ABC 1", sw.toString().equals(abc)); pr.read(); sw = new StringWriter(); c = pr.copyUntil(sw, '@'); assertEquals('@', c); assertEquals("ABC 1", abc, sw.toString()); } public void testUnreadLots() throws Exception { StringReader sr = new StringReader(""); XmlScanner pr = new XmlScanner(sr, 1); pr.unread('a'); try { pr.unread('b'); fail("Can't unread another"); } catch (IOException e) { } char buf[] = new char[64]; assertEquals("A", 'a', pr.read()); try { pr.unread(buf, 32, 2); fail("Can't unread 2"); } catch (IOException e) { } } public void testSkipUntil() throws Exception { String abc = "abcdefgh"; String s = abc + "#" + abc + "@" + abc + "#"; StringReader sr = new StringReader(s); XmlScanner pr = new XmlScanner(sr, 4, 2); int c = pr.skipUntil('#', '?'); assertEquals("ABC 1L", c, '#'); assertEquals("ABC 1", '#', pr.read()); pr.skipUntil('?', '@'); assertEquals("ABC 2", '@', pr.read()); pr.skipUntil('#'); assertEquals("ABC 3", '#', pr.read()); assertEquals("ABC 3", -1, pr.read()); try { pr.skipUntil('%'); fail("Expected EOF"); } catch (XmlException e) { } } public void testSkip() throws Exception { String abc = "abcdefgh"; String s = abc + "#" + abc + "@" + abc + "#"; StringReader sr = new StringReader(s); XmlScanner pr = new XmlScanner(sr, 4, 2); pr.skip(abc.length()); assertEquals("ABC 1", '#', pr.read()); pr.skip(abc.length()); assertEquals("ABC 2", '@', pr.read()); pr.skip(abc.length()); assertEquals("ABC 3", '#', pr.read()); assertEquals("ABC 3", -1, pr.read()); pr.skip(10); } public void testPeekMisc() throws Exception { XmlScanner pr; pr = new XmlScanner("<"); assertEquals("EOD", XmlEvent.EOD, pr.peekEvent()); pr = new XmlScanner(""); assertEquals("EOD", XmlEvent.EOD, pr.peekEvent()); } public void testPeek() throws Exception { String doc = "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "\n" + "stuff\n" + "\n" + "&'"<>\n" + "\n" + "<##>\n"; StringReader sr = new StringReader(doc); XmlScanner pr = new XmlScanner(sr, 16); assertEquals("Xml_DECL", XmlEvent.PI, pr.peekEvent()); pr.skipUntil('\n'); pr.read(); assertEquals("DOCTYPE_DECL", XmlEvent.DOCTYPE_DECL, pr.peekEvent()); pr.skipUntil('\n'); pr.read(); assertEquals("STAG", XmlEvent.STAG, pr.peekEvent()); pr.skipUntil('\n'); pr.read(); assertEquals("COMMENT", XmlEvent.COMMENT, pr.peekEvent()); pr.skipUntil('\n'); pr.read(); assertEquals("PI", XmlEvent.PI, pr.peekEvent()); pr.skipUntil('\n'); pr.read(); assertEquals("CDSECT", XmlEvent.CDSECT, pr.peekEvent()); pr.skipUntil('\n'); pr.read(); assertEquals("ENTITY_DECL", XmlEvent.ENTITY_DECL, pr.peekEvent()); pr.skipUntil('\n'); pr.read(); assertEquals("ELEMENT_DECL", XmlEvent.ELEMENT_DECL, pr.peekEvent()); pr.skipUntil('\n'); pr.read(); assertEquals("ATTLIST_DECL", XmlEvent.ATTLIST_DECL, pr.peekEvent()); pr.skipUntil('\n'); pr.read(); assertEquals("CONDITIONAL_SECT", XmlEvent.CONDITIONAL_SECT, pr.peekEvent()); pr.skipUntil('\n'); pr.read(); assertEquals("CONDITIONAL_SECT", XmlEvent.CONDITIONAL_SECT, pr.peekEvent()); pr.skipUntil('\n'); pr.read(); assertEquals("CHARDATA", XmlEvent.CHARDATA, pr.peekEvent()); pr.skipUntil('\n'); pr.read(); assertEquals("NOTATATION_DECL", XmlEvent.NOTATATION_DECL, pr.peekEvent()); pr.skipUntil('\n'); pr.read(); assertEquals("REFERENCE", XmlEvent.REFERENCE, pr.peekEvent()); pr.skipUntil('\n'); pr.read(); assertEquals("ETAG", XmlEvent.ETAG, pr.peekEvent()); pr.skipUntil('\n'); pr.read(); assertEquals("NONE", XmlEvent.NONE, pr.peekEvent()); pr.skipUntil('\n'); pr.read(); } public void testNoTranslateFakeReference() throws Exception { XmlScanner pr = new XmlScanner(""); pr.setReadString("≪"); assertTrue(!pr.translateReference()); pr.setReadString("≫"); assertTrue(!pr.translateReference()); pr.setReadString("&apot;"); assertTrue(!pr.translateReference()); pr.setReadString("&quoo;"); assertTrue(!pr.translateReference()); pr.setReadString("&amm;"); assertTrue(!pr.translateReference()); pr.setReadString("&nbst;"); assertTrue(!pr.translateReference()); } public void testTranslateReference() throws Exception { StringReader sr = new StringReader("<>'"& &;"); // testTranslateReference(new SlowReader(sr)); XmlScanner pr = new XmlScanner(sr, 16, 6); assertTrue("lt", pr.translateReference()); assertEquals(pr.read(), '<'); assertTrue("gt", pr.translateReference()); assertEquals(pr.read(), '>'); assertTrue("gt", pr.translateReference()); assertEquals(pr.read(), '\''); assertTrue("quot", pr.translateReference()); assertEquals(pr.read(), '"'); assertTrue("amp", pr.translateReference()); assertEquals(pr.read(), '&'); assertTrue("nbsp", !pr.translateReference()); pr.skip(6); try { pr.translateReference(); fail("Not enough data in reference"); } catch (XmlException e) { } } public void testReadString() throws Exception { XmlScanner pr = new XmlScanner(""); pr.setReadString("abcde"); assertEquals(pr.read(), 'a'); assertEquals(pr.read(), 'b'); pr.close(); pr.setReadString("fghij"); assertEquals(pr.read(), 'f'); assertEquals(pr.read(), 'g'); } public void testReadNS() throws Exception { XmlScanner pr = new XmlScanner("x a:b x c:d"); NamespaceImpl ns = new NamespaceImpl(); assertEquals(null, ns.getNamespaceURI()); assertEquals(null, ns.getPrefix()); assertEquals(null, ns.getLocalName()); assertEquals(null, ns.getName()); pr.readNamespace(ns); assertEquals(null, ns.getNamespaceURI()); assertEquals(null, ns.getPrefix()); assertEquals(null, ns.getLocalName()); assertEquals("x", ns.getName()); pr.read(); pr.readNamespace(ns); assertEquals(null, ns.getNamespaceURI()); assertEquals("a", ns.getPrefix()); assertEquals("b", ns.getLocalName()); assertEquals("a:b", ns.getName()); pr.read(); pr.readNamespace(ns); assertEquals(null, ns.getNamespaceURI()); assertEquals(null, ns.getPrefix()); assertEquals(null, ns.getLocalName()); assertEquals("x", ns.getName()); pr.read(); pr.readNamespace(ns); assertEquals(null, ns.getNamespaceURI()); assertEquals("c", ns.getPrefix()); assertEquals("d", ns.getLocalName()); assertEquals("c:d", ns.getName()); pr.readNamespace(ns); // EOF shouldn't matter assertEquals(null, ns.getNamespaceURI()); assertEquals(null, ns.getPrefix()); assertEquals(null, ns.getLocalName()); assertEquals(null, ns.getName()); } public void testReadNS2() throws Exception { XmlScanner pr; NamespaceImpl ns; pr = new XmlScanner("a:"); ns = new NamespaceImpl(); try { pr.readNamespace(ns); fail("bad namespace"); } catch (XmlException e) { } pr = new XmlScanner(":b"); ns = new NamespaceImpl(); try { pr.readNamespace(ns); fail("bad namespace"); } catch (XmlException e) { } pr = new XmlScanner(":"); try { pr.readNamespace(ns); fail("bad namespace"); } catch (XmlException e) { } pr = new XmlScanner(""); pr.readNamespace(ns); assertEquals(null, ns.getNamespaceURI()); assertEquals(null, ns.getPrefix()); assertEquals(null, ns.getLocalName()); assertEquals(null, ns.getName()); } public void testCanUnread() throws Exception { XmlScanner pr; pr = new XmlScanner("abc"); pr.read(); pr.read(); pr.read(); assertEquals(3, pr.canUnread()); pr.unread("xyz"); assertEquals('x', pr.read()); } public void testCharRef() throws Exception { XmlScanner pr; pr = new XmlScanner(" "); assertTrue(pr.charRef()); assertEquals('\r', pr.read()); pr = new XmlScanner(" "); assertTrue(pr.charRef()); assertEquals('\r', pr.read()); pr = new XmlScanner(""); try { pr.charRef(); fail("EOF"); } catch (XmlException e) { } pr = new XmlScanner(""); try { pr.charRef(); fail("EOF in ref"); } catch (XmlException e) { } pr = new XmlScanner("xyz"); assertTrue("not here", !pr.charRef()); pr = new XmlScanner("&xyz;"); assertTrue("not here", !pr.charRef()); pr = new XmlScanner("�"); try { pr.charRef(); fail("bad char"); } catch (XmlException e) { } } public void testSetReader() throws Exception { XmlScanner pr; pr = new XmlScanner("abc"); assertEquals('a', pr.read()); pr.setReader(new StringReader("xyz")); assertEquals('x', pr.read()); } public void testPeekEOF() throws Exception { XmlScanner pr; pr = new XmlScanner(""); int c = pr.peek(new char[10], 0, 10); assertEquals(-1, c); } public void testCopyUntilEOF() throws Exception { XmlScanner pr; pr = new XmlScanner(""); StringWriter sw = new StringWriter(); pr.copyUntil(sw, 'a', 'b'); assertEquals(0, sw.toString().length()); } public void testGetLongness() throws Exception { XmlScanner pr; StringBuffer sb = new StringBuffer(1024); for (int i = 0; i < 2048; i++) sb.append('a'); pr = new XmlScanner(new StringReader(sb.toString()), 16); try { pr.getName(); fail("long name"); } catch (XmlException e) { } pr = new XmlScanner(new StringReader("&#x" + sb + ";"), 16); try { pr.charRef(); fail("long charRef name"); } catch (XmlException e) { } } public void testGetNameSlow() throws Exception { XmlScanner pr; String a = "abcde"; pr = new XmlScanner(new StringReader(a + "||"), 2, 0); pr.getStringPool().add(a); String name = pr.getName(); assertEquals(a, name); assertTrue("object eq", a == name); } public void testGetNameSP() throws Exception { XmlScanner pr; pr = new XmlScanner("123"); assertNull(pr.getName()); pr = new XmlScanner("A:A "); assertEquals("equal", "A:A", pr.getName()); String A = "A"; StringPool sp = new StringPool(); sp.add(A); pr = new XmlScanner("A"); pr.setStringPool(sp); assertEquals(sp, pr.getStringPool()); String name = pr.getName(); assertEquals("equal", A, name); assertTrue("object equal", A == name); } public void testUriMap() throws Exception { XmlScanner pr = new XmlScanner("a:b c:d e"); NamespaceImpl ns = new NamespaceImpl(); assertTrue("not null", null != pr.getUriMap()); UriMap uriMap = new UriMap(); pr.setUriMap(uriMap); assertEquals(uriMap, pr.getUriMap()); String URI_1 = "http://example.net/a"; String URI_2 = "http://example.net/c"; uriMap.put("a", URI_1); uriMap.put("c", URI_2); pr.readNamespace(ns); assertEquals(URI_1, ns.getNamespaceURI()); assertEquals("a", ns.getPrefix()); assertEquals("b", ns.getLocalName()); assertEquals("a:b", ns.getName()); ns.toString(); // test .. pr.read(); pr.readNamespace(ns); assertEquals(URI_2, ns.getNamespaceURI()); assertEquals("c", ns.getPrefix()); assertEquals("d", ns.getLocalName()); assertEquals("c:d", ns.getName()); ns.toString(); // test .. pr.read(); pr.readNamespace(ns); assertEquals(null, ns.getNamespaceURI()); assertEquals(null, ns.getPrefix()); assertEquals(null, ns.getLocalName()); assertEquals("e", ns.getName()); } private class SlowReader extends Reader { Reader r; public SlowReader(Reader r) { this.r = r; } public int read(char[] cbuf, int off, int len) throws IOException { return r.read(cbuf, off, 1); } public void close() throws IOException { r.close(); } } public void testCanonicalCharData() throws Exception { XmlScanner pr; pr = new XmlScanner("<"); assertEquals("", pr.getCanonicalText()); pr = new XmlScanner("&fudge;"); assertEquals("", pr.getCanonicalText()); pr = new XmlScanner("&"); assertEquals("&", pr.getCanonicalText()); pr = new XmlScanner("&amp;"); assertEquals("&", pr.getCanonicalText()); pr = new XmlScanner("<"); assertEquals("<", pr.getCanonicalText()); pr = new XmlScanner("&fudge;"); assertEquals("", pr.getCanonicalText()); pr = new XmlScanner("apple"); assertEquals("apple", pr.getCanonicalText()); pr = new XmlScanner("applely"); assertTrue("apple" == pr.getCanonicalText()); pr.setReadString("&apple"); pr.read(); pr.setReadString("banana"); String B = pr.getCanonicalText(); pr.setReadString("banana&fud;ge"); assertTrue(B == pr.getCanonicalText()); pr.setReader(new SlowReader(new StringReader("banana"))); assertTrue(B == pr.getCanonicalText()); pr.setReader(new SlowReader(new StringReader("banana<"))); assertTrue(B == pr.getCanonicalText()); } } libexml-java-0.0.20080703.orig/e-xml/src/test/java/net/noderunner/exml/DtdTest.java0000644000175000017500000000237010762067376027404 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.exml; /** * This class is for unit testing the Dtd class. * * @see Dtd * @author Elias Ross * @version 1.0 */ public class DtdTest extends junit.framework.TestCase { public DtdTest(String name) { super(name); } public static void main(String[] args) { junit.textui.TestRunner.run(DtdTest.class); } public void testBasic() { ElementRule r = new ElementRule(); Dtd dtd = new Dtd(); dtd.addElementRule("foo", r); assertEquals("same rule", r, dtd.getElementRule("foo")); } } libexml-java-0.0.20080703.orig/e-xml/src/test/java/net/noderunner/exml/XmlPerfTest.java0000644000175000017500000001772010762067376030253 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.exml; import java.io.StringWriter; /** * This class is for performance testing. * * @author Elias Ross * @version 1.0 */ public class XmlPerfTest extends junit.framework.TestCase { public XmlPerfTest(String name) { super(name); } static boolean sax = false; static boolean dom = false; static boolean minml = false; static int times = 4; public static void main(String[] args) { for (int i = 0; i < args.length; i++) { if (args[i].equals("sax")) sax = true; if (args[i].equals("dom")) dom = true; if (args[i].equals("minml")) minml = true; if (args[i].equals("times")) times = Integer.parseInt(args[i+1]); } junit.textui.TestRunner.run(XmlPerfTest.class); } static StringWriter sw; static XmlCharArrayWriter xcaw; static XmlWriter xw; static XmlReader xr; static XmlParser xp; static XmlSParser xsp; long start; long total; void start() { start = System.currentTimeMillis(); } void stop(String s) { long took = System.currentTimeMillis() - start; System.out.println(s + " took: " + took); total += took; } void average(String s) { System.out.println(s + " average: " + total / times); total = 0; } /** * Create a new XmlWriter around a StringWriter for testing. */ static void newWriter() { // sw = new StringWriter(); xcaw = new XmlCharArrayWriter(); xw = new XmlWriter(xcaw); // xw = new XmlWriter(new BufferedWriter(sw)); } static void newParser() throws java.io.IOException { newReader(); Dtd dtd = xr.getDtd(); ElementRule rule = new ElementRule(); dtd.addElementRule("element", rule); ElementRule rule2 = new ElementRule(); rule2.setAllowPCData(true); dtd.addElementRule("stuff", rule2); xp = new XmlParser(xr); } static void newSParser() throws java.io.IOException { newReader(); xsp = new XmlSParser(xr); } static void newReader() throws java.io.IOException { xr = new XmlReader(); xr.setReadString(xcaw.toString()); } /* public void testReaderPerformance() throws Exception { newWriter(); xw.startElement("document"); Element se = new Element("stuff"); se.appendAttribute(new Attribute("name", "value")); se.appendAttribute(new Attribute("name2", "value2")); for (int i = 0; i < 2048; i++) { xw.startElement(se); for (int j = 0; j < 64; j++) { xw.startElement("stuff" + j); xw.endElement(); } xw.endElement(); } xw.up(0); xw.close(); for (int i = 0; i < times; i++) { start(); newReader(); Document d = xr.document(); Element e = d.getRootElement(); //ElementToSAX.pipe(e, new DefaultHandler()); stop("net.noderunner.exml.XmlReader.document"); } average("net.noderunner.exml.XmlReader.document"); if (sax) { SAXParser parser = new SAXParser(); ContentHandler handler = new DefaultHandler(); for (int i = 0; i < times; i++) { start(); parser.setContentHandler(handler); parser.parse(new InputSource(new StringReader(sw.getBuffer().toString()))); stop("apache.xerces.parsers.SAXParser"); } average("apache.xerces.parsers.SAXParser"); } if (dom) { DOMParser dparser = new DOMParser(); for (int i = 0; i < times; i++) { start(); dparser.parse(new InputSource(new StringReader(sw.getBuffer().toString()))); stop("apache.xerces.parsers.DOMParser"); } average("apache.xerces.parsers.DOMParser"); } if (minml) { uk.co.wilson.xml.MinML parser = new uk.co.wilson.xml.MinML(4092, 1024); for (int i = 0; i < times; i++) { start(); parser.parse(new StringReader(sw.getBuffer().toString())); stop("uk.co.wilson.xml.MinML"); } average("uk.co.wilson.xml.MinML"); } } */ public void testCanonicalPerformance() throws Exception { start(); newWriter(); String FISH = "fish heads fish heads"; for (int j = 0; j < 2048 * 40; j++) { xw.startElement("element"); xw.startElement("stuff"); xw.writeCData(FISH); xw.endElement(); } xw.up(0); xw.close(); stop("newWriter"); for (int i = 0; i < times; i++) { newSParser(); xsp.setEvents(XmlEvent.EOD | XmlEvent.CHARDATA); start(); while (xsp.hasNext()) { xsp.next(); if (xsp.isEvent(XmlEvent.CHARDATA)){ assertEquals(FISH, xsp.getText()); } } xsp.up(0); stop("testSParserPerformance"); } average("net.noderunner.exml.SParser"); System.out.println("-------------"); for (int i = 0; i < times; i++) { newSParser(); xr.getStringPool().add(FISH); xsp.setEvents(XmlEvent.EOD | XmlEvent.CHARDATA); start(); while (xsp.hasNext()) { xsp.next(); if (xsp.isEvent(XmlEvent.CHARDATA)){ //String s = xsp.getCanonicalText(); //assertTrue(s, FISH == s); assertEquals(FISH, xsp.getCanonicalText()); } } xsp.up(0); stop("testSParserPerformance"); } average("net.noderunner.exml.SParser"); System.out.println("-------------"); /* */ } /* public void testParserPerformance() throws Exception { start(); for (int i = 0; i < times; i++) { newWriter(); for (int j = 0; j < 2048 * 1; j++) { xw.startElement("element"); xw.startElement("stuff"); xw.writeCData("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"); xw.writeCData("xxxxxxxxx&xxxxxxxx&xxxxxxxx&xxxxxxxxxxx&xxxxxxxxxxx'xxxxxxxxxxxxx\"xxxxxxxxxxxxxx"); xw.writeCDSection("xxxxxxxxx&xxxxxxxx&xxxxxxxx&xxxxxxxxxxx&xxxxxxxxxxx'xxxxxxxxxxxxx\"xxxxxxxxxxxxxx"); xw.write(""); xw.endElement(); xw.startElement("stuff"); xw.writeCData("yyyyyyyyy&yyyyyyyy&yyyyyyyy&yyyyyyyyyyy&yyyyyyyyyyy'yyyyyyyyyyyyy\"yyyyyyyyyyyyyy"); xw.writeCData("yyyyyyyyyzzzzzzzzz"); xw.endElement(); } xw.up(0); xw.close(); stop("newWriter"); } average("net.noderunner.exml.XmlWriter"); final char stuff[] = "stuff".toCharArray(); for (int i = 0; i < times; i++) { newSParser(); start(); while (xsp.hasNext()) { xsp.next(); //if (xsp.matches(stuff)) { //} } xsp.up(0); stop("testSParserPerformance"); } average("net.noderunner.exml.SParser"); DefaultHandler handler = new DefaultHandler(); if (minml) { for (int i = 0; i < times; i++) { start(); //parser.setContentHandler(handler); //parser.parse(new InputSource(new StringReader(sw.getBuffer().toString()))); uk.co.wilson.xml.MinML parser = new uk.co.wilson.xml.MinML(4092, 1024); parser.parse(new StringReader(sw.getBuffer().toString())); stop("uk.co.wilson.xml.MinML"); } average("uk.co.wilson.xml.MinML"); } if (sax) { SAXParserFactory pf = SAXParserFactory.newInstance(); SAXParser parser = pf.newSAXParser(); char c[] = xcaw.toString().toCharArray(); for (int i = 0; i < times; i++) { start(); CharArrayReader car = new CharArrayReader(c); parser.parse(new InputSource(car), handler); stop("apache.xerces.parsers.SAXParser"); } average("apache.xerces.parsers.SAXParser"); } /* if (dom) { DOMParser parser = new DOMParser(); for (int i = 0; i < times; i++) { start(); parser.parse(new InputSource(new StringReader(sw.getBuffer().toString()))); stop("apache.xerces.parsers.DOMParser"); } average("apache.xerces.parsers.DOMParser"); } */ //} } libexml-java-0.0.20080703.orig/e-xml/src/test/java/net/noderunner/exml/XmlParserTest.java0000644000175000017500000001677210762067376030621 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.exml; import java.io.BufferedWriter; import java.io.Reader; import java.io.StringReader; import java.io.StringWriter; /** * This class is for unit testing the XmlParser class. * * @see XmlParser * @author Elias Ross * @version 1.0 */ public class XmlParserTest extends junit.framework.TestCase { public XmlParserTest(String name) { super(name); } public void testNoContent() throws Exception { XmlReader reader; XmlParser parser; reader = new XmlReader(new StringReader("")); parser = new XmlParser(reader); // no content here try { parser.getContent(); fail("Should get no content " + parser); } catch (XmlException e) { } // no endTag here try { parser.startTag(); parser.getContent(); fail("Should get EOF Exception " + parser); } catch (XmlException e) { } } // tests various rules public void testElementRules() throws Exception { XmlWriter writer; StringWriter sw = new StringWriter(); writer = new XmlWriter(new BufferedWriter(sw)); Element root = new Element("test"); Element a = new Element("a"); writer.startElement(root); writer.startElement(a); writer.writeCData(D_CONTENT); writer.endElement(); writer.endElement(); writer.flush(); String in = sw.getBuffer().toString(); XmlReader reader; XmlParser parser; ElementRule rule; // test unknown element rule reader = new XmlReader(new StringReader(in)); rule = new ElementRule(); reader.getDtd().addElementRule(root, rule); parser = new XmlParser(reader); try { parser.startTag(); parser.startTag(); fail("Should raise XmlException " + parser); } catch (XmlException xre) { } // test no pcdata rule reader = new XmlReader(new StringReader(in)); parser = new XmlParser(reader); rule = new ElementRule(); rule.setAllowPCData(false); reader.getDtd().addElementRule(root, rule); reader.getDtd().addElementRule(a, rule); try { parser.startTag(); parser.startTag(); parser.getContent(); fail("Should raise ElementRuleException " + parser); } catch (XmlException xre) { } // test not allowed rule reader = new XmlReader(new StringReader(in)); parser = new XmlParser(reader); rule = new ElementRule(); rule.allowNoElements(); rule.allowElement("b"); reader.getDtd().addElementRule(root, rule); reader.getDtd().addElementRule(a, rule); try { parser.startTag(); parser.startTag(); parser.endTag(); fail("Should raise ElementRuleException"); } catch (ElementRuleException xre) { } } public static final String D_CONTENT = "D's content here"; /** * Create a new parser for testing. Also checks that XmlWriter is * creating valid Xml. */ public static XmlParser newParser() throws Exception { XmlWriter writer; StringWriter sw = new StringWriter(); writer = new XmlWriter(new BufferedWriter(sw)); writer.writeHeader("UTF-8"); Element root = new Element("test"); Element a = new Element("a"); Element b = new Element("b"); Element b2 = new Element("b2"); Element c = new Element("c"); Element d = new Element("d"); writer.startElement(root); writer.startElement(a); writer.startElement(b); writer.emptyElement("c"); writer.startElement(d); writer.writeCData(D_CONTENT); writer.endElement(); writer.endElement(); writer.startElement(b2); writer.endElement(); writer.endElement(); writer.endElement(); writer.flush(); String in = sw.getBuffer().toString(); //System.out.println(in); ElementRule rule; rule = new ElementRule(); Dtd dtd = new Dtd(); dtd.addElementRule(root, rule); dtd.addElementRule(a, rule); dtd.addElementRule(b, rule); dtd.addElementRule(b2, rule); dtd.addElementRule(c, rule); rule = new ElementRule(); rule.setAllowPCData(true); dtd.addElementRule(d, rule); XmlReader reader = new XmlReader(new StringReader(in), dtd); return new XmlParser(reader); } public void testBasicDoc() throws Exception { Dtd dtd = new Dtd(); ElementRule rule = new ElementRule(); dtd.addElementRule("root", rule); String in = " "; XmlReader reader = new XmlReader(new StringReader(in), dtd); XmlParser parser = new XmlParser(reader); // do stuff parser.skipProlog(); assertEquals("root", parser.startTag().getName()); Element e = parser.endTag(); assertEquals("root", e.getName()); assertTrue("root", !e.isOpen()); assertTrue("more data true", reader.hasMoreData()); // try another doc parser.skipProlog(); assertEquals("root", parser.startTag().getName()); Element a = (Element)parser.getContent().getChild(0); assertTrue("closed a", !a.isOpen()); parser.up(0); assertTrue("more data false", !reader.hasMoreData()); } // tests up() method public void testParserUp() throws Exception { XmlParser parser = newParser(); parser.skipProlog(); assertEquals(null, parser.getTopElement()); assertEquals("test", parser.startTag().getName()); assertEquals("a", parser.startTag().getName()); int depth = parser.getDepth(); assertEquals("b", parser.startTag().getName()); assertEquals("c", parser.startTag().getName()); parser.up(depth); assertEquals("b2", parser.startTag().getName()); assertEquals("b2", parser.endTag().getName()); assertEquals("a", parser.endTag().getName()); assertEquals("test", parser.endTag().getName()); try { parser.endTag(); } catch (XmlException xre) { return; } fail("Should raise XmlException"); } /** * Tests skip misc. */ public void testSkipMisc() throws Exception { XmlParser parser = newParser(); Reader r = new StringReader(" "); parser.setReader(r); parser.alwaysSaveMisc(true); parser.toString(); assertEquals(parser.startTag().getName(), "test"); parser.toString(); assertEquals(parser.startTag().getName(), "a"); parser.emptyContent(); assertEquals(null, parser.startTag()); assertEquals(parser.endTag().getName(), "a"); parser.emptyContent(); assertEquals(parser.endTag().getName(), "test"); parser.skipMisc(); assertEquals(-1, r.read()); } /** * Tests whole tree parsing. */ public void testWholeTreeParsing() throws Exception { XmlParser parser = newParser(); parser.skipProlog(); assertEquals(parser.startTag().getName(), "test"); assertEquals(parser.startTag().getName(), "a"); assertEquals(parser.startTag().getName(), "b"); assertEquals(parser.startTag().getName(), "c"); assertEquals(parser.endTag().getName(), "c"); assertEquals(parser.startTag().getName(), "d"); assertEquals(parser.getContent().getName(), "d"); assertEquals(D_CONTENT, parser.getTopElement().getCharacterData().trim()); assertEquals(parser.endTag().getName(), "d"); assertEquals(parser.endTag().getName(), "b"); assertEquals(parser.startTag().getName(), "b2"); parser.close(); } } libexml-java-0.0.20080703.orig/e-xml/src/test/java/net/noderunner/exml/StringPoolPerfTest.java0000644000175000017500000000424710762067376031613 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.exml; import java.io.StringReader; public final class StringPoolPerfTest extends junit.framework.TestCase { static int times = 8; public static void main(String[] args) { for (int i = 0; i < args.length; i++) { if (args[i].equals("times")) times = Integer.parseInt(args[i+1]); } junit.textui.TestRunner.run(StringPoolPerfTest.class); } public StringPoolPerfTest(String name) { super(name); } long start; long total; void start() { start = System.currentTimeMillis(); } void stop(String s) { long took = System.currentTimeMillis() - start; System.out.println(s + " took: " + took); total += took; } void average(String s) { System.out.println(s + " average: " + total / times); total = 0; } static char pad[] = "abcdefgh".toCharArray(); public void testQuick() throws Exception { StringBuffer sb = new StringBuffer(1024 * 1024); int total = 1024 * 512; for (int i = 0; i < total; i++) { sb.append("t").append(i%64).append("ggy-short-"). append(pad, 0, i % 8).append(' '); } for (int i = 0; i < times; i++) { start(); StringReader sr = new StringReader(sb.toString()); XmlScanner xs = new XmlScanner(sr, 1024); for (int j = 0; j < total; j++) { xs.getName(); xs.read(); // a space } stop("scanning"); System.out.println(" " + xs.getStringPool()); System.out.println(" " + xs.getStringPool().buckets()); } average("scanning done "); } } libexml-java-0.0.20080703.orig/e-xml/src/test/java/net/noderunner/exml/DocumentTest.java0000644000175000017500000000314010762067376030443 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.exml; /** * This class is for unit testing the Document class. * * @see Document * @author Elias Ross * @version 1.0 */ public class DocumentTest extends junit.framework.TestCase { public DocumentTest(String name) { super(name); } public static void main(String[] args) { junit.textui.TestRunner.run(DocumentTest.class); } public void testInit() { Document d = new Document(); assertEquals("type is DOCUMENT_NODE", Node.DOCUMENT_NODE, d.getNodeType()); assertEquals("children default ", null, d.getChildNodes()); Element e = new Element("blah"); d.appendChild(e); try { d.appendChild(new Element("blah2")); fail("must check adding"); } catch (ElementException ee) { } assertEquals("root ", e, d.getRootElement()); d.appendChild(new PI("php")); assertEquals("size of children", 2, d.getChildNodes().size()); } } libexml-java-0.0.20080703.orig/e-xml/src/test/java/net/noderunner/exml/ElementRuleTest.java0000644000175000017500000004150210762067376031112 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.exml; import java.io.StringReader; /** * This class is for unit testing the ElementRule class. * * @see ElementRule * @author Elias Ross * @version 1.0 */ public class ElementRuleTest extends junit.framework.TestCase { public ElementRuleTest(String name) { super(name); } public static void main(String[] args) { junit.textui.TestRunner.run(ElementRuleTest.class); } static final Element A = new Element("a"); static final Element B = new Element("b"); static final Element C = new Element("c"); static final Element D = new Element("d"); static final Element E = new Element("e"); static ElementReq createReq(String s) throws Exception { // need a space, because we get EOF premature Dtd dtd = new Dtd(); dtd.addElementRule(A, new ElementRule()); dtd.addElementRule(B, new ElementRule()); dtd.addElementRule(C, new ElementRule()); dtd.addElementRule(D, new ElementRule()); dtd.addElementRule(E, new ElementRule()); XmlReader r = new XmlReader(new StringReader(s + " "), dtd); return r.contentspec(); } public void testSequenceParse() throws Exception { String s; ElementReq req; s = "(a, b, c)"; // basic req = createReq(s); assertEquals(s, req.toString()); // multi s = "(a+, b?, c*)"; req = createReq(s); assertEquals(s, req.toString()); // nested s = "((a, b))"; req = createReq(s); assertEquals(s, req.toString()); // deep s = "((a, b), (c, (d, (e, f)*)?)+)?"; req = createReq(s); assertEquals(s, req.toString()); } public void testAnyEmpty() throws Exception { String s; ElementReq req; s = "ANY"; req = createReq(s); assertTrue("Any", req.isANY()); // EMPTY s = "EMPTY"; req = createReq(s); assertTrue("EMPTY", req.size() == 0); } public void testPCDATA() throws Exception { String s; ElementReq req; s = "(#PCDATA | a | b)*"; req = createReq(s); assertTrue("PCDATA", req.isPCDATA()); assertTrue("PCDATA choice", req.isChoice()); assertTrue("PCDATA star", req.isStar()); assertEquals("PCDATA string", s, req.toString()); ElementRule rule = new ElementRule(req, null); ElementRule.ElementRuleState state = new ElementRule.ElementRuleState(); rule.encounterEnd(state); try { s = "(#PCDATA | a | b)"; req = createReq(s); fail("must have )*"); } catch (XmlException e) { } try { s = "(#PCDATA , a , b)"; req = createReq(s); fail("must not have comma"); } catch (XmlException e) { } try { s = "(#PCDATA | (a | b) | c)"; req = createReq(s); fail("must not have subparens"); } catch (XmlException e) { } } public void testNormalize() throws Exception { String s; ElementReq req; // star one s = "(a | b*)"; req = createReq(s); req.normalize(); assertTrue("choice", req.isChoice()); assertEquals("(a | b*)?", req.toString()); // question s = "(a | b | c?)"; req = createReq(s); req.normalize(); assertEquals("(a | b | c?)?", req.toString()); // sequence s = "(a?, b*)"; req = createReq(s); req.normalize(); assertEquals("(a?, b*)?", req.toString()); // nested s = "((a?, b*))"; req = createReq(s); req.normalize(); assertEquals("((a?, b*)?)?", req.toString()); } public void testChoiceParse() throws Exception { String s; ElementReq req; s = "(a | b | c)"; // basic req = createReq(s); assertEquals(s, req.toString()); // multi s = "(a+ | b? | c*)"; req = createReq(s); assertEquals(s, req.toString()); // nested s = "((a | b))"; req = createReq(s); assertEquals(s, req.toString()); // deep s = "((a | b) | (c | (d | (e | f)*)?)+)?"; req = createReq(s); assertEquals(s, req.toString()); } public void testDeep() throws Exception { String s; ElementReq req; s = "(((a)))"; // basic req = createReq(s); assertEquals(s, req.toString()); s = "(((a*)+)?)"; // basic req = createReq(s); assertEquals(s, req.toString()); } public void testEncounterSeq() throws Exception { String s; ElementReq req; s = "(a, b, c)"; req = createReq(s); ElementRule rule = new ElementRule(req, null); ElementRule.ElementRuleState state = new ElementRule.ElementRuleState(); rule.encounterElement(A, state); rule.encounterElement(B, state); rule.encounterElement(C, state); } public void testEncounterEnds() throws Exception { String s; ElementReq req; s = "(a, b?, c*)"; req = createReq(s); ElementRule rule = new ElementRule(req, null); ElementRule.ElementRuleState state = new ElementRule.ElementRuleState(); rule.encounterElement(A, state); rule.encounterEnd(state); state.clear(); rule.encounterElement(A, state); rule.encounterElement(B, state); rule.encounterEnd(state); try { state.clear(); rule.encounterEnd(state); fail("not done"); } catch (ElementRuleException e) { } } public void testEncounterEnds2() throws Exception { String s; ElementReq req; s = "(a, ((b*, c) | d+))"; req = createReq(s); ElementRule rule = new ElementRule(req, null); ElementRule.ElementRuleState state = new ElementRule.ElementRuleState(); rule.encounterElement(A, state); rule.encounterElement(D, state); rule.encounterEnd(state); state.clear(); rule.encounterElement(A, state); rule.encounterElement(B, state); rule.encounterElement(C, state); rule.encounterEnd(state); state.clear(); rule.encounterElement(A, state); rule.encounterElement(C, state); try { state.clear(); rule.encounterElement(A, state); rule.encounterEnd(state); fail("not done"); } catch (ElementRuleException e) { } try { state.clear(); rule.encounterElement(A, state); rule.encounterElement(B, state); rule.encounterEnd(state); fail("not done"); } catch (ElementRuleException e) { } } public void testEncounterEnds3() throws Exception { String s; ElementReq req; s = "(a*, ((b) | (d))+, ((c))+)"; req = createReq(s); ElementRule rule = new ElementRule(req, null); ElementRule.ElementRuleState state = new ElementRule.ElementRuleState(); rule.encounterElement(B, state); rule.encounterElement(C, state); rule.encounterEnd(state); state.clear(); rule.encounterElement(D, state); rule.encounterElement(B, state); rule.encounterElement(C, state); rule.encounterEnd(state); try { state.clear(); rule.encounterElement(D, state); rule.encounterElement(D, state); rule.encounterEnd(state); fail("not done"); } catch (ElementRuleException e) { } } public void testEncounterSeq2() throws Exception { String s; ElementReq req; s = "(a?, b?, c+)"; req = createReq(s); ElementRule rule = new ElementRule(req, null); ElementRule.ElementRuleState state = new ElementRule.ElementRuleState(); rule.encounterElement(B, state); rule.encounterElement(C, state); rule.encounterElement(C, state); } public void testEncounterSeq3() throws Exception { String s; ElementReq req; s = "(c, (a, b)*, c)"; req = createReq(s); ElementRule rule = new ElementRule(req, null); ElementRule.ElementRuleState state = new ElementRule.ElementRuleState(); rule.encounterElement(C, state); rule.encounterElement(C, state); state.clear(); rule.encounterElement(C, state); rule.encounterElement(A, state); rule.encounterElement(B, state); rule.encounterElement(A, state); rule.encounterElement(B, state); rule.encounterElement(C, state); } public void testEncounterSeq4() throws Exception { String s; ElementReq req; s = "(c?, (a?, b?), d+)"; req = createReq(s); ElementRule rule = new ElementRule(req, null); ElementRule.ElementRuleState state = new ElementRule.ElementRuleState(); rule.encounterElement(C, state); rule.encounterElement(B, state); rule.encounterElement(D, state); state.clear(); rule.encounterElement(D, state); state.clear(); rule.encounterElement(A, state); rule.encounterElement(D, state); rule.encounterElement(D, state); } public void testEncounterChoice() throws Exception { String s; ElementReq req; s = "(a | b | c)+"; req = createReq(s); ElementRule rule = new ElementRule(req, null); ElementRule.ElementRuleState state = new ElementRule.ElementRuleState(); rule.encounterElement(A, state); rule.encounterElement(B, state); rule.encounterElement(C, state); rule.encounterElement(B, state); rule.encounterElement(A, state); state.clear(); rule.encounterElement(C, state); state.clear(); try { rule.encounterElement(D, state); fail("should fail"); } catch (XmlException e) { } } public void testEncounterMix() throws Exception { String s; ElementReq req; s = "(a, (b | c), d)"; req = createReq(s); ElementRule rule = new ElementRule(req, null); ElementRule.ElementRuleState state = new ElementRule.ElementRuleState(); rule.encounterElement(A, state); rule.encounterElement(C, state); rule.encounterElement(D, state); state.clear(); rule.encounterElement(A, state); rule.encounterElement(B, state); rule.encounterElement(D, state); state.clear(); try { rule.encounterElement(A, state); rule.encounterElement(D, state); fail("should fail"); } catch (XmlException e) { } } public void testEncounterMix2() throws Exception { String s; ElementReq req; s = "(a?, (b | c)*, d)"; req = createReq(s); ElementRule rule = new ElementRule(req, null); ElementRule.ElementRuleState state = new ElementRule.ElementRuleState(); rule.encounterElement(A, state); rule.encounterElement(D, state); state.clear(); rule.encounterElement(B, state); rule.encounterElement(D, state); state.clear(); rule.encounterElement(C, state); rule.encounterElement(B, state); rule.encounterElement(B, state); rule.encounterElement(D, state); try { rule.encounterElement(D, state); fail("should fail"); } catch (XmlException e) { } } public void testEncounterMix3() throws Exception { String s; ElementReq req; s = "((b | c)+, (a+ | (d+, c+)))"; req = createReq(s); ElementRule rule = new ElementRule(req, null); ElementRule.ElementRuleState state = new ElementRule.ElementRuleState(); rule.encounterElement(B, state); rule.encounterElement(B, state); rule.encounterElement(C, state); rule.encounterElement(B, state); rule.encounterElement(A, state); state.clear(); rule.encounterElement(B, state); rule.encounterElement(C, state); rule.encounterElement(D, state); rule.encounterElement(C, state); state.clear(); try { rule.encounterElement(A, state); fail("should fail"); } catch (XmlException e) { } state.clear(); rule.encounterElement(B, state); rule.encounterElement(A, state); rule.encounterElement(A, state); try { rule.encounterElement(D, state); fail("should fail"); } catch (XmlException e) { } state.clear(); rule.encounterElement(C, state); rule.encounterElement(D, state); try { rule.encounterElement(A, state); fail("should fail"); } catch (XmlException e) { } } public void testEncounterSeq5() throws Exception { String s; ElementReq req; s = "(((a, b))+, (d)?, (c))"; req = createReq(s); ElementRule rule = new ElementRule(req, null); ElementRule.ElementRuleState state = new ElementRule.ElementRuleState(); rule.encounterElement(A, state); rule.encounterElement(B, state); rule.encounterElement(A, state); rule.encounterElement(B, state); rule.encounterElement(D, state); rule.encounterElement(C, state); state.clear(); rule.encounterElement(A, state); rule.encounterElement(B, state); rule.encounterElement(D, state); rule.encounterElement(C, state); state.clear(); try { rule.encounterElement(D, state); fail("should fail"); } catch (XmlException e) { } state.clear(); } public void testAny() throws Exception { ElementRule rule = new ElementRule(); ElementRule.ElementRuleState state = new ElementRule.ElementRuleState(); rule.encounterElement(A, state); rule.encounterElement(B, state); rule.toString(); } public void testEmpty() throws Exception { ElementRule rule = new ElementRule(); rule.allowNoElements(); ElementRule.ElementRuleState state = new ElementRule.ElementRuleState(); try { rule.encounterElement(A, state); fail("should not allow any elements"); } catch (XmlException e) { } rule.toString(); } public void testIllegalArgument() throws Exception { try { new ElementRule(null, null); fail("cannot have null root"); } catch (IllegalArgumentException e) { } try { new ElementRule(null, null, false); fail("cannot have null root"); } catch (IllegalArgumentException e) { } } public void testEncounterNest() throws Exception { String s; ElementReq req; s = "(((((a?, b?)))))"; req = createReq(s); ElementRule rule = new ElementRule(req, null); ElementRule.ElementRuleState state = new ElementRule.ElementRuleState(); rule.encounterElement(A, state); rule.encounterElement(B, state); state.clear(); rule.encounterElement(B, state); state.clear(); rule.encounterElement(A, state); try { rule.encounterElement(A, state); fail("should fail"); } catch (XmlException e) { } } public void testEncounterSeq4Bad() throws Exception { String s; ElementReq req; s = "(c?, (a?, b?), d+)"; req = createReq(s); ElementRule rule = new ElementRule(req, null); ElementRule.ElementRuleState state = new ElementRule.ElementRuleState(); rule.encounterElement(A, state); rule.encounterElement(B, state); try { rule.encounterElement(B, state); fail("Should fail with B " + s); } catch (XmlException e) { } state.clear(); rule.encounterElement(A, state); try { rule.encounterElement(A, state); fail("Should fail with A " + s); } catch (XmlException e) { } state.clear(); rule.encounterElement(D, state); rule.encounterElement(D, state); } public void testEncounterSeqBad() throws Exception { String s; ElementReq req; s = "(a+, b?, c+)"; req = createReq(s); ElementRule rule = new ElementRule(req, null); ElementRule.ElementRuleState state = new ElementRule.ElementRuleState(); try { rule.encounterElement(B, state); fail("must have a"); } catch (XmlException e) { } state.clear(); rule.encounterElement(A, state); rule.encounterElement(C, state); rule.encounterElement(C, state); try { rule.encounterElement(A, state); fail("cannot have an 'a'"); } catch (XmlException e) { } } public void testEncounterSeqRep() throws Exception { String s; ElementReq req; s = "((a?, b?)+)"; req = createReq(s); ElementRule rule = new ElementRule(req, null); ElementRule.ElementRuleState state = new ElementRule.ElementRuleState(); for (int i = 0; i < 10; i++) { rule.encounterElement(B, state); rule.encounterElement(A, state); } } public void testEncounterSeqBad2() throws Exception { String s; ElementReq req; s = "(c, (a, b)?, c)"; req = createReq(s); ElementRule rule = new ElementRule(req, null); ElementRule.ElementRuleState state = new ElementRule.ElementRuleState(); rule.encounterElement(C, state); rule.encounterElement(A, state); try { rule.encounterElement(C, state); } catch (XmlException e) { } state.clear(); rule.encounterElement(C, state); rule.encounterElement(A, state); try { rule.encounterElement(E, state); } catch (XmlException e) { } state.clear(); rule.encounterElement(C, state); rule.encounterElement(A, state); rule.encounterElement(B, state); try { rule.encounterElement(B, state); } catch (XmlException e) { } state.clear(); rule.encounterElement(C, state); rule.encounterElement(C, state); } public void testEmptyRuleEnd() throws Exception { ElementReq req = createReq("EMPTY"); ElementRule rule = new ElementRule(req, null); ElementRule.ElementRuleState state = new ElementRule.ElementRuleState(); rule.encounterEnd(state); } public void testStarRuleEnd() throws Exception { ElementReq req; ElementRule rule; ElementRule.ElementRuleState state; req = createReq("(e)*"); rule = new ElementRule(req, null); state = new ElementRule.ElementRuleState(); rule.encounterEnd(state); req = createReq("(e)?"); rule = new ElementRule(req, null); state = new ElementRule.ElementRuleState(); rule.encounterEnd(state); } } libexml-java-0.0.20080703.orig/e-xml/src/test/java/net/noderunner/exml/XmlReaderTest.java0000644000175000017500000010431010762067376030551 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.exml; import java.io.BufferedWriter; import java.io.Reader; import java.io.StringReader; import java.io.StringWriter; import java.io.Writer; import java.util.List; /** * This class is for unit testing the XmlReader class. * * @see XmlReader * @author Elias Ross * @version 1.0 */ public class XmlReaderTest extends junit.framework.TestCase { public XmlReaderTest(String name) { super(name); } StringWriter comment; StringWriter pi; String in; XmlReader reader; protected void setUp() { reader = new XmlReader(); } public Writer handleComment() { return (comment = new StringWriter()); } public Writer handleProcessingInstruction(String target) { pi = new StringWriter(); pi.write(target + " "); return pi; } // test Attribute() public void testAttlist() throws Exception { in = ""; reader.setReadString(in); reader.AttlistDecl(); ElementRule rule = reader.getDtd().getElementRule("doc"); AttributeRule ar; ar = (AttributeRule)rule.getAttributeRules().get(0); assertNotNull(ar); } public void testAttlistEnum() throws Exception { in = ""; reader.setReadString(in); reader.AttlistDecl(); ElementRule rule = reader.getDtd().getElementRule("doc"); AttributeRule ar; ar = (AttributeRule)rule.getAttributeRules().get(0); assertTrue(ar.allowedValue("on")); assertTrue(ar.allowedValue("off")); assertTrue(ar.allowedValue("middle")); assertTrue(!ar.allowedValue("fishy")); } // test Attribute() public void testAttribute() throws Exception { in = "name \n= '""I love traffic %& lights. " + "But Only when \"they\" are green.'"; reader = new XmlReader(new StringReader(in)); Attribute a = reader.Attribute(); assertEquals("name", a.getName()); assertTrue(a.getValue().startsWith("\"\"I love traffic %& lights. But Only")); } // test Attribute2() public void testAttribute2() throws Exception { in = "name \n= \"""\""; reader = new XmlReader(new StringReader(in)); Attribute a = reader.Attribute(); assertEquals("two quotes", "\"\"", a.getValue()); } public void testMissingStuff() throws Exception { in = ""; reader.setReadString(in); try { reader.element(); fail("no attribute name"); } catch (XmlException xre) { } in = ""; reader.setReadString(in); try { reader.element(); fail("expect />"); } catch (XmlException xre) { } in = ""; reader.setReadString(in); try { reader.element(); fail("expect "); } catch (XmlException xre) { } in = ""; reader.setReadString(in); try { reader.ETag(); fail("expect "); } catch (XmlException xre) { } in = ""); } catch (XmlException xre) { } in = "<%"; reader.setReadString(in); try { reader.element(); fail("expect <%"); } catch (XmlException xre) { } } /* // test Attribute3() public void testAttribute3() throws Exception { in = "name \n= ' > ' "; reader = new XmlReader(new StringReader(in)); try { Attribute a = reader.Attribute(); fail("NO > in attributes"); } catch (XmlException xre) { } } */ public void testPEReference() throws Exception { in = "'value %pef; &'"; reader = new XmlReader(new StringReader(in)); try { reader.EntityValue(); fail("Should fail reading bad PE"); } catch (XmlException xre) { } } public void testPEReferenceResolve() throws Exception { reader.setReadString("%hello;"); String e = ""; reader.getDtd().addParameterEntity("hello", new Entity(e)); reader.extSubsetDecl(); assertEquals("Bye", reader.getDtd().getEntity("Hello").getValue()); } public void testContentspec() throws Exception { in = ""; reader = new XmlReader(new StringReader(in)); reader.elementdecl(); in = ""; reader = new XmlReader(new StringReader(in)); reader.elementdecl(); in = ""; reader = new XmlReader(new StringReader(in)); reader.elementdecl(); in = ""; reader = new XmlReader(new StringReader(in)); reader.elementdecl(); try { in = ""; reader = new XmlReader(new StringReader(in)); reader.elementdecl(); fail("Must be ( #PCDATA | e ) with )*"); } catch (XmlException e) { } } public void testEntities() throws Exception { in = "" + " " + " " + " " + " " + "]>"; reader = new XmlReader(new StringReader(in)); reader.doctypedecl(); assertEquals("doctypedecl name", "doc", reader.getDtd().getName()); Entity ent; ent = reader.getDtd().getEntity("xml2"); assertEquals("&xml;&xml;", new String(ent.getValue())); ent = reader.getDtd().getEntity("xml3"); assertEquals("xmlxml", new String(ent.getValue())); ent = reader.getDtd().getEntity("foo"); assertEquals("", new String(ent.getValue())); } public void testDuplicateElement() throws Exception { in = "" + "" + "]>"; reader = new XmlReader(new StringReader(in)); try { reader.doctypedecl(); fail("cannot declare element bob twice"); } catch (XmlException e) { } } public void testEarlyAttlist() throws Exception { in = "" + "" + "" + "]>"; reader = new XmlReader(new StringReader(in)); reader.doctypedecl(); ElementRule rule = reader.getDtd().getElementRule("person"); assertNotNull("not null", rule); ElementRule.AttributeRuleState aruleState = new ElementRule.AttributeRuleState(); Attribute a; a = new Attribute("gender", "female"); AttributeRule arule; arule = rule.encounterAttribute(a, aruleState); assertEquals("fixed", true, arule.isFixed()); assertEquals("fixed female", "female", arule.getValue()); try { arule = rule.encounterAttribute(a, aruleState); fail("dupe attribute"); } catch (AttributeRuleException e) { } a = new Attribute("code", "white"); rule.encounterAttribute(a, aruleState); a = new Attribute("code", "blue"); try { rule.encounterAttribute(a, aruleState); fail("not fixed attribute"); } catch (AttributeRuleException e) { } } public void testConditionalSect() throws Exception { in = "" + " " + " " + " " + "]]>"; reader = new XmlReader(new StringReader(in)); reader.conditionalSect(); Entity ent; ent = reader.getDtd().getEntity("Hello"); assertEquals("Hello World", new String(ent.getValue())); ent = reader.getDtd().getParameterEntity("PEnt1"); assertEquals("#PCDATA", new String(ent.getValue())); } public void testParamConditionalSect() throws Exception { in = "" + "]]>"; reader = new XmlReader(new StringReader(in)); try { reader.conditionalSect(); fail("param not defined"); } catch (XmlException e) { } reader = new XmlReader(new StringReader(in)); reader.getDtd().addParameterEntity("ignore", new Entity("IGNORE")); reader.conditionalSect(); Entity ent = reader.getDtd().getEntity("Hello"); assertEquals(null, ent); } public void testEntityValue() throws Exception { String val; in = "'value %pe; &'"; reader = new XmlReader(new StringReader(in)); reader.getDtd().addParameterEntity("pe", new Entity("&")); val = reader.EntityValue(); assertEquals("value & &", val); in = "%pe; "; // try 2 reader = new XmlReader(new StringReader("%pe;")); reader.getDtd().addParameterEntity("pe", new Entity("&")); val = reader.EntityValue(); assertEquals("&", val); // try 3 reader = new XmlReader(new StringReader("&bad;")); try { val = reader.EntityValue(); fail("Not an entityvalue"); } catch (XmlException e) { } } public void testReference() throws Exception { in = "blah"; reader = new XmlReader(new StringReader(in)); assertEquals(reader.Reference(), null); } public void testReference2() throws Exception { in = "&blah ;"; reader = new XmlReader(new StringReader(in)); try { reader.Reference(); fail("Should fail reading bad Reference"); } catch (XmlException xre) { } } public void testReference3() throws Exception { in = "&blah;"; reader = new XmlReader(new StringReader(in)); try { reader.Reference(); fail("Should fail reading unknown Reference"); } catch (XmlException xre) { } } public void testReference4() throws Exception { // should succeed in = "&"; reader = new XmlReader(new StringReader(in)); reader.Reference(); assertEquals('&', reader.getScanner().read()); } public void testCDSect() throws Exception { // should succeed String in2 = "xxxx"; in = ""; reader = new XmlReader(new StringReader(in)); StringWriter w = new StringWriter(); reader.CDSect(w); assertEquals(in2, w.getBuffer().toString()); } public void testCDSect2() throws Exception { in = ""; reader = new XmlReader(new StringReader(in)); assertEquals(reader.CDSect(NullWriter.getInstance()), false); } public void testCharRef() throws Exception { in = " "; reader = new XmlReader(new StringReader(in)); reader.CharRef(); char c = (char)reader.getScanner().read(); assertEquals("Should get space", c, ' '); } public void testCharRef2() throws Exception { in = "z;"; reader = new XmlReader(new StringReader(in)); try { reader.CharRef(); fail("Should fail reading bad CharRef"); } catch (XmlException xre) { } } public void testCharRef3() throws Exception { in = "&#x"; for (int i = 0; i < XmlReaderPrefs.MAX_REF_LEN; i++) in += "00"; in += ";"; reader = new XmlReader(new StringReader(in)); try { reader.CharRef(); fail("Should fail reading long CharRef"); } catch (XmlException xre) { } } public void testCharRef4() throws Exception { in = "�"; reader = new XmlReader(new StringReader(in)); try { reader.CharRef(); fail("Should fail reading bad CharRef"); } catch (XmlException xre) { } } // tests STag() public void testSTag1() throws Exception { in = ""; reader = new XmlReader(new StringReader(in)); Element barney = reader.STag(); assertEquals(barney.getName(), "barney"); List l = barney.getAttributes(); assertEquals(l.size(), 2); assertEquals(barney.isOpen(), true); } // tests STag() public void testSTag1NS() throws Exception { in = ""; reader = new XmlReader(new StringReader(in)); Element barney = reader.STag(); assertEquals("a:barney", barney.getName()); assertEquals("barney", barney.getLocalName()); assertEquals("a", barney.getPrefix()); List l = barney.getAttributes(); assertEquals(l.size(), 3); assertEquals(barney.isOpen(), true); } // tests STag() public void testSTag2() throws Exception { in = ""; reader = new XmlReader(new StringReader(in)); Element bob = reader.STag(); List l = bob.getAttributes(); assertEquals(bob.isOpen(), false); assertEquals(l.size(), 2); } // tests STag() public void testSTag3() throws Exception { in = "not here "; reader = new XmlReader(new StringReader(in)); Element bob = reader.STag(); assertEquals(bob, null); } public void testSTag4() throws Exception { in = ""; reader = new XmlReader(new StringReader(in)); try { reader.STag(); fail("Should expect ="); } catch (XmlException xre) { } } // tests ETag() public void testETag() throws Exception { in = ""; reader = new XmlReader(new StringReader(in)); boolean found = reader.ETag(new Element("barney")); assertEquals(found, true); } // tests ETag() public void testETag2() throws Exception { in = ""; reader = new XmlReader(new StringReader(in)); try { reader.ETag(new Element("barney")); fail("Should not have found "); } catch (XmlException xre) { } in = ""; reader = new XmlReader(new StringReader(in)); try { reader.ETag(new Element("123")); fail("Should not have found an ETag "); } catch (XmlException xre) { } } // tests ETag() public void testETag3() throws Exception { in = " "; reader = new XmlReader(new StringReader(in)); boolean found = reader.ETag(new Element("barney")); assertEquals(found, false); } public void testXmlDecl() throws Exception { in = ""; reader = new XmlReader(new StringReader(in)); reader.Prolog(null); // xml decl can't be pi, but ignore anyway in = ""; reader = new XmlReader(new StringReader(in)); try { reader.Prolog(null); fail("xml decl must have version"); } catch (XmlException e) { } in = ""; reader = new XmlReader(new StringReader(in)); reader.Prolog(null); in = ""; reader = new XmlReader(new StringReader(in)); reader.TextDecl(); in = ""; reader.setReadString(in); try { reader.XmlDecl(); fail("xml standalone must be yes or no"); } catch (XmlException e) { } in = ""; reader.setReadString(in); reader.XmlDecl(); in = ""; reader.setReadString(in); reader.XmlDecl(); in = " encoding=\"UTF-8\""; reader.setReadString(in); assertEquals("UTF-8", reader.EncodingDecl()); in = " encoding = 'UTF_8'"; reader.setReadString(in); assertEquals("UTF_8", reader.EncodingDecl()); in = ""; reader = new XmlReader(new StringReader(in)); try { reader.TextDecl(); fail("TextDecl must not have standalone tag"); } catch (XmlException e) { } in = ""; reader = new XmlReader(new StringReader(in)); try { reader.Prolog(null); fail("XmlDecl must have xml not Xml tag"); } catch (XmlException e) { } in = ""; reader.setReadString(in); try { reader.XmlDecl(false); fail("XmlDecl must have version"); } catch (XmlException e) { } in = ""; reader.setReadString(in); try { reader.Prolog(null); fail("bad XML version"); } catch (XmlException e) { //System.out.println("XXXXXXXXXXXXXX " + e); } } static class DumbResolver implements SystemLiteralResolver { String got; String contents = ""; public Reader resolve(String literal) { got = literal; return new StringReader(contents); } } public void testNames() throws Exception { reader = new XmlReader(); reader.setReadString("a b c*"); String s[] = (String[])reader.Names().toArray(new String[0]); assertEquals(3, s.length); assertEquals("a", s[0]); assertEquals("b", s[1]); assertEquals("c", s[2]); } public void testCopyUntil() throws Exception { reader = new XmlReader(); String s = "fruit]]fruit"; reader.setReadString(s + new String(XmlTags.CDATA_END)); StringWriter w = new StringWriter(); reader.copyUntil(w, XmlTags.CDATA_END); assertEquals(s, w.toString()); reader.setReadString(s); try { reader.copyUntil(w, XmlTags.CDATA_END); fail("EOF exception"); } catch (XmlException e) { } } public void testToString() throws Exception { reader.setReadString(""); reader.toString(); reader.document(); reader.toString(); } public void testIgnore() throws Exception { reader.Ignore(); } public void testExtParsedEnt() throws Exception { reader.setReadString("fish"); Element e = new Element("foo"); reader.extParsedEnt(e); assertEquals("fish", e.getCharacterData()); } public void testExtSubset() throws Exception { reader.setReadString(""); reader.extSubset(); reader.setReadString(""); reader.extPE(); } public void testGEPE() throws Exception { reader.setReadString(""); reader.GEDecl(); reader.setReadString(""); reader.PEDecl(); } public void testNmtokens() throws Exception { reader = new XmlReader(); reader.setReadString("a b -c:d"); String s[] = (String[])reader.Nmtokens().toArray(new String[0]); assertEquals(3, s.length); assertEquals("a", s[0]); assertEquals("b", s[1]); assertEquals("-c:d", s[2]); assertNull(reader.Nmtoken()); reader.setReadString("a#"); assertEquals("a", reader.Nmtoken()); } public void testEncodingName() throws Exception { in = "UTF-16"; reader.EncName(in); in = "UTF:16"; try { reader.EncName(in); fail("bad encoding name"); } catch (XmlException e) { } in = "azAZ09-_."; reader.EncName(in); } // tests doctypedecl() public void test_doctypedecl() throws Exception { in = ""; reader.setReadString(in); DumbResolver slr; slr = new DumbResolver(); reader.setResolver(slr); assertEquals(reader.doctypedecl(), true); assertEquals(slr.got, "mybook.dtd"); in = ""; slr.contents = " bad content "; reader.setReadString(in); try { reader.doctypedecl(); fail("crap in DTD"); } catch (XmlException xre) { } reader.setReadString(""); try { assertEquals(reader.doctypedecl(), true); fail("should expect ] at end"); } catch (XmlException xre) { } reader.setReadString(""); try { assertEquals(reader.doctypedecl(), true); fail("should expect > at end"); } catch (XmlException xre) { } reader.setReadString(" "; reader = new XmlReader(new StringReader(in)); assertEquals(true, reader.Misc(null)); Document d = new Document(); assertEquals(true, reader.Misc(d)); assertTrue(d.getChildNodes().get(0) instanceof Comment); assertEquals(true, reader.Misc(d)); assertTrue(d.getChildNodes().get(1) instanceof PI); assertEquals(true, reader.Misc(null)); assertEquals(false, reader.Misc(null)); assertEquals(false, reader.hasMoreData()); } // tests Comment() public void testComment() throws Exception { String alpha = "abcdefghijklmnopqrstuvwxyz"; in = ""; reader = new XmlReader(new StringReader(in)); Element e = new Element("root"); Comment comment; e.appendChild(reader.comment(false)); e.appendChild(reader.comment(false)); e.appendChild(reader.comment(false)); comment = (Comment)reader.comment(true); assertEquals(null, comment); e.appendChild(reader.comment(false)); e.appendChild(reader.comment(false)); List l = e.getChildNodes(); comment = (Comment)l.get(0); assertEquals(comment.getData().toString(), alpha); comment = (Comment)l.get(1); assertEquals(comment.getData().toString(), "ackack"); comment = (Comment)l.get(2); assertEquals(comment.getData().toString(), ""); comment = (Comment)l.get(3); assertEquals(" bob bob ", comment.getData().toString()); assertEquals(reader.hasMoreData(), false); // test bad comment in = ""; reader = new XmlReader(new StringReader(in)); try { reader.comment(false); fail("should reject -- in comment"); } catch (XmlException xre) { } } // tests pi() public void testPI() throws Exception { String s = "echo \"hello \"; "; PI pi = new PI("php"); pi.getWriter().write(s); in = pi.toString(); Element e = new Element("test"); reader = new XmlReader(new StringReader(in)); e.appendChild(reader.pi(false)); pi = (PI)e.getChild(0); assertEquals(pi.getName(), "php"); assertEquals(pi.getData().toString(), s); reader.setReadString(in); assertEquals(null, reader.pi(true)); reader.setReadString(""); try { reader.pi(false); fail("bad PI"); } catch (XmlException ex) { } } public void testName() throws Exception { in = "123"; reader = new XmlReader(new StringReader(in)); assertEquals("Should not be a name", reader.Name(), null); } public void testName2() throws Exception { in = "_....-_:ab"; reader = new XmlReader(new StringReader(in)); assertEquals("Should be a name", reader.Name().toString(), in); } public void testName3() throws Exception { in = "abc "; reader = new XmlReader(new StringReader(in)); assertEquals("Should be a name", reader.Name().toString(), "abc"); } public void testName4() throws Exception { in = ""; for (int i = 0; i < XmlReaderPrefs.MAX_NAME_LEN * 2; i++) in += "xyz"; reader = new XmlReader(new StringReader(in)); try { reader.Name(); fail("Should fail reading long Name"); } catch (XmlException xre) { } reader = new XmlReader(new StringReader(in)); try { reader.Nmtoken(); fail("Should fail reading long Nmtoken"); } catch (XmlException xre) { } reader = new XmlReader(new StringReader('"' + in + '"')); try { reader.AttValue(); fail("Should fail reading long AttValue"); } catch (XmlException xre) { } } public void testPubidLiteral() throws Exception { String s = "system"; reader.setReadString("'" + s + "'"); assertEquals(s, reader.PubidLiteral()); reader.setReadString("' Make_Money_FAST <> '"); try { reader.PubidLiteral(); fail("bad PubidChar"); } catch (XmlException e) { } } public void testSystemLiteral() throws Exception { String s = "system"; reader.setReadString("'" + s + "'"); assertEquals(s, reader.SystemLiteral()); reader.setReadString("?" + s + "?"); try { reader.SystemLiteral(); fail("bad quote"); } catch (XmlException e) { } reader.setReadString("'" + s); try { reader.SystemLiteral(); fail("bad quote"); } catch (XmlException e) { } } public void testResolveAttValueExtEntity() throws Exception { reader.setReadString("'&ext;'"); Entity e = new Entity("publicID", "systemID"); reader.getDtd().addEntity("ext", e); try { reader.AttValue(); fail("external is not allowed"); } catch (XmlException ex) { } reader.setReadString("'¬ext;'"); e = new Entity("value"); reader.getDtd().addEntity("notext", e); String v = reader.AttValue(); assertEquals("value", v); } public void testBadAttReference() throws Exception { reader.setReadString("'&***'"); try { reader.AttValue(); fail("need name after &"); } catch (XmlException ex) { } reader.setReadString("'&ent*'"); Entity e = new Entity("value"); reader.getDtd().addEntity("ent", e); try { reader.AttValue(); fail("need ; after &ent"); } catch (XmlException ex) { } } public void testXmlWriterReader() throws Exception { String in; XmlReader reader; XmlWriter writer; StringWriter sw = new StringWriter(); writer = new XmlWriter(new BufferedWriter(sw)); writer.writeHeader("UTF-16"); Element root = new Element("test"); Element a = new Element("a"); Element b = new Element("b"); Element b2 = new Element("b2"); Element c = new Element("c"); writer.startElement(root); writer.startElement(a); writer.startElement(b); writer.endElement(); writer.startElement(b2); writer.emptyElement(c); String shouldbe = "& should be &"; writer.writeCData(shouldbe); writer.writeCData(""); writer.writeCData(""); writer.writeCDSection("ignore & everything "; in = "" + " %keanu;" + "]>"; reader = new XmlReader(new StringReader(in)); reader.doctypedecl(); Entity ent; ent = reader.getDtd().getParameterEntity("keanu"); assertEquals(val, ent.getValue()); ent = reader.getDtd().getEntity("keanu"); assertEquals("'woah'", ent.getValue()); } public void testPE2() throws Exception { String val = "" + " %keanu;>" + "]>"; reader = new XmlReader(new StringReader(in)); try { reader.doctypedecl(); fail("Incomplete parameter entity"); } catch (XmlException e) { } } public void testCheckReference() throws Exception { in = "" + "]>"; reader = new XmlReader(new StringReader(in)); try { reader.doctypedecl(); fail("checkReference failed"); } catch (XmlException e) { } } public void testCheckDoctypeName() throws Exception { in = "" + "]>"; reader = new XmlReader(new StringReader(in + "")); reader.document(); reader = new XmlReader(new StringReader(in + "")); try { reader.document(); fail("root element failed"); } catch (XmlException e) { } } public void testAttributeNaked() throws Exception { reader = new XmlReader(); in = "name = happy"; reader.setReadString(in); try { reader.Attribute(); fail("no quotes"); } catch (XmlException e) { } } public void testAttributeEOF() throws Exception { in = " ]>" + ""; reader = new XmlReader(new StringReader(in)); try { reader.document(); fail("checkReference failed"); } catch (XmlException e) { } } public void testNotation() throws Exception { Notation n; in = ""; reader = new XmlReader(new StringReader(in)); assertTrue("decl found", reader.NotationDecl()); n = (Notation)reader.getDtd().getNotations().get("note"); assertEquals("note pub", "MY NOTE", n.getPublicID()); assertEquals("note sys", "/tmp/blah", n.getSystemID()); in = ""; reader = new XmlReader(new StringReader(in)); reader.NotationDecl(); n = (Notation)reader.getDtd().getNotations().get("note"); assertEquals("note pub", null, n.getPublicID()); in = " " + "]> "; reader = new XmlReader(new StringReader(in)); reader.document(); n = (Notation)reader.getDtd().getNotations().get("note"); assertEquals("note pub", null, n.getPublicID()); assertEquals("note sys", "blah", n.getSystemID()); in = ""); } catch (XmlException xe) { } in = ""; reader.setReadString(in); try { reader.NotationDecl(); fail("bad name"); } catch (XmlException xe) { } in = ""; reader.setReadString(in); try { reader.NotationDecl(); fail("space after name"); } catch (XmlException xe) { } } public void testEntityExpansion() throws Exception { in = " " + " " + "]>" + "&e;&e;"; final String e = ""; SystemLiteralResolver slr = new SystemLiteralResolver() { public Reader resolve(String s) { return new StringReader(e); } }; reader = new XmlReader(new StringReader(in), new Dtd(), slr); reader.document(); } public void testAttributeGT() throws Exception { in = ""; reader = new XmlReader(new StringReader(in)); try { reader.document(); fail("cannot have > in attribute value"); } catch (XmlException xe) { } } public void testInternalPE() throws Exception { in = "" + "\">" + "%e; ]> "; reader = new XmlReader(new StringReader(in)); try { reader.document(); fail("cannot have declaration in internal decl"); } catch (XmlException xe) { } } public void testCheckReference2() throws Exception { in = "" + "]>"; reader = new XmlReader(new StringReader(in)); try { reader.doctypedecl(); fail("checkReference failed"); } catch (XmlException e) { } } public void testPESpace() throws Exception { in = ""; reader = new XmlReader(new StringReader(in)); try { reader.EntityDecl(); fail("testPESpace failed"); } catch (XmlException e) { } } public void testIgnoreRecursive() throws Exception { in = " lala ]]> ]]>"; reader.setReadString(in); reader.conditionalSect(); assertEquals(false, reader.hasMoreData()); reader.setReadString(in); reader.extSubsetDecl(); assertEquals(false, reader.hasMoreData()); } public void testIgnoreRecursive2() throws Exception { in = " ]]>"; reader = new XmlReader(new StringReader(in)); try { reader.conditionalSect(); fail("EOF in ignoreSectContents"); } catch (XmlException e) { } } public void testSetReader() throws Exception { Element e; in = "whatever"; reader = new XmlReader(new StringReader(in)); e = reader.document().getRootElement(); assertEquals(e.getName(), "doc"); in = "whatever"; reader.setReader(new StringReader(in)); e = reader.document().getRootElement(); assertEquals(e.getName(), "doc2"); } public void testGetResolver() throws Exception { XmlReader xr = new XmlReader(); assertTrue(xr.getResolver() instanceof NullResolver); } public void testCharAndSpace() throws Exception { assertTrue(XmlReader.Char('a')); assertTrue(XmlReader.Char(0x09)); assertTrue(XmlReader.Char(0x0a)); assertTrue(XmlReader.Char(0x0d)); assertTrue(XmlReader.Char(0xE000)); assertTrue(XmlReader.FirstNameChar('a')); assertTrue(XmlReader.FirstNameChar((char)0x41)); assertTrue(!XmlReader.Char('\u0000')); assertTrue(!XmlReader.Char('\b')); assertTrue(!XmlReader.Char('\uffff')); assertTrue(!XmlReader.PubidChar('"')); assertTrue(!XmlReader.PubidChar('&')); assertTrue(!XmlReader.PubidChar('\'')); assertTrue(!XmlReader.PubidChar('<')); assertTrue(!XmlReader.PubidChar('>')); XmlReader xr = new XmlReader(); xr.setReadString("\r\t\n "); xr.S(); assertTrue("got it all", !xr.hasMoreData()); assertTrue(!XmlReader.NameChar((char)174)); // (R) symbol assertTrue(XmlReader.Letter('a')); assertTrue(!XmlReader.Letter((char)174)); // (R) symbol } public void testStringPooling() throws Exception { XmlReader xr = new XmlReader(); final String n = "Name"; xr.setReadString(n); xr.getStringPool().add(n); String n2 = xr.Name(); assertEquals(n, n2); assertTrue("same object", n == n2); } public void testStringPoolingInit() throws Exception { Dtd dtd = new Dtd(); final String n = "Name"; final String s = "Socks"; dtd.addElementRule(n, new ElementRule()); XmlReader xr; xr = new XmlReader(new StringReader(n), dtd); assertTrue(xr.hasMoreData()); assertTrue("same object", n == xr.Name()); ElementRule er = new ElementRule(); er.addAttributeRule(new AttributeRule(AttributeValueType.CDATA, s)); dtd.addElementRule(n, er); xr = new XmlReader(new StringReader("<" + n + " " + s + "='x'/>"), dtd); Element e = xr.element(); assertTrue("element name canon", n == e.getName()); Attribute a = (Attribute)e.getAttributes().get(0); assertTrue("attr name canon", s == a.getName()); } public void testSetReader2() throws Exception { reader = new XmlReader(); try { reader.document(); fail("EOF"); } catch (XmlException e) { } Element e; in = "whatever"; reader = new XmlReader(); reader.setReadString(in); e = reader.document().getRootElement(); assertEquals(e.getName(), "doc"); in = "whatever"; reader.setReadString(in); e = reader.document().getRootElement(); assertEquals(e.getName(), "doc2"); } } libexml-java-0.0.20080703.orig/e-xml/src/test/java/net/noderunner/exml/CharacterDataTest.java0000644000175000017500000000255110762067376031360 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.exml; /** * This class is for unit testing the CharacterData class. * * @see CharacterData * @author Elias Ross * @version 1.0 */ public class CharacterDataTest extends junit.framework.TestCase { public CharacterDataTest(String name) { super(name); } public static void main(String[] args) { junit.textui.TestRunner.run(CharacterDataTest.class); } public void testInit() { CharacterData c = new CharacterData(); assertEquals("type is TEXT_NODE", Node.TEXT_NODE, c.getNodeType()); assertTrue("writer not null", c.getWriter() != null); assertEquals("data empty", "", c.toString()); } } libexml-java-0.0.20080703.orig/e-xml/src/test/java/net/noderunner/exml/XmlTester.java0000644000175000017500000000424010762067376027756 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.exml; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.Reader; /** * Given a list of filenames, tests their well-formedness. * This class is for end-to-end testing for the XmlReader class. * * @see XmlReader * @author Elias Ross * @version 1.0 */ public class XmlTester { public XmlTester(String filename) throws IOException, XmlException { Reader r = new InputStreamReader(new FileInputStream(filename)); XmlReader xr = new XmlReader(r); DefaultResolver dr = new DefaultResolver(); File f = new File(filename); dr.addSearchPath(f.getParent()); xr.setResolver(dr); xr.document(); while (xr.Misc(null)); if (xr.hasMoreData()) throw new XmlException("Data leftover"); xr.close(); } public static void main(String[] args) { if (args.length == 0) { System.err.println("Usage: java net.noderunner.exml.XmlTester files ..."); } for (int i = 0; i < args.length; i++) { String fname = args[i]; try { new XmlTester(fname); System.out.println("File passed: " + fname); } catch (IOException io) { System.out.println("File failed: " + fname); System.out.println("IO Reason: " + io); //io.printStackTrace(System.out); } catch (XmlException re) { System.out.println("File failed: " + fname); System.out.println("Reason: " + re); //re.printStackTrace(System.out); } } } } libexml-java-0.0.20080703.orig/e-xml/src/test/java/net/noderunner/exml/ElementTest.java0000644000175000017500000000604310762067376030263 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.exml; import java.util.ArrayList; /** * This class is for unit testing the Element class. * * @see Element * @author Elias Ross * @version 1.0 */ public class ElementTest extends junit.framework.TestCase { public ElementTest(String name) { super(name); } public static void main(String[] args) { junit.textui.TestRunner.run(ElementTest.class); } public void testInit() { String name = "name"; Element e = new Element(name); assertEquals("type is ELEMENT_NODE", Node.ELEMENT_NODE, e.getNodeType()); assertEquals("isOpen default ", true, e.isOpen()); assertEquals("children default ", null, e.getChildNodes()); assertEquals("children get ", null, e.getChild(0)); e.clearChildren(); assertEquals("children clear ", null, e.getChildNodes()); assertTrue("name node", e.toString().startsWith("")); } public void testClosed() { String name = "name"; Element e = new Element(name, null, false); assertEquals("type is ELEMENT_NODE", Node.ELEMENT_NODE, e.getNodeType()); assertEquals("isOpen ", false, e.isOpen()); try { e.appendChild(new Element("whatever")); fail("cannot append"); } catch (ElementException ee) { } assertEquals("children default ", null, e.getChildNodes()); assertEquals("children get ", null, e.getChild(0)); assertEquals("children clear ", null, e.getChildNodes()); assertTrue("name node", "".equals(e.toString())); } public void testAttr() { ArrayList al = new ArrayList(); al.add(new Attribute("name", "value")); al.add(new Attribute("name2", "value2")); Element e = new Element("name", al, false); assertEquals("attr", al, e.getAttributes()); assertEquals("value", "value", e.getAttValue("name", null)); assertEquals("value2", "value2", e.getAttValue("name2", null)); assertEquals("no", null, e.getAttValue("no", null)); assertEquals("no", "a", e.getAttValue("no", "a")); } public void testElement() { Element e = new Element("name"); Element a = new Element("a"); Element b = new Element("b"); Comment c = new Comment(); PI i = new PI("php"); e.appendChild(c); e.appendChild(a); e.appendChild(i); e.appendChild(b); assertEquals("a", a, e.getChildElement(0)); assertEquals("a", a, e.getChild(1)); assertEquals("b", b, e.getChildElement(1)); assertEquals("b", b, e.getChild(3)); } } libexml-java-0.0.20080703.orig/e-xml/src/test/java/net/noderunner/exml/AttributeRuleTest.java0000644000175000017500000001147510762067376031472 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.exml; import java.io.IOException; import java.io.StringReader; /** * This class is for unit testing the ElementRule class. * * @see ElementRule * @author Elias Ross * @version 1.0 */ public class AttributeRuleTest extends junit.framework.TestCase { public AttributeRuleTest(String name) { super(name); } public static void main(String[] args) { junit.textui.TestRunner.run(AttributeRuleTest.class); } public String[] attDefs = { "x CDATA #IMPLIED", "x (a | b | c) \"a\"", "x NOTATION (TeX | Tiff) #FIXED \"TeX\"", "x NMTOKENS #REQUIRED", "x NMTOKEN #IMPLIED", "x ID #REQUIRED", "x NOTATION (BOB) #REQUIRED", "x IDREF #REQUIRED", "x CDATA #REQUIRED", "x CDATA \"NORMAL\"", "x ENTITIES #IMPLIED", "x ENTITY \"far\""}; public void testAllow() throws Exception { AttributeRule arule; arule = makeRule("x (a | b) #FIXED \"a\""); assertTrue("fixed " + arule, arule.isFixed()); assertTrue("required " + arule, !arule.isRequired()); assertTrue("allow " + arule, arule.allowedValue("a")); assertTrue("allow " + arule, !arule.allowedValue("b")); try { arule = makeRule("y (a | b) #FIXED \"c\""); fail("should not fix to c " + arule); } catch (AttributeRuleException e) { } arule = makeRule("x (a | b) #REQUIRED"); assertTrue("fixed " + arule, !arule.isFixed()); assertTrue("required " + arule, arule.isRequired()); assertTrue("allow " + arule, arule.allowedValue("a")); assertTrue("allow " + arule, arule.allowedValue("b")); assertTrue("allow " + arule, !arule.allowedValue("c")); arule = makeRule("x (a | b) #IMPLIED"); assertTrue("fixed " + arule, !arule.isFixed()); assertTrue("required " + arule, !arule.isRequired()); assertTrue("allow " + arule, arule.allowedValue("a")); assertTrue("allow " + arule, !arule.allowedValue("c")); } public static AttributeRule makeRule(String s) throws XmlException, IOException { ElementRule erule = new ElementRule(); XmlReader reader; reader = new XmlReader(new StringReader(" " + s)); reader.AttDef(erule); AttributeRule arule = (AttributeRule)erule.getAttributeRules().get(0); return arule; } public void testDefs() throws Exception { for (int i = 0; i < attDefs.length; i++) { AttributeRule arule = makeRule(attDefs[i]); assertNotNull("not null", arule); assertEquals(attDefs[i], arule.toString()); } } public void testReq() throws Exception { String in = "" + "" + " " + " " + "]>"; Element e; XmlReader reader; reader = new XmlReader(new StringReader(in + "")); e = reader.document().getRootElement(); assertEquals(e.getAttValue("gender"), "m"); try { reader = new XmlReader(new StringReader(in + "")); reader.document(); fail("require gender"); } catch (XmlException xe) { assertTrue(xe instanceof AttributeRuleException); } try { reader = new XmlReader(new StringReader(in + "")); reader.document(); fail("require fun"); } catch (XmlException xe) { assertTrue(xe instanceof AttributeRuleException); } } public void testDef() throws Exception { String in = "" + "" + " " + " " + "]>"; XmlReader reader; reader = new XmlReader(new StringReader(in + "")); Element e; e = reader.document().getRootElement(); assertEquals(e.getAttValue("gender"), "f"); assertEquals(e.getAttValue("fun"), "n"); // accept defaults reader = new XmlReader(new StringReader(in + "")); e = reader.document().getRootElement(); assertEquals("m", e.getAttValue("gender")); assertEquals("y", e.getAttValue("fun")); // accept mix reader = new XmlReader(new StringReader(in + "")); e = reader.document().getRootElement(); assertEquals(e.getAttValue("gender"), "m"); assertEquals(e.getAttValue("fun"), "n"); } } libexml-java-0.0.20080703.orig/e-xml/src/test/java/net/noderunner/exml/RuleStackTest.java0000644000175000017500000000243410762067376030567 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.exml; import java.util.NoSuchElementException; import junit.framework.TestCase; import net.noderunner.exml.ElementRule.ElementRuleState; public class RuleStackTest extends TestCase { RuleStack rs; protected void setUp() throws Exception { rs = new RuleStack(); } public void testState() throws Exception { ElementRuleState state = rs.startElement(); assertSame(state, rs.state()); rs.endElement(); try { rs.state(); fail("empty"); } catch (NoSuchElementException e) {} } } libexml-java-0.0.20080703.orig/e-xml/src/test/java/net/noderunner/exml/XmlWriterTest.java0000644000175000017500000001572310762067376030634 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.exml; import java.io.BufferedWriter; import java.io.StringReader; import java.io.StringWriter; import java.util.List; import java.util.NoSuchElementException; import java.util.Vector; /** * This class tests the Xml writer against a DOM parser. */ public class XmlWriterTest extends junit.framework.TestCase { public XmlWriterTest(String name) { super(name); } /* public static junit.framework.TestSuite suite() { return new org.hansel.CoverageDecorator(XmlWriterTest.class, new Class[] { XmlWriter.class }); } */ public static void main(String[] args) { junit.textui.TestRunner.run(XmlWriterTest.class); } static StringWriter sw; static XmlWriter xw; static XmlReader xr; static StringReader sr; /** * Create a new XmlWriter around a StringWriter for testing. */ public static void newWriter() { sw = new StringWriter(); xw = new XmlWriter(new BufferedWriter(sw)); } public static void newReader() throws java.io.IOException { xw.close(); xr = new XmlReader(new StringReader(sw.getBuffer().toString())); } public void testEmptyDoc() throws Exception { newWriter(); xw.writeHeader("UTF-16"); xw.emptyElement("root"); newReader(); Document d = xr.document(); assertEquals("got ? ", d.getRootElement().getName(), "root"); while (xr.Misc(null)); assertEquals("Read everything in document", xr.hasMoreData(), false); } public void testSetWriter() throws Exception { newWriter(); xw.writeHeader("UTF-16"); xw.emptyElement("root"); sw = new StringWriter(); xw.setWriter(sw); xw.emptyElement("bob"); assertEquals("", sw.toString()); } public void testWriteCData() throws Exception { newWriter(); CharacterData cd = new CharacterData(); cd.getWriter().write("&"); xw.writeCData(cd); xw.close(); assertEquals("&", sw.toString()); } public void testWriteElementTree() throws Exception { newWriter(); Element e = new Element("f"); e.appendChild(new PI("php")); CharacterData cd = new CharacterData(); cd.getWriter().write("x"); e.appendChild(cd); xw.element(e); xw.close(); assertEquals("x", sw.toString()); } public void testWriteCharArray() throws Exception { newWriter(); xw.write("&".toCharArray()); xw.close(); assertEquals("&", sw.toString()); } public void testEmpty() throws Exception { newWriter(); Element e = new Element("frank"); Element e2 = new Element("larry"); e.appendChild(e2); xw.emptyElement(e); xw.close(); assertEquals("", sw.toString()); newWriter(); e2.setOpen(false); xw.emptyElement(e2); xw.close(); assertEquals("", sw.toString()); } public void testEntities() throws Exception { newWriter(); String sect = "<>&\"\'"; xw.writeCData(sect); newReader(); assertNull(xr.Reference()); // StringWriter out = new StringWriter(); // xr.CharData(out); // assertEquals("Should have <>& reference", sect, out.getBuffer().toString()); } public void testWrite() throws Exception { newWriter(); String s = "<>&'\""; xw.write(s); xw.flush(); assertTrue("No escape", s.equals(sw.toString())); } public void testWrite2() throws Exception { newWriter(); String s = "<>&'\""; char chars[] = s.toCharArray(); xw.write(chars, 0, chars.length); xw.flush(); assertTrue("No escape", s.equals(sw.toString())); } public void testSmallDoc() throws Exception { newWriter(); xw.writeHeader("UTF-16"); // document Element e = new Element("root"); e.appendChild(new Element("a")); List l = new Vector(); l.add(new Attribute("key", "value")); e.appendChild(new Element("b", l, false)); e.appendChild(new Element("c", l, true)); xw.element(e); newReader(); xr.document(); xr.Misc(null); assertEquals("Read everything in document", xr.hasMoreData(), false); } public void testCDSection() throws Exception { newWriter(); String sect = "<>!>&d '' \"[[ ] "; xw.writeCDSection(sect); newReader(); StringWriter out = new StringWriter(); assertEquals("Read CDSect", xr.CDSect(out), true); assertEquals("Content match", out.getBuffer().toString(), sect); } public void testCData() throws Exception { newWriter(); String sect = "abcabadababa"; xw.writeCData(sect + "<"); xw.close(); newReader(); StringWriter out = new StringWriter(); xr.CharData(out); assertEquals("Content matches", out.getBuffer().toString(), sect); } public void testEmptyList() throws Exception { newWriter(); String attrs4[] = new String[] { "a", "&", "c", "'" }; newWriter(); xw.emptyElement("baz", attrs4); xw.up(0); newReader(); Document d = xr.document(); Element e = d.getRootElement(); assertEquals("got ? ", e.getName(), "baz"); assertTrue("closed", !e.isOpen()); assertEquals("Read everything in document " + xr, false, xr.hasMoreData()); } public void testBad() throws Exception { newWriter(); String attrs[] = new String[] { }; String attrs3[] = new String[] { "a", "b", "c" }; String attrs4[] = new String[] { "a", "&", "c", "'" }; xw.startElement("foo", attrs); try { xw.startElement("bar", attrs3); fail("bad bar, bad!"); } catch (ArrayIndexOutOfBoundsException e) { } newWriter(); xw.startElement("baz", attrs4); xw.up(0); newReader(); Document d = xr.document(); assertEquals("got ? ", d.getRootElement().getName(), "baz"); List l = d.getRootElement().getAttributes(); assertEquals("2 attrs? ", 2, l.size()); Attribute a; a = (Attribute)l.get(0); assertEquals("1st attr & ? ", "&", a.getValue()); a = (Attribute)l.get(1); assertEquals("2nd attr ' ? ", "'", a.getValue()); newWriter(); try { xw.startElement("bar", null); fail("null, bad!"); } catch (NullPointerException e) { } } public void testUp() throws Exception { newWriter(); for (int i = 0; i < 128; i++) xw.startElement("element-" + i); assertEquals("Depth of 128", 128, xw.getDepth()); xw.up(64); assertEquals("Depth of 64", 64, xw.getDepth()); xw.up(0); assertEquals("Depth of 0", 0, xw.getDepth()); try { xw.endElement(); fail("Should fail"); } catch (NoSuchElementException e) { } newReader(); xr.document(); assertEquals("Read everything in document", true, xr.hasMoreData()); } } libexml-java-0.0.20080703.orig/e-xml/src/test/resources/0000755000175000017500000000000011111351354022320 5ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/0000755000175000017500000000000011111351370024560 5ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/0000755000175000017500000000000011111351365025663 5ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/ext-sa/0000755000175000017500000000000011111351354027062 5ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/ext-sa/out/0000755000175000017500000000000011111351354027671 5ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/ext-sa/out/001.xml0000644000175000017500000000002407477076020030725 0ustar twernertwernerData libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/ext-sa/out/010.xml0000644000175000017500000000001307477076020030723 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/ext-sa/out/002.xml0000644000175000017500000000001707477076020030730 0ustar twernertwernerDatalibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/ext-sa/out/011.xml0000644000175000017500000000002507477076020030727 0ustar twernertwernerxyzzy libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/ext-sa/out/003.xml0000644000175000017500000000001307477076020030725 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/ext-sa/out/012.xml0000644000175000017500000000001707477076020030731 0ustar twernertwerner(e5)libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/ext-sa/out/004.xml0000644000175000017500000000002407477076020030730 0ustar twernertwernerData libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/ext-sa/out/013.xml0000644000175000017500000000006207477076020030732 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/ext-sa/out/005.xml0000644000175000017500000000004007477076020030727 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/ext-sa/out/014.xml0000644000175000017500000000002207477076020030727 0ustar twernertwerner©Àdatalibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/ext-sa/out/006.xml0000644000175000017500000000007207477076020030735 0ustar twernertwernerData More data libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/ext-sa/out/007.xml0000644000175000017500000000001607477076020030734 0ustar twernertwernerXYZlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/ext-sa/out/008.xml0000644000175000017500000000001607477076020030735 0ustar twernertwernerXYZlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/ext-sa/out/009.xml0000644000175000017500000000002007477076020030731 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/ext-sa/010.ent0000644000175000017500000000000007477076020030076 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/ext-sa/001.ent0000644000175000017500000000000507477076020030103 0ustar twernertwernerData libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/ext-sa/011.ent0000644000175000017500000000000607477076020030105 0ustar twernertwernerxyzzy libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/ext-sa/002.ent0000644000175000017500000000000407477076020030103 0ustar twernertwernerDatalibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/ext-sa/012.ent0000644000175000017500000000000407477076020030104 0ustar twernertwerner&e4;libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/ext-sa/003.ent0000644000175000017500000000000007477076020030100 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/ext-sa/013.ent0000644000175000017500000000000407477076020030105 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/ext-sa/004.ent0000644000175000017500000000000407477076020030105 0ustar twernertwernerDatalibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/ext-sa/014.ent0000644000175000017500000000001407477076020030107 0ustar twernertwerner‘‘datalibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/ext-sa/005.ent0000644000175000017500000000001407477076020030107 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/ext-sa/006.ent0000644000175000017500000000003107477076020030107 0ustar twernertwernerData More data libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/ext-sa/007.ent0000644000175000017500000000000407477076020030110 0ustar twernertwerner‘Ylibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/ext-sa/008.ent0000644000175000017500000000006607477076020030121 0ustar twernertwerner‘<?xml encoding="UTF-16"?>Ylibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/ext-sa/009.ent0000644000175000017500000000000007477076020030106 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/ext-sa/010.xml0000644000175000017500000000013007477076020030114 0ustar twernertwerner ]> &e; libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/ext-sa/001.xml0000644000175000017500000000013007477076020030114 0ustar twernertwerner ]> &e; libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/ext-sa/002.xml0000644000175000017500000000013007477076020030115 0ustar twernertwerner ]> &e; libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/ext-sa/011.xml0000644000175000017500000000016607477076020030126 0ustar twernertwerner ]> &e; libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/ext-sa/003.xml0000644000175000017500000000013007477076020030116 0ustar twernertwerner ]> &e; libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/ext-sa/012.xml0000644000175000017500000000025207477076020030123 0ustar twernertwerner ]> &e1; libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/ext-sa/004.xml0000644000175000017500000000013007477076020030117 0ustar twernertwerner ]> &e; libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/ext-sa/013.xml0000644000175000017500000000025207477076020030124 0ustar twernertwerner ]> &x; libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/ext-sa/005.xml0000644000175000017500000000014607477076020030127 0ustar twernertwerner ]> &e; libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/ext-sa/014.xml0000644000175000017500000000013007477076020030120 0ustar twernertwerner ]> &e; libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/ext-sa/006.xml0000644000175000017500000000015607477076020030131 0ustar twernertwerner ]> &e; libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/ext-sa/007.xml0000644000175000017500000000013207477076020030124 0ustar twernertwerner ]> X&e;Z libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/ext-sa/009.xml0000644000175000017500000000013007477076020030124 0ustar twernertwerner ]> &e; libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/not-sa/0000755000175000017500000000000011111351365027064 5ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/not-sa/out/0000755000175000017500000000000011111351365027673 5ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/not-sa/out/001.xml0000644000175000017500000000001307477076020030723 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/not-sa/out/010.xml0000644000175000017500000000002307477076020030724 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/not-sa/out/020.xml0000644000175000017500000000002307477076020030725 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/not-sa/out/002.xml0000644000175000017500000000001307477076020030724 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/not-sa/out/011.xml0000644000175000017500000000002307477076020030725 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/not-sa/out/030.xml0000644000175000017500000000001307477076020030725 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/not-sa/out/021.xml0000644000175000017500000000002307477076020030726 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/not-sa/out/003.xml0000644000175000017500000000002307477076020030726 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/not-sa/out/012.xml0000644000175000017500000000002307477076020030726 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/not-sa/out/031.xml0000644000175000017500000000007407477076020030735 0ustar twernertwerner<!ATTLIST doc a1 CDATA "v1"> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/not-sa/out/022.xml0000644000175000017500000000002307477076020030727 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/not-sa/out/004.xml0000644000175000017500000000002607477076020030732 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/not-sa/out/013.xml0000644000175000017500000000002307477076020030727 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/not-sa/out/023.xml0000644000175000017500000000002307477076020030730 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/not-sa/out/005.xml0000644000175000017500000000002307477076020030730 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/not-sa/out/014.xml0000644000175000017500000000002307477076020030730 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/not-sa/out/015.xml0000644000175000017500000000002307477076020030731 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/not-sa/out/006.xml0000644000175000017500000000003307477076020030732 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/not-sa/out/024.xml0000644000175000017500000000002307477076020030731 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/not-sa/out/016.xml0000644000175000017500000000002307477076020030732 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/not-sa/out/007.xml0000644000175000017500000000002307477076020030732 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/not-sa/out/025.xml0000644000175000017500000000002207477076020030731 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/not-sa/out/008.xml0000644000175000017500000000002307477076020030733 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/not-sa/out/017.xml0000644000175000017500000000002307477076020030733 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/not-sa/out/026.xml0000644000175000017500000000003307477076020030734 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/not-sa/out/009.xml0000644000175000017500000000003307477076020030735 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/not-sa/out/018.xml0000644000175000017500000000002307477076020030734 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/not-sa/out/027.xml0000644000175000017500000000001307477076020030733 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/not-sa/out/019.xml0000644000175000017500000000002307477076020030735 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/not-sa/out/028.xml0000644000175000017500000000002307477076020030735 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/not-sa/out/029.xml0000644000175000017500000000002307477076020030736 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/not-sa/003-1.ent0000644000175000017500000000012707477076020030250 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/not-sa/003-2.ent0000644000175000017500000000000007477076020030237 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/not-sa/020.ent0000644000175000017500000000011007477076020030101 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/not-sa/005-1.ent0000644000175000017500000000007207477076020030251 0ustar twernertwerner %e; libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/not-sa/021.ent0000644000175000017500000000011207477076020030104 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/not-sa/005-2.ent0000644000175000017500000000003507477076020030251 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/not-sa/022.ent0000644000175000017500000000013307477076020030110 0ustar twernertwerner ]]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/not-sa/023.ent0000644000175000017500000000017007477076020030112 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/not-sa/024.ent0000644000175000017500000000014207477076020030112 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/not-sa/025.ent0000644000175000017500000000015307477076020030115 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/not-sa/026.ent0000644000175000017500000000003507477076020030115 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/not-sa/027.ent0000644000175000017500000000005607477076020030121 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/not-sa/028.ent0000644000175000017500000000010407477076020030114 0ustar twernertwerner ]]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/not-sa/010.xml0000644000175000017500000000011507477076020030117 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/not-sa/029.ent0000644000175000017500000000014007477076020030115 0ustar twernertwerner ]]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/not-sa/011.xml0000644000175000017500000000010207477076020030114 0ustar twernertwerner %e; ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/not-sa/012.xml0000644000175000017500000000010207477076020030115 0ustar twernertwerner %e; ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/not-sa/013.xml0000644000175000017500000000005407477076020030124 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/not-sa/014.xml0000644000175000017500000000011007477076020030116 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/not-sa/015.xml0000644000175000017500000000010707477076020030125 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/not-sa/016.xml0000644000175000017500000000011007477076020030120 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/not-sa/017.xml0000644000175000017500000000005407477076020030130 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/not-sa/018.xml0000644000175000017500000000005407477076020030131 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/not-sa/019.xml0000644000175000017500000000005407477076020030132 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/not-sa/031-1.ent0000644000175000017500000000013007477076020030243 0ustar twernertwerner "> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/not-sa/030.ent0000644000175000017500000000006607477076020030114 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/not-sa/031-2.ent0000644000175000017500000000003507477076020030250 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/not-sa/020.xml0000644000175000017500000000005407477076020030122 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/not-sa/021.xml0000644000175000017500000000005407477076020030123 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/not-sa/022.xml0000644000175000017500000000005407477076020030124 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/not-sa/023.xml0000644000175000017500000000005407477076020030125 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/not-sa/024.xml0000644000175000017500000000005407477076020030126 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/not-sa/025.xml0000644000175000017500000000005407477076020030127 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/not-sa/026.xml0000644000175000017500000000020007477076020030121 0ustar twernertwerner %e; ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/not-sa/004-1.ent0000644000175000017500000000012207477076020030244 0ustar twernertwerner %e1; libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/not-sa/027.xml0000644000175000017500000000005407477076020030131 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/not-sa/028.xml0000644000175000017500000000005407477076020030132 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/not-sa/029.xml0000644000175000017500000000005407477076020030133 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/not-sa/001.ent0000644000175000017500000000000007477076020030076 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/not-sa/002.ent0000644000175000017500000000000007477076020030077 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/not-sa/004-2.ent0000644000175000017500000000004007477076020030244 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/not-sa/006.ent0000644000175000017500000000010007477076020030104 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/not-sa/007.ent0000644000175000017500000000006607477076020030120 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/not-sa/008.ent0000644000175000017500000000006607477076020030121 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/not-sa/009.ent0000644000175000017500000000006607477076020030122 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/not-sa/030.xml0000644000175000017500000000005407477076020030123 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/not-sa/031.xml0000644000175000017500000000006107477076020030122 0ustar twernertwerner &e; libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/not-sa/010.ent0000644000175000017500000000006607477076020030112 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/not-sa/011.ent0000644000175000017500000000006607477076020030113 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/not-sa/012.ent0000644000175000017500000000013507477076020030111 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/not-sa/013.ent0000644000175000017500000000011007477076020030103 0ustar twernertwerner ]]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/not-sa/014.ent0000644000175000017500000000010407477076020030107 0ustar twernertwerner ]]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/not-sa/015.ent0000644000175000017500000000014107477076020030111 0ustar twernertwerner ]]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/not-sa/016.ent0000644000175000017500000000010207477076020030107 0ustar twernertwerner ]]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/not-sa/017.ent0000644000175000017500000000011207477076020030111 0ustar twernertwerner "> %e; libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/not-sa/018.ent0000644000175000017500000000011207477076020030112 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/not-sa/019.ent0000644000175000017500000000011107477076020030112 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/not-sa/001.xml0000644000175000017500000000010507477076020030116 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/not-sa/002.xml0000644000175000017500000000010507477076020030117 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/not-sa/003.xml0000644000175000017500000000005607477076020030125 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/not-sa/004.xml0000644000175000017500000000005607477076020030126 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/not-sa/005.xml0000644000175000017500000000005607477076020030127 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/not-sa/006.xml0000644000175000017500000000011507477076020030124 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/not-sa/007.xml0000644000175000017500000000005407477076020030127 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/not-sa/008.xml0000644000175000017500000000006707477076020030134 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/not-sa/009.xml0000644000175000017500000000013007477076020030124 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/0000755000175000017500000000000011111351370026262 5ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/0000755000175000017500000000000011111351370027071 5ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/089.xml0000644000175000017500000000002707477076020030152 0ustar twernertwernerÉÇÇŸÅÀ»ŸÅÀÀlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/010.xml0000644000175000017500000000002307477076020030126 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/011.xml0000644000175000017500000000003307477076020030130 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/012.xml0000644000175000017500000000002207477076020030127 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/013.xml0000644000175000017500000000003607477076020030135 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/014.xml0000644000175000017500000000005307477076020030135 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/050.xml0000644000175000017500000000003207477076020030132 0ustar twernertwerner€ Ç€¹ê€¹í€¹¬€ îlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/015.xml0000644000175000017500000000005307477076020030136 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/051.xml0000644000175000017500000000004307477076020030135 0ustar twernertwerner<€ Ç€¹ê€¹í€¹¬€ î>libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/016.xml0000644000175000017500000000002207477076020030133 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/052.xml0000644000175000017500000000002307477076020030134 0ustar twernertwernerÉÇÇŸÅÀ»libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/017.xml0000644000175000017500000000004207477076020030136 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/053.xml0000644000175000017500000000002207477076020030134 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/090.xml0000644000175000017500000000001307477076020030135 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/018.xml0000644000175000017500000000002607477076020030141 0ustar twernertwerner<foo>libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/054.xml0000644000175000017500000000001307477076020030135 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/055.xml0000644000175000017500000000002607477076020030142 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/019.xml0000644000175000017500000000002407477076020030140 0ustar twernertwerner<&libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/091.xml0000644000175000017500000000002107477076020030135 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/056.xml0000644000175000017500000000001407477076020030140 0ustar twernertwernerAlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/092.xml0000644000175000017500000000010107477076020030135 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/057.xml0000644000175000017500000000001307477076020030140 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/093.xml0000644000175000017500000000003207477076020030141 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/058.xml0000644000175000017500000000002407477076020030143 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/094.xml0000644000175000017500000000002407477076020030143 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/059.xml0000644000175000017500000000016407477076020030151 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/095.xml0000644000175000017500000000002507477076020030145 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/096.xml0000644000175000017500000000002407477076020030145 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/097.xml0000644000175000017500000000002307477076020030145 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/098.xml0000644000175000017500000000002507477076020030150 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/099.xml0000644000175000017500000000001307477076020030146 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/100.xml0000644000175000017500000000001307477076020030125 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/101.xml0000644000175000017500000000001307477076020030126 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/020.xml0000644000175000017500000000003207477076020030127 0ustar twernertwerner<&]>]libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/102.xml0000644000175000017500000000002607477076020030133 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/021.xml0000644000175000017500000000001307477076020030127 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/103.xml0000644000175000017500000000002607477076020030134 0ustar twernertwerner<doc>libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/022.xml0000644000175000017500000000001307477076020030130 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/104.xml0000644000175000017500000000002307477076020030132 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/023.xml0000644000175000017500000000001307477076020030131 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/105.xml0000644000175000017500000000002607477076020030136 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/024.xml0000644000175000017500000000002607477076020030136 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/060.xml0000644000175000017500000000002207477076020030132 0ustar twernertwernerX Ylibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/106.xml0000644000175000017500000000002707477076020030140 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/025.xml0000644000175000017500000000004107477076020030134 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/061.xml0000644000175000017500000000001507477076020030135 0ustar twernertwernerÃúlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/107.xml0000644000175000017500000000002707477076020030141 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/026.xml0000644000175000017500000000004107477076020030135 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/062.xml0000644000175000017500000000003207477076020030135 0ustar twernertwerner€ Ç€¹ê€¹í€¹¬€ îlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/108.xml0000644000175000017500000000002307477076020030136 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/027.xml0000644000175000017500000000004107477076020030136 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/063.xml0000644000175000017500000000004307477076020030140 0ustar twernertwerner<€ Ç€¹ê€¹í€¹¬€ î>libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/109.xml0000644000175000017500000000002007477076020030134 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/028.xml0000644000175000017500000000001307477076020030136 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/064.xml0000644000175000017500000000002307477076020030137 0ustar twernertwernerÉÇÇŸÅÀ»libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/065.xml0000644000175000017500000000001307477076020030137 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/029.xml0000644000175000017500000000001307477076020030137 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/066.xml0000644000175000017500000000002707477076020030145 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/067.xml0000644000175000017500000000002007477076020030137 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/068.xml0000644000175000017500000000002007477076020030140 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/069.xml0000644000175000017500000000001307477076020030143 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/110.xml0000644000175000017500000000002407477076020030130 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/111.xml0000644000175000017500000000002307477076020030130 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/030.xml0000644000175000017500000000001307477076020030127 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/031.xml0000644000175000017500000000001307477076020030130 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/112.xml0000644000175000017500000000002207477076020030130 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/032.xml0000644000175000017500000000001307477076020030131 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/113.xml0000644000175000017500000000001307477076020030131 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/033.xml0000644000175000017500000000001307477076020030132 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/114.xml0000644000175000017500000000002407477076020030134 0ustar twernertwerner&foo;libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/034.xml0000644000175000017500000000001307477076020030133 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/070.xml0000644000175000017500000000001307477076020030133 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/115.xml0000644000175000017500000000001407477076020030134 0ustar twernertwernervlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/035.xml0000644000175000017500000000001307477076020030134 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/071.xml0000644000175000017500000000001307477076020030134 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/116.xml0000644000175000017500000000002007477076020030132 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/036.xml0000644000175000017500000000002607477076020030141 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/072.xml0000644000175000017500000000001307477076020030135 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/117.xml0000644000175000017500000000001407477076020030136 0ustar twernertwerner]libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/037.xml0000644000175000017500000000001307477076020030136 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/073.xml0000644000175000017500000000001307477076020030136 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/118.xml0000644000175000017500000000001507477076020030140 0ustar twernertwerner]]libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/038.xml0000644000175000017500000000001307477076020030137 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/074.xml0000644000175000017500000000001307477076020030137 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/119.xml0000644000175000017500000000001307477076020030137 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/039.xml0000644000175000017500000000002607477076020030144 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/075.xml0000644000175000017500000000001307477076020030140 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/076.xml0000644000175000017500000000001307477076020030141 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/077.xml0000644000175000017500000000001307477076020030142 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/078.xml0000644000175000017500000000002107477076020030142 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/079.xml0000644000175000017500000000002107477076020030143 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/001.xml0000644000175000017500000000001307477076020030125 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/002.xml0000644000175000017500000000001307477076020030126 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/003.xml0000644000175000017500000000001307477076020030127 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/040.xml0000644000175000017500000000004507477076020030135 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/004.xml0000644000175000017500000000002307477076020030131 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/041.xml0000644000175000017500000000002207477076020030131 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/005.xml0000644000175000017500000000002307477076020030132 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/042.xml0000644000175000017500000000001407477076020030133 0ustar twernertwernerAlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/006.xml0000644000175000017500000000002307477076020030133 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/043.xml0000644000175000017500000000003007477076020030132 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/007.xml0000644000175000017500000000001407477076020030134 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/044.xml0000644000175000017500000000016407477076020030143 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/008.xml0000644000175000017500000000003707477076020030142 0ustar twernertwerner&<>"'libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/080.xml0000644000175000017500000000002107477076020030133 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/045.xml0000644000175000017500000000002307477076020030136 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/009.xml0000644000175000017500000000001407477076020030136 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/081.xml0000644000175000017500000000004707477076020030144 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/046.xml0000644000175000017500000000003307477076020030140 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/082.xml0000644000175000017500000000001307477076020030136 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/047.xml0000644000175000017500000000002207477076020030137 0ustar twernertwernerX Ylibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/083.xml0000644000175000017500000000001307477076020030137 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/048.xml0000644000175000017500000000001407477076020030141 0ustar twernertwerner]libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/084.xml0000644000175000017500000000001307477076020030140 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/049.xml0000644000175000017500000000001507477076020030143 0ustar twernertwernerÃúlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/085.xml0000644000175000017500000000001307477076020030141 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/086.xml0000644000175000017500000000001307477076020030142 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/087.xml0000644000175000017500000000002607477076020030147 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out/088.xml0000644000175000017500000000002607477076020030150 0ustar twernertwerner<foo>libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/089.xml0000644000175000017500000000014707477076020027346 0ustar twernertwerner ]> &e; libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/010.xml0000644000175000017500000000014207477076020027321 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/011.xml0000644000175000017500000000017307477076020027326 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/012.xml0000644000175000017500000000013707477076020027327 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/013.xml0000644000175000017500000000016707477076020027333 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/014.xml0000644000175000017500000000022107477076020027323 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/015.xml0000644000175000017500000000022107477076020027324 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/016.xml0000644000175000017500000000007607477076020027335 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/052.xml0000644000175000017500000000010007477076020027321 0ustar twernertwerner ]> ÉÇÇŸÅÀ» libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/017.xml0000644000175000017500000000011707477076020027332 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/053.xml0000644000175000017500000000013307477076020027330 0ustar twernertwerner"> ]> &e; libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/090.xml0000644000175000017500000000021707477076020027334 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/018.xml0000644000175000017500000000011107477076020027325 0ustar twernertwerner ]> ]]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/054.xml0000644000175000017500000000007607477076020027337 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/019.xml0000644000175000017500000000010607477076020027332 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/055.xml0000644000175000017500000000010507477076020027331 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/091.xml0000644000175000017500000000025607477076020027340 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/056.xml0000644000175000017500000000014407477076020027335 0ustar twernertwerner ]> A libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/092.xml0000644000175000017500000000013407477076020027334 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/057.xml0000644000175000017500000000006307477076020027336 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/093.xml0000644000175000017500000000007007477076020027334 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/058.xml0000644000175000017500000000015207477076020027336 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/094.xml0000644000175000017500000000015207477076020027336 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/059.xml0000644000175000017500000000033107477076020027336 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/095.xml0000644000175000017500000000020707477076020027340 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/096.xml0000644000175000017500000000013607477076020027342 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/086b.xml0000644000175000017500000000016707477076020027507 0ustar twernertwerner "> ]> &e1; libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/097.xml0000644000175000017500000000022507477076020027342 0ustar twernertwerner %e; ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/086c.xml0000644000175000017500000000022007477076020027476 0ustar twernertwerner "> ]> " libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/098.xml0000644000175000017500000000010207477076020027335 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/099.xml0000644000175000017500000000013707477076020027346 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/100.xml0000644000175000017500000000014007477076020027317 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/101.xml0000644000175000017500000000011407477076020027321 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/020.xml0000644000175000017500000000011107477076020027316 0ustar twernertwerner ]> ]]]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/102.xml0000644000175000017500000000014207477076020027323 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/021.xml0000644000175000017500000000011207477076020027320 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/103.xml0000644000175000017500000000010107477076020027317 0ustar twernertwerner ]> <doc> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/022.xml0000644000175000017500000000011407477076020027323 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/104.xml0000644000175000017500000000014007477076020027323 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/023.xml0000644000175000017500000000011207477076020027322 0ustar twernertwerner ]> &e; libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/105.xml0000644000175000017500000000014307477076020027327 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/024.xml0000644000175000017500000000015607477076020027333 0ustar twernertwerner "> ]> &e; libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/060.xml0000644000175000017500000000007707477076020027335 0ustar twernertwerner ]> X Y libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/106.xml0000644000175000017500000000014407477076020027331 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/025.xml0000644000175000017500000000013707477076020027333 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/061.xml0000644000175000017500000000007607477076020027335 0ustar twernertwerner ]> £ libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/107.xml0000644000175000017500000000014407477076020027332 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/026.xml0000644000175000017500000000013307477076020027330 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/062.xml0000644000175000017500000000012307477076020027327 0ustar twernertwerner ]> เจม€¹¬€ î libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/108.xml0000644000175000017500000000016207477076020027333 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/027.xml0000644000175000017500000000013107477076020027327 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/043b.xml0000644000175000017500000000014607477076020027475 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/109.xml0000644000175000017500000000013507477076020027334 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/028.xml0000644000175000017500000000011607477076020027333 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/064.xml0000644000175000017500000000011307477076020027330 0ustar twernertwerner ]> 𐀀􏿽 libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/029.xml0000644000175000017500000000011607477076020027334 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/065.xml0000644000175000017500000000011407477076020027332 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/066.xml0000644000175000017500000000022407477076020027335 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/067.xml0000644000175000017500000000007507477076020027342 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/068.xml0000644000175000017500000000011707477076020027340 0ustar twernertwerner ]> &e; libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/069.xml0000644000175000017500000000013007477076020027334 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/110.xml0000644000175000017500000000017307477076020027326 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/030.xml0000644000175000017500000000012007477076020027317 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/111.xml0000644000175000017500000000016607477076020027331 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/031.xml0000644000175000017500000000013707477076020027330 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/112.xml0000644000175000017500000000012407477076020027324 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/032.xml0000644000175000017500000000013707477076020027331 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/113.xml0000644000175000017500000000012607477076020027327 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/033.xml0000644000175000017500000000016007477076020027326 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/114.xml0000644000175000017500000000013307477076020027326 0ustar twernertwerner "> ]> &e; libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/034.xml0000644000175000017500000000006307477076020027331 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/070.xml0000644000175000017500000000011407477076020027326 0ustar twernertwerner"> %e; ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/115.xml0000644000175000017500000000014107477076020027326 0ustar twernertwerner ]> &e1; libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/035.xml0000644000175000017500000000006407477076020027333 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/024b.xml0000644000175000017500000000015207477076020027471 0ustar twernertwerner "> ]> &e; libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/071.xml0000644000175000017500000000012507477076020027331 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/116.xml0000644000175000017500000000010507477076020027327 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/036.xml0000644000175000017500000000010407477076020027327 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/008a.xml0000644000175000017500000000016607477076020027477 0ustar twernertwerner ]> &<>"' &myent; libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/072.xml0000644000175000017500000000013007477076020027326 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/117.xml0000644000175000017500000000012107477076020027326 0ustar twernertwerner ]> ] libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/037.xml0000644000175000017500000000011207477076020027327 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/073.xml0000644000175000017500000000013107477076020027330 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/118.xml0000644000175000017500000000012207477076020027330 0ustar twernertwerner ]> ] libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/038.xml0000644000175000017500000000011207477076020027330 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/074.xml0000644000175000017500000000013107477076020027331 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/119.xml0000644000175000017500000000007607477076020027341 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/039.xml0000644000175000017500000000010407477076020027332 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/075.xml0000644000175000017500000000013307477076020027334 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/076.xml0000644000175000017500000000027107477076020027340 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/077.xml0000644000175000017500000000013007477076020027333 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/078.xml0000644000175000017500000000013707477076020027343 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/out.out0000644000175000017500000000352107477076020027643 0ustar twernertwerner---------START--------- 012.xml The document is not parsed, seems to have problem --------- END -------- ---------START--------- 024.xml The document is not parsed, seems to have problem --------- END -------- ---------START--------- 043.xml The document is not parsed, seems to have problem --------- END -------- ---------START--------- 049.xml The document is not parsed, seems to have problem --------- END -------- ---------START--------- 050.xml The document is not parsed, seems to have problem --------- END -------- ---------START--------- 051.xml The document is not parsed, seems to have problem --------- END -------- ---------START--------- 058.xml The document is not parsed, seems to have problem --------- END -------- ---------START--------- 063.xml The document is not parsed, seems to have problem --------- END -------- ---------START--------- 069.xml Assertion failed: 0, file /home/mdasari/dasxml1/src/esxml/common/Parser.cpp, line 2207 Abort - core dumped --------- END -------- ---------START--------- 076.xml The document is not parsed, seems to have problem --------- END -------- ---------START--------- 087.xml Bus Error - core dumped --------- END -------- ---------START--------- 090.xml The document is not parsed, seems to have problem --------- END -------- ---------START--------- 091.xml Assertion failed: 0, file /home/mdasari/dasxml1/src/esxml/common/Parser.cpp, line 2207 Abort - core dumped --------- END -------- ---------START--------- 095.xml The document is not parsed, seems to have problem --------- END -------- ---------START--------- 096.xml The document is not parsed, seems to have problem --------- END -------- ---------START--------- 111.xml The document is not parsed, seems to have problem --------- END -------- ---------START--------- 113.xml The document is not parsed, seems to have problem --------- END -------- libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/079.xml0000644000175000017500000000014007477076020027336 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/001.xml0000644000175000017500000000007007477076020027321 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/002.xml0000644000175000017500000000007107477076020027323 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/003.xml0000644000175000017500000000007107477076020027324 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/040.xml0000644000175000017500000000017007477076020027325 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/004.xml0000644000175000017500000000014107477076020027323 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/041.xml0000644000175000017500000000014407477076020027327 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/005.xml0000644000175000017500000000014307477076020027326 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/042.xml0000644000175000017500000000013607477076020027331 0ustar twernertwerner ]> A libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/006.xml0000644000175000017500000000014107477076020027325 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/097.ent0000644000175000017500000000004107477076020027324 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/043.xml0000644000175000017500000000014607477076020027333 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/007.xml0000644000175000017500000000007507477076020027334 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/044.xml0000644000175000017500000000026107477076020027332 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/008.xml0000644000175000017500000000012107477076020027325 0ustar twernertwerner ]> &<>"' libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/080.xml0000644000175000017500000000013207477076020027327 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/045.xml0000644000175000017500000000016207477076020027333 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/009.xml0000644000175000017500000000007607477076020027337 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/081.xml0000644000175000017500000000020507477076020027331 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/046.xml0000644000175000017500000000016207477076020027334 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/082.xml0000644000175000017500000000012507477076020027333 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/047.xml0000644000175000017500000000007307477076020027336 0ustar twernertwerner ]> X Y libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/083.xml0000644000175000017500000000014007477076020027331 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/048.xml0000644000175000017500000000007107477076020027335 0ustar twernertwerner ]> ] libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/084.xml0000644000175000017500000000006507477076020027340 0ustar twernertwerner]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/085.xml0000644000175000017500000000016007477076020027335 0ustar twernertwerner "> ]> &ename; libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/086.xml0000644000175000017500000000013607477076020027341 0ustar twernertwerner "> ]> &e; libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/087.xml0000644000175000017500000000014507477076020027342 0ustar twernertwerner ]> &e; libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/valid/sa/088.xml0000644000175000017500000000012207477076020027336 0ustar twernertwerner "> ]> &e; libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/canonxml.html0000644000175000017500000000301407477076020027303 0ustar twernertwerner Canonical XML

Canonical XML

This document defines a subset of XML called canonical XML. The intended use of canonical XML is in testing XML processors, as a representation of the result of parsing an XML document.

Every well-formed XML document has a unique structurally equivalent canonical XML document. Two structurally equivalent XML documents have a byte-for-byte identical canonical XML document. Canonicalizing an XML document requires only information that an XML processor is required to make available to an application.

A canonical XML document conforms to the following grammar:

CanonXML    ::= Pi* element Pi*
element     ::= Stag (Datachar | Pi | element)* Etag
Stag        ::= '<'  Name Atts '>'
Etag        ::= '</' Name '>'
Pi          ::= '<?' Name ' ' (((Char - S) Char*)? - (Char* '?>' Char*)) '?>'
Atts        ::= (' ' Name '=' '"' Datachar* '"')*
Datachar    ::= '&amp;' | '&lt;' | '&gt;' | '&quot;'
                 | '&#9;'| '&#10;'| '&#13;'
                 | (Char - ('&' | '<' | '>' | '"' | #x9 | #xA | #xD))
Name        ::= (see XML spec)
Char        ::= (see XML spec)
S           ::= (see XML spec)

Attributes are in lexicographical order (in Unicode bit order).

A canonical XML document is encoded in UTF-8.

Ignorable white space is considered significant and is treated equivalently to data.

James Clark
libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/xmltest.xml0000644000175000017500000024542707477076020027040 0ustar twernertwerner Attribute values must start with attribute names, not "?". Names may not start with "."; it's not a Letter. Processing Instruction target name is required. SGML-ism: processing instructions end in '?>' not '>'. Processing instructions end in '?>' not '?'. XML comments may not contain "--" General entity references have no whitespace after the entity name and before the semicolon. Entity references must include names, which don't begin with '.' (it's not a Letter or other name start character). Character references may have only decimal or numeric strings. Ampersand may only appear as part of a general entity reference. SGML-ism: attribute values must be explicitly assigned a value, it can't act as a boolean toggle. SGML-ism: attribute values must be quoted in all cases. The quotes on both ends of an attribute value must match. Attribute values may not contain literal '<' characters. Attribute values need a value, not just an equals sign. Attribute values need an associated name. CDATA sections need a terminating ']]>'. CDATA sections begin with a literal '<![CDATA[', no space. End tags may not be abbreviated as '</>'. Attribute values may not contain literal '&' characters except as part of an entity reference. Attribute values may not contain literal '&' characters except as part of an entity reference. Character references end with semicolons, always! Digits are not valid name start characters. Digits are not valid name start characters. Text may not contain a literal ']]>' sequence. Text may not contain a literal ']]>' sequence. Comments must be terminated with "-->". Processing instructions must end with '?>'. Text may not contain a literal ']]>' sequence. A form feed is not a legal XML character. A form feed is not a legal XML character. A form feed is not a legal XML character. An ESC (octal 033) is not a legal XML character. A form feed is not a legal XML character. The '<' character is a markup delimiter and must start an element, CDATA section, PI, or comment. Text may not appear after the root element. Character references may not appear after the root element. Tests the "Unique Att Spec" WF constraint by providing multiple values for an attribute. Tests the Element Type Match WFC - end tag name must match start tag name. Provides two document elements. Provides two document elements. Invalid End Tag Provides #PCDATA text after the document element. Provides two document elements. Invalid Empty Element Tag This start (or empty element) tag was not terminated correctly. Invalid empty element tag invalid whitespace Provides a CDATA section after the roor element. Missing start tag Empty document, with no root element. CDATA is invalid at top level of document. Invalid character reference. End tag does not match start tag. PUBLIC requires two literals. Invalid Document Type Definition format. Invalid Document Type Definition format - misplaced comment. This isn't SGML; comments can't exist in declarations. Invalid character , in ATTLIST enumeration String literal must be in quotes. Invalid type NAME defined in ATTLIST. External entity declarations require whitespace between public and system IDs. Entity declarations need space after the entity name. Conditional sections may only appear in the external DTD subset. Space is required between attribute type and default values in <!ATTLIST...> declarations. Space is required between attribute name and type in <!ATTLIST...> declarations. Required whitespace is missing. Space is required between attribute type and default values in <!ATTLIST...> declarations. Space is required between NOTATION keyword and list of enumerated choices in <!ATTLIST...> declarations. Space is required before an NDATA entity annotation. XML comments may not contain "--" ENTITY can't reference itself directly or indirectly. Undefined ENTITY foo. Undefined ENTITY f. Internal general parsed entities are only well formed if they match the "content" production. ENTITY can't reference itself directly or indirectly. Undefined ENTITY foo. Undefined ENTITY bar. Undefined ENTITY foo. ENTITY can't reference itself directly or indirectly. ENTITY can't reference itself directly or indirectly. This tests the No External Entity References WFC, since the entity is referred to within an attribute. This tests the No External Entity References WFC, since the entity is referred to within an attribute. Undefined NOTATION n. Tests the Parsed Entity WFC by referring to an unparsed entity. (This precedes the error of not declaring that entity's notation, which may be detected any time before the DTD parsing is completed.) Public IDs may not contain "[". Public IDs may not contain "[". Public IDs may not contain "[". Attribute values are terminated by literal quote characters, and any entity expansion is done afterwards. Parameter entities "are" always parsed; NDATA annotations are not permitted. Attributes may not contain a literal "<" character; this one has one because of reference expansion. Parameter entities "are" always parsed; NDATA annotations are not permitted. The replacement text of this entity has an illegal reference, because the character reference is expanded immediately. Hexadecimal character references may not use the uppercase 'X'. Prolog VERSION must be lowercase. VersionInfo must come before EncodingDecl. Space is required before the standalone declaration. Both quotes surrounding VersionNum must be the same. Only one "version=..." string may appear in an XML declaration. Only three pseudo-attributes are in the XML declaration, and "valid=..." is not one of them. Only "yes" and "no" are permitted as values of "standalone". Space is not permitted in an encoding name. Provides an illegal XML version number; spaces are illegal. End-tag required for element foo. Internal general parsed entities are only well formed if they match the "content" production. Invalid placement of CDATA section. Invalid placement of entity declaration. Invalid document type declaration. CDATA alone is invalid. No space in '<![CDATA['. Tags invalid within EntityDecl. Entity reference must be in content of element. Entiry reference must be in content of element not Start-tag. CDATA sections start '<![CDATA[', not '<!cdata['. Parameter entity values must use valid reference syntax; this reference is malformed. General entity values must use valid reference syntax; this reference is malformed. The replacement text of this entity is an illegal character reference, which must be rejected when it is parsed in the context of an attribute value. Internal general parsed entities are only well formed if they match the "content" production. This is a partial character reference, not a full one. Internal general parsed entities are only well formed if they match the "content" production. This is a partial character reference, not a full one. Entity reference expansion is not recursive. Internal general parsed entities are only well formed if they match the "content" production. This is a partial character reference, not a full one. Character references are expanded in the replacement text of an internal entity, which is then parsed as usual. Accordingly, & must be doubly quoted - encoded either as &amp; or as &#38;#38;. A name of an ENTITY was started with an invalid character. Invalid syntax mixed connectors are used. Invalid syntax mismatched parenthesis. Invalid format of Mixed-content declaration. Invalid syntax extra set of parenthesis not necessary. Invalid syntax Mixed-content must be defined as zero or more. Invalid syntax Mixed-content must be defined as zero or more. Invalid CDATA syntax. Invalid syntax for Element Type Declaration. Invalid syntax for Element Type Declaration. Invalid syntax for Element Type Declaration. Invalid syntax mixed connectors used. Illegal whitespace before optional character causes syntax error. Illegal whitespace before optional character causes syntax error. Invalid character used as connector. Tag omission is invalid in XML. Space is required before a content model. Invalid syntax for content particle. The element-content model should not be empty. Character '&#x309a;' is a CombiningChar, not a Letter, and so may not begin a name. Character #x0E5C is not legal in XML names. Character #x0000 is not legal anywhere in an XML document. Character #x001F is not legal anywhere in an XML document. Character #xFFFF is not legal anywhere in an XML document. Character #xD800 is not legal anywhere in an XML document. (If it appeared in a UTF-16 surrogate pair, it'd represent half of a UCS-4 character and so wouldn't really be in the document.) Character references must also refer to legal XML characters; #x00110000 is one more than the largest legal character. XML Declaration may not be preceded by whitespace. XML Declaration may not be preceded by comments or whitespace. XML Declaration may not be within a DTD. XML declarations may not be within element content. XML declarations may not follow document content. XML declarations must include the "version=..." string. Text declarations may not begin internal parsed entities; they may only appear at the beginning of external parsed (parameter or general) entities. '<?XML ...?>' is neither an XML declaration nor a legal processing instruction target name. '<?xmL ...?>' is neither an XML declaration nor a legal processing instruction target name. '<?xMl ...?>' is neither an XML declaration nor a legal processing instruction target name. '<?xmL ...?>' is not a legal processing instruction target name. SGML-ism: "#NOTATION gif" can't have attributes. Uses '&' unquoted in an entity declaration, which is illegal syntax for an entity reference. Violates the PEs in Internal Subset WFC by using a PE reference within a declaration. Violates the PEs in Internal Subset WFC by using a PE reference within a declaration. Violates the PEs in Internal Subset WFC by using a PE reference within a declaration. Invalid placement of Parameter entity reference. Invalid placement of Parameter entity reference. Parameter entity declarations must have a space before the '%'. Character FFFF is not legal anywhere in an XML document. Character FFFE is not legal anywhere in an XML document. An unpaired surrogate (D800) is not legal anywhere in an XML document. An unpaired surrogate (DC00) is not legal anywhere in an XML document. Four byte UTF-8 encodings can encode UCS-4 characters which are beyond the range of legal XML characters (and can't be expressed in Unicode surrogate pairs). This document holds such a character. Character FFFF is not legal anywhere in an XML document. Character FFFF is not legal anywhere in an XML document. Character FFFF is not legal anywhere in an XML document. Character FFFF is not legal anywhere in an XML document. Character FFFF is not legal anywhere in an XML document. Start tags must have matching end tags. Character FFFF is not legal anywhere in an XML document. Invalid syntax matching double quote is missing. Invalid syntax matching double quote is missing. The Entity Declared WFC requires entities to be declared before they are used in an attribute list declaration. Internal parsed entities must match the content production to be well formed. Internal parsed entities must match the content production to be well formed. Mixed content declarations may not include content particles. In mixed content models, element names must not be parenthesized. Tests the Entity Declared WFC. Note: a nonvalidating parser is permitted not to report this WFC violation, since it would need to read an external parameter entity to distinguish it from a violation of the Standalone Declaration VC. Whitespace is required between attribute/value pairs. Conditional sections must be properly terminated ("]>" used instead of "]]>"). Processing instruction target names may not be "XML" in any combination of cases. Conditional sections must be properly terminated ("]]>" omitted). Conditional sections must be properly terminated ("]]>" omitted). Tests the Entity Declared VC by referring to an undefined parameter entity within an external entity. Conditional sections need a '[' after the INCLUDE or IGNORE. A <!DOCTYPE ...> declaration may not begin any external entity; it's only found once, in the document entity. In DTDs, the '%' character must be part of a parameter entity reference. Tests the No Recursion WFC by having an external general entity be self-recursive. External entities have "text declarations", which do not permit the "standalone=..." attribute that's allowed in XML declarations. Only one text declaration is permitted; a second one looks like an illegal processing instruction (target names of "xml" in any case are not allowed). Tests the "Proper Declaration/PE Nesting" validity constraint by fragmenting a comment between two parameter entities. Tests the "Proper Group/PE Nesting" validity constraint by fragmenting a content model between two parameter entities. Tests the "Proper Declaration/PE Nesting" validity constraint by fragmenting an entity declaration between two parameter entities. Tests the "Proper Declaration/PE Nesting" validity constraint by fragmenting an entity declaration between three parameter entities. Tests the "Proper Declaration/PE Nesting" validity constraint by fragmenting an entity declaration between two parameter entities. Tests the "Proper Declaration/PE Nesting" validity constraint by fragmenting an entity declaration between two parameter entities. Test demonstrates an Element Type Declaration with Mixed Content. Test demonstrates that whitespace is permitted after the tag name in a Start-tag. Test demonstrates that whitespace is permitted after the tag name in an End-tag. Test demonstrates a valid attribute specification within a Start-tag. Test demonstrates a valid attribute specification within a Start-tag that contains whitespace on both sides of the equal sign. Test demonstrates that the AttValue within a Start-tag can use a single quote as a delimter. Test demonstrates numeric character references can be used for element content. Test demonstrates character references can be used for element content. Test demonstrates that PubidChar can be used for element content. Test demonstrates that whitespace is valid after the Attribute in a Start-tag. Test demonstrates mutliple Attibutes within the Start-tag. Uses a legal XML 1.0 name consisting of a single colon character (disallowed by the latest XML Namespaces draft). Test demonstrates that the Attribute in a Start-tag can consist of numerals along with special characters. Test demonstrates that all lower case letters are valid for the Attribute in a Start-tag. Test demonstrates that all upper case letters are valid for the Attribute in a Start-tag. Test demonstrates that Processing Instructions are valid element content. Test demonstrates that Processing Instructions are valid element content and there can be more than one. Test demonstrates that CDATA sections are valid element content. Test demonstrates that CDATA sections are valid element content and that ampersands may occur in their literal form. Test demonstractes that CDATA sections are valid element content and that everyting between the CDStart and CDEnd is recognized as character data not markup. Test demonstrates that comments are valid element content. Test demonstrates that comments are valid element content and that all characters before the double-hypen right angle combination are considered part of thecomment. Test demonstrates that Entity References are valid element content. Test demonstrates that Entity References are valid element content and also demonstrates a valid Entity Declaration. Test demonstrates an Element Type Declaration and that the contentspec can be of mixed content. Test demonstrates an Element Type Declaration and that EMPTY is a valid contentspec. Test demonstrates an Element Type Declaration and that ANY is a valid contenspec. Test demonstrates a valid prolog that uses double quotes as delimeters around the VersionNum. Test demonstrates a valid prolog that uses single quotes as delimters around the VersionNum. Test demonstrates a valid prolog that contains whitespace on both sides of the equal sign in the VersionInfo. Test demonstrates a valid EncodingDecl within the prolog. Test demonstrates a valid SDDecl within the prolog. Test demonstrates that both a EncodingDecl and SDDecl are valid within the prolog. Test demonstrates the correct syntax for an Empty element tag. Test demonstrates that whitespace is permissible after the name in an Empty element tag. Test demonstrates a valid processing instruction. Test demonstrates a valid comment and that it may appear anywhere in the document including at the end. Test demonstrates a valid comment and that it may appear anywhere in the document including the beginning. Test demonstrates a valid processing instruction and that it may appear at the beginning of the document. Test demonstrates an Attribute List declaration that uses a StringType as the AttType. Test demonstrates an Attribute List declaration that uses a StringType as the AttType and also expands the CDATA attribute with a character reference. Test demonstrates an Attribute List declaration that uses a StringType as the AttType and also expands the CDATA attribute with a character reference. The test also shows that the leading zeros in the character reference are ignored. An element's attributes may be declared before its content model; and attribute values may contain newlines. Test demonstrates that the empty-element tag must be use for an elements that are declared EMPTY. Tests whether more than one definition can be provided for the same attribute of a given element type with the first declaration being binding. Test demonstrates that when more than one AttlistDecl is provided for a given element type, the contents of all those provided are merged. Test demonstrates that extra whitespace is normalized into single space character. Test demonstrates that character data is valid element content. Test demonstrates that characters outside of normal ascii range can be used as element content. Test demonstrates that characters outside of normal ascii range can be used as element content. The document is encoded in UTF-16 and uses some name characters well outside of the normal ASCII range. The document is encoded in UTF-8 and the text inside the root element uses two non-ASCII characters, encoded in UTF-8 and each of which expands to a Unicode surrogate pair. Tests inclusion of a well-formed internal entity, which holds an element required by the content model. Test demonstrates that extra whitespace within Start-tags and End-tags are nomalized into single spaces. Test demonstrates that extra whitespace within a processing instruction willnormalized into s single space character. Test demonstrates an Attribute List declaration that uses a StringType as the AttType and also expands the CDATA attribute with a character reference. The test also shows that the leading zeros in the character reference are ignored. Test demonstrates an element content model whose element can occur zero or more times. Test demonstrates that extra whitespace be normalized into a single space character in an attribute of type NMTOKENS. Test demonstrates an Element Type Declaration that uses the contentspec of EMPTY. The element cannot have any contents and must always appear as an empty element in the document. The test also shows an Attribute-list declaration with multiple AttDef's. Test demonstrates the use of decimal Character References within element content. Test demonstrates the use of decimal Character References within element content. Test demonstrates the use of hexadecimal Character References within element. The document is encoded in UTF-8 and the name of the root element type uses non-ASCII characters. Tests in-line handling of two legal character references, which each expand to a Unicode surrogate pair. Tests ability to define an internal entity which can't legally be expanded (contains an unquoted <). Expands a CDATA attribute with a character reference. Test demonstrates the use of decimal character references within element content. Tests definition of an entity holding a carriage return character reference, which must be normalized to a newline before being reported to the application. Verifies that an XML parser will parse a NOTATION declaration; the output phase of this test ensures that it's reported to the application. Verifies that internal parameter entities are correctly expanded within the internal subset. Test demonstrates that an AttlistDecl can use ID as the TokenizedType within the Attribute type. The test also shows that IMPLIED is a valid DefaultDecl. Test demonstrates that an AttlistDecl can use IDREF as the TokenizedType within the Attribute type. The test also shows that IMPLIED is a valid DefaultDecl. Test demonstrates that an AttlistDecl can use IDREFS as the TokenizedType within the Attribute type. The test also shows that IMPLIED is a valid DefaultDecl. Test demonstrates that an AttlistDecl can use ENTITY as the TokenizedType within the Attribute type. The test also shows that IMPLIED is a valid DefaultDecl. Test demonstrates that an AttlistDecl can use ENTITIES as the TokenizedType within the Attribute type. The test also shows that IMPLIED is a valid DefaultDecl. Verifies that an XML parser will parse a NOTATION attribute; the output phase of this test ensures that both notations are reported to the application. Test demonstrates that an AttlistDecl can use an EnumeratedType within the Attribute type. The test also shows that IMPLIED is a valid DefaultDecl. Test demonstrates that an AttlistDecl can use an StringType of CDATA within the Attribute type. The test also shows that REQUIRED is a valid DefaultDecl. Test demonstrates that an AttlistDecl can use an StringType of CDATA within the Attribute type. The test also shows that FIXED is a valid DefaultDecl and that a value can be given to the attribute in the Start-tag as well as the AttListDecl. Test demonstrates that an AttlistDecl can use an StringType of CDATA within the Attribute type. The test also shows that FIXED is a valid DefaultDecl and that an value can be given to the attribute. Test demonstrates the use of the optional character following a name or list to govern the number of times an element or content particles in the list occur. Tests that an external PE may be defined (but not referenced). Tests that an external PE may be defined (but not referenced). Test demonstrates that although whitespace can be used to set apart markup for greater readability it is not necessary. Parameter and General entities use different namespaces, so there can be an entity of each type with a given name. Tests whether entities may be declared more than once, with the first declaration being the binding one. Tests whether character references in internal entities are expanded early enough, by relying on correct handling to make the entity be well formed. Tests whether entity references in internal entities are expanded late enough, by relying on correct handling to make the expanded text be valid. (If it's expanded too early, the entity will parse as an element that's not valid in that context.) Tests entity expansion of three legal character references, which each expand to a Unicode surrogate pair. Verifies that an XML parser will parse a NOTATION attribute; the output phase of this test ensures that the notation is reported to the application. Verifies that an XML parser will parse an ENTITY attribute; the output phase of this test ensures that the notation is reported to the application, and for validating parsers it further tests that the entity is so reported. Test demostrates that extra whitespace is normalized into a single space character. Test demonstrates that extra whitespace is not intended for inclusion in the delivered version of the document. This refers to an undefined parameter entity reference within a markup declaration in the internal DTD subset, violating the PEs in Internal Subset WFC. Basically an output test, this requires extra whitespace to be normalized into a single space character in an attribute of type NMTOKENS. Test demonstrates that extra whitespace is normalized into a single space character in an attribute of type NMTOKENS. Basically an output test, this tests whether an externally defined attribute declaration (with a default) takes proper precedence over a subsequent internal declaration. Test demonstrates that extra whitespace within a processing instruction is converted into a single space character. Test demonstrates the name of the encoding can be composed of lowercase characters. Makes sure that PUBLIC identifiers may have some strange characters. NOTE: The XML editors have said that the XML specification errata will specify that parameter entity expansion does not occur in PUBLIC identifiers, so that the '%' character will not flag a malformed parameter entity reference. This tests whether entity expansion is (incorrectly) done while processing entity declarations; if it is, the entity value literal will terminate prematurely. Test demonstrates that a CDATA attribute can pass a double quote as its value. Test demonstrates that an attribute can pass a less than sign as its value. Test demonstrates that extra whitespace within an Attribute of a Start-tag is normalized to a single space character. Basically an output test, this requires a CDATA attribute with a tab character to be passed through as one space. Basically an output test, this requires a CDATA attribute with a newline character to be passed through as one space. Basically an output test, this requires a CDATA attribute with a return character to be passed through as one space. This tests normalization of end-of-line characters (CRLF) within entities to LF, primarily as an output test. Test demonstrates that an attribute can have a null value. Basically an output test, this requires that a CDATA attribute with a CRLF be normalized to one space. Character references expanding to spaces doesn't affect treatment of attributes. Test demonstrates shows the use of content particles within the element content. Test demonstrates that it is not an error to have attributes declared for an element not itself declared. Test demonstrates that all text within a valid CDATA section is considered text and not recognized as markup. Test demonstrates that an entity reference is processed by recursively processing the replacement text of the entity. Test demonstrates that a line break within CDATA will be normalized. Test demonstrates that entity expansion is done while processing entity declarations. Test demonstrates that entity expansion is done while processing entity declarations. Comments may contain any legal XML characters; only the string "--" is disallowed. Test demonstrates the use of an ExternalID within a document type definition. Test demonstrates the use of an ExternalID within a document type definition. Test demonstrates the expansion of an external parameter entity that declares an attribute. Expands an external parameter entity in two different ways, with one of them declaring an attribute. Test demonstrates the expansion of an external parameter entity that declares an attribute. Test demonstrates that when more than one definition is provided for the same attribute of a given element type only the first declaration is binding. Test demonstrates the use of an Attribute list declaration within an external entity. Test demonstrates that an external identifier may include a public identifier. Test demonstrates that an external identifier may include a public identifier. Test demonstrates that when more that one definition is provided for the same attribute of a given element type only the first declaration is binding. Test demonstrates a parameter entity declaration whose parameter entity definition is an ExternalID. Test demonstrates an enternal parsed entity that begins with a text declaration. Test demonstrates the use of the conditional section INCLUDE that will include its contents as part of the DTD. Test demonstrates the use of the conditional section INCLUDE that will include its contents as part of the DTD. The keyword is a parameter-entity reference. Test demonstrates the use of the conditonal section IGNORE the will ignore its content from being part of the DTD. The keyword is a parameter-entity reference. Test demonstrates the use of the conditional section INCLUDE that will include its contents as part of the DTD. The keyword is a parameter-entity reference. Test demonstrates a parameter entity declaration that contains an attribute list declaration. Test demonstrates an EnternalID whose contents contain an parameter entity declaration and a attribute list definition. Test demonstrates that a parameter entity will be expanded with spaces on either side. Parameter entities expand with spaces on either side. Test demonstrates a parameter entity declaration that contains a partial attribute list declaration. Test demonstrates the use of a parameter-entity reference as a keyword of a conditional section. The parameter entity must be replaced by its content before the processor decides whether to include the conditional section. Test demonstrates the use of a parameter entity reference within an attribute list declaration. Constructs an <!ATTLIST...> declaration from several PEs. Test demonstrates that when more that one definition is provided for the same entity only the first declaration is binding. Test demonstrates that when more that one definition is provided for the same attribute of a given element type only the first declaration is binding. Test demonstrates a parameter entity reference whose value is NULL. Test demonstrates the use of the conditional section INCLUDE that will include its contents. Test demonstrates the use of the conditonal section IGNORE the will ignore its content from being used. Test demonstrates the use of the conditonal section IGNORE the will ignore its content from being used. Expands a general entity which contains a CDATA section with what looks like a markup declaration (but is just text since it's in a CDATA section). A combination of carriage return line feed in an external entity must be normalized to a single newline. A carriage return (also CRLF) in an external entity must be normalized to a single newline. Test demonstrates that the content of an element can be empty. In this case the external entity is an empty file. A carriage return (also CRLF) in an external entity must be normalized to a single newline. Test demonstrates the use of optional character and content particles within an element content. The test also show the use of external entity. Test demonstrates the use of optional character and content particles within mixed element content. The test also shows the use of an external entity and that a carriage control line feed in an external entity must be normalized to a single newline. Test demonstrates the use of external entity and how replacement text is retrieved and processed. Test demonstrates the use of external entity and how replacement text is retrieved and processed. Also tests the use of an EncodingDecl of UTF-16. A carriage return (also CRLF) in an external entity must be normalized to a single newline. Test demonstrates the use of a public identifier with and external entity. The test also show that a carriage control line feed combination in an external entity must be normalized to a single newline. Test demonstrates both internal and external entities and that processing of entity references may be required to produce the correct replacement text. Test demonstrates that whitespace is handled by adding a single whitespace to the normalized value in the attribute list. Test demonstrates use of characters outside of normal ASCII range. libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/readme.html0000644000175000017500000000354407477076020026731 0ustar twernertwerner XML Test Cases

XML Test Cases version 1998-11-18

Copyright (C) 1998 James Clark. All rights reserved. Permission is granted to copy and modify this collection in any way for internal use within a company or organization. Permission is granted to redistribute the file xmltest.zip containing this collection to third parties provided that no modifications of any kind are made to this file. Note that permission to distribute the collection in any other form is not granted.

The collection is structured into three directories:

not-wf
this contains cases that are not well-formed XML documents
valid
this contains cases that are valid XML documents
invalid
this contains cases that are well-formed XML documents but are not valid XML documents

The not-wf and valid directories each have three subdirectories:

sa
this contains cases that are standalone (as defined in XML) and do not have references to external general entities
ext-sa
this contains case that are standalone and have references to external general entities
not-sa
this contains cases that are not standalone

In each directory, files with a .xml extension are the XML document test cases, and files with a .ent extension are external entities referenced by the test cases.

Within the valid directory, each of these three subdirectories has an out subdirectory which contains an equivalent canonical XML document for each of the cases.

Bug reports and contributions of new test cases are welcome.

James Clark
libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/invalid/0000755000175000017500000000000011111351370026206 5ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/invalid/001.xml0000644000175000017500000000005407477076020027247 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/invalid/002.xml0000644000175000017500000000005407477076020027250 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/invalid/003.xml0000644000175000017500000000005407477076020027251 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/invalid/004.xml0000644000175000017500000000005407477076020027252 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/invalid/005.xml0000644000175000017500000000005407477076020027253 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/invalid/006.xml0000644000175000017500000000005407477076020027254 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/invalid/001.ent0000644000175000017500000000006207477076020027234 0ustar twernertwerner %e; --> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/invalid/002.ent0000644000175000017500000000005507477076020027237 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/invalid/003.ent0000644000175000017500000000005607477076020027241 0ustar twernertwerner %e; doc (#PCDATA)> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/invalid/004.ent0000644000175000017500000000010707477076020027237 0ustar twernertwerner "> %e1; doc (#PCDATA) %e2; libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/invalid/005.ent0000644000175000017500000000005607477076020027243 0ustar twernertwerner"> "> ]> &e; libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/ext-sa/002.xml0000644000175000017500000000013007477076020030230 0ustar twernertwerner ]> &e; libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/ext-sa/003.xml0000644000175000017500000000013007477076020030231 0ustar twernertwerner ]> &e; libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/ext-sa/001.ent0000644000175000017500000000000307477076020030214 0ustar twernertwerner&e;libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/ext-sa/002.ent0000644000175000017500000000005507477076020030224 0ustar twernertwerner data libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/ext-sa/003.ent0000644000175000017500000000006007477076020030221 0ustar twernertwerner data libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/not-sa/0000755000175000017500000000000011111351370027173 5ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/not-sa/001.xml0000644000175000017500000000005407477076020030234 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/not-sa/002.xml0000644000175000017500000000016207477076020030235 0ustar twernertwerner "> %e; ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/not-sa/003.xml0000644000175000017500000000005407477076020030236 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/not-sa/004.xml0000644000175000017500000000005407477076020030237 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/not-sa/005.xml0000644000175000017500000000005407477076020030240 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/not-sa/006.xml0000644000175000017500000000005407477076020030241 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/not-sa/001.ent0000644000175000017500000000005207477076020030220 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/not-sa/007.xml0000644000175000017500000000005407477076020030242 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/not-sa/008.xml0000644000175000017500000000005407477076020030243 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/not-sa/003.ent0000644000175000017500000000004607477076020030225 0ustar twernertwerner %e; libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/not-sa/006.ent0000644000175000017500000000005007477076020030223 0ustar twernertwerner ]]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/not-sa/007.ent0000644000175000017500000000005407477076020030230 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/not-sa/008.ent0000644000175000017500000000004607477076020030232 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/0000755000175000017500000000000011111351371026376 5ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/011.xml0000644000175000017500000000001707477076020027436 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/013.xml0000644000175000017500000000002407477076020027436 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/135.xml0000644000175000017500000000006707477076020027452 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/091.xml0000644000175000017500000000014107477076020027444 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/019.xml0000644000175000017500000000001107477076020027440 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/172.xml0000644000175000017500000000002707477076020027447 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/056.xml0000644000175000017500000000005607477076020027452 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/137.xml0000644000175000017500000000006707477076020027454 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/174.xml0000644000175000017500000000003307477076020027446 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/093.xml0000644000175000017500000000002207477076020027444 0ustar twernertwernerX libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/139.xml0000644000175000017500000000006107477076020027450 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/058.xml0000644000175000017500000000013507477076020027452 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/176.xml0000644000175000017500000000006107477076020027451 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/095.xml0000644000175000017500000000006307477076020027453 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/178.xml0000644000175000017500000000014107477076020027452 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/099.xml0000644000175000017500000000005507477076020027460 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/020.xml0000644000175000017500000000002707477076020027437 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/101.xml0000644000175000017500000000006407477076020027440 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/022.xml0000644000175000017500000000003007477076020027433 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/103.xml0000644000175000017500000000007207477076020027441 0ustar twernertwerner"> ]> &e; libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/140.xml0000644000175000017500000000010607477076020027440 0ustar twernertwerner"> ]> &e; libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/024.xml0000644000175000017500000000003107477076020027436 0ustar twernertwerner <123> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/105.xml0000644000175000017500000000004707477076020027445 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/061.xml0000644000175000017500000000010407477076020027440 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/142.xml0000644000175000017500000000007407477076020027446 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/107.xml0000644000175000017500000000005407477076020027445 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/026.xml0000644000175000017500000000002007477076020027436 0ustar twernertwerner]]]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/063.xml0000644000175000017500000000005707477076020027451 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/144.xml0000644000175000017500000000010007477076020027436 0ustar twernertwerner ]> ￿ libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/109.xml0000644000175000017500000000006107477076020027445 0ustar twernertwerner"> ]> &e; libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/028.xml0000644000175000017500000000005007477076020027443 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/181.xml0000644000175000017500000000013207477076020027444 0ustar twernertwerner ]> &e;]]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/065.xml0000644000175000017500000000013407477076020027447 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/146.xml0000644000175000017500000000010207477076020027442 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/183.xml0000644000175000017500000000012607477076020027451 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/067.xml0000644000175000017500000000012507477076020027451 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/148.xml0000644000175000017500000000005307477076020027451 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/185.xml0000644000175000017500000000012607477076020027453 0ustar twernertwerner &e; libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/069.xml0000644000175000017500000000021407477076020027452 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/110.xml0000644000175000017500000000006207477076020027436 0ustar twernertwerner ]> &e; libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/112.xml0000644000175000017500000000003607477076020027441 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/031.xml0000644000175000017500000000007107477076020027440 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/114.xml0000644000175000017500000000006107477076020027441 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/033.xml0000644000175000017500000000002307477076020027437 0ustar twernertwernerabcdef libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/070.xml0000644000175000017500000000007107477076020027443 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/151.xml0000644000175000017500000000004307477076020027442 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/116.xml0000644000175000017500000000007207477076020027445 0ustar twernertwerner ]> &e;7; libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/035.xml0000644000175000017500000000004007477076020027440 0ustar twernertwerner1 < 2 but not in XML libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/072.xml0000644000175000017500000000002107477076020027440 0ustar twernertwerner&foo; libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/153.xml0000644000175000017500000000014207477076020027444 0ustar twernertwerner "> ]> &e; libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/118.xml0000644000175000017500000000006607477076020027452 0ustar twernertwerner ]> &&e;97; libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/037.xml0000644000175000017500000000002207477076020027442 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/074.xml0000644000175000017500000000011107477076020027442 0ustar twernertwerner"> ]> &e; libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/155.xml0000644000175000017500000000004207477076020027445 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/039.xml0000644000175000017500000000002407477076020027446 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/157.xml0000644000175000017500000000002507477076020027450 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/076.xml0000644000175000017500000000002607477076020027451 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/159.xml0000644000175000017500000000014307477076020027453 0ustar twernertwerner "> ]> &e; libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/078.xml0000644000175000017500000000012707477076020027455 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/001.xml0000644000175000017500000000003307477076020027433 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/003.xml0000644000175000017500000000002107477076020027432 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/040.xml0000644000175000017500000000003007477076020027433 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/121.xml0000644000175000017500000000007407477076020027443 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/005.xml0000644000175000017500000000003707477076020027443 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/042.xml0000644000175000017500000000001607477076020027441 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/123.xml0000644000175000017500000000007007477076020027441 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/160.xml0000644000175000017500000000013507477076020027444 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/007.xml0000644000175000017500000000003007477076020027436 0ustar twernertwerner& no refc libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/044.xml0000644000175000017500000000001507477076020027442 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/125.xml0000644000175000017500000000007207477076020027445 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/162.xml0000644000175000017500000000014007477076020027442 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/009.xml0000644000175000017500000000002107477076020027440 0ustar twernertwerner&#RE; libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/081.xml0000644000175000017500000000010007477076020027436 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/046.xml0000644000175000017500000000002507477076020027445 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/127.xml0000644000175000017500000000007107477076020027446 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/164.xml0000644000175000017500000000011607477076020027447 0ustar twernertwerner ] %e; > libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/083.xml0000644000175000017500000000010307477076020027443 0ustar twernertwerner ]> &e; libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/129.xml0000644000175000017500000000007407477076020027453 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/048.xml0000644000175000017500000000003207477076020027445 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/166.xml0000644000175000017500000000001707477076020027451 0ustar twernertwernerÀÀ libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/085.xml0000644000175000017500000000006107477076020027450 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/168.xml0000644000175000017500000000001707477076020027453 0ustar twernertwerneráÇ libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/087.xml0000644000175000017500000000010507477076020027451 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/089.xml0000644000175000017500000000011207477076020027451 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/010.xml0000644000175000017500000000002107477076020027430 0ustar twernertwernerA & B libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/012.xml0000644000175000017500000000002207477076020027433 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/185.ent0000644000175000017500000000003107477076020027434 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/130.xml0000644000175000017500000000007407477076020027443 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/014.xml0000644000175000017500000000002707477076020027442 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/132.xml0000644000175000017500000000011407477076020027440 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/051.xml0000644000175000017500000000005407477076020027443 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/016.xml0000644000175000017500000000003107477076020027437 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/134.xml0000644000175000017500000000006407477076020027446 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/053.xml0000644000175000017500000000001407477076020027441 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/171.xml0000644000175000017500000000003107477076020027441 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/018.xml0000644000175000017500000000003707477076020027447 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/090.xml0000644000175000017500000000010607477076020027444 0ustar twernertwerner"> ]> &e; libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/136.xml0000644000175000017500000000007407477076020027451 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/055.xml0000644000175000017500000000003407477076020027445 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/173.xml0000644000175000017500000000002407477076020027445 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/092.xml0000644000175000017500000000010607477076020027446 0ustar twernertwerner"> ]> &e; libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/138.xml0000644000175000017500000000006607477076020027454 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/057.xml0000644000175000017500000000010607477076020027447 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/175.xml0000644000175000017500000000011407477076020027447 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/094.xml0000644000175000017500000000004207477076020027447 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/059.xml0000644000175000017500000000012507477076020027452 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/177.xml0000644000175000017500000000007407477076020027456 0ustar twernertwerner ]> AÀÀ libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/096.xml0000644000175000017500000000006207477076020027453 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/179.xml0000644000175000017500000000006207477076020027455 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/098.xml0000644000175000017500000000005707477076020027461 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/100.xml0000644000175000017500000000006407477076020027437 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/021.xml0000644000175000017500000000002507477076020027436 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/102.xml0000644000175000017500000000004407477076020027437 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/023.xml0000644000175000017500000000002407477076020027437 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/104.xml0000644000175000017500000000007407477076020027444 0ustar twernertwerner"> ]> &e; libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/141.xml0000644000175000017500000000010607477076020027441 0ustar twernertwerner"> ]> &e; libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/060.xml0000644000175000017500000000013007477076020027436 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/025.xml0000644000175000017500000000001707477076020027443 0ustar twernertwerner]]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/106.xml0000644000175000017500000000003507477076020027443 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/062.xml0000644000175000017500000000007007477076020027443 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/143.xml0000644000175000017500000000007507477076020027450 0ustar twernertwerner ]>  libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/108.xml0000644000175000017500000000003507477076020027445 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/027.xml0000644000175000017500000000002607477076020027445 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/066.xml0000644000175000017500000000013407477076020027450 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/147.xml0000644000175000017500000000004307477076020027447 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/184.xml0000644000175000017500000000013007477076020027445 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/068.xml0000644000175000017500000000014107477076020027450 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/149.xml0000644000175000017500000000011607477076020027452 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/186.xml0000644000175000017500000000014307477076020027453 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/111.xml0000644000175000017500000000007307477076020027441 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/030.xml0000644000175000017500000000006007477076020027435 0ustar twernertwernerA form feed ( ) is not legal in data libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/113.xml0000644000175000017500000000006307477076020027442 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/032.xml0000644000175000017500000000010007477076020027432 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/150.xml0000644000175000017500000000004307477076020027441 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/115.xml0000644000175000017500000000007307477076020027445 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/034.xml0000644000175000017500000000010007477076020027434 0ustar twernertwernerA form-feed is not white space or a name character libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/071.xml0000644000175000017500000000013707477076020027447 0ustar twernertwerner ]> &e1; libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/152.xml0000644000175000017500000000004507477076020027445 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/117.xml0000644000175000017500000000007207477076020027446 0ustar twernertwerner ]> &e;#97; libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/036.xml0000644000175000017500000000003107477076020027441 0ustar twernertwerner Illegal data libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/073.xml0000644000175000017500000000007107477076020027446 0ustar twernertwerner ]> &f; libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/154.xml0000644000175000017500000000004207477076020027444 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/119.xml0000644000175000017500000000007407477076020027452 0ustar twernertwerner ]> &e;#38; libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/038.xml0000644000175000017500000000004407477076020027447 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/075.xml0000644000175000017500000000014507477076020027452 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/156.xml0000644000175000017500000000004307477076020027447 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/077.xml0000644000175000017500000000007707477076020027460 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/158.xml0000644000175000017500000000021107477076020027446 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/079.xml0000644000175000017500000000022207477076020027452 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/null.ent0000644000175000017500000000000007477076020030065 0ustar twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/002.xml0000644000175000017500000000003407477076020027435 0ustar twernertwerner <.doc> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/120.xml0000644000175000017500000000007007477076020027436 0ustar twernertwerner ]> &e; libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/004.xml0000644000175000017500000000003707477076020027442 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/122.xml0000644000175000017500000000007407477076020027444 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/041.xml0000644000175000017500000000002307477076020027436 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/006.xml0000644000175000017500000000005107477076020027440 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/124.xml0000644000175000017500000000007507477076020027447 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/043.xml0000644000175000017500000000002407477076020027441 0ustar twernertwerner Illegal data libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/080.xml0000644000175000017500000000023107477076020027442 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/008.xml0000644000175000017500000000002507477076020027443 0ustar twernertwerner&.entity; libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/161.xml0000644000175000017500000000011407477076020027442 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/126.xml0000644000175000017500000000007107477076020027445 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/045.xml0000644000175000017500000000002207477076020027441 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/082.xml0000644000175000017500000000015607477076020027452 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/163.xml0000644000175000017500000000011507477076020027445 0ustar twernertwerner ]> %e; libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/128.xml0000644000175000017500000000006407477076020027451 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/047.xml0000644000175000017500000000002407477076020027445 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/084.xml0000644000175000017500000000016607477076020027455 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/165.xml0000644000175000017500000000011007477076020027442 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/049.xml0000644000175000017500000000006607477076020027455 0ustar twernertwerner libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/086.xml0000644000175000017500000000010307477076020027446 0ustar twernertwerner ]> libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/167.xml0000644000175000017500000000001707477076020027452 0ustar twernertwernerÀ¾ libexml-java-0.0.20080703.orig/e-xml/src/test/resources/xml-samples/not-wf/sa/088.xml0000644000175000017500000000015707477076020027461 0ustar twernertwerner ]> i = paths.iterator(); while (true) { // try to create a URL try { String fn = systemLiteral; if (path != null) fn = path + '/' + systemLiteral; return openURL(fn); } catch (MalformedURLException ex) { // ignore } catch (IOException ioe) { if (!i.hasNext()) { throw ioe; } } // try the filesystem try { String fn = systemLiteral; if (path != null) fn = path + File.separator + systemLiteral; return openLocalFile(fn); } catch (FileNotFoundException fnf) { if (!i.hasNext()) { throw fnf; } } path = i.next(); } } } libexml-java-0.0.20080703.orig/e-xml/src/main/java/net/noderunner/exml/ObjectPool.java0000644000175000017500000000653110762067376030041 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.exml; /** * An object pool in which objects must be returned in the order that they were * checked out. */ class ObjectPool { private Object items[]; private Class prototype; private int at; private int initialSize; /** * Constructs an object pool using a class, which will be used to * create new instances. * @param prototype an instantiable class that has a default constructor * @param initialSize number of objects to allocate at first * @throws IllegalArgumentException if the size is invalid or the * prototype class cannot be instantiated */ public ObjectPool(Class prototype, int initialSize) { if (initialSize <= 0) throw new IllegalArgumentException("Invalid initial size: " + initialSize); if (prototype == null) throw new IllegalArgumentException("Null propotype"); this.initialSize = initialSize; this.prototype = prototype; at = 0; items = new Object[initialSize]; for (int i = 0; i < items.length; i++) items[i] = newObject(); } private Object newObject() { try { return prototype.newInstance(); } catch (InstantiationException e) { throw new IllegalArgumentException("Cannot instantiate " + prototype + ": " + e); } catch (IllegalAccessException e) { throw new IllegalArgumentException("Cannot access " + prototype + ": " + e); } } private void expandIfNeeded() { if (at == items.length) { Object newItems[] = new Object[items.length * 2]; System.arraycopy(items, 0, newItems, 0, items.length); for (int i = items.length; i < newItems.length; i++) newItems[i] = newObject(); items = newItems; } } private void shrinkIfNeeded() { if (items.length > initialSize && at < items.length / 2) { Object newItems[]; if (at <= initialSize / 2) newItems = new Object[initialSize]; else newItems = new Object[items.length / 2]; System.arraycopy(items, 0, newItems, 0, newItems.length); items = newItems; } } public Object checkOut() { expandIfNeeded(); return items[at++]; } /** * Returns the last object returned by the checkOut() method. */ public Object checkIn() { if (at == 0) throw new IllegalStateException("Cannot check in more than available"); Object last = items[--at]; shrinkIfNeeded(); return last; } /** * Returns all objects to the pool. */ public void clear() { at = 0; shrinkIfNeeded(); } public String toString() { StringBuffer sb = new StringBuffer(items.length * 8); sb.append("ObjectPool out=["); for (int i = 0; i < at; i++) { sb.append(items[i]); sb.append(' '); } sb.append("] capacity=" + items.length); return sb.toString(); } } libexml-java-0.0.20080703.orig/e-xml/src/main/java/net/noderunner/exml/StringPool.java0000644000175000017500000002542711014421656030070 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.exml; import java.lang.ref.Reference; import java.lang.ref.ReferenceQueue; import java.lang.ref.SoftReference; import java.util.AbstractSet; import java.util.Collection; import java.util.Iterator; import java.util.NoSuchElementException; /** * This string pool holds instances of String objects, * which makes it easy to re-use an existing String instance if a character * sequence was found previously. * For parsing, there is almost always a small set of different element and * attribute names, in comparison to the number of tags appearing in a given * document, so this pool should not grow very large. The number of buckets * will grow to at least half the number of entries within. For different * kinds of text documents, then, it makes sense to use a completely new * instance of this object. *

* To regulate the creation of large numbers of spurious String objects * that are no longer neccesary, internally the references are made * through the use of java.lang.ref.SoftReference * instances. *

*

* Data is maintained as a basic hash-table, with the buckets as * linked-list instances. *

*

* This class is not thread safe. *

*/ public class StringPool extends AbstractSet { private static class SoftString extends SoftReference { private char chars[]; private int hashCode; private SoftString(String s, char chars[], int hashCode, ReferenceQueue q) { super(s, q); this.hashCode = hashCode; this.chars = chars; } /** Returns a debug string */ @Override public String toString() { if (chars == null) return "SoftString null"; int len = chars.length; if (len > 40) len = 40; return "SoftString " + new String(chars, 0, len) + " len=" + chars.length; } @Override public int hashCode() { return hashCode; } @Override public boolean equals(Object o) { throw new UnsupportedOperationException(); } /** * It is important that clear() is called to remove the * character array reference. From what I can tell from * the heap manager, a SoftReference object holds a * next pointer and thus any memory held * here may not be garbage collected. */ @Override public void clear() { super.clear(); chars = null; } } private final class Entry { private SoftString softString; private Entry next; public Entry(Entry other) { softString = other.softString; next = null; } public Entry(String s, int hashCode) { char chars[] = s.toCharArray(); softString = new SoftString(s, chars, hashCode, refQueue); next = null; } public Entry(String s, char chars[], int hashCode) { softString = new SoftString(s, chars, hashCode, refQueue); next = null; } public boolean equals(char buf[], int off, int len, int hashCode) { if (softString.hashCode != hashCode || softString.chars == null || softString.chars.length != len) return false; for (int i = 0; i < len; i++) if (softString.chars[i] != buf[i + off]) return false; return true; } @Override public boolean equals(Object other) { // this is coming from the remove() method most likely if (other instanceof SoftString) { return softString == other; } // this is coming from intern Object string = softString.get(); if (string == null) { return false; } return string.equals(other.toString()); } private String recreate() { char c[] = softString.chars; int hc = softString.hashCode; String s = new String(c); softString = new SoftString(s, c, hc, refQueue); return s; } @Override public String toString() { Object string = softString.get(); if (string == null) { return recreate(); } return (String)string; } @Override public int hashCode() { return softString.hashCode; } } private Entry pool[]; private int numEntries = 0; private ReferenceQueue refQueue; /** * Constructs a StringPool with 128 buckets. */ public StringPool() { this(128); } /** * Constructs a StringPool with a specific size. * @param size number of buckets */ public StringPool(int size) { pool = new Entry[size]; refQueue = new ReferenceQueue(); } /** * Returns a canonical representation of a String. * For all String instances a and b * where a.equals(b) is true, itern(a) == * intern(b) will be true. */ public String intern(final String s) { rehash(); int hashCode = s.hashCode(); int index = index(hashCode, pool.length); Entry e = pool[index]; if (e == null) { // new entry String is = s.intern(); pool[index] = new Entry(is, hashCode); numEntries++; return is; } while (true) { if (e.equals(s)) return e.toString(); if (e.next == null) { // new entry String is = s.intern(); e.next = new Entry(is, hashCode); numEntries++; return is; } e = e.next; } } private static char[] charArray(char buf[], int off, int len) { char chars[] = new char[len]; System.arraycopy(buf, off, chars, 0, len); return chars; } /** * Returns a String representation of a character array * slice. */ public String intern(char buf[], int off, int len) { rehash(); int hashCode = hashCode(buf, off, len); int index = index(hashCode, pool.length); Entry e = pool[index]; if (e == null) { // new entry char[] chars = charArray(buf, off, len); String s = new String(chars).intern(); e = new Entry(s, chars, hashCode); pool[index] = e; numEntries++; return s; } while (true) { if (e.equals(buf, off, len, hashCode)) { return e.toString(); } if (e.next == null) { // new entry char[] chars = charArray(buf, off, len); String s = new String(chars).intern(); e.next = new Entry(s, chars, hashCode); numEntries++; return s; } e = e.next; } } /** * Returns the index of the bucket to use. */ private int index(int hash, int len) { return (hash & 0x7FFFFFFF) % len; } /** * Removes unused entries. */ private void removeSoftReferences() { Reference ref; while ((ref = refQueue.poll()) != null) { remove(ref); ref.clear(); } } /** * Expands the pool if neccessary. */ private void rehash() { if (numEntries / 2 < pool.length) return; removeSoftReferences(); if (numEntries / 2 < pool.length) return; Entry newPool[] = new Entry[pool.length * 2]; Iterator i = entryIterator(); while (i.hasNext()) { Entry e = i.next(); int newIndex = index(e.hashCode(), newPool.length); Entry e2 = newPool[newIndex]; if (e2 == null) { newPool[newIndex] = new Entry(e); } else { while (e2.next != null) e2 = e2.next; e2.next = new Entry(e); } } pool = newPool; } private class EntryIterator implements Iterator { private int index; private Entry e; public EntryIterator() { } public boolean hasNext() { if (e != null) return true; while (index < pool.length) { if (pool[index] != null) { e = pool[index]; index++; return true; } index++; } return false; } public Entry next() { if (e == null) { if (!hasNext()) throw new NoSuchElementException("No more pool elements"); } Entry orig = e; e = e.next; return orig; } public void remove() { throw new UnsupportedOperationException("Cannot remove using iterator"); } } private class StringIterator implements Iterator { private EntryIterator ei = new EntryIterator(); public boolean hasNext() { return ei.hasNext(); } public String next() { Entry e = ei.next(); return e.toString(); } public void remove() { ei.remove(); } } /** * Returns the number of used buckets. * This is used for hash performance estimation. */ int buckets() { int count = 0; for (int i = 0; i < pool.length; i++) { if (pool[i] != null && pool[i].next != null) count++; } return count; } /** * Returns an iterator of the strings. * * Note that the {@link Iterator#remove()} operation is not supported. */ @Override public Iterator iterator() { return new StringIterator(); } private Iterator entryIterator() { return new EntryIterator(); } /** * Returns the number of strings in this pool. */ @Override public int size() { return numEntries; } /** * Adds a string to this pool. * Always returns true, even if this string previously existed. * * @param o must be a java.lang.String instance */ @Override public boolean add(String o) { intern(o); return true; } /** * Removes a String or SoftString from * the pool. * Returns true if modification was done. */ @Override public boolean remove(Object o) { int index = index(o.hashCode(), pool.length); Entry e = pool[index]; if (e == null) return false; if (e.equals(o)) { pool[index] = e.next; numEntries--; return true; } while (e.next != null) { if (e.next.equals(o)) { e = e.next.next; numEntries--; return true; } e = e.next; } return false; } /** * Tests if this object is present in the pool. */ @Override public boolean contains(Object o) { int index = index(o.hashCode(), pool.length); Entry e = pool[index]; while (e != null) { if (e.equals(o)) return true; e = e.next; } return false; } /** * Adds a collection of strings to this pool. * Always returns true, even if additional entries were created. */ @Override public boolean addAll(Collection c) { Iterator i = c.iterator(); while (i.hasNext()) intern(i.next().toString()); return true; } /** * Computes a hash code of a character array slice using the same * algorithm as described in the Java documentation for * java.lang.String. */ static int hashCode(char val[], int off, int len) { int h = 0; for (int i = 0; i < len; i++) h = 31*h + val[off++]; return h; } } libexml-java-0.0.20080703.orig/e-xml/src/main/java/net/noderunner/exml/XmlSParser.java0000644000175000017500000010255611014421656030027 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.exml; import java.io.IOException; import java.io.Reader; import java.io.Writer; /** * A very fast incremental, streaming XML pull-parser. The XML * tree is not validated or checked for well-formedness. However, this * allows an XML tree to be read in without creating any unnecessary * objects. This implementation aims to be the most minimal (fastest) * and reasonably complete, so as to not create any reduceable overhead * or user inconvience. *

* In this implementation, it relies on the 'fatter' * XmlReader to do element tree parsing. This allows both * simple and efficient skipping as well as being able to build object * trees. Typically, XmlReader is not used except for its * hopefully significant convience. *

* Example usage: *

 * String document = 
 * 	"<?xml version='1.0'?>\n" +
 *	"<doc>\n" +
 *		"<empty1 attr='value1'/>\n" +
 *		"<empty2 attr='value2'/>\n" +
 *		"<para>Hello world!</para>\n" +
 *	"</doc>\n";
 * XmlSParser parser = new XmlSParser();
 * parser.setReadString(document);
 * parser.next();        // returns XmlEvent.STAG for 'doc' tag
 * parser.next();        // returns XmlEvent.STAG for empty1 tag
 * Element e = parser.startTag();
 * e.getAttValue("attr");// returns 'value1' attribute value from empty1
 * parser.next();        // returns XmlEvent.ETAG for empty1 tag
 * parser.next();        // returns XmlEvent.STAG for empty2 tag
 * parser.getAttValue(); // returns 'value2' attribute value from empty2
 * parser.next();        // returns XmlEvent.ETAG for empty2 tag
 * parser.next();        // returns XmlEvent.STAG for para tag
 * parser.next();        // returns XmlEvent.CHARDATA for text
 * String text = parser.getText(); // returns 'Hello world!'
 * parser.next();        // returns XmlEvent.ETAG for para tag
 * String etag = parser.getTagName(); // returns 'etag'
 * parser.next();        // returns XmlEvent.ETAG for 'doc' tag
 * parser.next();        // returns XmlEvent.EOD
 * 
*

* Additionally, this parser may be used to read document fragments, * specifically strings without surronding tags. It is suggested * that EOD notifcation be turned off. For example: *

 * XmlSParser parser = new XmlSParser(new XmlReader());
 * parser.setEvents(XmlEvent.CHARDATA | XmlEvent.STAG | XmlEvent.ETAG);
 * parser.setReadString("A string <i>with</i> mark-up!");
 * parser.next();        // returns XmlEvent.CHARDATA for 'a string '
 * parser.next();        // returns XmlEvent.STAG for the 'i' tag
 * parser.next();        // returns XmlEvent.CHARDATA for 'with'
 * String text = parser.getText(); // returns 'with'
 * parser.next();        // returns XmlEvent.ETAG for the 'i' tag
 * parser.next();        // returns XmlEvent.CHARDATA for 'mark-up!'
 * 
*

* * @author Elias Ross * @version 1.0 */ public class XmlSParser implements XmlEvent { /** * Underlying reader. */ private XmlReader reader; /** * Underlying scanner. */ private XmlScanner scanner; /** * Keeps track of parsing depth. */ private int depth; /** * If whitespace should be skipped from after start tags, otherwise, * whitespace is read. */ private boolean skipWS; /** * If all following text events should belong to the previous * sequential text event so the text: *
x &lt; <![CDATA[ y]]>
* will be treated as one CHARDATA event, not * CHARDATA-REFERENCE-CHARDATA-CDSECT event. */ private boolean skipRT; /** * Events that will be returned from next. */ private int events; /** * The event last returned by next. */ private int curEvent; /** * Whether or not the end tag really exists. This is * to make consistant the next() routinue in how it handles * both types of empty tags. */ private boolean fakeETAG; /** * Whether or not to return the last peek event during the next * next call. * @see #setPeekNext */ private boolean returnLast; /** * Reused to read text as a String. */ private XmlCharArrayWriter caw; /** * Constructs an XmlSParser, using a default XmlReader. * By default, the following events are returned: *
    *
  • {@link XmlEvent#STAG}
  • *
  • {@link XmlEvent#ETAG}
  • *
  • {@link XmlEvent#TEXT}
  • *
  • {@link XmlEvent#EOD}
  • *
* @param reader xml reader to wrap * @see #setEvents */ public XmlSParser() { this(new XmlReader()); } /** * Constructs an XmlSParser around an XmlReader. By default, * the following events are returned: *
    *
  • {@link XmlEvent#STAG}
  • *
  • {@link XmlEvent#ETAG}
  • *
  • {@link XmlEvent#TEXT}
  • *
  • {@link XmlEvent#EOD}
  • *
* @param reader xml reader to wrap * @see #setEvents */ public XmlSParser(XmlReader reader) { this(reader, STAG | ETAG | TEXT | EOD); } /** * Constructs an XmlSParser using a read string. */ public XmlSParser(String readString) { this(); setReadString(readString); } /** * Constructs an XmlSParser around an XmlReader with specific events * to trap. * @param reader xml reader to wrap * @see #setEvents */ public XmlSParser(XmlReader reader, int events) { this.reader = reader; this.scanner = reader.getScanner(); this.skipWS = true; this.skipRT = true; this.caw = new XmlCharArrayWriter(); setEvents(events); initState(); } /** * Resets this object to parse using another Reader source. * The parse depth is reset to zero. */ public void setReader(Reader reader) { this.reader.setReader(reader); initState(); } /** * Resets this object to parse a String source. * The parse depth is reset to zero. */ public void setReadString(String xml) { scanner.setReadString(xml); initState(); } /** * Returns the parser to its initial state. */ private void initState() { this.depth = 0; this.curEvent = XmlEvent.NONE; this.fakeETAG = false; this.returnLast = false; } /** * Specifies events to watch. * The following one or more events can be specified by OR'ing them * together: *
    *
  • {@link XmlEvent#ALL_EVENTS}
  • *
  • {@link XmlEvent#STAG}
  • *
  • {@link XmlEvent#ETAG}
  • *
  • {@link XmlEvent#TEXT}
  • *
  • {@link XmlEvent#CHARDATA}
  • *
  • {@link XmlEvent#REFERENCE}
  • *
  • {@link XmlEvent#CDSECT}
  • *
  • {@link XmlEvent#COMMENT}
  • *
  • {@link XmlEvent#DOCTYPE_DECL}
  • *
  • {@link XmlEvent#XML_DECL}
  • *
  • {@link XmlEvent#PI}
  • *
  • {@link XmlEvent#COMMENT}
  • *
  • {@link XmlEvent#EOD}
  • *
  • {@link XmlEvent#ELEMENT_DECL}
  • *
  • {@link XmlEvent#ATTLIST_DECL}
  • *
  • {@link XmlEvent#ENTITY_DECL}
  • *
  • {@link XmlEvent#CONDITIONAL_SECT}
  • *
  • {@link XmlEvent#NOTATATION_DECL}
  • *
* Note that TEXT composes the CHARDATA, * CDSECT, and REFERENCE flags. It does * not make much sense to ignore character references and only * accept unescaped text, but that is up to the discretion of the * user. *

* It is possible to want to ignore all events, in which case this * parser will continually read XML documents until error or EOF is * reached. *

*

* Example: (Very quickly check a XML document for basic well-formedness) *

	 * Reader r = ...;
	 * XmlSParser parser = new XmlSParser(new XmlReader(r));
	 * parser.setEvents(XmlEvent.EOD);
	 * boolean wellFormed = true;
	 * try {
	 * 	parser.next();
	 * } catch (XmlException e) {
	 * 	wellFormed = false;
	 * }
	 * 
*

*

* Example: (Extract all comments from an XML document) *

	 * Reader r = ...;
	 * XmlSParser parser = new XmlSParser(new XmlReader(r));
	 * parser.setEvents(XmlEvent.COMMENT | XmlEvent.EOD);
	 * while (parser.next() != XmlEvent.EOD) {
	 *	if (parser.isEvent(XmlEvent.COMMENT))
	 * 		Comment c = parser.getComment();
	 * }
	 * 
*

* @param events OR'd together event flags * @see XmlEvent */ public void setEvents(int events) { this.events = events; } /** * Returns true if end of document event {@link XmlEvent#EOD} hasn't * been reached. Note: It is still possible to read from the * stream and read another document if desired. */ public boolean hasNext() { return !isEvent(EOD); } /** * A convience method which tests for a particular event. * This is less error-prone than testing with bit flags in code. */ public boolean isEvent(int event) { return (curEvent == event) || (curEvent & event) != 0; } /** * Skips a CDSect or conditional section. */ private void skipCDSect() throws IOException, XmlException { int c = 0, c2 = 0; scanner.skip(XmlTags.CDATA_BEGIN.length); do { scanner.skipUntil(']'); c2 = c; c = scanner.read(); } while (c2 != ']' || c != ']' || scanner.peek() != '>'); scanner.read(); } /** * Skips a comment section. */ private void skipComment() throws IOException, XmlException { int c = 0; scanner.skip(4); while (true) { scanner.skipUntil('-'); scanner.read(); // '-' c = scanner.peek(); // ? '>' if (c == '-') { scanner.read(); c = scanner.peek(); if (c == '>') break; else throw new XmlException("-- not allowed in comments"); } } scanner.read(); } /** * Returns the next event. The stream is advanced such that * the last returned element is skipped. * * @throws XmlException if bad XML data is found or an unknown * state is reached */ public int next() throws IOException, XmlException { return next(this.events); } /** * Returns the next event matching the event(s) specified. * * @param events OR'd together event flags * @throws XmlException if bad XML data is found or an unknown * state is reached * @see #setEvents */ public int next(int events) throws IOException, XmlException { while (true) { if (returnLast) { returnLast = false; if (want(events, curEvent)) return curEvent; } switch (curEvent) { case NONE: if (reader.XmlDecl()) { curEvent = XML_DECL; } else { peekEvent(); } break; case STAG: int c = 0; depth++; do { c = scanner.skipUntil('>', '/'); scanner.read(); } while (c == '/' && scanner.peek() != '>'); if (c == '/') { curEvent = ETAG; fakeETAG = true; scanner.read(); } else { peekEvent(); } break; case ETAG: depth--; if (fakeETAG) { fakeETAG = false; peekEvent(); } else { scanner.skipUntil('>'); scanner.read(); if (depth == 0) curEvent = EOD; else peekEvent(); } break; case REFERENCE: scanner.skipUntil(';'); scanner.read(); peekEvent(); if (skipRT && isEvent(TEXT)) continue; break; case CHARDATA: scanner.skipUntil('<', skipRT ? (char)0 : '&'); peekEvent(); if (skipRT && isEvent(TEXT)) continue; break; case CDSECT: skipCDSect(); peekEvent(); if (skipRT && isEvent(TEXT)) continue; break; case COMMENT: skipComment(); peekEvent(); break; case PI: do { scanner.skipUntil('?'); scanner.read(); } while (scanner.peek() != '>'); scanner.read(); peekEvent(); break; case XML_DECL: peekEvent(); break; case EOD: // start anew curEvent = NONE; break; case DOCTYPE_DECL: // This should preceed the document, but no checking // is done. Since the data is in fact interpreted, // if it is invalid, it may cause trouble. reader.doctypedecl(); peekEvent(); break; case ELEMENT_DECL: case ATTLIST_DECL: case ENTITY_DECL: case NOTATATION_DECL: // This should only occur parsing a doctype or // external entity. scanner.skipUntil('>'); scanner.read(); peekEvent(); break; case CONDITIONAL_SECT: // This should only occur parsing an external // entity. reader.conditionalSect(); peekEvent(); break; // Not possible? default: throw new XmlException("Unable to process event: " + eventToString(curEvent)); } if (want(events, curEvent)) { return curEvent; } } } /** * Creates an Element with data about the current start * tag token under the cursor. Returns null if no tag was found. * * @see XmlReader#STag() */ public Element startTag() throws IOException, XmlException { depth++; Element e = reader.STag(); if (e == null) return null; if (!e.isOpen()) { returnLast = true; curEvent = ETAG; fakeETAG = true; if (skipWS) reader.S(); } else { setPeekNext(); } return e; } /** * Creates an Element with data about the current end * tag token under the cursor. If the prior element was an empty tag, * this function will not work as expected, as this only works for open * tags. * Returns null if no end tag was found. * @see XmlReader#ETag() */ public Element endTag() throws IOException, XmlException { Element e = reader.ETag(); if (e != null) depth--; setPeekNext(); return e; } private void checkTagName() throws IOException, XmlException { if (curEvent != ETAG && curEvent != STAG) throw new IllegalXmlParserStateException("Must be on ETAG or STAG"); scanner.read(); if (curEvent == ETAG) scanner.read(); } /** * Returns the name of the element (start or end tag) * under the cursor. Typically, this call will create no * Java objects at all, as all strings are re-used from the local * string pool. *

* Example: (Prints "Got foo!" to standard out.) *

	 * final String FOO = "foo";
	 *
	 * XmlReader xr = new XmlReader(r);
	 * xr.getStringPool().add(FOO);
	 * XmlSParser p = new XmlSParser(xr);
	 * p.setReadString("<foo></foo>");
	 *
	 * p.next();       // returns XmlEvent.STAG
	 * if (p.getTagName() == FOO)
	 * 	System.out.println("Got foo!");
	 * p.next();       // returns XmlEvent.ETAG;
	 * p.getTagName(); // returns 'foo'
	 * 
*

*/ public String getTagName() throws IOException, XmlException { checkTagName(); return scanner.getName(); } /** * Reads the name and tag of the element (start or end tag) * under the cursor into a {@link NamespaceImpl} instance. Typically, * this call will create no Java objects at all, as all * strings are re-used from the local string pool. *

* Example: *

	 * XmlSParser p = new XmlSParser();
	 * p.setReadString("<ns:foo></ns:foo>");
	 * NamespaceImpl ns = new NamespaceImpl();
	 * p.next();          // returns XmlEvent.STAG
	 * p.readTagName(ns); // sets prefix and localname
	 * p.next();          // returns XmlEvent.ETAG;
	 * p.readTagName(ns); // sets prefix and localname
	 * 
*

*/ public void readTagName(NamespaceImpl ns) throws IOException, XmlException { checkTagName(); scanner.readNamespace(ns); } private boolean checkAttName() throws IOException, XmlException { int c = scanner.peek(); if (c == '=') { scanner.read(); reader.S(); c = scanner.read(); // opening quote scanner.skipUntil((char)c); scanner.read(); // closing quote c = scanner.peek(); } if (c == '>') { return false; } if (c == '<') { scanner.read(); reader.Name(); } boolean space = reader.S(); if (space) c = scanner.peek(); if (c == '/' || c == '>') { return false; } if (!space) throw new XmlException("Expected whitespace after name or attribute"); return true; } /** * Returns an element's attribute name or null if no * more attributes exist. *

* Example: *

	 * XmlSParser p = new XmlSParser(new XmlReader(r));
	 * p.setReadString("<foo version='1.0' ref = 'bar'></foo>");
	 * p.next() == XmlEvent.STAG);
	 * p.getAttName();   // returns "version"
	 * p.getAttName();   // returns "ref"
	 * p.getAttName();   // returns null
	 * 
*

* @see #getAttValue */ public String getAttName() throws IOException, XmlException { if (curEvent != STAG) throw new IllegalXmlParserStateException("Must be on STAG"); if (!checkAttName()) return null; String name = reader.Name(); reader.S(); // clean up the space following the name return name; } /** * Returns an element's attribute name or null if no * more attributes exist. *

* Example: *

	 * XmlSParser p = new XmlSParser();
	 * p.setReadString("<foo ns:version='1.0' ns:ref = 'bar'></foo>");
	 * NamespaceImpl ns = new NamespaceImpl();
	 * p.next();         // returns XmlEvent.STAG
	 * p.getAttName(ns); // returns "version" localname
	 * p.getAttName(ns); // returns "ref" localname
	 * p.getAttName(ns); // returns a clear NamespaceImpl
	 * 
*

* @see NamespaceImpl#isClear */ public void readAttName(NamespaceImpl ns) throws IOException, XmlException { if (!checkAttName()) { ns.clear(); } else { scanner.readNamespace(ns); reader.S(); // clean up the space following the name } } /** * Retrives an element's attribute values. Note that this * advances the input stream past the beginning of the start tag, * such that {@link #startTag}, {@link #getElementTree} will * no longer correctly for the current tag. This is much * more efficient than a startTag call. * Returns dflt as a default value if no more * attributes were found. *

* Example: *

	 * XmlSParser p = new XmlSParser();
	 * p.setReadString("<foo version='1.0' ref='bar'></foo>");
	 * p.next()               // returns XmlEvent.STAG
	 * p.getAttValue();       // returns '1.0'
	 * p.getAttValue();       // returns 'bar'
	 * p.getAttValue("okay"); // returns 'okay'
	 * p.next();              // returns XmlEvent.ETAG
	 * 
*

* * @param dflt either null or a default value to * return * @see #getAttName */ public String getAttValue(String dflt) throws IOException, XmlException { if (curEvent != STAG) throw new IllegalXmlParserStateException("Must be on STAG"); int c = scanner.peek(); while (c != '=' && c != '/' && c != '>' && c != -1) { scanner.read(); c = scanner.peek(); } if (c != '=') { return dflt; } scanner.skipUntil('"', '\''); String v = reader.AttValue(); return v; } /** * This method calls getAttValue(null). * @see #getAttValue(String) */ public String getAttValue() throws IOException, XmlException { return getAttValue(null); } /** * Returns true if the tag data or text data at the current parse * position matches the given character array. In either case of * failure or success, the read position remains the same. * This works with any sort of tag. *

* Example usage: *

	 * static final char[] FOO = "foo".toCharArray();
	 * ...
	 * XmlSParser p = new XmlSParser(new XmlReader(), ALL_EVENTS);
	 * p.setReadString("<foo><!--fool-->");
	 * p.next();
	 * if (p.matches(FOO))
	 *	System.out.println("foo tag found!");
	 * p.next();
	 * if (p.matches(FOO))
	 *	System.out.println("foo comment found!");
	 * 
*

* * @param a characters to find * @return true if matches */ public boolean matches(final char a[]) throws IOException, XmlException { int offs = 0; switch (curEvent) { case CHARDATA: break; case STAG: offs = 1; break; case ETAG: offs = XmlTags.ETAG_BEGIN.length; break; case REFERENCE: offs = 1; break; case COMMENT: offs = XmlTags.COMMENT_BEGIN.length; break; case CDSECT: offs = XmlTags.CDATA_BEGIN.length; break; case XML_DECL: offs = XmlTags.PI_BEGIN.length; break; case PI: offs = XmlTags.PI_BEGIN.length; break; case DOCTYPE_DECL: offs = XmlTags.DOCTYPE_BEGIN.length; break; case ELEMENT_DECL: offs = XmlTags.ELEMENT_DECL_BEGIN.length; break; case ATTLIST_DECL: offs = XmlTags.ATTLIST_DECL_BEGIN.length; break; case ENTITY_DECL: offs = XmlTags.ENTITY_DECL_BEGIN.length; break; case CONDITIONAL_SECT: offs = XmlTags.CONDITIONAL_BEGIN.length; break; case NOTATATION_DECL: offs = XmlTags.NOTATION_DECL_BEGIN.length; break; case PE_REFERENCE: offs = 1; break; case EOD: /* TODO */ break; } int num = scanner.peek(reader.cbuf, 0, a.length + offs); if (num < a.length) return false; for (int i = 0; i < a.length; i++) if (reader.cbuf[i + offs] != a[i]) { return false; } return true; } /** * Indicates that next should return this * event, rather than acting upon it and skipping it. */ private void setPeekNext() throws IOException, XmlException { peekEvent(); returnLast = true; } /** * Creates an Element with data about the current token * under the cursor, with its content. Do not expect an ETAG * event to occur once this element is read. * Returns null if no element at this location. */ public Element getElementTree() throws IOException, XmlException { Element e = reader.element(); setPeekNext(); return e; } /** * Adds content to an Element until an end tag * is reached. This does not read in the element's end tag. * @param e element's end tag to reach */ public void getContent(Element e) throws IOException, XmlException { reader.content(e); setPeekNext(); } /** * Returns a processing instruction at the parse location. * Returns null if no processing instruction was * found. */ public PI getPI() throws IOException, XmlException { PI pi = reader.pi(false); setPeekNext(); return pi; } /** * Returns a comment at the parse location. * Returns null if no comment was found. */ public Comment getComment() throws IOException, XmlException { Comment c = reader.comment(false); setPeekNext(); return c; } /** * Returns text at the parse location as a new String * instance. * If we are located at a start tag, returns the text immediately following * this tag, until another tag is reached. */ public String getText() throws IOException, XmlException { caw.reset(); copyText(caw); String s = caw.toString(); if (caw.size() > 1024) caw = new XmlCharArrayWriter(); return s; } /** * Copies text at the parse location to a Writer. * Text is copied from the underlying stream until a non-text entity * is reached, such as an end tag or comment. If a non-built-in * reference is found, it is ignored. * If we are located at a start tag, returns the text immediately following * this tag, until another tag is reached. *

* Use a StringWriter or XmlCharArrayWriter * instance to collect text data in a memory buffer. *

* @see XmlCharArrayWriter */ public void copyText(Writer w) throws IOException, XmlException { if (curEvent == XmlEvent.STAG || curEvent == XmlEvent.ETAG) { next(XmlEvent.ALL_EVENTS); curEvent = scanner.peekEvent(); } while (true) { switch (curEvent) { case XmlEvent.CHARDATA: reader.CharData(w); break; case XmlEvent.CDSECT: reader.CDSect(w); break; case XmlEvent.REFERENCE: Entity entity = reader.Reference(); if (entity == null) w.write((char)scanner.read()); else w.write(entity.resolveAll(reader)); break; default: returnLast = true; return; } curEvent = scanner.peekEvent(); } } /** * Skips an start tag, writing to w. * Returns true if it read an open tag. */ private boolean copyStartTag(Writer w) throws IOException, XmlException { int c; do { c = scanner.copyUntil(w, '>', '/'); w.write(c); scanner.read(); } while (c == '/' && scanner.peek() != '>'); if (c != '/') { return true; } w.write(scanner.read()); return false; } /** * Copies all content at the parse location to a Writer. * Content must be copied at a start tag. * Text is copied from the underlying stream until the matching * closing tag is read. If the tag is an closed tag, for example * <tag />, no data is written, and per general * convention ETAG will be returned. *

* Example: *

	 * XmlSParser parser = new XmlSParser(new XmlReader());
	 * parser.setReadString("<doc>Some <i>content</i> here.</doc>");
	 * parser.next();           // returns XmlEvent.STAG for the 'doc' tag
	 * XmlCharArrayWriter caw = new XmlCharArrayWriter();
	 * parser.copyContent(caw); // writes 'Some <i>content</i> here.'
	 * parser.next();           // returns XmlEvent.ETAG
	 * 
*

*

* Example 2: *

	 * XmlSParser parser = new XmlSParser(new XmlReader());
	 * XmlCharArrayWriter caw = new XmlCharArrayWriter();
	 * parser.setReadString("<foo/>  <bar/>");
	 * parser.next();           // returns XmlEvent.STAG for the 'foo' tag
	 * parser.copyContent(caw); // writes nothing
	 * parser.next();           // returns XmlEvent.ETAG
	 * // whitespace is skipped ...
	 * parser.next();           // returns XmlEvent.STAG for the 'bar' tag
	 * 
*

*

* @see XmlCharArrayWriter */ public void copyContent(Writer w) throws IOException, XmlException { if (curEvent != STAG) throw new IllegalXmlParserStateException("Must be on STAG"); depth++; int depth2 = depth; do { if (depth > depth2) { int c = scanner.copyUntil(w, '<'); if (c != '<') throw new XmlException("EOF in copyContent"); curEvent = scanner.peekEvent(); } switch (curEvent) { case ETAG: depth--; fakeETAG = false; if (depth > depth2) { scanner.copyUntil(w, '>'); w.write((char)scanner.read()); } break; case STAG: Writer w2 = (depth > depth2) ? w : NullWriter.getInstance(); boolean open = copyStartTag(w2); if (open) { depth++; } else { curEvent = ETAG; fakeETAG = true; } break; case COMMENT: reader.copyUntil(w, XmlTags.COMMENT_END); w.write(XmlTags.COMMENT_END); break; case CDSECT: w.write(XmlTags.CDATA_BEGIN); reader.CDSect(w); w.write(XmlTags.CDATA_END); break; default: w.write(scanner.read()); break; } } while (depth > depth2); if (fakeETAG && skipWS) { reader.S(); } returnLast = true; } /** * Returns a text string, which, once found, * is internalized using the underlying string pool. * This is useful for short text segments which are often repeated * within XML tags. Note that long text segments may cause much worse * performance than expected, as this routine is optimized to handle * only data within the current buffer. Character and built-in * parameter references will not cause the text reading to stop, * meaning even strings with & in them will be made canonical. * Reading stops at EOF or before a < character. *

* This routine behaves almost exactly the same as {@link #getText}, * with the following notes: *

    *
  • String object creation is saved; the same string is * not created twice.
  • *
  • Non-built-in references (see {@link Entity#resolveAll}) are * not substituted. *
  • *
  • {@link #getText} performs better for non-canonical text segments, * since a string pool reference is then unnecessarily created. *
  • *

    *

    * In the following example foo1 and foo2 * are assigned to the exact same String object: *

    	 * XmlSParser xs = new XmlSParser(new XmlReader(), XmlEvent.CHARDATA);
    	 * xs.setReadString("Fo'oFo'o");
    	 * xs.next();
    	 * String foo1 = xs.getCanonicalText();
    	 * xs.next();
    	 * String foo2 = xs.getCanonicalText();
    	 * System.out.println(foo1 == foo2);
    	 * 
    * This code performs slightly worse: (object creation not avoided) *
    	 * XmlReader xr = new XmlReader();
    	 * StringPool sp = xr.getStringPool();
    	 * XmlSParser xs = new XmlSParser(xr, XmlEvent.CHARDATA);
    	 * xs.setReadString("Fo'oFo'o");
    	 * xs.next();
    	 * String foo1 = sp.intern(xs.getText());
    	 * xs.next();
    	 * String foo2 = sp.intern(xs.getText());
    	 * System.out.println(foo1 == foo2);
    	 * 

    * @see StringPool */ public String getCanonicalText() throws IOException, XmlException { return scanner.getCanonicalText(); } /* * Returns the event last returned by the next method. * This may not be valid if the stream was read from since * next was called. * * @see #next public int getEvent() { return curEvent; } */ /** * Returns true if interested in this event. */ private static boolean want(int events, int event) { return (events & event) != 0; } /** * Determines the next event, also skips over whitespace if * set as such. Sets curEvent. */ private void peekEvent() throws IOException, XmlException { if (skipWS) reader.S(); curEvent = scanner.peekEvent(); if (curEvent == NONE) { throw new XmlException("Unknown or invalid token read: " + scanner); } } /** * Sets whether or not to preserve whitespace. This is to eliminate * the frustration of getting {@link XmlEvent#CHARDATA CHARDATA} events * for whitespace. However, this means that initial whitespace for * elements is not preserved. Note that whitespace following a * CHARDATA event is not trimmed by the * {@link #getText} methods. *

    * Currently, this has no effect on the behavior of the * {@link #getContent} and {@link #getElementTree} * methods. Create a {@link Dtd} and supply it to the * {@link XmlReader} if whitespace preservation is * not important for creating object trees. *

    */ public void setSkipWS(boolean skipWS) { this.skipWS = skipWS; } /** * Sets if repeated text events should be ignored. The parser * can return multiple events when a reference, text block, * or character data section is read, but this is usually * surperfluous information. However, upon encountering non-text * data within a text block a separate event is generated. *

    * By default, this is set true. This means that the text: *

    x &lt; <![CDATA[ y]]>
    * will be treated as one CHARDATA event, not as a string of * four different text events. *

    */ public void setSkipRepeatTextEvents(boolean skip) { this.skipRT = skip; } /** * Closes the underlying stream. * Calling any more methods on this object will likely result in an * IOException. */ public void close() throws IOException { reader.close(); } /** * Returns the parse tree depth of this tree. The depth is incremented * once next is called following a STAG event, * and decremented once next is called following an * ETAG event. * @return an integer, representing the number of open element tags * encountered so far that have not been ended */ public int getDepth() { return depth; } /** * Moves the stream up to the depth given. * If depth exceeds the current level, this method has * no effect. If depth is zero, this reads until the * end of the document. This is useful for reading in the remaining * content of an entire XML document that is no longer important. * Negative values are allowed. * * @see #close * @see #getDepth */ public void up(int depth) throws IOException, XmlException { while (this.depth > depth) { next(); } } /** * Returns a string representation of this object for debugging. */ @Override public String toString() { String s = "XmlSParser [reader=" + reader + " event=" + eventToString(curEvent) + " depth=" + depth + "]"; return s; } /** * Converts an event to a debug string. This does not * function for OR'd together flags, except TEXT, since * only one string is returned. *

    * Example use: XmlSParser.eventToString(XmlEvent.STAG) *

    * * @see XmlEvent */ public static String eventToString(int event) { switch (event) { case NONE: return "NONE"; case TEXT: return "TEXT"; case ALL_EVENTS: return "ALL_EVENTS"; case STAG: return "STAG"; case ETAG: return "ETAG"; case CHARDATA: return "CHARDATA"; case CDSECT: return "CDSECT"; case REFERENCE: return "REFERENCE"; case DOCTYPE_DECL: return "DOCTYPE_DECL"; case XML_DECL: return "XML_DECL"; case COMMENT: return "COMMENT"; case PI: return "PI"; case ELEMENT_DECL: return "ELEMENT_DECL"; case ATTLIST_DECL: return "ATTLIST_DECL"; case ENTITY_DECL: return "ENTITY_DECL"; case CONDITIONAL_SECT: return "CONDITIONAL_SECT"; case NOTATATION_DECL: return "NOTATATION_DECL"; case EOD: return "EOD"; default: return "EVENT_" + event; } } } libexml-java-0.0.20080703.orig/e-xml/src/main/java/net/noderunner/exml/ElementReq.java0000644000175000017500000001734111014421656030025 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.exml; import java.util.ArrayList; import java.util.Iterator; import java.util.List; /** * This is an Element Requirement object, which is used as a node in a parse * tree. It maintains no internal state, so may be used across threads. */ public class ElementReq { private static class ElementNS { public String name; public String namespaceURI; @Override public String toString() { return name; } } static final int SOLE = 1; // a static final int SEQUENCE = 2; // (a, b, c) static final int CHOICE = 4; // (a | b | c) static final int STAR = 8; // (a | b | c)* d* static final int PLUS = 16; // (a | b | c)+ d+ static final int QUESTION = 32; // (a | b | c)? d? static final int PCDATA = 128; // PCDATA static final int ANY = 256; /** * OR'ed together flags, such as PCDATA | CHOICE. */ private int kind; /** * Contains either a List (isSequence() || isChoice() == true) or * ElementNS (isSole() == true). If a List, it contains ElementReq * instances. */ private Object content; private ElementReq parent; /** * Constructs an empty requirement. Sub-requirements must be added with * the add method. */ public ElementReq() { kind = 0; content = null; parent = null; } /** * Constructs a requirement for a specific element. */ public ElementReq(String name) { this(name, null); } /** * Constructs a requirement for a specific element. * @param name element name to add * @param namespaceURI namespace element belongs to or null */ public ElementReq(String name, String namespaceURI) { ElementNS ns = new ElementNS(); ns.name = name; ns.namespaceURI = namespaceURI; kind = SOLE; content = ns; } /** * Constructs a requirement for a specific element. * For performance reasons, element instances in the Dtd and in the * document must belong to the same string pool instance. * @param e Element */ public ElementReq(Element e) { this(e.getName(), e.getNamespaceURI()); } /** * Adds an ElementReq instance to this tree. * An example use of this would be adding (c | d) to * (a, b) to make (a, b, (c | d)). */ public void add(ElementReq req) { req.parent = this; if (content == null) content = new ArrayList(); ((List)content).add(req); } /** * Returns the i'th child of this ElementReq. */ public ElementReq getChild(int i) { List l = (List)content; return (ElementReq)l.get(i); } /** * Returns the number of children of this ElementReq. */ public int size() { if (content == null) return 0; List l = (List)content; return l.size(); } /** * Returns the rule that allows that element in a choice. * Thus, looking for 'c' in (a | (b?, c) | d) will return * the rule for c. If it is not in this sub-tree, * null is returned. */ public ElementReq followChoice(Element e) { // System.out.println("followChoice " + e + " " + this); int size = size(); for (int i = 0; i < size; i++) { ElementReq subreq = getChild(i); if (subreq.isSole()) { if (subreq.isElement(e)) { // System.out.println("Returning " + e + " " + subreq); return subreq; } } else { ElementReq subsubreq = subreq.followChoice(e); if (subsubreq != null) return subsubreq; } if (isSequence() && !subreq.isQuestion() && !subreq.isStar()) break; } return null; } public void setStar() { kind |= STAR; } public void setQuestion() { kind |= QUESTION; } public void setPlus() { kind |= PLUS; } public void setPCDATA() { kind |= PCDATA; } public void setPCDATA(boolean yes) { if (!yes) kind &= ~PCDATA; else setPCDATA(); } public void setANY() { kind |= ANY; } public void setSequence() { kind |= SEQUENCE; } public void setChoice() { kind |= CHOICE; } /** * Sets the type by a character; one of: ? * +. */ public void setRepeating(int c) { if (c == '?') setQuestion(); if (c == '*') setStar(); if (c == '+') setPlus(); } public boolean isSequence() { return (kind & SEQUENCE) != 0; } public boolean isChoice() { return (kind & CHOICE) != 0; } public boolean isSole() { return (kind & SOLE) != 0; } public boolean isEmpty() { return (kind == 0); } public boolean isStar() { return (kind & STAR) != 0; } public boolean isPlus() { return (kind & PLUS) != 0; } public boolean isQuestion() { return (kind & QUESTION) != 0; } public boolean isANY() { return (kind & ANY) != 0; } public boolean isPCDATA() { return (kind & PCDATA) != 0; } /** * This must be called before element rules can be tested. * This sets the isQuestion() state *
    	 * (b | c? | d) becomes (b | c | d)?
    	 * (b?, c?, d?) becomes (b, c, d)?
    	 * (b | c* | d) becomes (b | c* | d)?
    	 * (b*, c*, d*) becomes (b*, c*, d*)?
    	 * (b*)         becomes (b*)*
    	 * 
    */ public void normalize() { if (!isSequence() && !isChoice()) return; boolean flip = isSequence(); for (int i = 0; i < size(); i++) { ElementReq req = getChild(i); // first normalize children req.normalize(); if (isSequence() && !req.isQuestion() && !req.isStar()) flip = false; if (isChoice() && (req.isQuestion() || req.isStar())) flip = true; } if (size() == 1) { if (getChild(0).isStar()) setStar(); if (getChild(0).isPlus()) setPlus(); } if (flip) { setQuestion(); } } /** * Returns the parent rule for this element requirement. */ public ElementReq getParent() { return parent; } /** * Returns the location of the occurance of this element in the parent * element requirement. For example in this tree: * (a, (b, c), d) * for the object (b, c), this method * will return 1. */ public int getParentIndex() { List l = (List)getParent().content; return l.indexOf(this); } /** * Returns a string representation of this rule. */ @Override public String toString() { StringBuffer sb = new StringBuffer(32); if (isANY()) sb.append("ANY"); if (isPCDATA()) { sb.append("(#PCDATA"); if (isChoice()) sb.append(" | "); else sb.append(')'); } if (isSequence() || isChoice()) { if (!isPCDATA()) sb.append('('); Iterator i = ((List)content).iterator(); while (i.hasNext()) { sb.append(i.next()); if (i.hasNext()) sb.append(isSequence() ? ", " : " | "); } sb.append(')'); } if (isSole()) { sb.append(content.toString()); } if (isEmpty()) sb.append(XmlTags.CONTENTSPEC_EMPTY); if (isStar()) sb.append('*'); if (isPlus()) sb.append('+'); if (isQuestion()) sb.append('?'); return sb.toString(); } private boolean eq(String s1, String s2) { if (s1 == s2) return true; if (s1 == null) return false; return s1.equals(s2); } public boolean isElement(Element e) { ElementNS ns = (ElementNS)content; return eq(ns.name, e.getName()) && eq(ns.namespaceURI, e.getNamespaceURI()); } } libexml-java-0.0.20080703.orig/e-xml/src/main/java/net/noderunner/exml/Comment.java0000644000175000017500000000354010762067376027400 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.exml; /** * Stores the characters of a XML comment. * There may be many instances of this object per Element. * * @version 1.0 * @author Elias Ross */ public class Comment implements Node { private XmlCharArrayWriter w; /** * Constructs an empty comment. * Append data using the {@link #getWriter} method. */ public Comment() { w = new XmlCharArrayWriter(); } /** * Returns the underlying XmlCharArrayWriter object. */ public XmlCharArrayWriter getWriter() { return w; } /** * Returns the value COMMENT_NODE. */ public short getNodeType() { return COMMENT_NODE; } /** * Returns a newly constructed String * containing the comment data. */ public String getData() { return w.toString(); } /** * Returns a string representation of this object, including the * comment tags <!-- and -->. */ public String toString() { StringBuffer sb = new StringBuffer(w.size() + 12); sb.append(XmlTags.COMMENT_BEGIN); sb.append(w.getBuffer(), 0, w.size()); sb.append(XmlTags.COMMENT_END); return sb.toString(); } } libexml-java-0.0.20080703.orig/e-xml/src/main/java/net/noderunner/exml/PI.java0000644000175000017500000000426210762067376026310 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.exml; /** * Stores data belonging to a processing instruction. * A processing instruction looks like this: *
     * <?pi something here ?> 
     * 
    * * @version 1.0 * @author Elias Ross */ public class PI implements Node { private XmlCharArrayWriter w; private String name; /** * Constructs an empty processing instruction. * @param name processing instruction name, for example * php or foo */ public PI(String name) { this.name = name; w = new XmlCharArrayWriter(); } /** * Returns the underlying XmlCharArrayWriter. */ public XmlCharArrayWriter getWriter() { return w; } /** * Returns the value PI_NODE. */ public short getNodeType() { return PI_NODE; } /** * Returns the name of the processing instruction. */ public String getName() { return name; } /** * Returns the underlying data as a newly constructed * string. */ public String getData() { return w.toString(); } /** * Returns a string representation of this object. * Wraps the data in <? ?> strings. */ public String toString() { StringBuffer sb = new StringBuffer(w.size() + 16); sb.append(XmlTags.PI_BEGIN); sb.append(name); sb.append(' '); // sb.append(XmlWriter.escape(getData())); // I don't think you're suppose to escape this sb.append(w.getBuffer(), 0, w.size()); sb.append(XmlTags.PI_END); return sb.toString(); } } libexml-java-0.0.20080703.orig/e-xml/src/main/java/net/noderunner/exml/AttributeValueType.java0000644000175000017500000000324110762067376031576 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.exml; /** * An enumeration of the different kinds of attribute value types, * as specified by the XML standard. *

    * @see AttributeRule * @author Elias Ross * @version 1.0 */ public interface AttributeValueType { /** Attribute value can contain any character data. */ int CDATA = 0; /** Attribute value must contain a name. */ int NMTOKEN = 1; /** Attribute value must contain a list of names. */ int NMTOKENS = 2; /** Attribute value must contain an entity. */ int ENTITY = 3; /** Attribute value must contain a list of entities. */ int ENTITIES = 4; /** Attribute value must be a document unique identifier. */ int ID = 5; /** Attribute must reference some other ID. */ int IDREF = 6; /** Attribute must reference some other IDs. */ int IDREFS = 7; /** Attribute must reference a notation. */ int NOTATION = 8; /** Attribute must be a name group. */ int NAME_GROUP = 9; } libexml-java-0.0.20080703.orig/e-xml/src/main/java/net/noderunner/exml/Attribute.java0000644000175000017500000000477511014421656027736 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.exml; import java.io.StringWriter; /** * A very basic read-only XML attribute. * The {@link Namespace} interface is implemented, however, its * methods, excepting {@link Namespace#getName}, merely return * null. * * @author Elias Ross * @version 1.0 */ public class Attribute implements Namespace { private String name; private String value; /** * Constructs an Xml attribute. * @param name Name of element * @param value Attribute value */ public Attribute(String name, String value) { this.name = name; this.value = value; } /** * Returns the name of this Attribute. * @return the name */ public String getName() { return name; } /** * Returns the value of this Attribute, without escaping any * characters. * @return the value */ public String getValue() { return value; } /** * By default, returns null. * @see AttributeNS#getNamespaceURI */ public String getNamespaceURI() { return null; } /** * By default, returns null. * @see AttributeNS#getPrefix */ public String getPrefix() { return null; } /** * By default, returns null. * @see AttributeNS#getLocalName */ public String getLocalName() { return null; } /** * Returns a string representation of this Attribute. Also, * escapes single quotes, <, and &. * @return this object as the string name='value' */ @Override public String toString() { StringWriter sw = new StringWriter(64); StringBuffer sb = sw.getBuffer(); if (getPrefix() != null) sb.append(getPrefix()).append('.'); sb.append(name).append("=\""); try { XmlWriter.escape(value, sw); } catch (java.io.IOException e) { throw new RuntimeException(e.toString()); } return sb.append('"').toString(); } } libexml-java-0.0.20080703.orig/e-xml/src/main/java/net/noderunner/exml/ArrayStack.java0000644000175000017500000001053711014421656030030 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.exml; import java.util.Iterator; import java.util.NoSuchElementException; /** * This is a basic stack data-structure, which holds items internally in * an array. * It dynamically re-allocates to grow and shrink. It will not shrink * below its initial capacity. *

    * Although internally, the datastructure is essentially * a list, it does not implement the methods from * java.util.List since in the strictest sense, a stack * should not allow access to its non-top element. *

    */ final class ArrayStack extends java.util.AbstractCollection implements Stack { private Object items[]; private int size; private int initialCapacity; /** * Creates a ArrayStack with a default capacity of 16. * The capacity will automatically double or half if necessary. */ public ArrayStack() { this(16); } /** * Creates a ArrayStack with a specific capacity. * The capacity will automatically double or half if necessary. * @param capacity non-zero, positive capacity */ public ArrayStack(int capacity) { if (capacity <= 0) throw new IllegalArgumentException("Must specify non-zero, positive capacity: " + capacity); // the last entry is always null items = new Object[capacity]; size = 0; initialCapacity = capacity; } @Override public int size() { return size; } private void expandIfNeeded() { if (size == items.length) { Object newItems[] = new Object[items.length * 2]; System.arraycopy(items, 0, newItems, 0, size); items = newItems; } } private void shrinkIfNeeded() { if (items.length > initialCapacity && size < items.length / 2) { Object newItems[]; if (size <= initialCapacity / 2) newItems = new Object[initialCapacity]; else newItems = new Object[items.length / 2]; System.arraycopy(items, 0, newItems, 0, size); items = newItems; } } /** * Adds an object to the end of this array stack. * This object can be null. * @return true * @see #push */ @Override public boolean add(T element) { expandIfNeeded(); items[size++] = element; return true; } @SuppressWarnings("unchecked") private T item(int i) { return (T)items[i]; } private class ArrayStackIterator implements Iterator { int at = size; @SuppressWarnings("unchecked") public T next() { if (at == 0) throw new NoSuchElementException("No more elements"); return (T)item(--at); } public boolean hasNext() { return at != 0; } public void remove() { if (at == size) throw new UnsupportedOperationException("Call next first"); if (at != size - 1) throw new UnsupportedOperationException("Cannot remove non-top elements"); pop(); } } /** * Returns an iterator that first returns the top element, then * the next item below, etc. The Iterator.remove * operation is only supported for removing the top element. */ @Override public Iterator iterator() { return new ArrayStackIterator(); } @Override public void clear() { size = 0; shrinkIfNeeded(); } public void push(T element) { add(element); } public T peek() { if (size == 0) throw new NoSuchElementException("Empty ArrayStack"); return item(size - 1); } public T pop() { if (size == 0) throw new NoSuchElementException("Empty ArrayStack"); shrinkIfNeeded(); size--; T top = item(size); items[size] = null; return top; } /** * For unit-testing, returns the capacity of this collection. */ int capacity() { return items.length; } /** * Constructs a new instance. */ public static ArrayStack create() { return new ArrayStack(); } } libexml-java-0.0.20080703.orig/e-xml/src/main/java/net/noderunner/exml/AttributeNS.java0000644000175000017500000000437510762067376030211 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.exml; /** * An XML attribute with namespace information. * * @author Elias Ross * @version 1.0 */ public class AttributeNS extends Attribute { private String namespaceURI; private String prefix; private String localName; /** * Constructs an XML attribute with a namespace. * Fields from the given interface are copied internally. * @param namespace Attribute namespace * @param value Attribute value */ public AttributeNS(Namespace namespace, String value) { this(namespace.getName(), value, namespace.getNamespaceURI(), namespace.getPrefix(), namespace.getLocalName()); } /** * Constructs an XML attribute with a namespace. * @param name Name of element, minus prefix * @param value Attribute value * @param namespaceURI Attribute namespace * @param prefix Attribute namespace prefix */ public AttributeNS(String name, String value, String namespaceURI, String prefix, String localName) { super(name, value); this.namespaceURI = namespaceURI; this.prefix = prefix; this.localName = localName; } /** * Returns the namespace of this Attribute, or null if this * attribute belongs to no particular namespace. */ public String getNamespaceURI() { return namespaceURI; } /** * Returns the namespace of this Attribute, or null if this * attribute belongs to no particular namespace. */ public String getPrefix() { return prefix; } /** * Returns the local name of this Attribute. */ public String getLocalName() { return localName; } } libexml-java-0.0.20080703.orig/e-xml/src/main/java/net/noderunner/exml/ElementToSAX.java0000644000175000017500000000764111014421656030236 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.exml; import java.util.List; import org.xml.sax.Attributes; import org.xml.sax.ContentHandler; import org.xml.sax.SAXException; /** * This class translates an Element into a series of calls to a * SAX ContentHandler instance. */ public class ElementToSAX { private ElementToSAX() { } /** * Calls startElement, endElement, * and characters of this handler for element * events. Note that the Attributes instance passed in * to the startElement is reused, hence will be no * longer valid once the callback ends. */ public static void pipe(Element e, ContentHandler h) throws SAXException { pipe(new EAttributes(), e, h); } /** * This recycles the same EAttributes instance. */ private static void pipe(EAttributes attr, Element e, ContentHandler h) throws SAXException { attr.setList(e.getAttributes()); h.startElement("", e.getName(), e.getName(), attr); List list = e.getChildNodes(); if (list != null) { for (int i = 0; i < list.size(); i++) { Node node = list.get(i); if (node.getNodeType() == Node.ELEMENT_NODE) pipe((Element)node, h); if (node.getNodeType() == Node.TEXT_NODE) { XmlCharArrayWriter writer = ((CharacterData)node).getWriter(); h.characters(writer.getBuffer(), 0, writer.size()); } } } h.endElement("", e.getName(), ""); } static class EAttributes implements Attributes { private List list; /** * Construct using a null list. */ public EAttributes() { } /** * Sets the underlying list. */ public void setList(List list) { this.list = list; } public int getIndex(String qName) { if (list == null) return -1; for (int i = 0; i < list.size(); i++) { Attribute a = list.get(i); if (a.getName().equals(qName)) return i; } return -1; } public int getIndex(String uri, String localPart) { return -1; } public int getLength() { if (list == null) return 0; return list.size(); } public String getLocalName(int index) { return ""; } public String getQName(int index) { if (list == null) return ""; Attribute a = list.get(index); return a.getName(); } public String getType(int index) { return "CDATA"; } public String getType(String qName) { return "CDATA"; } public String getType(String uri, String localName) { return ""; } public String getURI(int index) { return ""; } public String getValue(int index) { if (list == null) return ""; Attribute a = list.get(index); return a.getValue(); } public String getValue(String qName) { if (list == null) return ""; Attribute a; for (int i = 0; i < list.size(); i++) { a = list.get(i); if (a.getName().equals(qName)) return a.getValue(); } return ""; } public String getValue(String uri, String localName) { return ""; } @Override public String toString() { if (list == null) return ""; StringBuffer sb = new StringBuffer(32); for (int i = 0; i < list.size(); i++) { sb.append(' ').append(list.get(i)); } return sb.toString(); } } } libexml-java-0.0.20080703.orig/e-xml/src/main/java/net/noderunner/exml/NullWriter.java0000644000175000017500000000344710762067376030113 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.exml; import java.io.Writer; /** * Used to copy unwanted information to the bit-bucket. * Implemented as a singleton, since only one * instance is ever needed. * * @author Elias Ross * @version 1.0 */ public final class NullWriter extends Writer { private static final NullWriter nw = new NullWriter(); /** * Returns the only instance of a NullWriter. * @return a null writer */ public static Writer getInstance() { return nw; } /** * This method is private to keep this from being constructed outside * the class. */ private NullWriter() { } /** * Does nothing. */ public void flush() { } /** * Does nothing. */ public void write(int c) { } /** * Does nothing. */ public void write(char cbuf[]) { } /** * Does nothing. */ public void write(char cbuf[], int off, int len) { } /** * Does nothing. */ public void write(String str) { } /** * Does nothing. */ public void write(String str, int off, int len) { } /** * Does nothing. */ public void close() { } } libexml-java-0.0.20080703.orig/e-xml/src/main/java/net/noderunner/exml/SystemLiteralResolver.java0000644000175000017500000000224610762067376032323 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.exml; import java.io.IOException; import java.io.Reader; /** * An interface for classes that resolve system literals by filename or other name. */ public interface SystemLiteralResolver { /** * Returns an input stream to the contents of the * specified system literal. * * @throws IOException if this literal could not be found or loaded */ Reader resolve(String systemLiteral) throws IOException; } libexml-java-0.0.20080703.orig/e-xml/src/main/java/net/noderunner/exml/ElementException.java0000644000175000017500000000212710762067376031246 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.exml; /** * Indicates an invalid operation was performed on an * element. */ public class ElementException extends RuntimeException { private static final long serialVersionUID = -2800027552006941201L; /** * Construct a new ElementException with a message. */ public ElementException(String message) { super(message); } } libexml-java-0.0.20080703.orig/e-xml/src/main/java/net/noderunner/exml/Entity.java0000644000175000017500000001263711014421656027243 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.exml; import java.io.IOException; import java.io.Reader; import java.util.StringTokenizer; /** * Contains an XML Entity and its attributes. * Also, contains logic for resolving and evaluating an entity. */ public class Entity { private String value; private boolean resolved; private boolean resolving; private String publicID; private String systemID; /** * Constructs an Entity with a string value. */ public Entity(String value) { this.value = value; } /** * Constructs an unresolved entity. */ public Entity(String publicID, String systemID) { this.publicID = publicID; this.systemID = systemID; } private StringBuffer evaluate(Reader r) throws IOException { StringBuffer sb = new StringBuffer(64); int len = 0; char cbuf[] = new char[256]; do { len = r.read(cbuf, 0, cbuf.length); if (len > 0) sb.append(cbuf, 0, len); } while (len > 0); return sb; } /** * Returns a character for the given built-in entity, * or -1 if it isn't built-in. */ private static int builtin(String entityName) { if (entityName.equals("lt")) return '<'; if (entityName.equals("gt")) return '>'; if (entityName.equals("quot")) return '"'; if (entityName.equals("apos")) return '\''; if (entityName.equals("amp")) return '&'; return -1; } /** * Resolves all entities in the given string. * Returns the result. */ private static String doResolve(String s, XmlReader reader, boolean all) throws XmlException, IOException { StringTokenizer st = new StringTokenizer(s, "&;", true); if (st.countTokens() == 1) // no &'s here return s; StringBuffer sb = new StringBuffer(s.length()); while (st.hasMoreTokens()) { String token = st.nextToken(); if (token.equals("&")) { if (!st.hasMoreTokens()) throw new XmlException("Expected name in entity " + s); String entityName = st.nextToken(); if (!st.hasMoreTokens()) throw new XmlException("Expected ; in entity " + s); st.nextToken(); int c = builtin(entityName); if (c > 0) { if (all) sb.append(c); else sb.append('&').append(entityName).append(';'); } else { Entity entity = reader.getDtd().getEntity(entityName); if (entity == null) throw new XmlException("Entity not found " + entityName); sb.append(entity.resolve(reader)); } } else { sb.append(token); } } return sb.toString(); } /** * Returns the resolved entity value with escaped characters. * Returns immediately if the entity has already been resolved. * If it hasn't been yet resolved, uses the resolver from the * given {@link XmlReader}. * * @see XmlReader#getResolver */ private String resolve(XmlReader reader) throws XmlException, IOException { if (resolved) return value; if (value == null) { if (systemID == null) throw new XmlException("SystemID not set, could not resolve entity"); Reader r = reader.getResolver().resolve(systemID); value = evaluate(r).toString(); return value; } if (resolving) throw new XmlException("Circular entity evaluation for " + this); resolving = true; value = doResolve(value, reader, false); resolving = false; resolved = true; return value; } /** * Returns true if this Entity is external. * An entity is external if it has a system ID. */ public boolean isExternal() { return systemID != null; } /** * Returns the resolved entity value. * Returns immediately if the entity has already been resolved. * If it hasn't been yet resolved, uses the resolver from the * given {@link XmlReader}. * * @see XmlReader#getResolver */ public String resolveAll(XmlReader reader) throws XmlException, IOException { if (!resolved) resolve(reader); return value; } /** * Returns the resolved value, if it exists. * Returns null if it has not yet been resolved. * @see #resolveAll */ public String getValue() { return value; } /** * Sets the resolved value. */ public void setValue(String value) { this.value = value; } /** * Returns the system ID. */ public String getSystemID() { return systemID; } /** * Returns the optional public ID. */ public String getPublicID() { return publicID; } /** * Returns true if this Entity is being resolved, internally or * externally. */ boolean isResolving() { return resolving; } /** * Sets if this Entity is being resolved, internally or externally. */ void setResolving(boolean resolving) { this.resolving = resolving; } /** * Returns a string representation of this object. */ @Override public String toString() { return "Entity value=" + value + " systemID=" + systemID + " publicID=" + publicID; } } libexml-java-0.0.20080703.orig/e-xml/src/main/java/net/noderunner/exml/NamespaceImpl.java0000644000175000017500000000675410762067376030526 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.exml; /** * Describes a re-useable structure for namespaces. * * @author Elias Ross * @version 1.0 */ public class NamespaceImpl implements Namespace { private String namespaceURI; private String prefix; private String localName; private String name; /** * Constructs a new NamespaceImpl with no parameters. */ public NamespaceImpl() { this(null, null, null, null); } /** * Constructs a new NamespaceImpl * with all required parameters. These parameters * may be null. * Note that the values are not checked for correctness. */ public NamespaceImpl(String namespaceURI, String prefix, String localName, String name) { this.namespaceURI = namespaceURI; this.prefix = prefix; this.localName = localName; this.name = name; } /** * Returns the namespace URI or null if this name * belongs to the default namespace. */ public String getNamespaceURI() { return namespaceURI; } /** * Sets the namespace URI. */ public void setNamespaceURI(String namespaceURI) { this.namespaceURI = namespaceURI; } /** * Returns the prefix in use. */ public String getPrefix() { return prefix; } /** * Sets the prefix to use. */ public void setPrefix(String prefix) { this.prefix = prefix; } /** * Returns the local name, without the prefix. */ public String getLocalName() { return localName; } /** * Sets the local name to use. */ public void setLocalName(String localName) { this.localName = localName; } /** * Returns the full name, including the colon. */ public String getName() { if (name == null) if (prefix != null && localName != null) name = prefix + ':' + localName; return name; } /** * Sets the full name to use. */ public void setName(String name) { this.name = name; } /** * Clears and sets all fields to null. * @see #isClear */ public void clear() { this.namespaceURI = null; this.prefix = null; this.localName = null; this.name = null; } /** * Returns true if no data has been stored within this * namespace object, specifically if all fields are null. * * @see #clear */ public boolean isClear() { return this.namespaceURI == null && this.prefix == null && this.localName == null && this.name == null; } /** * Returns true if the namespace fields * prefix and localName are set. * Returns false if the name defined has no * namespace. */ public boolean hasNamespace() { return prefix != null || localName != null; } public String toString() { return "NamespaceImpl prefix=" + prefix + " name=" + name + " localName=" + localName + " namespaceURI=" + namespaceURI; } } libexml-java-0.0.20080703.orig/e-xml/src/main/java/net/noderunner/exml/XmlTags.java0000644000175000017500000001215710762067376027361 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.exml; /** * Tags for matching regions; these are all character arrays to assist * in the matching algorithm. */ interface XmlTags { char [] ATTLIST_DECL_BEGIN = "".toCharArray(); char [] COMMA = ",".toCharArray(); char [] COMMENT_BEGIN = "".toCharArray(); char [] CONDITIONAL_BEGIN = "".toCharArray(); char [] PUBLIC_BEGIN = "PUBLIC".toCharArray(); char [] REQUIRED_BEGIN = "#REQUIRED".toCharArray(); char [] STANDALONE_BEGIN = "standalone".toCharArray(); char [] SYSTEM_BEGIN = "SYSTEM".toCharArray(); char [] VERSION_BEGIN = "version".toCharArray(); char [] XML_DECL = " * char c = 'f'; * if (c < 127) return FIRST_NAME_CHAR[c]; *
    boolean FIRST_NAME_CHAR[] = { false,false,false,false,false,false,false,false, false,false,false,false,false,false,false,false, false,false,false,false,false,false,false,false, false,false,false,false,false,false,false,false, false,false,false,false,false,false,false,false, false,false,false,false,false,false,false,false, false,false,false,false,false,false,false,false, false,false,true ,false,false,false,false,false, false,true ,true ,true ,true ,true ,true ,true , true ,true ,true ,true ,true ,true ,true ,true , true ,true ,true ,true ,true ,true ,true ,true , true ,true ,true ,false,false,false,false,true , false,true ,true ,true ,true ,true ,true ,true , true ,true ,true ,true ,true ,true ,true ,true , true ,true ,true ,true ,true ,true ,true ,true , true ,true ,true ,false,false,false,false,false}; /* * Quick lookup to see if a character is a NameChar. *
    	 * char c = '_';
    	 * if (c < 127) return NAME_CHAR[c];
    	 * 
    boolean NAME_CHAR[] = { false,false,false,false,false,false,false,false, false,false,false,false,false,false,false,false, false,false,false,false,false,false,false,false, false,false,false,false,false,false,false,false, false,false,false,false,false,false,false,false, false,false,false,false,false,true ,true ,false, true ,true ,true ,true ,true ,true ,true ,true , true ,true ,true ,false,false,false,false,false, false,true ,true ,true ,true ,true ,true ,true , true ,true ,true ,true ,true ,true ,true ,true , true ,true ,true ,true ,true ,true ,true ,true , true ,true ,true ,false,false,false,false,true , false,true ,true ,true ,true ,true ,true ,true , true ,true ,true ,true ,true ,true ,true ,true , true ,true ,true ,true ,true ,true ,true ,true , true ,true ,true ,false,false,false,false,false}; */ } libexml-java-0.0.20080703.orig/e-xml/src/main/java/net/noderunner/exml/ElementRule.java0000644000175000017500000004124311014421656030203 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.exml; import java.io.IOException; import java.io.StringReader; import java.util.ArrayList; import java.util.BitSet; import java.util.Iterator; import java.util.List; /** * This class is useful for validating the contents of elements within XML * documents. When element or attribute validation is taking place, various * conditions can be checked by passing in state objects. Internally contains a * tree of ElementReq objects and a list of * AttributeRule objects. *

    * * @author Elias Ross * @version 1.0 * @see Dtd */ public class ElementRule { private ElementReq rootReq; private List attributeRules; private boolean normalized; /** * A handle for maintaining state when verifying an element tree. */ public static final class ElementRuleState { private int index; private boolean repeat; // current element private boolean matched; // a choice was matched private boolean done; private ElementReq req; /** * Constructs a new ElementRuleState instance. */ public ElementRuleState() { clear(); } /** * Recyles this object, so it may be used with other elements. */ public void clear() { index = 0; req = null; repeat = false; done = false; matched = false; } private void incIndex() throws ElementRuleException { if (isDone()) return; index++; if (req.isChoice() && matched && !req.isStar() && !req.isPlus()) { goUp(); incIndex(); return; } if (getIndex() >= req.size()) { if (req.isChoice() && !matched) throw new ElementRuleException("Choice did not match element", req); if (!req.isStar() && !req.isPlus()) { goUp(); incIndex(); } else { // boolean wasChoice = req.isChoice(); goUp(); // if (wasChoice && matched) // incIndex(); } } else { if (req.isSequence()) { matched = false; } } repeat = false; } private int getIndex() { return index; } private boolean isRepeat() { return repeat; } private boolean isMatched() { return matched; } private void setRepeat() { repeat = true; } private void setMatch() throws ElementRuleException { matched = true; if (!isRepeat() && req.isChoice()) { if (!req.isStar() && !req.isPlus()) { goUp(); incIndex(); } else { goUp(); } } } private void setDone(boolean done) { this.done = done; } private ElementReq getReq() { return req; } private void setReq(ElementReq req) { this.req = req; } private void setIndex(int index) { this.index = index; } /** * Returns a debug string. */ @Override public String toString() { return "i=" + getIndex() + " req=" + req + " rp=" + isRepeat() + " m=" + matched + " d=" + isDone(); } private void goUp() throws ElementRuleException { ElementReq parent = req.getParent(); if (parent == null) { setDone(true); } else { setIndex(req.getParentIndex()); setReq(parent); setRepeat(); setMatch(); } } /** * Returns true if the pattern was successfully * completed. */ private boolean isDone() { return done; } } /** * If a bit is set true, that attribute is required. */ // private BitSet requiredAttributes = new BitSet(128); /** * Returns -1 if not found, otherwise index in attributeRules list. */ private int indexOf(Attribute a) { for (int i = 0; i < attributeRules.size(); i++) { AttributeRule r = attributeRules.get(i); if (r.matches(a)) return i; } return -1; } /** * A handle for maintaining state when verifying an attribute tree. */ public static final class AttributeRuleState { /** * Set of visited attributes. Bits correspond to indicies in the * attributes list. */ private BitSet visited = new BitSet(32); private static final BitSet EMPTY_SET = new BitSet(0); /** * Constructs a new AttributeRuleState instance. */ public AttributeRuleState() { clear(); } /** * If this object is to be recycled, call this method to clear its * fields. */ public void clear() { visited.and(EMPTY_SET); } private boolean encountered(int index) { return visited.get(index); } /** * Checks for duplicate attribute declarations. */ private void encounterAttribute(int index) throws AttributeRuleException { if (visited.get(index)) throw new AttributeRuleException( "Duplicate attribute declaration"); visited.set(index); } /** * Returns debug information. */ @Override public String toString() { return "AttributeRuleState visited=" + visited; } } /** * Constructs a plain ElementRule. Call * allowElement and allowAttribute with * elements and attributes to allow, otherwise this element will accept * any element or attribute, as well as PCDATA. * * @see #allowElement * @see #allowAttribute * @see ElementReq#setANY */ public ElementRule() { this(new ElementReq(), null); rootReq.setANY(); } /** * Constructs an "undeclared" element rule, with attribute rules. This is * useful when scanning DTD's with attribute rules that proceed an element * declaration. */ public ElementRule(List attributeRules) { this.rootReq = null; this.attributeRules = attributeRules; this.normalized = false; } /** * Constructs an ElementRule. * * @param req * an element requirements tree (non-null) * @param attributeRules * a list of AttributeRule objects; null implying any attribute * is allowed * @see Element */ public ElementRule(ElementReq rootReq, List attributeRules) { if (rootReq == null) throw new IllegalArgumentException("Must specify root element"); this.rootReq = rootReq; this.attributeRules = attributeRules; this.normalized = false; } /** * Constructs an ElementRule. As a convience, optionally allows PCDATA * within this element. * * @see ElementReq */ public ElementRule(ElementReq rootReq, List attributeRules, boolean pcdata) { this(rootReq, attributeRules); setAllowPCData(pcdata); } /** * Parses a String, such as "(A | B* | C)" and returns a simple * rule. * * @param s string to parse * @return new rule * @throws XmlException if parsing fails */ public static ElementRule parse(String s) throws XmlException { XmlReader r = new XmlReader(new StringReader(s + " ")); try { return new ElementRule(r.contentspec(), null); } catch (IOException e) { throw new XmlException(e); } } /** * Returns true if character data is allowed in for this element. * * @see ElementReq#isPCDATA */ public boolean isPCDataAllowed() { return rootReq.isPCDATA(); } /** * Validates that the given attribute can be added to this element, given a * AttributeRuleState. Returns the rule appropriate for the * given attribute. If no rule was matched, returns null. * * @throws AttributeRuleException * if the attribute does not belong in the element or has an * invalid value */ public AttributeRule encounterAttribute(Attribute a, AttributeRuleState state) throws AttributeRuleException { if (attributeRules == null) return null; int index = indexOf(a); if (index == -1) throw new AttributeRuleException("Unknown attribute " + a); AttributeRule rule = attributeRules.get(index); if (!rule.allowedValue(a.getValue())) throw new AttributeRuleException( "Attribute value not allowed " + a, rule); state.encounterAttribute(index); return rule; } /** * Returns true when encountered something, false if to call this method * again. */ private boolean encounter(Element e, ElementRuleState state) throws ElementRuleException { if (rootReq.isANY()) return true; ElementReq req = state.getReq(); if (rootReq.size() == 0) throw new ElementRuleException("No child elements allowed", req); if (req.isSole()) throw new IllegalStateException("Parse state incorrect " + state); if (state.isDone()) { state.setDone(false); if (req.isPlus() || req.isStar()) state.setIndex(0); else throw new ElementRuleException("Reached end of pattern, encountered " + e + " state " + state, req); } ElementReq child = req.getChild(state.getIndex()); if (!child.isSole()) { // going down the tree here ElementReq newchild = child.followChoice(e); if (newchild != null) { // arrived at either a child sequence or choice state.clear(); state.setIndex(newchild.getParentIndex()); state.setReq(newchild.getParent()); return false; } } else if (child.isElement(e)) { if (!child.isStar() && !child.isPlus()) { if (req.isChoice()) { // we found it if (req.isPlus() || req.isStar()) { state.setIndex(0); } } else { state.incIndex(); } } else { state.setRepeat(); } state.setMatch(); return true; } // couldn't find in subtree or as child if (req.isSequence()) { if (!child.isQuestion() && !child.isStar() && !(child.isPlus() && state.isMatched())) { throw new ElementRuleException("Unexpected element " + e + " state " + state, req); } } state.incIndex(); return false; } /** * Normalizes the ElementReq tree, which is required for content validation * to work. */ private void normalize() { if (!normalized) rootReq.normalize(); } /** * Verifies when encountering an child element, that it may be added. Pass * in a non-null instance of ElementRuleState to be modified. * * @param e * the element being encountered * @param state * the last state posted to this method, or if no initial state * (this is the first child element encountered), clear it first * using state.clear() */ public void encounterElement(Element e, ElementRuleState state) throws ElementRuleException { normalize(); if (state.getReq() == null) state.setReq(rootReq); while (!encounter(e, state)) ; } private boolean findEnd(ElementRuleState state) throws ElementRuleException { ElementReq req = state.getReq(); // System.out.println("findEnd " + req + " " + state); ElementReq child = req.getChild(state.getIndex()); if (child.isQuestion() || child.isStar() || (child.isPlus() && state.isMatched())) { state.incIndex(); return state.isDone(); } throw new ElementRuleException("Pattern not completed", req); } /** * Verifies that there are no more elements required to be encountered * before closing the element. Otherwise, throws an exception. * * @throws ElementRuleException * if more elements must be visited */ public void encounterEnd(ElementRuleState state) throws ElementRuleException { if (rootReq.isPCDATA() || rootReq.isANY() || rootReq.isEmpty()) return; normalize(); if (state.getReq() == null) state.setReq(rootReq); if (state.isDone()) return; if (rootReq.isStar() || rootReq.isQuestion()) return; while (!findEnd(state)) ; } /** * Verifies that there are no more attributes are required within the start * tag. Also, appends any default or undeclared attributes to the given * list. * * @param attributes * an existing list instance or null if no attributes were yet * encountered * @return an appended or a newly constructed list * @throws AttributeRuleException * if more attributes must be visited */ public List encounterEnd(AttributeRuleState state, List attributes) throws AttributeRuleException { if (attributeRules == null) return attributes; // attributes for (int i = 0; i < attributeRules.size(); i++) { AttributeRule r = attributeRules.get(i); boolean enc = state.encountered(i); if (!enc && r.isRequired()) throw new AttributeRuleException("Required attribute missing", r); if (!enc && r.isDefault()) { if (attributes == null) attributes = new ArrayList(); attributes.add(new Attribute(r.getName(), r.getValue())); } } return attributes; } /** * Allows an element to be inside this element. * * @param e * allow this element to be added */ public void allowElement(Element e) { if (rootReq.isANY()) { rootReq = new ElementReq(); rootReq.isChoice(); rootReq.isStar(); } rootReq.add(new ElementReq(e)); } /** * Allows an element to be inside this element. * * @param name * allow this named element to be added */ public void allowElement(String name) { if (rootReq.isANY()) { rootReq = new ElementReq(); rootReq.isChoice(); rootReq.isStar(); } rootReq.add(new ElementReq(name)); } /** * Allows an attribute (CDATA) to belong inside this element. * * @param a * the attribute to be allowed in this element * @see AttributeValueType#CDATA */ public void allowAttribute(Attribute a) { if (attributeRules == null) attributeRules = new ArrayList(); AttributeRule r = new AttributeRule(AttributeValueType.CDATA); r.setName(a.getName()); attributeRules.add(AttributeRule.cdata(a.getName())); } /** * Adds an AttributeRule to this element rule, if it does not * already exist. */ public void addAttributeRule(AttributeRule rule) { if (attributeRules == null) attributeRules = new ArrayList(); for (int i = 0; i < attributeRules.size(); i++) { AttributeRule r = attributeRules.get(i); if (r.getName().equals(rule.getName())) return; } attributeRules.add(rule); } /** * Allows no elements to be inside this element. */ public void allowNoElements() { rootReq = new ElementReq(); } /** * Allows no attributes to be inside this element. */ public void allowNoAttributes() { attributeRules = new ArrayList(); } /** * Returns the attribute rules for this element, a list of * AttributeRule instances. * * @see AttributeRule */ public List getAttributeRules() { return attributeRules; } /** * Sets the root ElementReq for undeclared elements. This * method operates only on previously undeclared elements. * * @throws ElementRuleException * if this was constructed with a rootReq */ public void setRootReq(ElementReq rootReq) throws ElementRuleException { if (this.rootReq != null) throw new ElementRuleException("Cannot setElementReq", this); this.rootReq = rootReq; } /** * Allows PCDATA. * * @see ElementReq#setPCDATA */ public void setAllowPCData(boolean allow) { if (allow) rootReq.setPCDATA(); } /** * Returns a String representation of this object for debugging. */ @Override public String toString() { return "rootReq=" + rootReq + " attr=" + getAttributeRules(); } /** * Formats the ElementReq tree as a DTD-style declaration. *

    * Example result: * *

    	 * <!ELEMENT name (a | b+)>
    	 * 
    * *

    * * @param name * an element name to indicate this rule belonging to */ public String elementString(String name) { return ""; } /** * Formats the AttributeRule list as a DTD-style declaration. *

    * Example result: * *

    	 * <!ATTLIST name att1 #FIXED "value">
    	 * 
    * *

    * * @param name * an element name to indicate this rule belonging to */ public String attlistString(String ename) { if (getAttributeRules() == null) return ""; StringBuffer sb = new StringBuffer(64); Iterator i = getAttributeRules().iterator(); while (i.hasNext()) { sb.append("'); if (i.hasNext()) sb.append('\n'); } return sb.toString(); } /** * For internal use. */ ElementReq getRootReq() { return rootReq; } } libexml-java-0.0.20080703.orig/e-xml/src/main/java/net/noderunner/exml/AttributeRule.java0000644000175000017500000001443711014421656030562 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.exml; import java.util.Collection; import java.util.Iterator; /** * Contains DTD rules for an attribute. *

    * @author Elias Ross * @version 1.0 */ public class AttributeRule { /** Name of the attribute */ private String name; /** One of the types in AttributeValueType interface */ private int valueType; /** True if attribute is required to be specified */ private boolean required; /** True if attribute is fixed */ private boolean fixed; /** If fixed, the value it must have, otherwise its default value */ private String value; /** If NAME_GROUP or NOTATION then the value must belong to this collection of strings */ private Collection enumeration; /** * Constructs a new AttributeRule for an * {@link AttributeValueType}. */ public AttributeRule(int valueType) { this(valueType, (Collection)null); } /** * Constructs a new AttributeRule for an * {@link AttributeValueType} with an attribute name. * @see AttributeValueType */ public AttributeRule(int valueType, String name) { this(valueType, (Collection)null); setName(name); } /** * Constructs a new AttributeRule for an * AttributeValueType along with an enumeration, a * collection of possible string values. * @see AttributeValueType */ public AttributeRule(int valueType, Collection enumeration) { this.valueType = valueType; this.enumeration = enumeration; this.fixed = false; this.required = false; this.value = null; } /** * Returns a new rule where attribute can contain "CDATA". */ public static AttributeRule cdata(String name) { return new AttributeRule(AttributeValueType.CDATA, name); } /** * Sets the name of the attribute. * TODO: Set up namespace correctly. */ public void setName(String name) { this.name = name; } /** * Returns the name of this attribute. */ public String getName() { return name; } /** * Returns true if the name matches the given attribute. */ public boolean matches(Attribute a) { return name.equals(a.getName()); } /** * Returns true if the attribute value is fixed. */ public boolean isFixed() { return fixed; } /** * Returns true if the attribute is required to be declared. */ public boolean isRequired() { return required; } /** * Returns true if the attribute has a default or fixed value. */ public boolean isDefault() { return value != null; } /** * Returns the default or fixed value. */ public String getValue() { return value; } /** * Sets this attribute to have a fixed value. */ public void setFixed(String value) throws AttributeRuleException { if (valueType == AttributeValueType.NAME_GROUP || valueType == AttributeValueType.NOTATION) { if (!enumeration.contains(value)) throw new AttributeRuleException("FIXED value not in enumeration " + value, this); } this.value = value; fixed = true; } /** * Sets this attribute to be required. */ public void setRequired() { required = true; } /** * Sets the default value for this attribute. */ public void setDefault(String value) { this.value = value; } /** * Returns true if the value is allowed. */ public boolean allowedValue(String value) { if (fixed) return this.value.equals(value); if (valueType == AttributeValueType.NAME_GROUP || valueType == AttributeValueType.NOTATION) return enumeration.contains(value); return true; } /** * Returns the string form of a value, from the interface * AttributeValueType. * @see AttributeValueType */ public static String valueTypeToString(int value) { switch (value) { case AttributeValueType.CDATA: return XmlTags.ST_CDATA; case AttributeValueType.NMTOKEN: return XmlTags.TT_NMTOKEN; case AttributeValueType.NMTOKENS: return XmlTags.TT_NMTOKENS; case AttributeValueType.ENTITY: return XmlTags.TT_ENTITY; case AttributeValueType.ENTITIES: return XmlTags.TT_ENTITIES; case AttributeValueType.ID: return XmlTags.TT_ID; case AttributeValueType.IDREF: return XmlTags.TT_IDREF; case AttributeValueType.IDREFS: return XmlTags.TT_IDREFS; case AttributeValueType.NOTATION: return XmlTags.ET_NOTATION; case AttributeValueType.NAME_GROUP: return "name group"; default: return "unknown type " + value; } } /** * Creates a string formed by a set of Objects as a concatenation. * The concatenation consists of their Object.toString * values in the form: *

    ( obj1 | obj2 | obj3 )
    */ public static String collectionToString(Collection c) { Iterator i = c.iterator(); StringBuffer sb = new StringBuffer(16 * c.size()); sb.append("("); while (i.hasNext()) { sb.append(i.next()); if (i.hasNext()) sb.append(" | "); } sb.append(")"); return sb.toString(); } /** * Constructs a debug string which should match the DTD declaration * used to construct this object. */ @Override public String toString() { StringBuffer sb = new StringBuffer(); sb.append(getName()).append(' '); if (valueType == AttributeValueType.NAME_GROUP) sb.append(collectionToString(enumeration)); else if (valueType == AttributeValueType.NOTATION) sb.append("NOTATION ").append(collectionToString(enumeration)); else sb.append(valueTypeToString(valueType)); if (required) sb.append(' ').append(XmlTags.REQUIRED_BEGIN); else { if (value == null) sb.append(' ').append(XmlTags.IMPLIED_BEGIN); } if (fixed) sb.append(' ').append(XmlTags.FIXED_BEGIN); if (value != null) sb.append(" \"").append(value).append('"'); return sb.toString(); } } libexml-java-0.0.20080703.orig/e-xml/src/main/java/net/noderunner/exml/NullElement.java0000644000175000017500000000317211014421656030205 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.exml; /** * An element where nodes can be "added," but data is not * actually appended. Returns no data as well. * Implemented as a singleton. */ public final class NullElement extends Element { private static final NullElement ne = new NullElement(); public static NullElement getInstance() { return ne; } protected NullElement() { super(null); } /** * Does nothing. */ @Override public void appendAttribute(Attribute a) { } /** * Does nothing. */ @Override public void setAttributes(java.util.List attributes) { } /** * Does nothing. */ @Override public void setName(String name) { } /** * Does nothing. */ @Override public void appendChild(Node n) { } /** * Returns the comment
    <!-- null element -->
    . */ @Override public String toString() { return ""; } } libexml-java-0.0.20080703.orig/e-xml/src/main/java/net/noderunner/exml/Node.java0000644000175000017500000000274210762067376026666 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.exml; /** * A common interface for XML node classes. * This is a very brief version of the org.w3c.Node object. */ public interface Node { /** * Node is an Element. * @see Element */ short ELEMENT_NODE = 1; /** * Node is a CharacterData instance. * @see CharacterData */ short TEXT_NODE = 2; /** * Node is a Comment. * @see Comment */ short COMMENT_NODE = 3; /** * Node is a Processing Instruction. * @see PI */ short PI_NODE = 4; /** * Node is a Document. * @see Document */ short DOCUMENT_NODE = 5; /** Returns this Node's Type */ short getNodeType(); /** * Returns this Node as it would * appear in an XML document. */ String toString(); } libexml-java-0.0.20080703.orig/e-xml/src/main/java/net/noderunner/exml/ElementRuleException.java0000644000175000017500000000260610762067376032100 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.exml; /** * Indicates an element rule was violated. */ public class ElementRuleException extends XmlException { private static final long serialVersionUID = 7261993462734780866L; /** * Construct a new ElementRuleException. * @param message explaination * @param rule rule that was violated */ public ElementRuleException(String message, ElementRule rule) { super(message + " -- " + rule); } /** * Construct a new ElementRuleException. * @param message explaination * @param req requirement that was violated */ public ElementRuleException(String message, ElementReq req) { super(message + " -- " + req); } } libexml-java-0.0.20080703.orig/e-xml/src/main/java/net/noderunner/exml/XmlCharArrayWriter.java0000644000175000017500000001237411014421656031517 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.exml; import java.io.IOException; import java.io.Writer; /** * Collects characters in an array. The data copied can be put in an escaped * or unescaped format to other Writers. * It uses no locking or synchronization, meaning, this class is not * thread-safe. * * @version 1.0 * @author Elias Ross */ public class XmlCharArrayWriter extends Writer { /** * The buffer where data is stored. */ private char buf[]; /** * The number of chars in the buffer. */ private int count; /** * Creates a new XmlCharArrayWriter with an initial size of 32. */ public XmlCharArrayWriter() { this(32); } /** * Creates a new XmlCharArrayWriter with the specified initial size. * * @throws IllegalArgumentException if initialSize is negative */ public XmlCharArrayWriter(int initialSize) { if (initialSize < 0) throw new IllegalArgumentException("Negative size"); buf = new char[initialSize]; } /** * Writes a character to the buffer. */ @Override public void write(int c) { int newcount = count + 1; if (newcount > buf.length) { char newbuf[] = new char[Math.max(buf.length << 1, newcount)]; System.arraycopy(buf, 0, newbuf, 0, count); buf = newbuf; } buf[count] = (char)c; count = newcount; } /** * Writes characters to the buffer. * Writes the entire length of the array to the buffer. * * @param c source array */ @Override public void write(char c[]) { write(c, 0, c.length); } /** /** * Writes characters to the buffer. * * @param c source array * @param off array offset * @param len number of characters to write */ @Override public void write(char c[], int off, int len) { if (len == 0) return; int newcount = count + len; if (newcount > buf.length) { char newbuf[] = new char[Math.max(buf.length << 1, newcount)]; System.arraycopy(buf, 0, newbuf, 0, count); buf = newbuf; } System.arraycopy(c, off, buf, count, len); count = newcount; } /** * Writes a portion of a string to the buffer. * * @param s source string * @param off string offset * @param len number of characters to write */ @Override public void write(String s, int off, int len) { int newcount = count + len; if (newcount > buf.length) { char newbuf[] = new char[Math.max(buf.length << 1, newcount)]; System.arraycopy(buf, 0, newbuf, 0, count); buf = newbuf; } s.getChars(off, off + len, buf, count); count = newcount; } /** * Writes a string to the buffer. * * @param s source string */ @Override public void write(String s) { write(s, 0, s.length()); } /** * Writes the contents of the buffer to another character stream. * * @param out the output stream to write to */ public void writeTo(Writer out) throws IOException { out.write(buf, 0, count); } /** * Writes the contents of the buffer to another character stream. * * @param out the output stream to write to */ public void writeEscapedTo(Writer out) throws IOException { for (int i = 0; i < count; i++) { char c = buf[i]; switch (c) { case '\'' : out.write("'"); break; case '"' : out.write("""); break; case '<' : out.write("<"); break; case '>' : out.write(">"); break; case '&' : out.write("&"); break; default: out.write(c); } } } /** * Writes the contents of the buffer to a string buffer. * * @param sb a string buffer */ public void writeEscapedTo(StringBuffer sb) { for (int i = 0; i < count; i++) { char c = buf[i]; switch (c) { case '\'' : sb.append("'"); break; case '"' : sb.append("""); break; case '<' : sb.append("<"); break; case '>' : sb.append(">"); break; case '&' : sb.append("&"); break; default: sb.append(c); } } } /** * Returns the underlying buffer. * The utilized length may be less than the array length. * @see #size */ public char[] getBuffer() { return buf; } /** * Resets the underlying buffer so that it may be used again. */ public void reset() { count = 0; } /** * Returns the utilized length of the underlying buffer. */ public int size() { return count; } /** * Returns the written data as a string. */ @Override public String toString() { if (count == 0) return ""; return new String(buf, 0, count); } /** * Does nothing. */ @Override public void flush() { } /** * Does nothing. */ @Override public void close() { } } libexml-java-0.0.20080703.orig/e-xml/src/main/java/net/noderunner/exml/Namespace.java0000644000175000017500000000415110762067376027671 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.exml; /** * A common interface for classes that support namespaces. * A namespace in this case consists of a {@link #getName name} made up * of a {@link #getPrefix prefix} and {@link #getLocalName localName}. For * example in the case of this element: *

    * <foo:bar foo:xmlns='http://example.net/foospace' /> *

    * The element local name is bar, the prefix is * foo and the Name itself is foo:bar. * The namespace is defined to belonging to the {@link #getNamespaceURI URI} at * http://example.net/foospace. Strictly speaking, a real * namespace can be defined by its URI alone. This interface * may (should?) have been called NameNamespace. * * @author Elias Ross * @version 1.0 * @see UriMap */ public interface Namespace { /** * Returns the namespace URI, or null if this * name belongs to the default namespace. */ String getNamespaceURI(); /** * Returns the prefix in use, or null if this * name belongs to the default namespace. */ String getPrefix(); /** * Returns the local name, the name without its prefix. Returns * null if this name belongs to the default namespace. */ String getLocalName(); /** * Returns the full name, including the colon. */ String getName(); } libexml-java-0.0.20080703.orig/e-xml/src/main/java/net/noderunner/exml/NullResolver.java0000644000175000017500000000254010762067376030431 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.exml; import java.io.Reader; /** * Used for ignoring (or blocking) the obtaining of * external entities. This class is a singleton. * * @see NullReader */ public final class NullResolver implements SystemLiteralResolver { static SystemLiteralResolver resolver = new NullResolver(); private NullResolver() { } /** * Returns the sole NullResolver instance. */ public static SystemLiteralResolver getInstance() { return resolver; } /** * Returns a dummy NullReader. */ public Reader resolve(String literal) { return NullReader.getInstance(); } } libexml-java-0.0.20080703.orig/e-xml/src/main/java/net/noderunner/exml/XmlException.java0000644000175000017500000000204310762067376030412 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.exml; /** * Indicates a parse operation failed. */ public class XmlException extends Exception { private static final long serialVersionUID = -9158892743284973280L; public XmlException(String message) { super(message); } public XmlException(Exception e) { super(e); } } libexml-java-0.0.20080703.orig/e-xml/src/main/java/net/noderunner/exml/XmlEvent.java0000644000175000017500000000404210762067376027536 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.exml; /** * A collection of numerical events returned by the XML parsers. These * are done as bit flags, so they can be OR'd and AND'd together. * @see XmlSParser * @see XmlScanner */ public interface XmlEvent { /** No event */ int NONE = 0; /** Start tag event */ int STAG = 1<<0; /** End tag event */ int ETAG = 1<<1; /** Character data event */ int CHARDATA = 1<<2; /** Character data section event */ int CDSECT = 1<<3; /** Reference event */ int REFERENCE = 1<<4; /** Event composed of the OR'ing of CHARDATA, CDSECT, and REFERENCE */ int TEXT = CHARDATA | CDSECT | REFERENCE; /** Document type declaration event */ int DOCTYPE_DECL = 1<<5; /** XML Declaration event */ int XML_DECL = 1<<6; /** Processing instruction event */ int PI = 1<<7; /** Comment event */ int COMMENT = 1<<8; /** End Of Document or Stream event */ int EOD = 1<<9; /** Element declaration event */ int ELEMENT_DECL = 1<<10; /** Attribute declaration event */ int ATTLIST_DECL = 1<<11; /** Entity declaration event */ int ENTITY_DECL = 1<<12; /** Conditional section event */ int CONDITIONAL_SECT = 1<<13; /** Notation declaration event */ int NOTATATION_DECL = 1<<14; /** Parameter entity reference event */ int PE_REFERENCE = 1<<15; /** All events */ int ALL_EVENTS = 0xEFFFFFFF; } libexml-java-0.0.20080703.orig/e-xml/src/main/java/net/noderunner/exml/Stack.java0000644000175000017500000000105411014421656027023 0ustar twernertwernerpackage net.noderunner.exml; interface Stack { /** * Returns and removes the last item pushed. * @throws NoSuchElementException if no elements are in the * collection */ T pop(); /** * Returns the last item pushed. * @throws NoSuchElementException if no elements are in the * collection */ T peek(); /** * Returns the number of elements on the stack. */ int size(); /** * Adds an item to the top of the stack. * This object can be null. * @param obj object to add */ void push(T obj); } libexml-java-0.0.20080703.orig/e-xml/src/main/java/net/noderunner/exml/XmlScanner.java0000644000175000017500000003662011014421656030037 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.exml; import java.io.IOException; import java.io.Reader; import java.io.Writer; /** * This is an implementation of an XML input scanner. This is not * synchronized. It is fully buffered, so using a * java.io.BufferedReader around the underlying stream is not * necessary and can only hurt performance. */ public class XmlScanner { private Reader reader; /** position in array, pointing at the next character to read */ private int pos; /** buffer itself */ private char cbuf[]; /** amount to reserve, used for fill() */ private int reserve; /** string pool for names */ private StringPool stringPool; /** URI map, used for getting the URI from Name prefixes */ private UriMap uriMap; /** * Constructs an XmlScanner with specific buffer size and reserve * size of at most 4. */ public XmlScanner(Reader reader, int size) { this(reader, size, Math.min(4, size)); } /** * Constructs an XmlScanner out of a string. * @param xml an XML document */ public XmlScanner(String xml) { setReadString(xml); this.stringPool = new StringPool(8); this.uriMap = new UriMap(); } /** * Constructs an XmlScanner with specific buffer size and * unread reserve size. */ public XmlScanner(Reader reader, int size, int reserve) { this.reader = reader; cbuf = new char[size]; pos = cbuf.length; this.reserve = reserve; this.stringPool = new StringPool(); this.uriMap = new UriMap(); } /** * Sets the underlying reader to a different reader. */ public void setReader(Reader reader) { this.reader = reader; pos = cbuf.length; } /** * Sets the scanner to read a character String. */ public void setReadString(String xml) { this.reader = NullReader.getInstance(); this.reserve = 0; this.cbuf = xml.toCharArray(); this.pos = 0; } /** * Closes the underlying reader. */ public void close() throws IOException { reader.close(); } /** * Returns the next character. * @return a character, or -1 if EOF */ public int read() throws IOException { if (pos < cbuf.length) return cbuf[pos++]; fill(); if (pos < cbuf.length) return cbuf[pos++]; return -1; } /** * Returns the number of characters that can be unread. */ public int canUnread() { return pos; } /** * Unreads a character. * @param c character, cannot be less than zero */ public void unread(int c) throws IOException { if (c < 0) throw new IllegalArgumentException("Cannot unread " + c); if (pos == 0) throw new IOException("Out of space unreading " + c); cbuf[--pos] = (char)c; } /** * Fills in the buffer if it's empty. * TODO: Should check for invalid XML characters */ void fill() throws IOException { if (pos != cbuf.length) return; int want = pos - reserve; int take = reader.read(cbuf, reserve, want); if (take <= 0) return; pos -= take; if (take < want) { System.arraycopy(cbuf, reserve, cbuf, pos, take); } } /** * Determines an event from a buffer. */ static int determineEvent(final char buf[], final int off) { char c = buf[off + 1]; if (c == '/') { return XmlEvent.ETAG; } else if (c == '!') { switch (buf[off + 2]) { case '-': return XmlEvent.COMMENT; case '[': if (buf[off + 3] == 'C') return XmlEvent.CDSECT; else return XmlEvent.CONDITIONAL_SECT; case 'D': return XmlEvent.DOCTYPE_DECL; case 'E': if (buf[off + 3] == 'L') return XmlEvent.ELEMENT_DECL; else return XmlEvent.ENTITY_DECL; case 'A': return XmlEvent.ATTLIST_DECL; case 'N': return XmlEvent.NOTATATION_DECL; } } else if (c == '?') { return XmlEvent.PI; } else if (XmlReader.FirstNameChar(c)) { return XmlEvent.STAG; } return XmlEvent.NONE; } /** * Translates a character reference, starting from the & * character. Rewrites the stream with an appropriate character. * * @return true if a character reference was found * @throws XmlException if bad number, invalid character, * excessive number, or EOF */ public boolean charRef() throws IOException, XmlException { int amp = read(); if (amp == -1) throw new XmlException("EOF scanning for CharRef"); if (amp != '&' || peek() != '#') { unread(amp); return false; } read(); // # int c = read(); // x or digit int radix = 10; StringBuffer sb = new StringBuffer(16); if (c == 'x') { radix = 16; } else { sb.append((char)c); } while (true) { c = read(); if (c == ';') { try { int result = Integer.parseInt(sb.toString(), radix); if (!XmlReader.Char(result)) throw new XmlException("CharRef not valid Xml char " + result); unread((char)result); return true; } catch (NumberFormatException e) { throw new XmlException("Bad CharRef " + sb + " " + e); } } if (c == -1) throw new XmlException("CharRef expected ; after " + sb); if (sb.length() > XmlReaderPrefs.MAX_NAME_LEN) throw new XmlException("CharRef exceeded MAX_NAME_LEN, expected ; after " + sb); sb.append((char)c); } } /** * Translates a reference. If a built-reference, * rewrites the stream with an appropriate character, returns true. * Must have at least 6 reserve characters. * @throws XmlException if EOF reached */ public boolean translateReference() throws XmlException, IOException { if (pos >= cbuf.length - 6) { char rbuf[] = new char[6]; int count = read(rbuf, 0, 6); if (count < 3) throw new XmlException("Not enough data in reference"); unread(rbuf, 0, count); } // 0123 012345 // < ' char a = cbuf[pos+1]; char b = cbuf[pos+2]; if (a == '#') { charRef(); return true; } if (b == 't' && cbuf[pos+3] == ';') { if (a == 'l') { pos += 3; cbuf[pos] = '<'; return true; } if (a == 'g') { pos += 3; cbuf[pos] = '>'; return true; } } if (a == 'a') { if (b == 'm' && cbuf[pos+3] == 'p' && cbuf[pos+4] == ';') { pos += 4; cbuf[pos] = '&'; return true; } if (b == 'p' && cbuf[pos+3] == 'o' && cbuf[pos+4] == 's' && cbuf[pos+5] == ';') { pos += 5; cbuf[pos] = '\''; return true; } } if (a == 'q' && b == 'u' && cbuf[pos+3] == 'o' && cbuf[pos+4] == 't' && cbuf[pos+5] == ';') { pos += 5; cbuf[pos] = '"'; return true; } return false; } /** * Returns the next event (as defined in {@link XmlEvent}) or returns * {@link XmlEvent#NONE} if there is no (valid?) event at this parse * location. {@link XmlEvent#EOD} is returned if end of file. * * @see XmlEvent */ public int peekEvent() throws IOException { int c = peek(); if (c != '<') { if (c == -1) return XmlEvent.EOD; else if (c == '&') { return XmlEvent.REFERENCE; } else { return XmlEvent.CHARDATA; } } // If we don't have 4 characters available: this is a rare case // (which is not so fast) if (pos >= cbuf.length - 4) { char rbuf[] = new char[4]; int count = peek(rbuf, 0, 4); if (count < 4) return XmlEvent.EOD; return determineEvent(rbuf, 0); } return determineEvent(cbuf, pos); } /** * Places in the fields information about the * name found at the parse location. * Re-uses an existing structure. */ public void readNamespace(NamespaceImpl ns) throws IOException, XmlException { String s = getName(true); if (s == null) { ns.clear(); return; } if (s.length() == 0) throw new XmlException("Local name without prefix"); if (peek() == ':') { read(); ns.setPrefix(s); ns.setNamespaceURI(uriMap.get(s)); s = getName(true); if (s == null) throw new XmlException("Prefix without local name"); ns.setLocalName(s); ns.setName(null); } else { ns.setNamespaceURI(null); ns.setPrefix(null); ns.setLocalName(null); ns.setName(s); } } /** * Creates a 'Name' until a non-name character is found. * The name returned is the fully-qualified name. * This String is guaranteed to be Object equal (with the == * operator) to any created before it. */ public String getName() throws IOException, XmlException { return getName(false); } /** * Creates a 'Name' until a non-name character is found. * @param part true if we should stop parsing at the colon */ private String getName(boolean part) throws IOException, XmlException { int c = peek(); if (c == -1) return null; if (!XmlReader.FirstNameChar((char)c)) { return null; } String result = null; while (true) { fill(); if (pos == cbuf.length) return stringPool.intern(result); for (int i = pos; i < cbuf.length; i++) { c = cbuf[i]; if (!XmlReader.NameChar((char)c) || (c == ':' && part)) { // match if (result == null) { result = stringPool.intern(cbuf, pos, i - pos); } else { result += new String(cbuf, pos, i - pos); result = stringPool.intern(result); } pos = i; return result; } } if (result == null) result = new String(cbuf, pos, cbuf.length - pos); else result += new String(cbuf, pos, cbuf.length - pos); if (result.length() > XmlReaderPrefs.MAX_NAME_LEN) throw new XmlException("Exceeded MAX_NAME_LEN in Name"); pos = cbuf.length; } } /** * Returns a text string, which, once found, * is internalized using the underlying string pool. * This routine was written along the same lines as {@link #readNamespace}. * @see XmlSParser#getCanonicalText */ public String getCanonicalText() throws IOException, XmlException { int c = peek(); if (c == -1 || c == '<') return ""; StringBuffer result = null; while (true) { fill(); if (pos == cbuf.length) { return (result == null) ? "" : stringPool.intern(result.toString()); } if (peek() == '&') { if (!translateReference()) return (result == null) ? "" : stringPool.intern(result.toString()); else if (result == null) result = new StringBuffer().append((char)read()); else result.append((char)read()); } int i; for (i = pos; i < cbuf.length; i++) { c = cbuf[i]; if (c == '&') break; if (c == '<') { // match String s; if (result == null) { s = stringPool.intern(cbuf, pos, i - pos); } else { result.append(cbuf, pos, i - pos); s = stringPool.intern(result.toString()); } pos = i; return s; } } if (result == null) result = new StringBuffer().append(cbuf, pos, i - pos); else result.append(cbuf, pos, i - pos); pos = i; } } /** * Returns the next character without removing it from the pushback stream. * If there are no more characters to be read from the underlying stream, a * character is read from it and put back. */ public int peek() throws IOException { if (pos < cbuf.length) { return cbuf[pos]; } fill(); int c = read(); if (c != -1) unread(c); return c; } /** * Peeks into the stream, this is faster than reading and unreading for * scanning. Returns the number of characters copied into * buf. */ public int peek(char buf[], int off, int len) throws IOException { if (pos < cbuf.length - len) { System.arraycopy(cbuf, pos, buf, off, len); return len; } else { int count = read(buf, off, len); if (count == -1) return -1; unread(buf, off, count); return count; } } /** * Skips until a is found. * Returns the character found or -1 if EOF. */ public int skipUntil(char a) throws IOException, XmlException { return skipUntil(a, a); } /** * Skips until a or b is found. * Returns the character found or -1 if EOF. * @throws XmlException if match could not be found */ public int skipUntil(char a, char b) throws IOException, XmlException { while (true) { fill(); if (pos == cbuf.length) throw new XmlException("Premature EOF looking for match"); for (int i = pos; i < cbuf.length; i++) { if (cbuf[i] == a || cbuf[i] == b) { // match pos = i; return cbuf[i]; } } pos = cbuf.length; } } /** * Copies until a is found. * Returns the character found or -1 if EOF. */ public int copyUntil(Writer w, char a) throws IOException, XmlException { return copyUntil(w, a, a); } /** * Copies until a or b is found. * Returns the character found or -1 if EOF. */ public int copyUntil(Writer w, char a, char b) throws IOException, XmlException { while (true) { fill(); if (pos == cbuf.length) return -1; for (int i = pos; i < cbuf.length; i++) { if (cbuf[i] == a || cbuf[i] == b) { // match w.write(cbuf, pos, i - pos); pos = i; return cbuf[i]; } } w.write(cbuf, pos, cbuf.length - pos); pos = cbuf.length; } } /** * Skips characters in the stream. If attempting to read beyond EOF, does * nothing. */ public void skip(int len) throws IOException { if (pos < cbuf.length) { int got = Math.min(len, cbuf.length - pos); len -= got; pos += got; } while (len-- > 0) read(); } /** * Unreads an entire string. */ public void unread(String s) throws IOException { unread(s.toCharArray(), 0, s.length()); } /** * Unreads characters. */ public void unread(char buf[], int off, int len) throws IOException { if (pos < len) throw new IOException("Attempt to unread too many characters: " + len); pos -= len; System.arraycopy(buf, off, cbuf, pos, len); } /** * Reads characters. * @return -1 if EOF and no characters were pushed back */ public int read(char buf[], int off, int len) throws IOException { int got = 0; // read from our array if (pos < cbuf.length) { got = Math.min(len, cbuf.length - pos); System.arraycopy(cbuf, pos, buf, off, got); len -= got; pos += got; off += got; } // read from our array again if (len > 0) { fill(); if (pos == cbuf.length) { if (got == 0) return -1; } else { int min = Math.min(len, cbuf.length - pos); System.arraycopy(cbuf, pos, buf, off, min); pos += min; got += min; } } return got; } /** * Returns a string representation of this XmlScanner. */ @Override public String toString() { String s = "XmlScanner avail=" + (cbuf.length - pos) + " ["; for (int i = pos; i < cbuf.length ; i++) { s += cbuf[i]; } s += "]"; return s; } /** * Returns the underlying StringPool instance. */ public StringPool getStringPool() { return stringPool; } /** * Sets the underlying StringPool instance. */ public void setStringPool(StringPool stringPool) { this.stringPool = stringPool; } /** * Returns the underlying UriMap instance. */ public UriMap getUriMap() { return uriMap; } /** * Sets the underlying UriMap instance. */ public void setUriMap(UriMap uriMap) { this.uriMap = uriMap; } } libexml-java-0.0.20080703.orig/e-xml/src/main/java/net/noderunner/exml/Dtd.java0000644000175000017500000001541211014421656026474 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.exml; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.Map; /** * This class contains all the same textual information represented in a DTD as * a collection of various Java objects. A DTD, or Document Type Description, * describes the entities, element rules, attributes, etc, to be used and * allowed in an XML document. This class does the same. *

    * Typically, a DTD is built by reading in actual text, using * XmlReader on a document-type declaration. However, it may also * be built by calling various add methods. Once created, it can be re-used for * any document. *

    * * @author Elias Ross * @version 1.0 * @see XmlReader */ public class Dtd { /** * Fixed instance that has no declared entities. */ public static final Dtd EMPTY_DTD = new Dtd(Collections.emptyMap(), Collections.emptyMap(), Collections.emptyMap(), Collections.emptyMap(), null); /** * Document type name, the name of the root element. */ public String name; /** * Contains document-definied XML entities. */ private Map entities; /** * Contains parameter entities, for DTD processing. */ private Map pentities; /** * Known element rules, what they can contain, etc. Maps String to * ElementRule objects. */ private Map elementRules; /** * Known notations. Maps String to Notation objects. */ private Map notations; /** * Constructs a new DTD with no declared entities or element rules. */ public Dtd() { this(new HashMap(), new HashMap(), new HashMap(), null, null); } /** * Constructs a new DTD with declared entities, parameter entities, element * rules, notation declarations, and a document name. * * @param entities * regular entities; map of String names to values * @param pentities * paramter entities; map of String names to values * @param elementRules * map of String names to {@link ElementRule} instances * @param notations * map of String names to {@link Notation} * @param name * document name */ public Dtd(Map entities, Map pentities, Map elementRules, Map notations, String name) { this.entities = entities; this.pentities = pentities; this.elementRules = elementRules; this.notations = notations; this.name = name; } /** * Returns a Map of element names, which are * String instances, to ElementRule instances. * * @see #addElementRule * @see ElementRule */ public Map getKnownElements() { return elementRules; } /** * Adds an element rule to this DTD. * * @param name * element name to apply the rule to * @param rule * rule to use.entrySet */ public void addElementRule(String name, ElementRule rule) { elementRules.put(name, rule); } /** * Add an element rule to this DTD. * * @param element * element to apply the rule to * @param rule * rule to use */ public void addElementRule(Element element, ElementRule rule) { elementRules.put(element.getName(), rule); } /** * Returns a rule stored in this DTD. * * @param element * element name to retrive the rule for * @return matching ElementRule or null if no rule */ public ElementRule getElementRule(String element) { return (ElementRule) elementRules.get(element); } /** * Returns a rule stored in this DTD. * * @param element * element to retrive the rule for * @return matching ElementRule or null if no rule */ public ElementRule getElementRule(Element e) { return getElementRule(e.getName()); } /** * Adds a known entity. If this entity already was declared, it is not * added, per the XML specification. * * @param name * entity name, without its & and terminating ; * @param value * entity value */ public void addEntity(String name, Entity value) { if (!entities.containsKey(name)) entities.put(name, value); } /** * Returns a stored entity. * * @return null if the entity is not recognized */ public Entity getEntity(String name) { return (Entity) entities.get(name); } /** * Returns a stored parameter entity. * * @return null if the paramter entity is not recognized */ public Entity getParameterEntity(String name) { return pentities.get(name); } /** * Adds a known parameter entity to recognize. * * @param name * parameter entity name, without its & and terminating ; * @param value * parameter entity value */ public void addParameterEntity(String name, Entity value) { pentities.put(name, value); } /** * Returns the name of the document type. */ public String getName() { return name; } /** * Sets the name of the document type. */ public void setName(String name) { this.name = name; } /** * Adds a recognized notation. */ public void addNotation(String name, Notation n) { if (notations == null) notations = new HashMap(); notations.put(name, n); } /** * Returns recognized notations as a String to * Notation map. May return null if no * notations exist. */ public Map getNotations() { return notations; } /** * Formats and returns this object as a textual DTD. */ @Override public String toString() { Iterator i = getKnownElements().entrySet().iterator(); StringBuffer sb = new StringBuffer(getKnownElements().size() * 32); while (i.hasNext()) { Map.Entry entry = (Map.Entry) i.next(); String name = (String) entry.getKey(); ElementRule rule = (ElementRule) entry.getValue(); sb.append(rule.elementString(name)); sb.append('\n'); sb.append(rule.attlistString(name)); } return sb.toString(); } } libexml-java-0.0.20080703.orig/e-xml/src/main/java/net/noderunner/exml/XmlParser.java0000644000175000017500000002506311014421656027701 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.exml; import java.io.IOException; import java.io.Reader; import java.util.Iterator; import net.noderunner.exml.ElementRule.ElementRuleState; /** * An incremental, streaming XML pull-parser. * The performance, and CPU/memory usage of this class is comparable to a * typical SAX parser. *

    * Through an underlying stack, parse steps are kept track of, and the tree can * be moved back down to any level, by reading forwards, but the stream cannot * be read backwards. Element rules must be added to the underlying {@link * XmlReader}, otherwise elements will not be recognized. This class supports * full validity checking. *

    *

    * Example usage: (document) *

     * <?xml version="1.0" encoding="UTF-8"?>
     * <a><b><c/>
     *    <d>D&apos;s content here</d>
     * </b></a>
     * 
    * (create the reader with DTD) *
     * ElementRule rule;
     * rule = new ElementRule();
     * Dtd dtd = new Dtd();
     * dtd.addElementRule("a", rule);
     * dtd.addElementRule("b", rule);
     * dtd.addElementRule("c", rule);
     * rule = new ElementRule();
     * rule.setAllowPCData(true);
     * dtd.addElementRule(d, rule);
     * XmlReader reader = new XmlReader(new StringReader( ... ), dtd);
     * 
    * (create the parser) *
     * XmlParser parser = new XmlParser(reader);
     * parser.skipProlog();
     * parser.startTag().getName(); // returns "test"
     * parser.startTag().getName(); // returns "a"
     * parser.startTag().getName(); // returns "b"
     * parser.startTag().getName(); // returns "c"
     * parser.endTag().getName();   // returns "c"
     * parser.startTag().getName(); // returns "d"
     * Element d = parser.getContent();
     * d.getCharacterData();        // returns "D's content here"
     * 
    * * @author Elias Ross * @version 1.0 */ public class XmlParser { /** * Underlying reader. */ private XmlReader reader; /** * Helps keep track of parsing. This stack should store only * Element instances. */ private ArrayStack readStack; /** * If Misc data should be kept as part of elements that * disallow PCDATA. */ private boolean alwaysSaveMisc; /** * Constructs an XmlParser around an XmlReader. XmlReader must contain * a DTD in it which provides element rules for all elements that are * to be encountered by input. Without this DTD, any unknown elements * parsed will throw an ElementRuleException. * * @param reader xml reader to wrap * @see Dtd */ public XmlParser(XmlReader reader) { this.reader = reader; this.readStack = ArrayStack.create(); } /** * Resets this object for parsing another Reader * source. */ public void setReader(Reader reader) { this.reader.setReader(reader); readStack.clear(); } /** * Skips over any initial XML prolog data and comments. * * @see XmlReader#Prolog * @throws XmlException if bad XML data * @throws IOException if bad underlying stream */ public void skipProlog() throws IOException, XmlException { reader.Prolog(null); } /** * Returns the element returned by the last * startTag call. * * @return the stack top, or null if there is no top element * @see #startTag() */ public Element getTopElement() { if (readStack.size() == 0) return null; return readStack.peek(); } /** * Creates a new element if one exists at the current stream point. * Like the XmlReader.STag call, but validating. The * method endTag must be called for every * startTag call. Even if the tag returned is not * open, endTag must be called. In the case of this * document fragment: *
    	 * <a></a>
    	 * 
    * even though <a> is considered a closed element, the parser * will not know this until endTag is called. * * @return null, if no start tag exists * @throws XmlException if bad XML data * @throws IOException if bad underlying stream * @see #endTag */ public Element startTag() throws IOException, XmlException { Element e = reader.STag(); if (e == null) return null; // check if okay to add ElementRule erule = null; RuleStack ruleStack = reader.getRuleStack(); if (!readStack.isEmpty()) { erule = reader.getDtd().getElementRule(getTopElement()); erule.encounterElement(e, ruleStack.state()); } else { // should check doctype } ruleStack.startElement(); ElementRule nrule = reader.getDtd().getElementRule(e.getName()); if (nrule == null) throw new XmlException("Unknown element " + e); // clear out Misc if no PCDATA and open tag if (!alwaysSaveMisc) { if ((e.isOpen() && !nrule.isPCDataAllowed()) || (!e.isOpen() && erule != null && !erule.isPCDataAllowed())) { reader.Misc(null); } } // add to stack (even if closed) readStack.add(e); return e; } /** * Adds content to object returned by last startTag * call. May parse recursively. Call endTag to * finally close this element. This element is stored within this * parser, so if the memory is no longer needed, call * Element.clearChildren. * * @see Element#clearChildren * @see #emptyContent * @return the element with read in information */ public Element getContent() throws IOException, XmlException { if (readStack.isEmpty()) throw new XmlException("No current tag"); reader.content(getTopElement()); return getTopElement(); } /** * Reads all remaining content of last startTag call * into a NullElement. This effectively reads in all * further content preceeding the end tag. * Call endTag to finally close this element. * * @see NullElement * @see #endTag */ public void emptyContent() throws IOException, XmlException { reader.content(NullElement.getInstance()); } /** * Searches for end of the last element read. Skips over any * existant content in the current element and reads in the end tag. * @throws XmlException if bad Xml data * @throws IOException if bad underlying stream * @return last element returned by startTag */ public Element endTag() throws IOException, XmlException { if (readStack.isEmpty()) throw new XmlException("Too many endTag() calls: No more elements"); Element top = (Element)getTopElement(); if (top.isOpen()) { // throw away whatever content emptyContent(); boolean ok = reader.ETag(top); if (!ok) throw new XmlException("Element expected, not found"); } ElementRule elementRule = reader.getDtd().getElementRule(getTopElement()); RuleStack ruleStack = reader.getRuleStack(); ElementRuleState state = ruleStack.state(); elementRule.encounterEnd(state); readStack.pop(); ruleStack.endElement(); // read in Misc if current rule does not allow PCData if (top.isOpen() && !readStack.isEmpty()) { elementRule = reader.getDtd().getElementRule(getTopElement()); if (!alwaysSaveMisc && !elementRule.isPCDataAllowed()) reader.Misc(null); } return top; } /** * Closes the underlying input stream. * Calling any more methods on this object will likely result in a * java.io.IOException. */ public void close() throws IOException { reader.close(); } /** * Skips over any whitespace or comments or processing instructions. * This may be useful for reading everything trailing at * the end of a document. */ public void skipMisc() throws IOException, XmlException { while (reader.Misc(null)); } /** * Returns the parse tree depth of this tree. * For example, assuming this much of the document stream has been * read: *
    	 * <a>
    	 *   <b>
    	 * 
    * the depth returned is 2. * * @return an integer, counting from 0, representing the number of * open element tags encountered so far that have not been ended */ public int getDepth() { return readStack.size(); } /** * Moves the stream up to the depth given. For example, if * depth = getDepth() was called when * getTopElement was the element <bob>, then * up(depth) will read until the matching element </bob> is * read. If depth exceeds the current level, this * method has no effect. If depth is zero, reads until * the end of the document. This is useful for reading in the * remaining content of an entire XML document that is no longer * important. *

    * For example, calling up(1), having read the * document this far: *

    	 * <a>
    	 *   <b>
    	 *     <c>
    	 * 
    * will read the remainder of the document up until the final *
    </a>
    tag. * * @throws IllegalArgumentException if negative depth is given * @see #close * @see #getDepth */ public void up(int depth) throws IOException, XmlException { if (depth < 0) throw new IllegalArgumentException("Depth must be positive: " + depth); while (readStack.size() > depth) { emptyContent(); endTag(); } } /** * Sets whether or not miscellaneous data, like whitespace, * comments, processing instructions are to be kept. * By default, whitespace, comments, and processing instructions are * not saved into children of elements that do not allow PCDATA. This * is to simplify parsing in many ways. However, if this information * should be kept, call this method to have these nodes saved. * * @param yes to save misc data for all elements */ public void alwaysSaveMisc(boolean yes) { this.alwaysSaveMisc = yes; } /** * Returns a string representation of this object for debugging. */ @Override public String toString() { String s = "XmlParser [reader=" + reader + " readStack="; Iterator i = readStack.iterator(); while (i.hasNext()) s += i.next().getName() + " "; s += "]"; return s; } } libexml-java-0.0.20080703.orig/e-xml/src/main/java/net/noderunner/exml/AttributeRuleException.java0000644000175000017500000000251010762067376032444 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.exml; /** * Indicates an attribute rule was violated. */ public class AttributeRuleException extends XmlException { private static final long serialVersionUID = 4013663718416205714L; /** * Construct a new AttributeRuleException. * @param message explaination * @param rule rule that was violated */ public AttributeRuleException(String message, AttributeRule rule) { super(message + " -- " + rule); } /** * Construct a new AttributeRuleException. * @param message explaination */ public AttributeRuleException(String message) { super(message); } } libexml-java-0.0.20080703.orig/e-xml/src/main/java/net/noderunner/exml/Document.java0000644000175000017500000000520511014421656027536 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.exml; import java.util.ArrayList; import java.util.Iterator; import java.util.List; /** * This class is for holding a root element. * Processing instructions and comments not belonging to any element can be * added as well. * @see Element */ public class Document implements Node { private List children; /** * Constructs a new document with no children. */ public Document() { } /** * Returns the value DOCUMENT_NODE. */ public short getNodeType() { return DOCUMENT_NODE; } /** * Returns the list of child nodes. * @return returns null if no children in this object */ public List getChildNodes() { return children; } /** * Returns the root element of this document. * @return null if no root element was found */ public Element getRootElement() { if (children == null) return null; Iterator i = children.iterator(); while (i.hasNext()) { Node n = i.next(); if (n.getNodeType() == ELEMENT_NODE) return (Element)n; } return null; } /** * Appends a child node to this Document. * @param n child node to append * @throws ElementException if this node is an * element, and a root element already exists. */ public void appendChild(Node n) { if (n.getNodeType() == ELEMENT_NODE && getRootElement() != null) throw new ElementException("Attempt to add another root element"); if (children == null) { children = new ArrayList(); } children.add(n); } /** * Returns a string representation of this document, containing * all this document's children. * @return a string version of the Document */ public String toString() { StringBuffer sb = new StringBuffer(64); sb.append("\r\n"); if (children != null) { Iterator i = children.iterator(); while (i.hasNext()) { sb.append(i.next().toString()); } } return sb.toString(); } } libexml-java-0.0.20080703.orig/e-xml/src/main/java/net/noderunner/exml/package.html0000644000175000017500000000071207522337515027405 0ustar twernertwerner

    Provides classes for parsing XML as a stream.

    Refer to the JavaDoc examples at the top of these classes:

    1. XmlParser
    2. XmlSParser
    3. XmlReader

    libexml-java-0.0.20080703.orig/e-xml/src/main/java/net/noderunner/exml/ResolverException.java0000644000175000017500000000231310762067376031453 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.exml; /** * Indicates a resolver operation failed. */ public class ResolverException extends XmlException { private static final long serialVersionUID = -8945898310205225082L; Throwable cause; public ResolverException(String message) { super(message); } public ResolverException(String message, Throwable cause) { super(message + " -- cause: " + cause.getMessage()); this.cause = cause; } public Throwable getCause() { return cause; } } libexml-java-0.0.20080703.orig/e-xml/src/main/java/net/noderunner/exml/XmlReader.java0000644000175000017500000016036211014421656027651 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.exml; import java.io.IOException; import java.io.Reader; import java.io.Writer; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import net.noderunner.exml.ElementRule.ElementRuleState; /** * This is a very simple XML reader, which follows the "XML road map," a * parsing guide found in "The XML Companion" by Neil Bradley. * Parsing can be done discretely, by stopping at element declarations. * The names follow the road map naming scheme, so the Java naming * convention is not followed. *

    * The parsing is not 100% strict. Here are the following known (by design) * liberties: *

      *
    • Input data is not checked for invalid values, such as formfeed, * out-of-range unicode, etc. This would create unnecessary overhead.
    • *
    • XML data is not checked past the end of the last document closing tag. * This allows for streaming data to be parsed. Check for EOF by calling * hasMoreData when done parsing to enforce this.
    • *
    • Unescaped > is allowed in character data.
    • *
    *

    *

    * The parsing is not 100% conformant. Here are the following known * issues: *

      *
    • Parameter entities are not treated as complete objects.
    • *
    • Attribue value whitespace is not normalized.
    • *
    * *

    * How to parse an XML document: *

     * java.io.Reader r = new java.io.StringReader("<doc>Text<doc>");
     * XmlReader xr = new XmlReader(r);
     * Document d = xr.document();
     * 
    *

    * * @see Document * @author Elias Ross * @version 1.0 */ public class XmlReader { /** * Does the reading. */ private XmlScanner scanner; /** * Set if in a entity scan. */ private boolean inEntityScan; /** * cbufSize should be sufficiently large for finding tag matches. */ private static final int cbufSize = 64; char cbuf[] = new char[cbufSize]; /** * Stores the document type description (Dtd) information. May be * created ahead of time, or read from file. */ private Dtd dtd; /** * Stores the current element rule state. */ private RuleStack eruleStack; /** * Stores the attribute rule state. */ private ElementRule.AttributeRuleState aruleState; /** * Stores attribute value data. * Also used in {@link #Nmtoken} function. */ private XmlCharArrayWriter attValue = new XmlCharArrayWriter(64); /** * Holds the last resolved name. */ private NamespaceImpl namespaceElement = new NamespaceImpl(); /** * Holds the last resolved for an attribute. */ private NamespaceImpl namespaceAttr = new NamespaceImpl(); /** * A SystemLiteralResolver is used to parse system (Dtd) files. */ private SystemLiteralResolver resolver; /** * Construct a new reader with a pre-defined Dtd and specific resolver. * @param dtd existing Dtd * @param resolver specific resolver */ public XmlReader(Reader reader, Dtd dtd, SystemLiteralResolver resolver) { this.dtd = dtd; this.resolver = resolver; this.eruleStack = new RuleStack(); this.aruleState = new ElementRule.AttributeRuleState(); scanner = createXmlScanner(reader); setupStringPool(); } private void setupStringPool() { scanner.getStringPool().add(XmlTags.XMLNS); // required for XML-namespace resolution scanner.getStringPool().addAll(dtd.getKnownElements().keySet()); Iterator i = dtd.getKnownElements().values().iterator(); while (i.hasNext()) { ElementRule er = (ElementRule)i.next(); List l = er.getAttributeRules(); if (l != null) { for (int j = 0; j < l.size(); j++) { String name = ((AttributeRule)l.get(j)).getName(); scanner.getStringPool().add(name); } } } } private static XmlScanner createXmlScanner(Reader reader) { return new XmlScanner(reader, 1024 * 4, cbufSize); } /** * Construct a new reader with a pre-defined Dtd and null resolver. * @param dtd existing Dtd */ public XmlReader(Reader reader, Dtd dtd) { this(reader, dtd, NullResolver.getInstance()); } /** * Construct a new reader with a default Dtd and null resolver. */ public XmlReader(Reader reader) { this(reader, new Dtd()); } /** * Construct a reader that reads a string. * @see #setReadString */ public XmlReader(String s) { this(); setReadString(s); } /** * Construct a dummy reader. * @see #setReader * @see #setReadString */ public XmlReader() { this(NullReader.getInstance()); } /** * Reuse this reader on another input stream. */ public void setReader(Reader reader) { scanner.setReader(reader); } /** * Reuse this reader on string input. */ public void setReadString(String xml) { scanner = new XmlScanner(xml); } /** * Returns the underlying Dtd. */ public Dtd getDtd() { return dtd; } /** * Returns the underlying scanner. */ public XmlScanner getScanner() { return scanner; } /** * Returns the underlying string pool. * The string pool can be used to add pre-existing canonical strings to * the pool, so that all element tags of the same value are the same * object. */ public StringPool getStringPool() { return scanner.getStringPool(); } /** * Sets the SystemLiteralResolver for this XmlReader. */ public void setResolver(SystemLiteralResolver resolver) { this.resolver = resolver; } /** * Returns the SystemLiteralResolver for this XmlReader. */ public SystemLiteralResolver getResolver() { return resolver; } /** * Tests if no more bytes can be read from the stream, by trying to * read a character and pushing it back if it was read. This * indicates the entire document was read. * @return false if no more bytes can be read */ public boolean hasMoreData() throws IOException { int c = scanner.peek(); if (c == -1) return false; return true; } /** * Closes the underlying input stream. Once this method is called, * do not attempt to parse any more data. * @throws IOException if closing failed for some reason */ public void close() throws IOException { scanner.close(); } /** * Reads in XML document. * By specification, all Misc data should be read in at the end of * reading a document. However, to support streaming this is not done. * Call while (Misc(document)); to remove this data. *

    {01} document

    * @see #Misc * @return document */ public Document document() throws IOException, XmlException { Document d = new Document(); Prolog(d); Element e = element(); if (e == null) { throw new XmlException("Could not find root object"); } String docname = dtd.getName(); if (docname != null && !docname.equals(e.getName())) { throw new XmlException("Root element name does not match doctype " + docname); } d.appendChild(e); return d; } /** * Check if valid XML character. This is not used for performance * reasons. *

    {02} Char (Character) {15.1} {16.3} {20.1} {65.1} {S37.1}

    * @return is valid XML character */ public static boolean Char(int i) { if (i >= 0x20 && i <= 0xD7FF) return true; if (i == 0x09 || i == 0x0a || i == 0x0d) return true; if (i >= 0xE000 && i <= 0xFFFD) return true; if (i >= 0x10000 && i <= 0x10FFFF) return true; // not checked, we're using UTF-16 return false; } /** * @return true if character is a space */ boolean isS(int c) { return (c == 0x20 || c == 0x0a || c == 0x0d || c == 0x09); } /** * Parse white space. This is a little bit different than the java * idea of whitespace. This is optimized to read in just a little * bit of space at a time. *

    {03} S (Space) {06.2} ... :

    * @return true if space was found, false if EOF or no spaces */ public boolean S() throws IOException { boolean found = false; while (true) { if (!isS(scanner.peek())) return found; scanner.read(); found = true; } } /** * Determines if the given character is a valid NameChar. * Note: Does not conform to exact XML spec, since I have no idea * what a CombiningChar or Extender is. *

    {04} NameChar (Name Character) {05.2 .3 .4} * {07.1}

    */ public static boolean NameChar(final char c) { if ((c >= 0x61 && c <= 0x7a) || (c >= 0x41 && c <= 0x5a) || (c >= 0x30 && c <= 0x3a) || c == '.' || c == '-' || c == '_') return true; if (c < 128) return false; return Character.isLetterOrDigit(c); } /** * Not a builtin rule. */ static boolean FirstNameChar(final char c) { if ((c >= 0x61 && c <= 0x7a) || (c >= 0x41 && c <= 0x5a) || c == ':' || c == '_') return true; if (c < 128) return false; return Character.isLetter(c); } /** * Parses a Name. *

    {05} Name {06.1 .3} {17.1} {28.2} {40.1} {42.1} {44.1} * {45.2} {48.1} {51.6} {52.2} {53.2} {58.3 .6} {59.1 .3 .4 .6} * {68.1} {71.2} {72.3}

    * @return null if not a name, or a String containing the * name. */ public String Name() throws XmlException, IOException { String name = scanner.getName(); return name; } /** * Parses multiple names. Not implemented. *

    * {06} Names (not part of any other rule - however, * TokenizedType{56} refers to 'IDREFS' content, which is of type Names): * *

    * @return null */ public List Names() throws XmlException, IOException { List l = new ArrayList(); while (true) { String s = Name(); if (s == null) break; l.add(s); S(); } return l; } /** * Parse Nmtoken. *

    {07} Nmtoken (Name token) {08.1 .3} {59.2 .5} *

    */ public String Nmtoken() throws XmlException, IOException { int c = scanner.peek(); if (!NameChar((char)c)) { return null; } int len = 0; attValue.reset(); while (true) { c = scanner.read(); if (!NameChar((char)c)) { if (c > 0) scanner.unread(c); return attValue.toString(); } attValue.write((char)c); if (len++ > XmlReaderPrefs.MAX_NAME_LEN) { throw new XmlException("Exceeded MAX_NAME_LEN, read to " + attValue); } } } /** * Parse Nmtokens. *

    {08} Nmtokens (Name tokens) * (not part of any other rule - however, * TokenizedType{56} refers to 'NMTOKENS' content): *

    * @return a list of String instances */ public List Nmtokens() throws XmlException, IOException { List l = new ArrayList(); while (true) { String s = Nmtoken(); if (s == null) break; l.add(s); S(); } return l; } /** * Parse Entity Value. Calls the same code as AttValue(), though * it parses PEReference as well as References. *

    {09} EntityValue {73.1} {74.1} *

    * @return entity value without quotes, or null if not an entity */ public String EntityValue() throws IOException, XmlException { int q = scanner.peek(); if (q != '"' && q != '\'' && q != '%') throw new XmlException("Expected EntityValue quote or %, got " + (char)q); if (q == '%') { Entity e = PEReference(); return e.resolveAll(this); } return AttValue(true); } /** * @param resolvePE true to resolve and append parameter entities * @see #AttValue() */ private String AttValue(boolean resolvePE) throws IOException, XmlException { int q = scanner.read(); if (q != '"' && q != '\'') throw new XmlException("Expected AttValue quote, got " + (char)q); attValue.reset(); int c; while (true) { c = scanner.peek(); if (c == -1) throw new XmlException("EOF in AttValue"); if (c == '>' && !resolvePE) throw new XmlException("Must not have > in AttValue"); // check for reference if (c == '&') { if (CharRef()) { // expand immediately attValue.write(scanner.read()); continue; // for case } else if (!resolvePE) { Entity ent = Reference(); if (ent != null) { if (ent.isExternal()) throw new XmlException("No external entity in att value"); attValue.write(ent.resolveAll(this)); } else { attValue.write((char)scanner.read()); } continue; // for && case } else { checkEntityReference(attValue); } } // check for parameter reference if (c == '%' && resolvePE) { Entity e = PEReference(); attValue.write(e.resolveAll(this)); continue; // for %ref;%ref; case } c = scanner.read(); // closing quote if (q == c) return attValue.toString(); attValue.write(c); if (attValue.size() > XmlReaderPrefs.MAX_ATTRIBUTE_LEN) { throw new XmlException("Exceeded MAX_ATTRIBUTE_LEN, read to " + attValue); } } } /** * Parse attribute value. *

    {10} AttValue (Attribute Value) {41.1} * {60.2}

    * @return attribute value * @throws XmlException if bad attribute value */ public String AttValue() throws IOException, XmlException { return AttValue(false); } /** * Parse system literal value. *

    {11} SystemLiteral {75.2 .6}

    * @return literal value * @throws XmlException if bad system literal */ public String SystemLiteral() throws IOException, XmlException { int q = scanner.read(); if (q != '"' && q != '\'') throw new XmlException("Expected SystemLiteral quote, got " + q); attValue.reset(); int c; int len = 0; while (true) { c = scanner.read(); // closing quote if (q == c) return attValue.toString(); if (len++ > XmlReaderPrefs.MAX_SYSTEM_LITERAL_LEN) throw new XmlException("Exceeded MAX_SYSTEM_LITERAL_LEN, read to " + attValue); if (c == -1) { throw new XmlException("Expecting closing quote, read to " + attValue); } attValue.write((char)c); } } /** * Parse a public identifier value. *

    {12} PubidLiteral {75.4 83.2}

    * @return public identifier value * @throws XmlException if bad public literal */ public String PubidLiteral() throws IOException, XmlException { String s = SystemLiteral(); for (int i = 0; i < s.length(); i++) { if (!PubidChar(s.charAt(i))) throw new XmlException("Bad PubidChar in " + s); } return s; } /** * Check if valid PubidChar. *

    {13} PubidChar {12.1 .2}

    * @return is valid Pubid character */ public static boolean PubidChar(char c) { if (c == '\"' || c == '&' || c == '\'' || c == '<' || c == '>') return false; if (c >= ' ' && c <= 'Z') return true; if (c >= 'a' && c <= 'z') return true; if (c == '_') return true; return false; } /** * Parse char data, until < or & character. *

    {14} CharData {43.2}

    * @param w writer to copy CharData to * @throws XmlException if bad character data */ public void CharData(Writer w) throws IOException, XmlException { scanner.copyUntil(w, '<', '&'); } /** * Parse comment. *

    {15} Comment {27.1} {29.6} {43.6}

    * @throws XmlException if premature EOF or bad comment data * @param skip if true, skips over a comment; if false, * returns a new Comment instance * @return null if comment was not found. */ public Comment comment(boolean skip) throws IOException, XmlException { // read in Comment c = null; if (skip) { copyUntil(NullWriter.getInstance(), XmlTags.COMMENT_DASH); } else { c = new Comment(); copyUntil(c.getWriter(), XmlTags.COMMENT_DASH); } if (scanner.read() != '>') throw new XmlException("Cannot have -- in comment"); return c; } /** * Parse processing instruction. *

    {16} PI (Processing Instruction) {27.1} {29.5} * {43.5}

    * @return false, if PI was not found. * @throws XmlException if premature EOF or bad PI data * @param skip false to return this processing instruction as * as PI; if true, skips this processing instruction * and returns null */ public PI pi(boolean skip) throws IOException, XmlException { // read in if (skip) { copyUntil(NullWriter.getInstance(), XmlTags.PI_END); } else { PI pi = new PI(target); copyUntil(pi.getWriter(), XmlTags.PI_END); return pi; } return null; } /** * Parse processing instruction target. *

    {17} PITarget (Processing Instruction Target) * {16.1}

    * @throws XmlException if premature EOF or bad target data */ public String PITarget() throws IOException, XmlException { String name = Name(); if (name == null) throw new XmlException("Expected a Name following {18} CDSect (Character Data Section) {43.4}

    *

    {19} CDStart (Character Data Start) {18.1}

    *

    {20} CData (Character Data) {18.1}

    *

    {21} CDEnd (Character Data End) {18.3}

    * @param Writer write contents to this object * @return null, if CDSect was not found. * @throws XmlException if premature EOF or bad CDSect data */ public boolean CDSect(Writer w) throws IOException, XmlException { // read in copyUntil(w, XmlTags.CDATA_END); return true; } /** * Parse prolog. *

    {22} Prolog {01.1}

    */ public void Prolog(Document d) throws IOException, XmlException { XmlDecl(); while (Misc(d)); boolean found = doctypedecl(); if (found) while (Misc(d)); } /** * Parse an XmlDecl or TextDecl. * @param allowSA allow standalone */ boolean XmlDecl(boolean allowSA) throws IOException, XmlException { // read in for XmlDecl"); return true; } /** * Parse XML declaration. *

    {23} XmlDecl (XML Declaration) {22.1}

    * @return false, if XmlDecl was not found. * @throws XmlException if premature EOF or bad PI data */ public boolean XmlDecl() throws IOException, XmlException { return XmlDecl(true); } /** * Parse version info. *

    {24} VersionInfo {23.1}

    */ public void VersionInfo() throws IOException, XmlException { if (!S()) throw new XmlException("Expected space after XML"); if (!matches(XmlTags.VERSION_BEGIN)) { throw new XmlException("Expected 'version'"); } Eq(); String version = SystemLiteral(); if (!VersionNum(version)) throw new XmlException("Version contains invalid characters: " + version); } /** * Parse equals. *

    {25} Eq (Equals) {24.2} {32.2} {41.2} {80.2}

    */ public void Eq() throws IOException, XmlException { S(); if (scanner.read() != '=') throw new XmlException("Expected ="); S(); } /** * Parse version number. *

    {26} VersionNum {24.3 .4}

    * @param c character to check * @return if valid character */ public boolean VersionNum(String ver) throws IOException, XmlException { int len = ver.length(); for (int i = 0; i < len; i++) { char c = ver.charAt(i); if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || (c == '.')) { continue; } return false; } return true; } /** * Parse misc stuff. *

    {27} Misc (Miscellaneous) {01.3} {22.2 .4}

    * @param d a document to store comments and processing instructions * in; can be null if no comments or processing instructions are to * be stored * @return true if any miscellaneous text was found * @see #comment * @see #pi * @see #S */ public boolean Misc(Document d) throws IOException, XmlException { if (S()) return true; Comment c = comment(false); if (c != null) { if (d != null) d.appendChild(c); return true; } PI pi = pi(false); if (pi != null) { if (d != null) d.appendChild(pi); return true; } return false; } /** * Parse doctypedecl. *

    {28} doctypedecl {22.3}

    * @return true if doctypedecl exists */ public boolean doctypedecl() throws IOException, XmlException { // read in ') throw new XmlException("Expected > at end of doctypedecl, not " + (char)c); if (dtd != null) { resolveExtSubset(dtd); } return true; } /** * Parse markup declaration. *

    {29} markupdecl {28.6} {31.1}

    * @return false if no element found * @throws XmlException */ public boolean markupdecl() throws IOException, XmlException { switch (scanner.peekEvent()) { case XmlEvent.ELEMENT_DECL: if (!elementdecl()) throw new XmlException("Expected elementdecl"); break; case XmlEvent.ATTLIST_DECL: if (!AttlistDecl()) throw new XmlException("Expected AttlistDecl"); break; case XmlEvent.ENTITY_DECL: if (!EntityDecl()) throw new XmlException("Expected EntityDecl"); break; case XmlEvent.NOTATATION_DECL: if (!NotationDecl()) throw new XmlException("Expected NotationDecl"); break; case XmlEvent.PI: if (pi(false) == null) throw new XmlException("Expected PI"); break; case XmlEvent.COMMENT: if (comment(false) == null) throw new XmlException("Expected Comment"); break; default: return false; } return true; } /** * Parse an extSubset. *

    {30} extSubset: the Dtd file

    * @throws XmlException if data found in bad form */ public void extSubset() throws XmlException, IOException { TextDecl(); extSubsetDecl(); } /** * Begins scanning using an parameter entity. */ private void peScan(Entity entity) throws IOException, XmlException { XmlScanner newScanner; XmlScanner oldScanner = scanner; if (entity.getValue() == null) { Reader r = resolver.resolve(entity.getSystemID()); newScanner = createXmlScanner(r); } else { newScanner = new XmlScanner(entity.getValue()); } scanner = newScanner; extSubsetDecl(); if (hasMoreData()) throw new XmlException("Incomplete parameter entity content " + entity); scanner = oldScanner; } /** * Parse external subset declaration. *

    {31} extSubsetDecl {30.2} {62.3} {79.2}

    * @return when done reading * @throws XmlException */ public void extSubsetDecl() throws IOException, XmlException { while (true) { // exits when no more valid events S(); switch (scanner.peekEvent()) { case XmlEvent.ELEMENT_DECL: case XmlEvent.ATTLIST_DECL: case XmlEvent.ENTITY_DECL: case XmlEvent.NOTATATION_DECL: case XmlEvent.PI: case XmlEvent.COMMENT: markupdecl(); break; case XmlEvent.CONDITIONAL_SECT: conditionalSect(); break; default: if (scanner.peek() == '%') { peScan(PEReference()); } else { return; } } } } /** * Parse an standalone document declaration. *

    {32} SDDecl {23.3}

    * @throws XmlException if encoding incorrect * @return yes, no, or null */ public String SDDecl() throws XmlException, IOException { boolean space = S(); if (matches(XmlTags.STANDALONE_BEGIN)) { if (!space) throw new XmlException("Expected space before standalone declaration"); Eq(); String yesNo = AttValue(); if (!yesNo.equals("yes") && !yesNo.equals("no")) throw new XmlException("Expected yes or no for standalone value"); return yesNo; } return null; } /** * Parse element. *

    {39} element {01.2} {43.1}

    * @return false if no element found * @throws XmlException */ public Element element() throws IOException, XmlException { Element e = STag(); if (e == null) { return null; } if (e.isOpen()) { content(e); if (!ETag(e)) { throw new XmlException("Expected tag "); } } return e; } /** * Creates and returns either a Element or ElementNS; also configures namespaces. * @throws XmlException if something is wrong with the namespace */ private Element makeElement(NamespaceImpl namespace, List attr, boolean open) throws XmlException { UriMap m = scanner.getUriMap(); boolean useNS = namespace.hasNamespace(); // || // m.getDefaultNamespace() != null; if (attr != null) { for (int i = 0; i < attr.size(); i++) { Attribute a = attr.get(i); if (a.getPrefix() == XmlTags.XMLNS) { // form String ln = a.getLocalName(); String v = a.getValue(); m.put(ln, v); } if (a.getName() == XmlTags.XMLNS) { // form String v = a.getValue(); if (v.length() != 0) v = null; namespace.setNamespaceURI(v); // m.setDefaultNamespace(v); useNS = true; } } } if (useNS) return new ElementNS(namespace, attr, open); else return new Element(namespace.getName(), attr, open); } /** * Parse STag. Also parses EmptyElemTag. *

    {40} STag {39.2}

    *

    {44} EmptyElemTag {39.1}

    * @return Element, which will indicate open or closed. * @throws XmlException if bad STag */ public Element STag() throws IOException, XmlException { if (!matches(XmlEvent.STAG, 1)) return null; scanner.readNamespace(namespaceElement); // TODO select DTD based on this namespace ElementRule rule = dtd.getElementRule(namespaceElement.getName()); if (rule != null) aruleState.clear(); List attr = null; int c; while (true) { boolean space = S(); c = scanner.read(); if (c == '/') { c = scanner.read(); if (c != '>') throw new XmlException("Expected > for empty element"); if (rule != null) attr = rule.encounterEnd(aruleState, attr); return makeElement(namespaceElement, attr, false); } if (c == '>') { if (rule != null) attr = rule.encounterEnd(aruleState, attr); return makeElement(namespaceElement, attr, true); } scanner.unread(c); if (!space) throw new XmlException("Expected whitespace after name or attribute"); // if not closing, assume we got an attribute to parse Attribute a = Attribute(); if (rule != null) rule.encounterAttribute(a, aruleState); if (attr == null) attr = new ArrayList(); attr.add(a); } } /** * Parse Attribute. Returns either a regular * {@link Attribute} or a {@link AttributeNS} depending * on if namespace information is available or not. *

    {41} Attribute {40.3} {44.3}

    * * @return an attribute * @throws XmlException if no or an invalid attribute was found */ public Attribute Attribute() throws IOException, XmlException { scanner.readNamespace(namespaceAttr); if (namespaceAttr.isClear()) throw new XmlException("Expected Attribute name"); Eq(); String value = AttValue(); if (namespaceAttr.hasNamespace()) return new AttributeNS(namespaceAttr, value); else return new Attribute(namespaceAttr.getName(), value); } /** * Parse ETag. *

    {42} ETag (End Tag) {39.4}

    * @return an element, if exists */ public Element ETag() throws IOException, XmlException { if (!matches(XmlEvent.ETAG, 2)) return null; String name = Name(); if (name == null) throw new XmlException("Expected name for ETag"); S(); int c = scanner.read(); if (c != '>') throw new XmlException("Expected > for ETag " + name); return new Element(name); } /** * Parse ETag. *

    {42} ETag (End Tag) {39.4}

    * @param match beginning element to match * @return true, if exists * @throws XmlException if etag does not match "match" */ public boolean ETag(Element match) throws IOException, XmlException { if (!matches(XmlEvent.ETAG, 2)) return false; String name = Name(); if (name == null) throw new XmlException("Expected name for ETag"); if (name != match.getName() && !name.equals(match.getName())) throw new XmlException("Expected got "); S(); int c = scanner.read(); if (c != '>') throw new XmlException("Expected > for ETag " + name); return true; } /** * Begins scanning using an entity that appears within a document. */ private void entityScan(Element e, Entity entity) throws IOException, XmlException { XmlScanner newScanner; XmlScanner oldScanner = scanner; boolean oldInEntityScan = inEntityScan; if (entity.getValue() == null) { Reader r = resolver.resolve(entity.getSystemID()); newScanner = createXmlScanner(r); } else { newScanner = new XmlScanner(entity.getValue()); } newScanner.setStringPool(oldScanner.getStringPool()); if (entity.isResolving()) throw new XmlException("Circular entity evaluation for " + entity); entity.setResolving(true); inEntityScan = true; scanner = newScanner; content(e); if (hasMoreData()) throw new XmlException("Unmatched end tag in entity content " + entity); if (!oldInEntityScan) inEntityScan = false; scanner = oldScanner; entity.setResolving(false); } /** * Parse content. *

    {43} content {39.3} {78.2}

    * @param e Element to add content to * @throws XmlException if bad content */ public void content(Element e) throws IOException, XmlException { ElementRule rule = dtd.getElementRule(e.getName()); ElementRuleState eruleState = null; boolean pcdata = true; if (rule != null) { pcdata = rule.isPCDataAllowed(); // during entity scanning, we want to continue to use the old rule if (inEntityScan) eruleState = eruleStack.state(); else eruleState = eruleStack.startElement(); if (!inEntityScan) eruleState.clear(); } Writer w = NullWriter.getInstance(); CharacterData cd = null; whileLoop: while (true) { if (!pcdata) S(); switch (scanner.peekEvent()) { case XmlEvent.ETAG: if (cd != null) e.appendChild(cd); break whileLoop; case XmlEvent.STAG: if (cd != null) e.appendChild(cd); Element child = element(); if (rule != null) rule.encounterElement(child, eruleState); e.appendChild(child); break; case XmlEvent.COMMENT: if (cd != null) e.appendChild(cd); Comment c = comment(false); if (c != null) e.appendChild(c); break; case XmlEvent.PI: if (cd != null) e.appendChild(cd); PI pi = pi(false); if (pi != null) e.appendChild(pi); break; case XmlEvent.CHARDATA: if (!pcdata) throw new ElementRuleException("Not allowed to have PCDATA section: " + e, rule); if (cd == null) { cd = new CharacterData(); w = cd.getWriter(); } CharData(w); break; case XmlEvent.CDSECT: if (!pcdata) throw new ElementRuleException("Not allowed to have PCDATA section: " + e, rule); if (cd == null) { cd = new CharacterData(); w = cd.getWriter(); } if (!CDSect(w)) { throw new XmlException("Bad CDSect tag found"); } break; case XmlEvent.REFERENCE: Entity entity = Reference(); if (entity != null) { entityScan(e, entity); } else { if (!pcdata) throw new ElementRuleException("Not allowed to have PCDATA section: " + e, rule); if (cd == null) { cd = new CharacterData(); w = cd.getWriter(); } w.write((char)scanner.read()); } break; case XmlEvent.NONE: throw new XmlException("Illegal content for element"); case XmlEvent.EOD: if (inEntityScan) { if (cd != null) e.appendChild(cd); break whileLoop; } throw new XmlException("EOF in scanning"); default: throw new XmlException("Unknown content for element " + e); } } if (rule != null) { if (!inEntityScan) { rule.encounterEnd(eruleState); eruleStack.endElement(); } } } /** * Parse element declaration. Adds entity rule, if found. *

    {45} elementdecl {29.1}

    * @throws XmlException if bad element declaration or duplicate found * @return false if an elementdecl was not found. */ public boolean elementdecl() throws IOException, XmlException { if (!matches(XmlTags.ELEMENT_DECL_BEGIN)) return false; if (!S()) throw new XmlException("Expected space after elementdecl"); String name = Name(); if (name == null) throw new XmlException("Expected name after elementdecl: " + this); if (!S()) throw new XmlException("Expected space after elementdecl name"); ElementReq req = contentspec(); S(); int c = scanner.read(); if (c != '>') throw new XmlException("Expected > at end of elementdecl"); ElementRule rule = dtd.getElementRule(name); if (rule == null) { dtd.addElementRule(name, new ElementRule(req, null)); } else { rule.setRootReq(req); } return true; } /** * Parse content specification. *

    {46} contentspec (content specification) * {45.4}

    * @throws XmlException if bad content specification * @return ElementRule rule containing allowable elements */ public ElementReq contentspec() throws IOException, XmlException { ElementReq req; if (matches(XmlTags.CONTENTSPEC_EMPTY)) { req = new ElementReq(); } else if (matches(XmlTags.CONTENTSPEC_ANY)) { req = new ElementReq(); req.setANY(); } else { req = Mixed(); if (req == null) throw new XmlException("Expected Mixed or children in contentspec"); } return req; } /** * Parse children. *

    {47} children {46.2}

    * @throws XmlException if bad children */ public ElementReq children() throws IOException, XmlException { ElementReq req = choiceSeq(true); int c = scanner.read(); if (c == '>' || isS(c)) { scanner.unread(c); } else if (c != '?' && c != '*' && c != '+') { throw new XmlException("Expected *, ?, or +"); } req.setRepeating(c); return req; } /** * Parse content particle. *

    {48} cp {49.2 .5} {50.2 .5}

    * @throws XmlException if bad children */ public ElementReq cp() throws IOException, XmlException { ElementReq req; String name = Name(); if (name != null) { req = new ElementReq(name); } else { req = choiceSeq(); } int c = scanner.peek(); if (c == '?' || c == '*' || c == '+') scanner.read(); req.setRepeating(c); return req; } /** * Parse choice or sequence. *

    {49} choice {47.1} {48.2}

    *

    {50} seq (sequence) {47.2} {48.3}

    * @throws XmlException if bad children */ public ElementReq choiceSeq() throws IOException, XmlException { return choiceSeq(false); } private ElementReq choiceSeq(boolean initial) throws IOException, XmlException { boolean isSeq = false; boolean isChoice = false; ElementReq req = new ElementReq(); if (!initial) { if (!matches(XmlTags.PAREN_BEGIN)) throw new XmlException("Expected ( in choiceSeq" + this); } while (true) { S(); req.add(cp()); S(); int c = scanner.read(); if (c == ',') { if (isChoice) throw new XmlException("Expect | not , in choice"); isSeq = true; continue; } if (c == '|') { if (isSeq) throw new XmlException("Expect , not | in sequence"); isChoice = true; continue; } if (c == ')') { if (isSeq) req.setSequence(); else req.setChoice(); return req; } throw new XmlException("Expect ) to end choiceSeq"); } } void fillMixed(ElementReq req) throws IOException, XmlException { while (true) { S(); // get space after #PCDATA or last name if (unreadPEReference()) S(); if (matches(XmlTags.PAREN_END_STAR)) { req.setChoice(); req.setStar(); return; } if (matches(XmlTags.PAREN_END)) { if (req.size() > 0) throw new XmlException("Expected )* not )"); return; } if (!matches(XmlTags.BAR)) throw new XmlException("Expected | or )*"); S(); String name = Name(); if (name == null) throw new XmlException("Expected element name"); req.add(new ElementReq(name)); } } /** * Parse content specification's mixed or children content. *

    {51} Mixed (mixed content) {46.1}

    *

    {47} children {46.2}

    * @throws XmlException if bad specification * @return null if not a specification or rule containing allowable elements */ public ElementReq Mixed() throws IOException, XmlException { if (!matches(XmlTags.PAREN_BEGIN)) throw new XmlException("Expected ("); S(); // Truly Mixed if (matches(XmlTags.PCDATA_TAG)) { ElementReq req = new ElementReq(); req.setPCDATA(); fillMixed(req); return req; } else { // children return children(); } } /** * Parse attribute declaration. Affects entity rule, if found. *

    {52} AttlistDecl {29.2}

    * @throws XmlException if bad element declaration * @return false if an attribute declaration was not found. */ public boolean AttlistDecl() throws IOException, XmlException { if (!matches(XmlTags.ATTLIST_DECL_BEGIN)) return false; boolean space = S(); if (unreadPEReference()) { space = S(); } if (!space) throw new XmlException("Expected space after AttlistDecl"); String name = Name(); if (name == null) throw new XmlException("Expected name after AttlistDecl"); ElementRule rule = dtd.getElementRule(name); // This is just a warning if (rule == null) { rule = new ElementRule(null); dtd.addElementRule(name, rule); } while (true) { AttDef(rule); int c = scanner.peek(); if (c == '>') break; // throw new XmlException("Expected > at end of AttlistDecl"); } scanner.read(); return true; } /** * Parse attribute declaration. *

    {53} AttDef (Attribute Definition) {52.4}

    * @param erule a rule in which to store the name to AttributeRule mappings * @throws XmlException if bad element declaration */ public void AttDef(ElementRule erule) throws IOException, XmlException { boolean space = S(); if (unreadPEReference()) space = S(); String name = Name(); if (name == null) { return; } if (space == false) throw new XmlException("Expected space before AttDef name"); if (!S()) throw new XmlException("Expected space after AttDef name"); AttributeRule arule = AttType(); arule.setName(name); unreadPEReference(); if (!S()) throw new XmlException("Expected space after AttDef name"); DefaultDecl(arule); erule.addAttributeRule(arule); } /** * Parse an attribute type. Returns a new rule. *

    {53} AttType (Attribute Type) {53.4}

    *

    {54} StringType {54.1}

    *

    {55} TokenizedType {54.2}

    *

    {56} EnumeratedType {54.3}

    * @throws XmlException if unknown or bad attribute type */ public AttributeRule AttType() throws IOException, XmlException { String type = Name(); if (type != null) { if (type.equals(XmlTags.ST_CDATA)) return new AttributeRule(AttributeValueType.CDATA); if (type.equals(XmlTags.TT_ID)) return new AttributeRule(AttributeValueType.ID); if (type.equals(XmlTags.TT_IDREF)) return new AttributeRule(AttributeValueType.IDREF); if (type.equals(XmlTags.TT_IDREFS)) return new AttributeRule(AttributeValueType.IDREFS); if (type.equals(XmlTags.TT_ENTITY)) return new AttributeRule(AttributeValueType.ENTITY); if (type.equals(XmlTags.TT_ENTITIES)) return new AttributeRule(AttributeValueType.ENTITIES); if (type.equals(XmlTags.TT_NMTOKEN)) return new AttributeRule(AttributeValueType.NMTOKEN); if (type.equals(XmlTags.TT_NMTOKENS)) return new AttributeRule(AttributeValueType.NMTOKENS); if (type.equals(XmlTags.ET_NOTATION)) { if (!S()) throw new XmlException("Expected space after NOTATION"); return new AttributeRule(AttributeValueType.NOTATION, Enumeration()); } throw new XmlException("Unknown AttType " + type); } return new AttributeRule(AttributeValueType.NAME_GROUP, Enumeration()); } /** * Parses an attribute enumeration. Returns a Collection of String instances. *

    {59} Enumeration {57.2}

    * @throws XmlException if bad enumeration */ public Collection Enumeration() throws IOException, XmlException { if (!matches(XmlTags.PAREN_BEGIN)) throw new XmlException("Expected ( in Enumeration"); Collection list = new ArrayList(); while (true) { S(); String nmtoken = Nmtoken(); list.add(nmtoken); S(); int c = scanner.read(); if (c == ')') break; if (c != '|') throw new XmlException("Expected | in Enumeration: " + (char)c); } return list; } /** * Parses a default declaration. *

    {60} DefaultDecl {53.6}

    * @param rule sets either the fixed or default value for this object * @throws XmlException if bad declaration */ public void DefaultDecl(AttributeRule rule) throws IOException, XmlException { unreadPEReference(); if (matches(XmlTags.REQUIRED_BEGIN)) { rule.setRequired(); } else if (matches(XmlTags.IMPLIED_BEGIN)) { } else if (matches(XmlTags.FIXED_BEGIN)) { S(); String v = AttValue(); rule.setFixed(v); } else { S(); String v = AttValue(); rule.setDefault(v); } } /** * Parses a condition section. *

    {61} conditionalSect {31.2}

    * @throws XmlException if bad conditional section */ public void conditionalSect() throws IOException, XmlException { if (!matches(XmlEvent.CONDITIONAL_SECT, 3)) return; S(); unreadPEReference(); S(); String name = Name(); if (name == null) throw new XmlException("Expected INCLUDE or IGNORE"); S(); if (scanner.read() != '[') throw new XmlException("Expected [ after " + name); if (name.equals(XmlTags.IGNORE_BEGIN)) ignoreSect(); else if (name.equals(XmlTags.INCLUDE_BEGIN)) includeSect(); else throw new XmlException("Expected INCLUDE or IGNORE, not " + name); } /** * Parses an includeSect, past the <![INCLUDE[ tag. *

    {62} includeSect {61.1}

    */ public void includeSect() throws IOException, XmlException { extSubsetDecl(); if (!matches(XmlTags.CDATA_END)) throw new XmlException("Expected ]]> at end of includeSect"); } /** * Parses an ignoreSect, past the <![IGNORE[ tag. *

    {63} ignoreSect {61.2}

    */ public void ignoreSect() throws IOException, XmlException { ignoreSectContents(); } /** * Parses ignore section contents. *

    {64} ignoreSectContents {63.3} {64.2}

    */ public void ignoreSectContents() throws IOException, XmlException { while (true) { int c = scanner.skipUntil('<', ']'); if (c == '<' && matches(XmlTags.CONDITIONAL_BEGIN)) { ignoreSectContents(); } if (c == ']' && matches(XmlTags.CDATA_END)) { break; } if (c == -1) throw new XmlException("EOF in ignoreSectContents"); scanner.read(); } } /** * Parses ignore contents. *

    {65} Ignore {64.1 .3}

    */ public void Ignore() { } /** * Parse character reference. Once read, is put back on the stream. *

    {66} CharRef {67.2}

    * @throws XmlException if bad character reference * @return true if a CharRef was found */ public boolean CharRef() throws IOException, XmlException { return scanner.charRef(); } /** * Checks a reference for valid syntax, and if valid appends * it to the writer. */ private void checkEntityReference(Writer writer) throws IOException, XmlException { scanner.read(); // & String name = Name(); if (name == null) throw new XmlException("Expected name after & in entity"); if (scanner.read() != ';') throw new XmlException("Expected ; after " + name + " in entity"); writer.write('&'); writer.write(name); writer.write(';'); } /** * Parse a reference, starting with & character. *

    {67} Reference {09.2 .4} {10.1 .2} {43.3}

    * @return Entity value, if significant entity exists * @throws XmlException if bad reference */ public Entity Reference() throws IOException, XmlException { if (scanner.peek() != '&') return null; if (scanner.translateReference()) return null; if (CharRef()) return null; scanner.read(); // & String name = Name(); if (name == null) throw new XmlException("Expected name after &"); if (scanner.read() != ';') throw new XmlException("Expected ; after " + name); Entity entity = dtd.getEntity(name); if (entity == null) throw new XmlException("Unknown entity " + name); return entity; } boolean unreadPEReference() throws IOException, XmlException { Entity e = PEReference(); if (e != null) { scanner.unread(' '); scanner.unread(e.resolveAll(this)); scanner.unread(' '); return true; } return false; } /** * Parse an parameter entity reference. *

    {69} PEReference {09.1 .3} {28.7} {31.3}

    * @return Entity instance * @throws XmlException if PEReference is bad */ public Entity PEReference() throws IOException, XmlException { if (scanner.peek() != '%') return null; scanner.read(); String pe = Name(); if (pe == null) throw new XmlException("Expected name after %"); if (scanner.read() != ';') throw new XmlException("Expected ; after " + pe); Entity entity = dtd.getParameterEntity(pe); if (entity == null) throw new XmlException("Unknown parameter entity " + pe); return entity; } /** * Parse an entity declaration. Adds its value to the Dtd. *

    {70} EntityDecl {29.3}

    * @return false if not found * @throws XmlException if entity decl is bad */ public boolean EntityDecl() throws IOException, XmlException { if (!matches(XmlTags.ENTITY_DECL_BEGIN)) return false; if (!S()) throw new XmlException("Expected space after ') throw new XmlException("Expected > after for entity declaration"); return true; } /** * Parse a general entity declaration. *

    {71} GEDecl {70.1}

    */ public void GEDecl() throws IOException, XmlException { EntityDecl(); } /** * Parse an parameter entity declaration. *

    {72} PEDecl {70.2}

    */ public void PEDecl() throws IOException, XmlException { EntityDecl(); } /** * Parse an entity definition. *

    {73} EntityDef {71.4}

    * @throws XmlException if entity definition is bad * @return value of this entity */ public Entity EntityDef() throws IOException, XmlException { Entity entity = ExternalID(); if (entity != null) { NDataDecl(); } else { String value = EntityValue(); entity = new Entity(value); } return entity; } /** * Parse an parameter entity definition. *

    {74} PEDef {72.5}

    * @throws XmlException if parameter entity definition is bad * @return value of this parameter entity */ public Entity PEDef() throws IOException, XmlException { Entity entity = ExternalID(); if (entity == null) { String value = EntityValue(); entity = new Entity(value); } return entity; } private Entity ExternalID(boolean reqSystemLiteral) throws IOException, XmlException { if (matches(XmlTags.PUBLIC_BEGIN)) { if (!S()) throw new XmlException("Expected space after PUBLIC"); String pubid = PubidLiteral(); Entity entity; if (S()) { String sys = SystemLiteral(); entity = new Entity(pubid, sys); } else { if (reqSystemLiteral) { throw new XmlException("Expected SystemLiteral"); } entity = new Entity(pubid, null); } return entity; } if (matches(XmlTags.SYSTEM_BEGIN)) { if (!S()) throw new XmlException("Expected space after SYSTEM"); String sys = SystemLiteral(); Entity entity = new Entity(null, sys); return entity; } return null; } /** * Parse an ExternalID. *

    {75} ExternalID {04.1} {05.1}

    * @return the external identifier, with public and system id's */ public Entity ExternalID() throws XmlException, IOException { return ExternalID(true); } /** * Parse notational data declaration. *

    {76} NDataDecl {73.2}

    * @return name of the notation system if found * @throws XmlException if NDATA found but bad name */ public String NDataDecl() throws XmlException, IOException { boolean spaced = S(); if (matches(XmlTags.NDATA_BEGIN)) { if (!spaced) throw new XmlException("Expected space before NDATA"); if (!S()) throw new XmlException("Expected space after NDATA"); String name = Name(); if (name == null) throw new XmlException("Expected name after NDATA"); return name; } return null; } /** * Parse XML text declaration. *

    {77} TextDecl (Text Declaration) {30.1} {78.1} {79.1}

    * @return false, if TextDecl was not found. * @throws XmlException if premature EOF or bad PI data */ public boolean TextDecl() throws IOException, XmlException { return XmlDecl(false); } /** * Parse an external parsed entity. *

    {79} extParsedEnt

    * @throws XmlException if data found in bad form * @param e an element to add content to */ public void extParsedEnt(Element e) throws XmlException, IOException { TextDecl(); inEntityScan = true; content(e); inEntityScan = false; } /** * Parse an extPE. *

    {79} extPE

    * @throws XmlException if data found in bad form */ public void extPE() throws XmlException, IOException { TextDecl(); extSubsetDecl(); } /** * Parse an encoding. *

    {80} EncodingDecl: {23.2} {77.2}

    * @throws XmlException if encoding incorrect * @return the encoding or null */ public String EncodingDecl() throws XmlException, IOException { boolean space = S(); if (matches(XmlTags.ENCODING_BEGIN)) { if (!space) throw new XmlException("Expected space before encoding declaration"); Eq(); String enc = AttValue(false); EncName(enc); return enc; } else { if (space) scanner.unread(' '); } return null; } /** * Parse an encoding name. *

    {81} EncName: {80.3 .4}

    * @throws XmlException if encoding name is bad * @return the encoding name */ public void EncName(String name) throws XmlException, IOException { int len = name.length(); for (int i = 0; i < len; i++) { char c = name.charAt(i); if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '-' || c == '_' || c == '.') { continue; } throw new XmlException("Encoding name invalid " + name); } } /** * Parse notational declaration. Adds its value to the Dtd. *

    {82} NotationDecl {29.4}

    * @return true if notation declaration found * @throws XmlException if data found in bad form */ public boolean NotationDecl() throws XmlException, IOException { if (!matches(XmlTags.NOTATION_DECL_BEGIN)) { return false; } if (!S()) throw new XmlException("Expected space after NotationDecl"); if (unreadPEReference()) S(); String name = Name(); if (name == null) throw new XmlException("Expected name after NotationDecl"); if (!S()) throw new XmlException("Expected space after NotationDecl name"); Entity entity = PublicID(); Notation n = new Notation(entity.getPublicID(), entity.getSystemID()); dtd.addNotation(name, n); S(); if (scanner.read() != '>') throw new XmlException("Expected > at end of NotationDecl"); return true; } /** * Parse a PublicID. *

    {83} PublicID {82.5}

    * @return the public literal */ public Entity PublicID() throws XmlException, IOException { return ExternalID(false); } /** * Checks if a character is a valid XML letter or not. *

    {84} Letter {04.1} {05.1}

    * @return true if is a XML letter */ public static boolean Letter(char l) { return Character.isLetter(l); } /** * Attempts to match an event, if so, skips ahead n characters. */ private boolean matches(int event, int skip) throws XmlException, IOException { if (scanner.peekEvent() == event) { scanner.skip(skip); return true; } return false; } /** * Retrives the next a.length characters from the input stream. If * these do not match the contents of the array, they are put back. * If they do match, they are thrown away and true is returned. * This is used to test for beginnings of tags and such. * @param a characters to find * @return true if matches */ boolean matches(final char a[]) throws IOException { int num = scanner.peek(cbuf, 0, a.length); if (num < a.length) return false; for (int i = 0; i < a.length; i++) if (cbuf[i] != a[i]) { return false; } scanner.skip(a.length); return true; } /** * This method copies until it finds a pattern of characters in the * input stream. This pattern of characters is not copied. * If EOF is found prematurely, an exception is raised. * @param w output stream to copy to * @param a character pattern to find * @throws XmlException if premature EOF is found */ void copyUntil(Writer w, char[] a) throws IOException, XmlException { int num; int alen = a.length; int alen_ = a.length - 1; while (true) { scanner.copyUntil(w, a[0], a[0]); num = scanner.read(cbuf, 0, alen); if (num < alen) throw new XmlException("Premature EOF looking for " + new String(a)); boolean match = true; for (int i = 1; i < alen; i++) { if (cbuf[i] != a[i]) { match = false; } } if (!match) { w.write(a[0]); scanner.unread(cbuf, 1, alen_); } else { return; } } } /** * Returns the ObjectPool for element rules. */ RuleStack getRuleStack() { return eruleStack; } /** * Used internally to read in a system literal. */ private void resolveExtSubset(Entity entity) throws IOException, XmlException { try { Reader r = resolver.resolve(entity.getSystemID()); XmlReader xr = new XmlReader(r, getDtd()); xr.setResolver(resolver); xr.extSubset(); if (xr.hasMoreData()) throw new XmlException("Unknown tags or data found in external subset"); xr.close(); } catch (XmlException r) { throw new ResolverException("Could not resolveExtSubset " + entity, r); } } /** * Returns a string containing the next 16 characters to be read * from the XmlScanner. These characters are put back after * reading. * @return a string for debugging purposes */ @Override public String toString() { try { int num = scanner.peek(cbuf, 0, 16); if (num == -1) return "XmlReader [ EOF ]"; String s = new String(cbuf, 0, num); return "XmlReader [" + s + "] (" + num + ") "; } catch (IOException ioe) { return super.toString() + " " + ioe.toString(); } } } libexml-java-0.0.20080703.orig/e-xml/src/main/java/net/noderunner/exml/XmlReaderPrefs.java0000644000175000017500000000226710762067376030666 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.exml; /** * This defines maximum overruns and such for the parser. * This keeps the parser from reading in too much due to bad data. * This should actually be configurable, however, they are just really * safety and sanity preferences. * * @author Elias Ross * @version 1.0 */ interface XmlReaderPrefs { int K = 1024; int MAX_SYSTEM_LITERAL_LEN = K; int MAX_ATTRIBUTE_LEN = K; int MAX_NAME_LEN = K; int MAX_REF_LEN = K; } libexml-java-0.0.20080703.orig/e-xml/src/main/java/net/noderunner/exml/CharacterData.java0000644000175000017500000000415510762067376030467 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.exml; /** * Stores characters and character data sections. * There may be many instances of this object per Element. * It uses a XmlCharArrayWriter to hold character data. The * XmlReader parse methods take java.io.Writer * instances as parameters. * * @see XmlCharArrayWriter * @version 1.0 * @author Elias Ross */ public class CharacterData implements Node { private XmlCharArrayWriter writer; /** * Constructs an empty character data string. */ public CharacterData() { writer = new XmlCharArrayWriter(); } /** * Returns the underlying XmlCharArrayWriter object. */ public XmlCharArrayWriter getWriter() { return writer; } /** * Returns the value TEXT_NODE. */ public short getNodeType() { return TEXT_NODE; } /** * Returns the data as a newly constructed String. * Does not escape punctuation, such as the & or < symbols. * * @see #toString */ public String getData() { return writer.toString(); } /** * Returns a string representation of this Object. Also, * escapes characters not allowed in CharData. * @return this object's data as a escaped XML string */ public String toString() { StringBuffer sb = new StringBuffer(writer.size() + 8); getWriter().writeEscapedTo(sb); return sb.toString(); } } libexml-java-0.0.20080703.orig/e-xml/src/main/java/net/noderunner/exml/Element.java0000644000175000017500000002166511014421656027361 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.exml; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; /** * This Element stores its name and attributes, and may contain * children. In that way, this Element object is similar to the * org.w3c.dom.Element. It has a few convenience functions * for getting at the character data of children. * The {@link Namespace} interface is implemented, however, its * methods, excepting {@link Namespace#getName}, merely return * null. */ public class Element implements Node, Namespace { private String name; private List attributes; private List children; private boolean open; /** * Constructs a simple open element from a string name. * @param name name of this element */ public Element(String name) { this.name = name; this.open = true; } /** * Returns ELEMENT_NODE. */ public final short getNodeType() { return ELEMENT_NODE; } /** * Constructs an Element with typical parameters. * Note: For performance reasons, the passed in List object is not * copied. * @param name Name of element * @param attributes List of attributes, or null if no attributes * @param open If this tag is open or closed */ public Element(String name, List attributes, boolean open) { this.name = name; this.attributes = attributes; this.open = open; } /** * Returns true if this element is open. A closed element * can have no children. */ public boolean isOpen() { return open; } /** * Makes this element open or closed. If this element is closed, * all child elements are erased. * @see #clearChildren */ public void setOpen(boolean open) { if (!open) clearChildren(); this.open = open; } /** * Returns the name of this element. */ public String getName() { return name; } /** * Sets the name of this element. */ public void setName(String name) { this.name = name; } /** * Sets the attributes of this element. */ public void setAttributes(List attributes) { this.attributes = attributes; } /** * Returns the attributes of this element as a list. */ public List getAttributes() { return attributes; } /** * Returns true if there is no namespace URI defined in ns1 and * the qualified names are the same. * Or, returns true if the namespace URI match and the local names * are the same. */ boolean equal(Namespace ns1, Namespace ns2) { if (ns1.getNamespaceURI() == null && ns1.getName() != null && ns1.getName().equals(ns2.getName())) { return true; } if (ns1.getNamespaceURI() == null || ns1.getLocalName() == null) return false; return ns1.getNamespaceURI().equals(ns2.getNamespaceURI()) && ns1.getLocalName().equals(ns2.getLocalName()); } /** * Returns the value of an attribute with the given name, or null * if no matching attribute was found. * @param name name of the attribute */ public String getAttValue(String name) { return getAttValue(name, null); } /** * Returns the value of an attribute with the given name. * @param name name of the attribute * @param dflt value returned if no matching attribute was found */ public String getAttValue(String name, String dflt) { if (attributes == null) return dflt; for (int i = 0; i < attributes.size(); i++) { Attribute a = attributes.get(i); if (a.getName().equals(name)) return a.getValue(); } return dflt; } /** * Returns the value of an attribute with the given namespace, * or null if no matching attribute was found. * @param ns namespace of the attribute */ public String getAttValue(Namespace ns) { return getAttValue(ns, null); } /** * Returns the value of an attribute with the given namespace. * @param ns namespace of the attribute * @param dflt value returned if no matching attribute was found */ public String getAttValue(Namespace ns, String dflt) { if (attributes == null) return dflt; for (int i = 0; i < attributes.size(); i++) { Attribute a = attributes.get(i); if (equal(ns, a)) return a.getValue(); } return dflt; } /** * Returns a character data string concatenated from all character * data child nodes. * @throws ElementException * @return a character data string; * null is never returned, an empty * string is returned even if no character data was found. */ public String getCharacterData() { if (children == null) return ""; StringBuffer sb = new StringBuffer(); for (int i = 0; i < children.size(); i++) { Node n = children.get(i); if (n.getNodeType() == TEXT_NODE) { CharacterData d = (CharacterData)n; XmlCharArrayWriter w = d.getWriter(); sb.append(w.getBuffer(), 0, w.size()); } } return sb.toString(); } /** * Returns a list of the child nodes. * @return null if no children are in this object */ public List getChildNodes() { return children; } /** * Appends an attribute to this Element. * @param a attribute to append * @throws ElementException */ public void appendAttribute(Attribute a) { if (attributes == null) { attributes = new ArrayList(); } attributes.add(a); } /** * Appends a child node to this Element. * @param n child node to append * @throws ElementException */ public void appendChild(Node n) { if (!open) throw new ElementException("Attempt to add child to closed element"); if (children == null) { children = new ArrayList(); } children.add(n); } /** * Returns the n-th child of this Element, starting with 0. * @return a node or null if no such node exists */ public Node getChild(int n) { if (children == null) return null; if (children.size() <= n) return null; return children.get(n); } /** * Returns the n-th child element of this element, starting with 0. * @return an element or null if no such element exists */ public Element getChildElement(int n) { if (children == null) return null; int count = 0; Iterator i = children.iterator(); while (i.hasNext()) { Node node = i.next(); if (node.getNodeType() == ELEMENT_NODE) { if (count == n) return (Element)node; count++; } } return null; } /** * Returns the n-th child element of this element, starting with 0, * with the given Namespace. * @return an element or null if no such element */ public Element getChildElement(Namespace ns, int n) { if (children == null) return null; int count = 0; Iterator i = children.iterator(); while (i.hasNext()) { Node node = i.next(); if (node.getNodeType() == ELEMENT_NODE) { Element e = (Element)node; if (equal(ns, e)) { if (count == n) return e; count++; } } } return null; } /** * Returns the n-th child element of this element, starting with 0, * with the given name. * @return an element or null if no such element */ public Element getChildElement(String name, int n) { if (children == null) return null; int count = 0; Iterator i = children.iterator(); while (i.hasNext()) { Node node = i.next(); if (node.getNodeType() == ELEMENT_NODE) { Element e = (Element)node; if (e.getName().equals(name)) { if (count == n) return e; count++; } } } return null; } /** * Clears the children of this element. This can be used to release * memory held by this object. */ public void clearChildren() { children = null; } /** * By default, returns null. * @see ElementNS#getNamespaceURI */ public String getNamespaceURI() { return null; } /** * By default, returns null. * @see ElementNS#getPrefix */ public String getPrefix() { return null; } /** * By default, returns null. * @see ElementNS#getLocalName */ public String getLocalName() { return null; } /** * Returns a string representation of this Element. */ @Override public String toString() { XmlCharArrayWriter w = new XmlCharArrayWriter(); XmlWriter xw = new XmlWriter(w); try { xw.element(this); xw.flush(); } catch (IOException e) { // this should not happen ever throw new ElementException(e.toString()); } return w.toString(); } } libexml-java-0.0.20080703.orig/e-xml/src/main/java/net/noderunner/exml/ElementNS.java0000644000175000017500000000440611014421656027614 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.exml; import java.util.List; /** * An XML element with namespace information. */ public class ElementNS extends Element { private String namespaceURI; private String prefix; private String localName; /** * Constructs an element from a {@link Namespace} and list of attributes, * either as open or closed. * Note: For performance reasons, the passed in List object is not * copied. * @param namespace Namespace of element; * fields from the this object are copied internally * @param attributes List of attributes, or null if no attributes * @param open If this tag is open or closed */ public ElementNS(Namespace namespace, List attr, boolean open) { super(namespace.getName(), attr, open); this.namespaceURI = namespace.getNamespaceURI(); this.prefix = namespace.getPrefix(); this.localName = namespace.getLocalName(); } /** * Sets the namespace of this Element. */ public void setNamespace(Namespace namespace) { setName(namespace.getName()); this.namespaceURI = namespace.getNamespaceURI(); this.prefix = namespace.getPrefix(); this.localName = namespace.getLocalName(); } /** * Returns the namespace URI of this Element. * By default, returns null. */ @Override public String getNamespaceURI() { return namespaceURI; } /** * Returns the prefix of this Element. */ @Override public String getPrefix() { return prefix; } /** * Returns the local name of this Element. */ @Override public String getLocalName() { return localName; } } ././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootlibexml-java-0.0.20080703.orig/e-xml/src/main/java/net/noderunner/exml/IllegalXmlParserStateException.javalibexml-java-0.0.20080703.orig/e-xml/src/main/java/net/noderunner/exml/IllegalXmlParserStateExceptio0000644000175000017500000000253510762067376032772 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.exml; /** * Unchecked exception used to indicate the use of the XML * library was incorrect. */ public class IllegalXmlParserStateException extends IllegalStateException { private static final long serialVersionUID = 8299996175459081780L; /** * Constructs a new IllegalXmlParserStateException with a message. * @param message explaination */ public IllegalXmlParserStateException(String message) { super(message); } /** * Constructs a new IllegalXmlParserStateException with no message. */ public IllegalXmlParserStateException() { super(); } } libexml-java-0.0.20080703.orig/e-xml/src/main/java/net/noderunner/exml/Notation.java0000644000175000017500000000246410762067376027575 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.exml; /** * This class holds an XML Notation. * * @see Dtd#addNotation * @see Dtd#getNotations */ public class Notation { private String publicID; private String systemID; /** * Constructs a Notation with all fields. */ public Notation(String publicID, String systemID) { this.publicID = publicID; this.systemID = systemID; } /** * Returns the required system ID. */ public String getSystemID() { return systemID; } /** * Returns the optional public ID. */ public String getPublicID() { return publicID; } } libexml-java-0.0.20080703.orig/e-xml/src/main/java/net/noderunner/exml/RuleStack.java0000644000175000017500000000336511014421656027662 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.exml; import java.util.NoSuchElementException; import net.noderunner.exml.ElementRule.ElementRuleState; /** * Element rule stack. * @author Elias Ross */ class RuleStack { private Stack stack = ArrayStack.create(); /** * Constructs a new RuleStack. */ public RuleStack() { } /** * Encounters a new element, creates a new rule state. * @param e element visited * @return * @throws ElementRuleException if encounter is invalid */ public ElementRuleState startElement() { ElementRuleState state = new ElementRuleState(); stack.push(state); return state; } /** * Encounters the end of an element. */ public void endElement() { stack.pop(); } /** * Returns the current element rule state. * @throws NoSuchElementException if no state is present */ public ElementRuleState state() { return stack.peek(); } } libexml-java-0.0.20080703.orig/e-xml/src/main/java/net/noderunner/exml/NullReader.java0000644000175000017500000000266310762067376030040 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.exml; import java.io.Reader; /** * A reader that returns EOF always. */ public final class NullReader extends Reader { static Reader r = new NullReader(); private NullReader() { } /** * Returns this sole instance. * @return a null reader */ public static Reader getInstance() { return r; } /** * Does nothing. */ public void close() { } /** * Returns EOF. */ public int read() { return -1; } /** * Returns EOF. */ public int read(char[] cbuf) { return -1; } /** * Returns EOF. */ public int read(char[] cbuf, int off, int len) { return -1; } /** * Does nothing, returns 0. */ public long skip(long n) { return 0; } } libexml-java-0.0.20080703.orig/e-xml/src/main/java/net/noderunner/exml/UriMap.java0000644000175000017500000000465711014421656027167 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.exml; import java.util.HashMap; import java.util.Map; /** * Maps String prefixes to URI's, and * maintains the current default namespace in use. */ public class UriMap { private Map map; // private String defaultNamespace; /** * Constructs a URI map with no contents. */ public UriMap() { map = new HashMap(); } /** * Constructs a URI map wrapping a Map. */ public UriMap(Map map) { if (map == null) throw new IllegalArgumentException("null map"); this.map = map; } /* * Returns either the default namespace URI, or null if * unspecified. public String getDefaultNamespace() { return defaultNamespace; } */ /* * Sets either the default namespace URI, may be null if * unspecified. public void setDefaultNamespace(String defaultNamespace) { this.defaultNamespace = defaultNamespace; } */ /** * Returns the appropriate URI for the given prefix. * If the prefix is not found, returns the default namespace. */ public String get(String prefix) { if (prefix == null) throw new IllegalArgumentException("null prefix"); if (map == null) return null; return map.get(prefix); } /** * Sets the mapping of a prefix to a URI. */ public void put(String prefix, String uri) { if (prefix == null) throw new IllegalArgumentException("null prefix"); if (map == null) map = new HashMap(); map.put(prefix, uri); } /** * Clears all URI mappings. */ public void clear() { if (map == null) return; map.clear(); } /** * Returns a string representation of this URIMap. */ @Override public String toString() { return "URIMap map=" + map; } } libexml-java-0.0.20080703.orig/e-xml/src/main/java/net/noderunner/exml/XmlWriter.java0000644000175000017500000002225311014421656027717 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.exml; import java.io.IOException; import java.io.Writer; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; /** * Writes and serializes XML data to a character Writer. * It is a good idea to call flush or close when * finished, otherwise, any buffered data may not be sent. * Buffering the underlying output stream is recommended. */ public class XmlWriter { /** * This stack should store only String instances. */ ArrayStack writeStack; /** * Output writer. */ Writer writer; /** * Constructs a new XmlWriter around a Writer instance. */ public XmlWriter(Writer writer) { this.writer = writer; this.writeStack = ArrayStack.create(); } /** * Sets the writer to output with. * @param writer writer to wrap */ public void setWriter(Writer writer) { this.writer = writer; writeStack.clear(); } /** * Writes the <?xml ?> header. * @param encoding for outputting the corrent Xml header. */ public void writeHeader(String encoding) throws IOException { writer.write("\n"); } /** * Writes a String as a start tag, like this: * <element>. * @param elem name of element */ public void startElement(String elem) throws IOException { writer.write('<'); writer.write(elem); writeStack.add(elem); writer.write('>'); } /** * Writes a String as a start tag, and writes a * series of attribute names and values. * Example usage: *
    	 * w.startElement("elem", new String[] { "a", "b", "c", "d"});
    	 * 
    * Output result: *
    	 * <elem a="b" c="d">
    	 * 
    	 * @param elem name of element
    	 * @param attrs list of attribute name-value pairs,
    	 * which must be even in length
    	 * @throws ArrayIndexOutOfBoundsException if attr array
    	 * length was not even
    	 */
    	public void startElement(String elem, String attrs[]) 
    		throws IOException
    	{
    		startElement(elem, attrs, true);
    	}
    
    	private void startElement(String elem, String attrs[], boolean open) 
    		throws IOException
    	{
    		writer.write('<');
    		writer.write(elem);
    		for (int i = 0; i < attrs.length; i += 2) {
    			writer.write(' ');
    			writer.write(attrs[i]);
    			writer.write("=\"");
    			escape(attrs[i + 1], writer);
    			writer.write('"');
    		}
    		if (open) {
    			writeStack.add(elem);
    			writer.write('>');
    		} else {
    			writer.write("/>");
    		}
    	}
    
    	/**
    	 * Writes an Element object as a start tag, including its attributes.
    	 * This works for empty elements as well.  Once written, it can be
    	 * closed with
    	 * endElement or endAll.  Do not call
    	 * try to call endElement for closed elements.
    	 * Output appears like this: <element
    	 * attribute1='value'>.
    	 *
    	 * @see #endElement
    	 */
    	public void startElement(Element elem) 
    		throws IOException
    	{
    		writer.write('<');
    		writer.write(elem.getName());
    		List l = elem.getAttributes();
    		if (l != null) {
    			Iterator i = l.iterator();
    			while (i.hasNext()) {
    				writer.write(' ');
    				writer.write(i.next().toString());
    			}
    		}
    		if (elem.isOpen()) {
    			writer.write('>');
    			writeStack.add(elem.getName());
    		}
    		else {
    			writer.write("/>");
    		}
    	}
    
    	/**
    	 * Writes an Element object completely.
    	 * Example: <element x='value'> stuff
    	 * </element>.
    	 */
    	public void element(Element e) 
    		throws IOException
    	{
    		startElement(e);
    		List l = e.getChildNodes();
    		if (l != null) {
    			int size = l.size();
    			for (int i = 0; i < size; i++) {
    				Node n = l.get(i);
    				switch (n.getNodeType()) {
    					case Node.ELEMENT_NODE:
    						element((Element)n);
    					break;
    					case Node.TEXT_NODE: 
    						writeCData((CharacterData)n);
    					break;
    					default: 
    						write(n.toString());
    					break;
    
    				}
    			}
    		}
    		if (e.isOpen())
    			endElement();
    	}
    
    	/**
    	 * Writes an end tag, matching the tag written at this tree depth.
    	 * @throws NoSuchElementException if the written tree depth is already at zero
    	 */
    	public void endElement() 
    		throws IOException
    	{
    		writer.write("');
    		// writer.flush();
    	}
    
    	/**
    	 * Closes all remaining open tags beyond a certain depth.  Does nothing if
    	 * depth of the tree is lower than depth.  A value of
    	 * 0 closes the entire document.
    	 *
    	 * @throws IllegalArgumentException if negative depth is given
    	 * @param depth positive tree depth
    	 * @see XmlParser#getDepth()
    	 */
    	public void up(int depth)
    		throws IOException
    	{
    		if (depth < 0)
    			throw new IllegalArgumentException("Depth must be positive: " + depth);
    		while (writeStack.size() > depth)
    			endElement();
    	}
    
    	/**
    	 * Returns the depth of the tree currently written.  Returns zero if no
    	 * open elements have been written.  This can be used in conjunction with
    	 * the up function.
    	 * @see #up
    	 */
    	public int getDepth()
    	{
    		return writeStack.size();
    	}
    
    	/**
    	 * Writes a string as an empty element tag.
    	 * Example: <element/> .
    	 */
    	public void emptyElement(String elem) 
    		throws IOException
    	{
    		writer.write("<");
    		writer.write(elem);
    		writer.write("/>");
    	}
    
    	/**
    	 * Writes a string as an empty element tag.
    	 * Example: <element/> .
    	 *
    	 * @see #startElement
    	 */
    	public void emptyElement(String elem, String attrs[]) 
    		throws IOException
    	{
    		startElement(elem, attrs, false);
    	}
    
    	/**
    	 * Writes this element as an empty tag, without its
    	 * children or contents.
    	 * Calls {@link startElement(Element)}, since it also writes empty elements.
    	 * If this element is considered open, a matching close tag is appended
    	 * automatically, so the depth of the XML tree is not affected.
    	 * @see #startElement
    	 * @see Element#isOpen
    	 */
    	public void emptyElement(Element elem) 
    		throws IOException
    	{
    		startElement(elem);
    		if (elem.isOpen())
    			endElement();
    	}
    
    	/**
    	 * Writes a CDSection.  Do not pass in a string with the
    	 * text ']]', since it is not allowed, this function does no
    	 * checking for that.
    	 */
    	public void writeCDSection(String text) 
    		throws IOException
    	{
    		writer.write(XmlTags.CDATA_BEGIN);
    		writer.write(text);
    		writer.write(XmlTags.CDATA_END);
    	}
    
    	/**
    	 * Escapes a string, appends the results to out.
    	 */
    	static void escape(String in, Writer out)
    		throws IOException
    	{
    		int l = in.length();
    		for (int i = 0; i < l; i++) {
    			char c = in.charAt(i);
    			switch (c) {
    			case '\'' :
    				out.write("'");
    				break;
    			case '"' :
    				out.write(""");
    				break;
    			case '<' :
    				out.write("<");
    				break;
    			case '>' :
    				out.write(">");
    				break;
    			case '&' :
    				out.write("&");
    				break;
    			default:
    				out.write(c);
    			}
    		}
    	}
    
    	/**
    	 * Escapes a string, appends the results to out.
    	 */
    	static void escape(StringBuffer in, Writer out)
    		throws IOException
    	{
    		int l = in.length();
    		for (int i = 0; i < l; i++) {
    			char c = in.charAt(i);
    			switch (c) {
    			case '\'' :
    				out.write("'");
    				break;
    			case '"' :
    				out.write(""");
    				break;
    			case '<' :
    				out.write("<");
    				break;
    			case '>' :
    				out.write(">");
    				break;
    			case '&' :
    				out.write("&");
    				break;
    			default:
    				out.write(c);
    			}
    		}
    	}
    
    	/**
    	 * Writes character data, transforms < > & " ' symbols.
    	 */
    	public void writeCData(CharacterData cd) 
    		throws IOException
    	{
    		cd.getWriter().writeEscapedTo(writer);
    	}
    
    	/**
    	 * Writes character data, transforms < > & " ' symbols.
    	 */
    	public void writeCData(String text) 
    		throws IOException
    	{
    		escape(text, writer);
    	}
    	
    	/**
    	 * Writes character data, does no entity transforms.
    	 */
    	public void write(char[] text)
    		throws IOException
    	{
    		writer.write(text);
    	}
    
    	/**
    	 * Writes character data, does no entity transforms.
    	 */
    	public void write(char[] text, int off, int len) 
    		throws IOException
    	{
    		writer.write(text, off, len);
    	}
    
    	/**
    	 * Writes character data, does no entity transforms.
    	 */
    	public void write(String text) 
    		throws IOException
    	{
    		writer.write(text);
    	}
    
    	/**
    	 * Flushes the underlying output stream.
    	 */
    	public void flush() 
    		throws IOException
    	{
    		writer.flush();
    	}
    
    	/**
    	 * Closes the underlying output stream.
    	 */
    	public void close() 
    		throws IOException
    	{
    		writer.close();
    	}
    }
    libexml-java-0.0.20080703.orig/e-xml/src/net/0000755000175000017500000000000011111351372020115 5ustar  twernertwernerlibexml-java-0.0.20080703.orig/e-xml/src/net/noderunner/0000755000175000017500000000000011111351372022274 5ustar  twernertwernerlibexml-java-0.0.20080703.orig/e-xml/.classpath0000644000175000017500000000102111014421656020522 0ustar  twernertwerner
    
    	
    	
    	
    	
    	
    	
    
    libexml-java-0.0.20080703.orig/e-xml/LICENCE.txt0000644000175000017500000005750507477076020020375 0ustar  twernertwerner		  GNU LESSER GENERAL PUBLIC LICENSE
    		       Version 2.1, February 1999
    
     Copyright (C) 1991, 1999 Free Software Foundation, Inc.
         59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
     Everyone is permitted to copy and distribute verbatim copies
     of this license document, but changing it is not allowed.
    
    [This is the first released version of the Lesser GPL.  It also counts
     as the successor of the GNU Library Public License, version 2, hence
     the version number 2.1.]
    
    			    Preamble
    
      The licenses for most software are designed to take away your
    freedom to share and change it.  By contrast, the GNU General Public
    Licenses are intended to guarantee your freedom to share and change
    free software--to make sure the software is free for all its users.
    
      This license, the Lesser General Public License, applies to some
    specially designated software packages--typically libraries--of the
    Free Software Foundation and other authors who decide to use it.  You
    can use it too, but we suggest you first think carefully about whether
    this license or the ordinary General Public License is the better
    strategy to use in any particular case, based on the explanations below.
    
      When we speak of free software, we are referring to freedom of use,
    not price.  Our General Public Licenses are designed to make sure that
    you have the freedom to distribute copies of free software (and charge
    for this service if you wish); that you receive source code or can get
    it if you want it; that you can change the software and use pieces of
    it in new free programs; and that you are informed that you can do
    these things.
    
      To protect your rights, we need to make restrictions that forbid
    distributors to deny you these rights or to ask you to surrender these
    rights.  These restrictions translate to certain responsibilities for
    you if you distribute copies of the library or if you modify it.
    
      For example, if you distribute copies of the library, whether gratis
    or for a fee, you must give the recipients all the rights that we gave
    you.  You must make sure that they, too, receive or can get the source
    code.  If you link other code with the library, you must provide
    complete object files to the recipients, so that they can relink them
    with the library after making changes to the library and recompiling
    it.  And you must show them these terms so they know their rights.
    
      We protect your rights with a two-step method: (1) we copyright the
    library, and (2) we offer you this license, which gives you legal
    permission to copy, distribute and/or modify the library.
    
      To protect each distributor, we want to make it very clear that
    there is no warranty for the free library.  Also, if the library is
    modified by someone else and passed on, the recipients should know
    that what they have is not the original version, so that the original
    author's reputation will not be affected by problems that might be
    introduced by others.
    
      Finally, software patents pose a constant threat to the existence of
    any free program.  We wish to make sure that a company cannot
    effectively restrict the users of a free program by obtaining a
    restrictive license from a patent holder.  Therefore, we insist that
    any patent license obtained for a version of the library must be
    consistent with the full freedom of use specified in this license.
    
      Most GNU software, including some libraries, is covered by the
    ordinary GNU General Public License.  This license, the GNU Lesser
    General Public License, applies to certain designated libraries, and
    is quite different from the ordinary General Public License.  We use
    this license for certain libraries in order to permit linking those
    libraries into non-free programs.
    
      When a program is linked with a library, whether statically or using
    a shared library, the combination of the two is legally speaking a
    combined work, a derivative of the original library.  The ordinary
    General Public License therefore permits such linking only if the
    entire combination fits its criteria of freedom.  The Lesser General
    Public License permits more lax criteria for linking other code with
    the library.
    
      We call this license the "Lesser" General Public License because it
    does Less to protect the user's freedom than the ordinary General
    Public License.  It also provides other free software developers Less
    of an advantage over competing non-free programs.  These disadvantages
    are the reason we use the ordinary General Public License for many
    libraries.  However, the Lesser license provides advantages in certain
    special circumstances.
    
      For example, on rare occasions, there may be a special need to
    encourage the widest possible use of a certain library, so that it becomes
    a de-facto standard.  To achieve this, non-free programs must be
    allowed to use the library.  A more frequent case is that a free
    library does the same job as widely used non-free libraries.  In this
    case, there is little to gain by limiting the free library to free
    software only, so we use the Lesser General Public License.
    
      In other cases, permission to use a particular library in non-free
    programs enables a greater number of people to use a large body of
    free software.  For example, permission to use the GNU C Library in
    non-free programs enables many more people to use the whole GNU
    operating system, as well as its variant, the GNU/Linux operating
    system.
    
      Although the Lesser General Public License is Less protective of the
    users' freedom, it does ensure that the user of a program that is
    linked with the Library has the freedom and the wherewithal to run
    that program using a modified version of the Library.
    
      The precise terms and conditions for copying, distribution and
    modification follow.  Pay close attention to the difference between a
    "work based on the library" and a "work that uses the library".  The
    former contains code derived from the library, whereas the latter must
    be combined with the library in order to run.
    
    		  GNU LESSER GENERAL PUBLIC LICENSE
       TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
    
      0. This License Agreement applies to any software library or other
    program which contains a notice placed by the copyright holder or
    other authorized party saying it may be distributed under the terms of
    this Lesser General Public License (also called "this License").
    Each licensee is addressed as "you".
    
      A "library" means a collection of software functions and/or data
    prepared so as to be conveniently linked with application programs
    (which use some of those functions and data) to form executables.
    
      The "Library", below, refers to any such software library or work
    which has been distributed under these terms.  A "work based on the
    Library" means either the Library or any derivative work under
    copyright law: that is to say, a work containing the Library or a
    portion of it, either verbatim or with modifications and/or translated
    straightforwardly into another language.  (Hereinafter, translation is
    included without limitation in the term "modification".)
    
      "Source code" for a work means the preferred form of the work for
    making modifications to it.  For a library, complete source code means
    all the source code for all modules it contains, plus any associated
    interface definition files, plus the scripts used to control compilation
    and installation of the library.
    
      Activities other than copying, distribution and modification are not
    covered by this License; they are outside its scope.  The act of
    running a program using the Library is not restricted, and output from
    such a program is covered only if its contents constitute a work based
    on the Library (independent of the use of the Library in a tool for
    writing it).  Whether that is true depends on what the Library does
    and what the program that uses the Library does.
      
      1. You may copy and distribute verbatim copies of the Library's
    complete source code as you receive it, in any medium, provided that
    you conspicuously and appropriately publish on each copy an
    appropriate copyright notice and disclaimer of warranty; keep intact
    all the notices that refer to this License and to the absence of any
    warranty; and distribute a copy of this License along with the
    Library.
    
      You may charge a fee for the physical act of transferring a copy,
    and you may at your option offer warranty protection in exchange for a
    fee.
    
      2. You may modify your copy or copies of the Library or any portion
    of it, thus forming a work based on the Library, and copy and
    distribute such modifications or work under the terms of Section 1
    above, provided that you also meet all of these conditions:
    
        a) The modified work must itself be a software library.
    
        b) You must cause the files modified to carry prominent notices
        stating that you changed the files and the date of any change.
    
        c) You must cause the whole of the work to be licensed at no
        charge to all third parties under the terms of this License.
    
        d) If a facility in the modified Library refers to a function or a
        table of data to be supplied by an application program that uses
        the facility, other than as an argument passed when the facility
        is invoked, then you must make a good faith effort to ensure that,
        in the event an application does not supply such function or
        table, the facility still operates, and performs whatever part of
        its purpose remains meaningful.
    
        (For example, a function in a library to compute square roots has
        a purpose that is entirely well-defined independent of the
        application.  Therefore, Subsection 2d requires that any
        application-supplied function or table used by this function must
        be optional: if the application does not supply it, the square
        root function must still compute square roots.)
    
    These requirements apply to the modified work as a whole.  If
    identifiable sections of that work are not derived from the Library,
    and can be reasonably considered independent and separate works in
    themselves, then this License, and its terms, do not apply to those
    sections when you distribute them as separate works.  But when you
    distribute the same sections as part of a whole which is a work based
    on the Library, the distribution of the whole must be on the terms of
    this License, whose permissions for other licensees extend to the
    entire whole, and thus to each and every part regardless of who wrote
    it.
    
    Thus, it is not the intent of this section to claim rights or contest
    your rights to work written entirely by you; rather, the intent is to
    exercise the right to control the distribution of derivative or
    collective works based on the Library.
    
    In addition, mere aggregation of another work not based on the Library
    with the Library (or with a work based on the Library) on a volume of
    a storage or distribution medium does not bring the other work under
    the scope of this License.
    
      3. You may opt to apply the terms of the ordinary GNU General Public
    License instead of this License to a given copy of the Library.  To do
    this, you must alter all the notices that refer to this License, so
    that they refer to the ordinary GNU General Public License, version 2,
    instead of to this License.  (If a newer version than version 2 of the
    ordinary GNU General Public License has appeared, then you can specify
    that version instead if you wish.)  Do not make any other change in
    these notices.
    
      Once this change is made in a given copy, it is irreversible for
    that copy, so the ordinary GNU General Public License applies to all
    subsequent copies and derivative works made from that copy.
    
      This option is useful when you wish to copy part of the code of
    the Library into a program that is not a library.
    
      4. You may copy and distribute the Library (or a portion or
    derivative of it, under Section 2) in object code or executable form
    under the terms of Sections 1 and 2 above provided that you accompany
    it with the complete corresponding machine-readable source code, which
    must be distributed under the terms of Sections 1 and 2 above on a
    medium customarily used for software interchange.
    
      If distribution of object code is made by offering access to copy
    from a designated place, then offering equivalent access to copy the
    source code from the same place satisfies the requirement to
    distribute the source code, even though third parties are not
    compelled to copy the source along with the object code.
    
      5. A program that contains no derivative of any portion of the
    Library, but is designed to work with the Library by being compiled or
    linked with it, is called a "work that uses the Library".  Such a
    work, in isolation, is not a derivative work of the Library, and
    therefore falls outside the scope of this License.
    
      However, linking a "work that uses the Library" with the Library
    creates an executable that is a derivative of the Library (because it
    contains portions of the Library), rather than a "work that uses the
    library".  The executable is therefore covered by this License.
    Section 6 states terms for distribution of such executables.
    
      When a "work that uses the Library" uses material from a header file
    that is part of the Library, the object code for the work may be a
    derivative work of the Library even though the source code is not.
    Whether this is true is especially significant if the work can be
    linked without the Library, or if the work is itself a library.  The
    threshold for this to be true is not precisely defined by law.
    
      If such an object file uses only numerical parameters, data
    structure layouts and accessors, and small macros and small inline
    functions (ten lines or less in length), then the use of the object
    file is unrestricted, regardless of whether it is legally a derivative
    work.  (Executables containing this object code plus portions of the
    Library will still fall under Section 6.)
    
      Otherwise, if the work is a derivative of the Library, you may
    distribute the object code for the work under the terms of Section 6.
    Any executables containing that work also fall under Section 6,
    whether or not they are linked directly with the Library itself.
    
      6. As an exception to the Sections above, you may also combine or
    link a "work that uses the Library" with the Library to produce a
    work containing portions of the Library, and distribute that work
    under terms of your choice, provided that the terms permit
    modification of the work for the customer's own use and reverse
    engineering for debugging such modifications.
    
      You must give prominent notice with each copy of the work that the
    Library is used in it and that the Library and its use are covered by
    this License.  You must supply a copy of this License.  If the work
    during execution displays copyright notices, you must include the
    copyright notice for the Library among them, as well as a reference
    directing the user to the copy of this License.  Also, you must do one
    of these things:
    
        a) Accompany the work with the complete corresponding
        machine-readable source code for the Library including whatever
        changes were used in the work (which must be distributed under
        Sections 1 and 2 above); and, if the work is an executable linked
        with the Library, with the complete machine-readable "work that
        uses the Library", as object code and/or source code, so that the
        user can modify the Library and then relink to produce a modified
        executable containing the modified Library.  (It is understood
        that the user who changes the contents of definitions files in the
        Library will not necessarily be able to recompile the application
        to use the modified definitions.)
    
        b) Use a suitable shared library mechanism for linking with the
        Library.  A suitable mechanism is one that (1) uses at run time a
        copy of the library already present on the user's computer system,
        rather than copying library functions into the executable, and (2)
        will operate properly with a modified version of the library, if
        the user installs one, as long as the modified version is
        interface-compatible with the version that the work was made with.
    
        c) Accompany the work with a written offer, valid for at
        least three years, to give the same user the materials
        specified in Subsection 6a, above, for a charge no more
        than the cost of performing this distribution.
    
        d) If distribution of the work is made by offering access to copy
        from a designated place, offer equivalent access to copy the above
        specified materials from the same place.
    
        e) Verify that the user has already received a copy of these
        materials or that you have already sent this user a copy.
    
      For an executable, the required form of the "work that uses the
    Library" must include any data and utility programs needed for
    reproducing the executable from it.  However, as a special exception,
    the materials to be distributed need not include anything that is
    normally distributed (in either source or binary form) with the major
    components (compiler, kernel, and so on) of the operating system on
    which the executable runs, unless that component itself accompanies
    the executable.
    
      It may happen that this requirement contradicts the license
    restrictions of other proprietary libraries that do not normally
    accompany the operating system.  Such a contradiction means you cannot
    use both them and the Library together in an executable that you
    distribute.
    
      7. You may place library facilities that are a work based on the
    Library side-by-side in a single library together with other library
    facilities not covered by this License, and distribute such a combined
    library, provided that the separate distribution of the work based on
    the Library and of the other library facilities is otherwise
    permitted, and provided that you do these two things:
    
        a) Accompany the combined library with a copy of the same work
        based on the Library, uncombined with any other library
        facilities.  This must be distributed under the terms of the
        Sections above.
    
        b) Give prominent notice with the combined library of the fact
        that part of it is a work based on the Library, and explaining
        where to find the accompanying uncombined form of the same work.
    
      8. You may not copy, modify, sublicense, link with, or distribute
    the Library except as expressly provided under this License.  Any
    attempt otherwise to copy, modify, sublicense, link with, or
    distribute the Library is void, and will automatically terminate your
    rights under this License.  However, parties who have received copies,
    or rights, from you under this License will not have their licenses
    terminated so long as such parties remain in full compliance.
    
      9. You are not required to accept this License, since you have not
    signed it.  However, nothing else grants you permission to modify or
    distribute the Library or its derivative works.  These actions are
    prohibited by law if you do not accept this License.  Therefore, by
    modifying or distributing the Library (or any work based on the
    Library), you indicate your acceptance of this License to do so, and
    all its terms and conditions for copying, distributing or modifying
    the Library or works based on it.
    
      10. Each time you redistribute the Library (or any work based on the
    Library), the recipient automatically receives a license from the
    original licensor to copy, distribute, link with or modify the Library
    subject to these terms and conditions.  You may not impose any further
    restrictions on the recipients' exercise of the rights granted herein.
    You are not responsible for enforcing compliance by third parties with
    this License.
    
      11. If, as a consequence of a court judgment or allegation of patent
    infringement or for any other reason (not limited to patent issues),
    conditions are imposed on you (whether by court order, agreement or
    otherwise) that contradict the conditions of this License, they do not
    excuse you from the conditions of this License.  If you cannot
    distribute so as to satisfy simultaneously your obligations under this
    License and any other pertinent obligations, then as a consequence you
    may not distribute the Library at all.  For example, if a patent
    license would not permit royalty-free redistribution of the Library by
    all those who receive copies directly or indirectly through you, then
    the only way you could satisfy both it and this License would be to
    refrain entirely from distribution of the Library.
    
    If any portion of this section is held invalid or unenforceable under any
    particular circumstance, the balance of the section is intended to apply,
    and the section as a whole is intended to apply in other circumstances.
    
    It is not the purpose of this section to induce you to infringe any
    patents or other property right claims or to contest validity of any
    such claims; this section has the sole purpose of protecting the
    integrity of the free software distribution system which is
    implemented by public license practices.  Many people have made
    generous contributions to the wide range of software distributed
    through that system in reliance on consistent application of that
    system; it is up to the author/donor to decide if he or she is willing
    to distribute software through any other system and a licensee cannot
    impose that choice.
    
    This section is intended to make thoroughly clear what is believed to
    be a consequence of the rest of this License.
    
      12. If the distribution and/or use of the Library is restricted in
    certain countries either by patents or by copyrighted interfaces, the
    original copyright holder who places the Library under this License may add
    an explicit geographical distribution limitation excluding those countries,
    so that distribution is permitted only in or among countries not thus
    excluded.  In such case, this License incorporates the limitation as if
    written in the body of this License.
    
      13. The Free Software Foundation may publish revised and/or new
    versions of the Lesser General Public License from time to time.
    Such new versions will be similar in spirit to the present version,
    but may differ in detail to address new problems or concerns.
    
    Each version is given a distinguishing version number.  If the Library
    specifies a version number of this License which applies to it and
    "any later version", you have the option of following the terms and
    conditions either of that version or of any later version published by
    the Free Software Foundation.  If the Library does not specify a
    license version number, you may choose any version ever published by
    the Free Software Foundation.
    
      14. If you wish to incorporate parts of the Library into other free
    programs whose distribution conditions are incompatible with these,
    write to the author to ask for permission.  For software which is
    copyrighted by the Free Software Foundation, write to the Free
    Software Foundation; we sometimes make exceptions for this.  Our
    decision will be guided by the two goals of preserving the free status
    of all derivatives of our free software and of promoting the sharing
    and reuse of software generally.
    
    			    NO WARRANTY
    
      15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
    WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
    EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
    OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
    KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
    IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
    PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
    LIBRARY IS WITH YOU.  SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
    THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
    
      16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
    WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
    AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
    FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
    CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
    LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
    RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
    FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
    SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
    DAMAGES.
    
    		     END OF TERMS AND CONDITIONS
    libexml-java-0.0.20080703.orig/e-xml/TODO.txt0000644000175000017500000000042607560272057020067 0ustar  twernertwerner
    * Better XmlReader interface (allow the user to supply his own XmlReader)
    * Full namespace support in document validation
    * Attribute canonical whitespace
    * Support string pooling for character data segments
    * Check for invalid character ranges (note: XML 1.1 changes these) 
    
    libexml-java-0.0.20080703.orig/e-xml/.project0000644000175000017500000000105711014421656020217 0ustar  twernertwerner
    
    	e-xml
    	
    	
    	
    	
    		
    			org.eclipse.jdt.core.javabuilder
    			
    			
    		
    		
    			org.maven.ide.eclipse.maven2Builder
    			
    			
    		
    	
    	
    		org.eclipse.jdt.core.javanature
    		org.maven.ide.eclipse.maven2Nature
    	
    
    libexml-java-0.0.20080703.orig/e-xml/HEADER.txt0000644000175000017500000000134707522337515020254 0ustar  twernertwerner/* 
     * E-XML Library:  For XML, XML-RPC, HTTP, and related.
     * Copyright (C) 2002  Elias Ross
     * 
     * genman@maison-otaku.net
     * http://maison-otaku.net/~genman
     * 
     * 470 2nd Ave S #313
     * Kirkland WA 98033
     *
     * This library is free software; you can redistribute it and/or
     * modify it under the terms of the GNU Lesser General Public
     * License as published by the Free Software Foundation; either
     * version 2.1 of the License, or (at your option) any later version.
     *
     * This library is distributed in the hope that it will be useful,
     * but WITHOUT ANY WARRANTY; without even the implied warranty of
     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
     * Lesser General Public License for more details.
     * 
     * $Id$
     */
    libexml-java-0.0.20080703.orig/e-xml/README.txt0000644000175000017500000000510307522337515020253 0ustar  twernertwerner
    	      E-XML Library:  For XML, XML-RPC, HTTP, and related.
    			 Copyright (C) 2002  Elias Ross
    
    genman@maison-otaku.net
    http://maison-otaku.net/~genman
    
    
    				  WHAT IS IT?
    
    This library is a collection of tools for parsing XML.  For better or worse,
    DOM and SAX are fairly heavy-weight and cumbersome parsing tools, which have
    lead others to create libraries such as JDOM and KXML (Enhydra).  For most
    of you, the Xerces library will be just fine, and I suggest you stick with
    that if performance is not a big problem.
    
    
    			       PARSE PERFORMANCE
    
    XML parsing is pretty damn inefficient, at least when you're parsing
    hundreds of XML messages a second.  Take a look at XMLSParser.  It
    is a XML pull-parser (look that up on Google) which makes it very
    cheap in terms of object creation overhead.
    
    Most of the pull-parsers don't support String pools or allow for
    re-using existing objects.  Most small-footprint parsers have lousy
    performance, often much worse than Xerces SAX and DOM.
    
    If you test this library's performance against Xerces DOM, it's comparable 
    (perhaps a little faster) for reading a whole document.
    
    For the ultimate in parse speed, use XmlSParser.
    
    
    				 STREAMING XML
    
    Another problem is handling streaming protocol data, which can't be
    gracefully done with SAX, and cannot be done with any DOM parsers.
    An XML pull-parser makes it fairly simple to write efficient protocol
    handling routines.  However, the XML pull-parsers I've seen are fairly
    cumbersome as well, maybe because they were designed for low-memory
    devices.
    
    The XmlParser class lets you parse streaming data in a straight-forward
    manner.  XmlSParser is a little more complicated to use, and does not
    support DTD validation.
    
    
    				    XML-RPC
    
    I include an XML-RPC implementation which streams XML data over HTTP.
    It doesn't do any fancy object marshalling or demarshalling, but you can
    follow my example package and implement your own streaming conversion routines.
    
    
    			  RELATED TOOLS AND LIBRARIES
    
    The java.net.URLConnection library is not very good at sending streaming data,
    so I had to write my own HTTP library.  It's not exactly user-friendly, but it
    is better than any other library I've seen so far.  You will have to write
    your own "smart" HttpClient if you want to do more than what I wrote there.
    
    
    			   EXAMPLES AND DOCUMENTATION
    
    First, create the Java-Docs.  Take a look at the "src-test" directory, which
    demonstrates every method in the library.  Since this is open-source, you
    of course have access to the source code.  Please send me e-mail if you
    have a suggestion.
    
    I will eventually add in example programs later.
    
    libexml-java-0.0.20080703.orig/e-xml/pom.xml0000644000175000017500000000070110670424757020074 0ustar  twernertwerner
      4.0.0
      net.noderunner
      exml
      jar
      1.0
      e-xml XML parser
      http://e-xml.sourceforge.net
      
        
          junit
          junit
          3.8.1
          test
        
      
    
    libexml-java-0.0.20080703.orig/e-xml/.cvsignore0000644000175000017500000000000607514617561020555 0ustar  twernertwernerbuild
    libexml-java-0.0.20080703.orig/xmlrpc/0000755000175000017500000000000011111351376017027 5ustar  twernertwernerlibexml-java-0.0.20080703.orig/xmlrpc/src/0000755000175000017500000000000011111351372017612 5ustar  twernertwernerlibexml-java-0.0.20080703.orig/xmlrpc/src/test/0000755000175000017500000000000011111351372020571 5ustar  twernertwernerlibexml-java-0.0.20080703.orig/xmlrpc/src/test/java/0000755000175000017500000000000011111351372021512 5ustar  twernertwernerlibexml-java-0.0.20080703.orig/xmlrpc/src/test/java/net/0000755000175000017500000000000011111351372022300 5ustar  twernertwernerlibexml-java-0.0.20080703.orig/xmlrpc/src/test/java/net/noderunner/0000755000175000017500000000000011111351372024457 5ustar  twernertwernerlibexml-java-0.0.20080703.orig/xmlrpc/src/test/java/net/noderunner/xmlrpc/0000755000175000017500000000000011111351372025764 5ustar  twernertwernerlibexml-java-0.0.20080703.orig/xmlrpc/src/test/java/net/noderunner/xmlrpc/example/0000755000175000017500000000000011111351372027417 5ustar  twernertwerner././@LongLink0000000000000000000000000000015100000000000011562 Lustar  rootrootlibexml-java-0.0.20080703.orig/xmlrpc/src/test/java/net/noderunner/xmlrpc/example/XmlRpcAdapterTest.javalibexml-java-0.0.20080703.orig/xmlrpc/src/test/java/net/noderunner/xmlrpc/example/XmlRpcAdapterTest.0000644000175000017500000000456510762067376033023 0ustar  twernertwerner/* 
     * E-XML Library:  For XML, XML-RPC, HTTP, and related.
     * Copyright (C) 2002-2008  Elias Ross
     * 
     * genman@noderunner.net
     * http://noderunner.net/~genman
     * 
     * 1025 NE 73RD ST
     * SEATTLE WA 98115
     * USA
     *
     * This library is free software; you can redistribute it and/or
     * modify it under the terms of the GNU Lesser General Public
     * License as published by the Free Software Foundation; either
     * version 2.1 of the License, or (at your option) any later version.
     *
     * This library is distributed in the hope that it will be useful,
     * but WITHOUT ANY WARRANTY; without even the implied warranty of
     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
     * Lesser General Public License for more details.
     * 
     * $Id$
     */
    
    package net.noderunner.xmlrpc.example;
    
    import java.io.StringReader;
    import java.io.StringWriter;
    import java.util.Vector;
    
    import net.noderunner.xmlrpc.ParamIterator;
    import net.noderunner.xmlrpc.XmlRpcReader;
    import net.noderunner.xmlrpc.XmlRpcReaderImpl;
    import net.noderunner.xmlrpc.XmlRpcWriter;
    import net.noderunner.xmlrpc.XmlRpcWriterImpl;
    
    /**
     * This class uses tests the XmlRpcAdapter classes for proper behavior.
     *
     * @author Elias Ross
     * @version 1.0
     */
    public class XmlRpcAdapterTest
    	extends junit.framework.TestCase
    {
    
    	public XmlRpcAdapterTest(String name) {
    		super(name);
    	}
    
    	public static void main(String[] args) {
    		junit.textui.TestRunner.run(XmlRpcAdapterTest.class);
    	}
    
    	public static IteratorAdapter makeIA() {
    		Vector v = new Vector();
    		v.add(new SubscriberImpl("name", "password"));
    		v.add(new SubscriberImpl("name2", "password2"));
    		v.add(new SubscriberSearchImpl("smith"));
    		v.add(new ProvResult("failed to add", 
    			new SubscriberImpl("bob", "1234")));
    		return new IteratorAdapter(v.iterator());
    	}
    
    	public void testInputOutput() 
    		throws Exception
    	{
    		StringWriter sw = new StringWriter();
    		XmlRpcWriter xrw = new XmlRpcWriterImpl(sw);
    		xrw.writeResponse(new XmlRpcOutputAdapter(makeIA()));
    	
    		// compare out to input 
    		StringReader sr = new StringReader(sw.getBuffer().toString());
    		XmlRpcReader xrr = new XmlRpcReaderImpl(sr);
    		ParamIterator pi = xrr.readMethodResponse();
    		XmlRpcInputAdapter in = new XmlRpcInputAdapter(pi);
    
    		ProvIterator ia = makeIA();
    		while (in.hasNext()) {
    			ProvEntity entity1 = in.next();
    			ProvEntity entity2 = ia.next();
    			assertEquals(entity1.getClass(), entity2.getClass());
    		}
    	}
    }
    libexml-java-0.0.20080703.orig/xmlrpc/src/test/java/net/noderunner/xmlrpc/Base64Test.java0000644000175000017500000000325310762067376030541 0ustar  twernertwerner/* 
     * E-XML Library:  For XML, XML-RPC, HTTP, and related.
     * Copyright (C) 2002-2008  Elias Ross
     * 
     * genman@noderunner.net
     * http://noderunner.net/~genman
     * 
     * 1025 NE 73RD ST
     * SEATTLE WA 98115
     * USA
     *
     * This library is free software; you can redistribute it and/or
     * modify it under the terms of the GNU Lesser General Public
     * License as published by the Free Software Foundation; either
     * version 2.1 of the License, or (at your option) any later version.
     *
     * This library is distributed in the hope that it will be useful,
     * but WITHOUT ANY WARRANTY; without even the implied warranty of
     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
     * Lesser General Public License for more details.
     * 
     * $Id$
     */
    
    package net.noderunner.xmlrpc;
    
    /**
     * This class uses tests the Base64 class for proper behavior.
     *
     * @author Elias Ross
     * @version 1.0
     */
    public class Base64Test
    	extends junit.framework.TestCase
    {
    
    	public Base64Test(String name) {
    		super(name);
    	}
    
    	public static void main(String[] args) {
    		junit.textui.TestRunner.run(Base64Test.class);
    	}
    
    	public void test() 
    		throws Exception
    	{
    		assertTrue(Base64.getInstance() != null);
    
    		for (int size = 64; size < 75; size++) {
    			byte[] stuff = new byte[size];
    			java.util.Random r = new java.util.Random();
    			r.nextBytes(stuff);
    			String out = new String(Base64.getInstance().encode(stuff));
    			byte[] outb = Base64.getInstance().decode(out.toCharArray());
    			for (int i = 0; i < stuff.length; i++)
    				assertEquals(stuff[i], outb[i]);
    		}
    
    		try {
    			Base64.getInstance().decode("\t\t\t\t\t=".toCharArray());
    			fail("Should have failed decoding array");
    		} catch (Base64Exception be) {
    		}
    	}
    }
    libexml-java-0.0.20080703.orig/xmlrpc/src/test/java/net/noderunner/xmlrpc/ServletTest.java0000644000175000017500000001053110762067376031136 0ustar  twernertwerner/* 
     * E-XML Library:  For XML, XML-RPC, HTTP, and related.
     * Copyright (C) 2002-2008  Elias Ross
     * 
     * genman@noderunner.net
     * http://noderunner.net/~genman
     * 
     * 1025 NE 73RD ST
     * SEATTLE WA 98115
     * USA
     *
     * This library is free software; you can redistribute it and/or
     * modify it under the terms of the GNU Lesser General Public
     * License as published by the Free Software Foundation; either
     * version 2.1 of the License, or (at your option) any later version.
     *
     * This library is distributed in the hope that it will be useful,
     * but WITHOUT ANY WARRANTY; without even the implied warranty of
     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
     * Lesser General Public License for more details.
     * 
     * $Id$
     */
    
    package net.noderunner.xmlrpc;
    
    // Servlet-related
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.util.Vector;
    
    import javax.servlet.ServletConfig;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    /**
     * This class shows how a Servlet can be written to handle Xml-Rpc
     * requests.  Copy this source code into your own project and register
     * handlers.
     *
     * @author Elias Ross
     * @version 1.0
     */
    public class ServletTest
    	extends HttpServlet
    	implements XmlRpcHandler
    {
    
    	/**
    	 * 
    	 */
    	private static final long serialVersionUID = 972350369680613449L;
    	XmlRpcServer server;
    	
    	/**
    	 * Use this method to register handlers with the XmlRpcServer.
    	 */
    	public void init(ServletConfig config)
    		throws ServletException
    	{
    		server = new XmlRpcServerImpl();
    		server.addHandler("test", this);
    		super.init(config);
    	}
    
    	public static ParamIterator makeLongParamIterator(final int until) {
    		return new ParamIterator() {
    			int times = 0;
    			public Object next() 
    			{
    				times++;
    				if (times % 2 == 0)
    					return " AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA ";
    				else
    					return new Integer(1);
    			}
    			public boolean hasNext() {
    				return times < until;
    			}
    			public int getIteratorType() {
    				return PARAMS_ITERATOR;
    			}
    			public void close() {
    			}
    		};
    	}
    
    	/** 
    	 * This method adds numbers together, then returns a list of more
    	 * numbers to add, as an example.
    	 */
    	public ParamIterator execute(String method, ParamIterator params) 
    		throws XmlRpcException
    	{
    		int total = 0;
    		int last = 0;
    		Integer i;
    		Vector v = new Vector();
    		while (params.hasNext()) {
    			Object o = params.next();
    			if (o instanceof Integer) {
    				i = (Integer)o;
    				last = i.intValue();
    				total += i.intValue();
    			} 
    		}
    		v.add("Total of Integers was:  " + total);
    		return makeLongParamIterator(last);
    	}
    
    	/** This method shows the server is available. */
    	protected void doGet(HttpServletRequest req, HttpServletResponse resp) 
    		throws ServletException, IOException
    	{
    		PrintWriter writer = resp.getWriter();
    		writer.println("XmlRpcServer " + server);
    	}
    
    	/** This method calls the Xml-Rpc server. */
    	protected void doPost(HttpServletRequest req, HttpServletResponse resp) 
    		throws ServletException, IOException
    	{
    		/*
    		Enumeration enum = req.getHeaderNames();
    		while (enum.hasMoreElements()) {
    			String s = (String)enum.nextElement();
    			System.out.println(s + ": " + req.getHeader(s));
    		}
    		*/
    		try {
    			server.accept(req.getReader(), resp.getWriter());
    		} catch (XmlRpcException e) {
    			e.printStackTrace();
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    	}
    }
    libexml-java-0.0.20080703.orig/xmlrpc/src/test/java/net/noderunner/xmlrpc/XmlRpcTest.java0000644000175000017500000003675010762067376030732 0ustar  twernertwerner/* 
     * E-XML Library:  For XML, XML-RPC, HTTP, and related.
     * Copyright (C) 2002-2008  Elias Ross
     * 
     * genman@noderunner.net
     * http://noderunner.net/~genman
     * 
     * 1025 NE 73RD ST
     * SEATTLE WA 98115
     * USA
     *
     * This library is free software; you can redistribute it and/or
     * modify it under the terms of the GNU Lesser General Public
     * License as published by the Free Software Foundation; either
     * version 2.1 of the License, or (at your option) any later version.
     *
     * This library is distributed in the hope that it will be useful,
     * but WITHOUT ANY WARRANTY; without even the implied warranty of
     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
     * Lesser General Public License for more details.
     * 
     * $Id$
     */
    
    package net.noderunner.xmlrpc;
    
    import java.io.IOException;
    import java.io.Reader;
    import java.io.StringReader;
    import java.io.StringWriter;
    import java.util.Collection;
    import java.util.Date;
    import java.util.HashMap;
    import java.util.Vector;
    
    import net.noderunner.exml.Document;
    import net.noderunner.exml.NullWriter;
    import net.noderunner.exml.XmlException;
    import net.noderunner.exml.XmlReader;
    
    /**
     * This class is for unit testing.the Xml-Rpc classes.
     *
     * @see XmlRpcServer
     * @see XmlRpcClient
     * @author Elias Ross
     * @version 1.0
     */
    public class XmlRpcTest
    	extends junit.framework.TestCase
    	implements XmlRpcHandler
    {
    	public XmlRpcTest(String name) {
    		super(name);
    	}
    
    	public static void main(String[] args) {
    		junit.textui.TestRunner.run(XmlRpcTest.class);
    	}
    
    	static final String RETURN_TO_SENDER  = "return_to_sender";
    	static final String UNPACK_PACK = "unpack_pack";
    	static final String FAIL_FAIL = "fail";
    	static final String HANDLER = "generic_handler";
    	static final String ADDITION = "add_handler";
    	static final XmlRpcException WRATH_OF_THE_PROGRAMMER_EXCEPTION =
    		new XmlRpcException("Wrath of the Programmer Exception occured");
    	static final XmlRpcException NO_IDEA_EXCEPTION =
    		new XmlRpcException("I have no idea what you want.");
    
    	/**
    	 * Calls itself recursively to "unravel" a ParamIterator.
    	 * @return an object that contains all the ParamIterator contents
    	 */
    	static Object createCollection(ParamIterator pi) 
    		throws XmlRpcException
    	{
    		Vector v = new Vector();
    		// The HashMap is used if a StructPair is detected.  
    		HashMap map = new HashMap();
    		while (pi.hasNext()) {
    			Object o = pi.next();
    			if (o instanceof StructPair) {
    				StructPair pair = (StructPair)o;
    				Object value = pair.getValue();
    				if (value instanceof ParamIterator)
    					value = createCollection((ParamIterator)value);
    				map.put(pair.getName(), value);
    			}
    			if (o instanceof ParamIterator) {
    				o = createCollection((ParamIterator)o);
    				v.add(o);
    			} else {
    				v.add(o);
    			}
    		}
    		pi.close();
    		if (map.isEmpty())
    			return v;
    		return map;
    	}
    
    	/**
    	 * Supports several test methods.
    	 * RETURN_TO_SENDER -- just pass the same parameter iterator back.
    	 * The response should be the same as the response.  (However, this
    	 * will obviously fail, since params must be closed
    	 * before a response is sent to the client by the server.
    	 * UNPACK_PACK -- iterate over the parameter iterator, create a
    	 * bunch of Vector and HashMaps, return a IteratorAdapter.
    	 * FAIL -- throws an exception.
    	 */
    	public ParamIterator execute(String method, ParamIterator params) 
    		throws XmlRpcException
    	{
    		if (method.equals(RETURN_TO_SENDER)) {
    			return params;
    		}
    		else if (method.equals(UNPACK_PACK)) {
    			Object o = createCollection(params);
    			// A StructPair, hence Map, cannot occur at the "top-level"
    			assertTrue(o instanceof Collection);
    			Collection c = (Collection)o;
    			ParamIterator pia = new IteratorAdapter(c.iterator());
    			return pia;
    		}
    		else if (method.equals(ADDITION)) {
    			int total = 0;
    			while (params.hasNext()) {
    				Object o = params.next();
    				if (o instanceof Integer) {
    					Integer i = (Integer)o;
    					total += i.intValue();
    				}
    			}
    			Vector v = new Vector();
    			v.add(new Integer(total));
    			return new IteratorAdapter(v.iterator());
    		}
    		else if (method.equals(FAIL_FAIL)) {
    			throw WRATH_OF_THE_PROGRAMMER_EXCEPTION;
    		}
    		throw NO_IDEA_EXCEPTION;
    	}
    
    	/**
    	 * Creates a bunch of stuff to iterate over.
    	 */
    	public static ParamIterator createStuff() {
    		// Simple lists
    		Vector fruits = new Vector();
    		fruits.add(""); 
    		fruits.add("&Bananas&");
    		fruits.add("_Cherries_");
    		Vector veggies = new Vector();
    		veggies.add("Potato"); veggies.add("Tomato"); veggies.add("Brocolli");
    		// Random types to test
    		Vector types = new Vector();
    		types.add(null); types.add(new Integer(42)); 
    		types.add(new Boolean(true)); types.add(new Double(1.0f));
    		types.add(new Date(0)); types.add(new byte[] { 1, 2, 3, 4 });
    		types.add(fruits.elements());
    		// A HashMap with a Vector inside
    		HashMap map = new HashMap(); 
    		map.put("favorite fruits", fruits);
    		// List of lists
    		Vector list = new Vector();
    		list.add(fruits); list.add(veggies); list.add(types);
    		list.add(map);
    		ParamIterator pia = new IteratorAdapter(list.iterator());
    		return pia;
    	}
    
    	public static String makeNoDotRequest(String method) 
    		throws IOException, XmlRpcException
    	{
    		StringWriter out = new StringWriter();
    		XmlRpcWriter writer = new XmlRpcWriterImpl(out);
    		writer.writeRequest(method, createStuff());
    		return out.getBuffer().toString();
    	}
    
    	public static String makeRequest(String method) 
    		throws IOException, XmlRpcException
    	{
    		StringWriter out = new StringWriter();
    		XmlRpcWriter writer = new XmlRpcWriterImpl(out);
    		writer.writeRequest(HANDLER + "." + method, createStuff());
    		return out.getBuffer().toString();
    	}
    
    	public static String makeResponse(ParamIterator pi) 
    		throws IOException, XmlRpcException
    	{
    		StringWriter out = new StringWriter();
    		XmlRpcWriter writer = new XmlRpcWriterImpl(out);
    		writer.writeResponse(pi);
    		return out.getBuffer().toString();
    	}
    
    	public static String makeErrorResponse(XmlRpcException xre) 
    		throws IOException, XmlRpcException
    	{
    		StringWriter out = new StringWriter();
    		XmlRpcWriter writer = new XmlRpcWriterImpl(out);
    		writer.writeError(xre);
    		return out.getBuffer().toString();
    	}
    
    	public static String makeLongRequest(String method) 
    		throws IOException, XmlRpcException
    	{
    		StringWriter out = new StringWriter();
    		XmlRpcWriter writer = new XmlRpcWriterImpl(out);
    		writer.writeRequest(HANDLER + "." + method, 
    			makeLongParamIterator(1000));
    		return out.getBuffer().toString();
    	}
    
    
    	StringReader in;
    	StringWriter out;
    
    	/**
    	 * Test XmlRpcServerImpl class, see if default handler works.
    	 */
    	public void testXmlRpcServerDefaultHandler() 
    		throws XmlRpcException, XmlException, IOException
    	{
    		XmlRpcServer server = new XmlRpcServerImpl();
    		server.addHandler(XmlRpcServer.DEFAULT_HANDLER, this);
    		in = new StringReader(makeRequest(ADDITION));
    		server.accept(in, NullWriter.getInstance());
    
    		server.removeHandler(XmlRpcServer.DEFAULT_HANDLER);
    		System.out.println(makeRequest(ADDITION));
    		in = new StringReader(makeRequest(ADDITION));
    		try {
    			server.accept(in, NullWriter.getInstance());
    			fail("Should get NoHandlerException");
    		} catch (NoHandlerException nhe) {
    		}
    	}
    
    	public void testNoDotMethod() 
    		throws XmlRpcException, XmlException, IOException
    	{
    		XmlRpcServer server = new XmlRpcServerImpl();
    		server.addHandler(XmlRpcServer.DEFAULT_HANDLER, this);
    		in = new StringReader(makeNoDotRequest(ADDITION));
    		// should work, because of default handler
    		server.accept(in, NullWriter.getInstance());
    
    		// should fail because of bad request
    		server.removeHandler(XmlRpcServer.DEFAULT_HANDLER);
    		server.addHandler(HANDLER, this);
    		in = new StringReader(makeNoDotRequest(ADDITION));
    		try {
    			server.accept(in, NullWriter.getInstance());
    			fail("Should get NoHandlerException");
    		} catch (NoHandlerException nhe) {
    		}
    	}
    
    
    	public void testEmptyMethodName() 
    		throws XmlRpcException, IOException
    	{
    		XmlRpcServer server = new XmlRpcServerImpl();
    		server.addHandler(XmlRpcServer.DEFAULT_HANDLER, this);
    
    		in = new StringReader(makeNoDotRequest(""));
    		XmlRpcReader reader = new XmlRpcReaderImpl(in);
    		try {
    			String name = reader.readMethodName();
    			fail("Should get XmlRpcException, not " + name);
    		} catch (XmlRpcException xre) {
    		}
    	}
    
    	public void testReadResponseForRequest() 
    		throws XmlRpcException, IOException
    	{
    		in = new StringReader(makeRequest(RETURN_TO_SENDER));
    		XmlRpcReader reader = new XmlRpcReaderImpl(in);
    		try {
    			reader.readMethodResponse();
    			fail("Should get XmlRpcException");
    		} catch (XmlRpcException xre) {
    			// xre.printStackTrace();
    		}
    	}
    
    	public void testGarbageXml() 
    		throws XmlRpcException, XmlException, IOException
    	{
    		XmlRpcServer server = new XmlRpcServerImpl();
    		server.addHandler(XmlRpcServer.DEFAULT_HANDLER, this);
    		String problematic = "";
    		in = new StringReader(problematic);
    		try {
    			server.accept(in, NullWriter.getInstance());
    			fail("Should get XmlRpcException");
    		} catch (XmlRpcException xre) {
    		}
    	}
    
    	public void testInValidXml() 
    		throws XmlRpcException, XmlException, IOException
    	{
    		XmlRpcServer server = new XmlRpcServerImpl();
    		server.addHandler(XmlRpcServer.DEFAULT_HANDLER, this);
    
    		StringBuffer problematic = new StringBuffer();
    		problematic.append(
    			"" +
    			"generic_handler." + ADDITION + "" +
    			"");
    		for (int i = 0; i < 64; i++) {
    			problematic.append("");
    		}
    
    		// Ensure handler okay
    		in = new StringReader(problematic.toString());
    		out = new StringWriter();
    		server.accept(in, out);
    		in = new StringReader(out.getBuffer().toString());
    		XmlRpcReader reader = new XmlRpcReaderImpl(in);
    		ParamIterator pi = reader.readMethodResponse();
    		assertEquals("Fault occured", pi.getIteratorType(), ParamIterator.FAULT_ITERATOR);
    	}
    
    	public void testValidXml2() 
    		throws XmlRpcException, XmlException, IOException
    	{
    		String okay = 
            "" +
            "" + HANDLER + "." + UNPACK_PACK + "" +
            "" +
                    "" +
                    "" +
                            "Apples" +
                            "Bananas" +
                            "Cherries" +
                    "" +
                    "" +
                    "" +
                    "" +
            "" +
            "";
    
    		// Ensure Xml is valid Xml
    		in = new StringReader(okay);
    		XmlReader reader = new XmlReader(in);
    		Document document = reader.document();
    		assertTrue(document != null);
    
    		// Ensure handler okay
    		in = new StringReader(okay);
    		XmlRpcServer server = new XmlRpcServerImpl();
    		server.addHandler(HANDLER, this);
    		out = new StringWriter();
    		server.accept(in, out);
    	}
    
    	/**
    	 * Test XmlRpcWriter class.
    	 */
    	public void testValidXml() 
    		throws XmlRpcException, XmlException, IOException
    	{
    		XmlReader reader;
    		Document document;
    
    		// Ensure Xml is valid Xml
    		in = new StringReader(makeRequest(RETURN_TO_SENDER));
    		reader = new XmlReader(in);
    		document = reader.document();
    		assertTrue(document != null);
    
    		// Ensure Xml is valid Xml for failure
    		in = new StringReader(makeRequest(FAIL_FAIL));
    		reader = new XmlReader(in);
    		document = reader.document();
    		assertTrue(document != null);
    
    		// Ensure Xml is valid Xml for response
    		in = new StringReader(makeResponse(createStuff()));
    		reader = new XmlReader(in);
    		document = reader.document();
    		assertTrue(document != null);
    
    		// Ensure Xml is valid Xml for long request
    		in = new StringReader(makeLongRequest(ADDITION));
    		reader = new XmlReader(in);
    		document = reader.document();
    		assertTrue(document != null);
    
    		// ensure valid NoDotRequest
    		in = new StringReader(makeNoDotRequest(""));
    		reader = new XmlReader(in);
    		document = reader.document();
    		assertTrue(document != null);
    	}
    
    	/**
    	 * Test XmlRpcServer classes.
    	 */
    	public void testValidXmlRpcServer() 
    		throws XmlRpcException, IOException
    	{
    		XmlRpcServer server = new XmlRpcServerImpl();
    		server.addHandler(HANDLER, this);
    
    		// Try the UNPACK_PACK
    		System.out.println(" XXX " + makeRequest(UNPACK_PACK));
    		in = new StringReader(makeRequest(UNPACK_PACK));
    		out = new StringWriter();
    		server.accept(in, out);
    		// See if what the server wrote matches what was received
    		assertEquals(out.getBuffer().toString(),
    			makeResponse(createStuff()));
    
    		// Try the FAIL_FAIL
    		in = new StringReader(makeRequest(FAIL_FAIL));
    		out = new StringWriter();
    		server.accept(in, out);
    		// See if what the server wrote matches what was received
    		assertEquals(out.getBuffer().toString(),
    			makeErrorResponse(WRATH_OF_THE_PROGRAMMER_EXCEPTION));
    
    		// Try the ""
    		in = new StringReader(makeRequest(""));
    		out = new StringWriter();
    		server.accept(in, out);
    		// See if what the server wrote matches what was received
    		assertEquals(out.getBuffer().toString(),
    			makeErrorResponse(NO_IDEA_EXCEPTION));
    
    		// Try the ADDITION
    		in = new StringReader(makeLongRequest(ADDITION));
    		out = new StringWriter();
    		server.accept(in, out);
    		// See if what the server wrote matches the total we want
    		Vector v = new Vector();
    		v.add(new Integer(500));
    		assertEquals(out.getBuffer().toString(), 
    			makeResponse(new IteratorAdapter(v.iterator())));
    	}
    
    	private static class TestReader extends Reader {
    		private Reader r;
    		public boolean closed;
    		public TestReader(Reader r) {
    			this.r = r;
    		}
    		public int read(char[] c, int off, int len)
    			throws IOException
    		{
    			return r.read(c, off, len);
    		}
    		public void close()
    			throws IOException
    		{
    			r.close();
    			closed = false;
    		}
    	}
    
    	/**
    	 * Test no closing at end of reading.
    	 */
    	public void testCloseReading() 
    		throws XmlRpcException, IOException
    	{
    		XmlRpcServer server = new XmlRpcServerImpl();
    		server.addHandler(HANDLER, this);
    
    		TestReader in = new TestReader(new StringReader(makeRequest(UNPACK_PACK)));
    		out = new StringWriter();
    		server.accept(in, out);
    		assertTrue("Not closed", !in.closed); 
    	}
    
    	/**
    	 * Test no closing at end.
    	 */
    	public void testValidRR() 
    		throws XmlRpcException, IOException
    	{
    	}
    
    	/**
    	 * Returns an interator with until entries, half of
    	 * these are the integer 1, the other half are strings.
    	 */
    	public static ParamIterator makeLongParamIterator(final int until) {
    		return new ParamIterator() {
    			int times = 0;
    			public Object next() 
    			{
    				times++;
    				if (times % 2 == 0)
    					return " AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA ";
    				else
    					return new Integer(1);
    			}
    			public boolean hasNext() {
    				return times < until;
    			}
    			public int getIteratorType() {
    				return PARAMS_ITERATOR;
    			}
    			public void close() {
    			}
    		};
    	}
    
    }
    libexml-java-0.0.20080703.orig/xmlrpc/src/test/java/net/noderunner/xmlrpc/XmlRpcDateFormatTest.java0000644000175000017500000000316110762067376032667 0ustar  twernertwerner/* 
     * E-XML Library:  For XML, XML-RPC, HTTP, and related.
     * Copyright (C) 2002-2008  Elias Ross
     * 
     * genman@noderunner.net
     * http://noderunner.net/~genman
     * 
     * 1025 NE 73RD ST
     * SEATTLE WA 98115
     * USA
     *
     * This library is free software; you can redistribute it and/or
     * modify it under the terms of the GNU Lesser General Public
     * License as published by the Free Software Foundation; either
     * version 2.1 of the License, or (at your option) any later version.
     *
     * This library is distributed in the hope that it will be useful,
     * but WITHOUT ANY WARRANTY; without even the implied warranty of
     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
     * Lesser General Public License for more details.
     * 
     * $Id$
     */
    
    package net.noderunner.xmlrpc;
    
    import java.text.ParseException;
    import java.util.Date;
    
    /**
     * This class uses tests the XmlRpcDateFormatTest for proper behavior.
     *
     * @author Elias Ross
     * @version 1.0
     */
    public class XmlRpcDateFormatTest
    	extends junit.framework.TestCase
    {
    
    	public XmlRpcDateFormatTest(String name) {
    		super(name);
    	}
    
    	public static void main(String[] args) {
    		junit.textui.TestRunner.run(XmlRpcDateFormatTest.class);
    	}
    
    	public void test() 
    		throws Exception
    	{
    		XmlRpcDateFormat format = new XmlRpcDateFormat();
    		try {
    			Date d = format.parse("xxxxxxxxxxx");
    			fail("Should fail on bad date parse");
    		} catch (ParseException pe) {
    		}
    		String s = "20000101T04:01:01";
    		Date d = null;
    		try {
    			d = format.parse(s);
    		} catch (ParseException pe) {
    			fail("Shouldn't fail on good date parse " + pe);
    		}
    		String s2 = format.format(d);
    		assertEquals(s, s2);
    	}
    }
    libexml-java-0.0.20080703.orig/xmlrpc/src/test/java/net/noderunner/xmlrpc/XmlRpcReaderTest.java0000644000175000017500000000301610762067376032042 0ustar  twernertwerner/* 
     * E-XML Library:  For XML, XML-RPC, HTTP, and related.
     * Copyright (C) 2002-2008  Elias Ross
     * 
     * genman@noderunner.net
     * http://noderunner.net/~genman
     * 
     * 1025 NE 73RD ST
     * SEATTLE WA 98115
     * USA
     *
     * This library is free software; you can redistribute it and/or
     * modify it under the terms of the GNU Lesser General Public
     * License as published by the Free Software Foundation; either
     * version 2.1 of the License, or (at your option) any later version.
     *
     * This library is distributed in the hope that it will be useful,
     * but WITHOUT ANY WARRANTY; without even the implied warranty of
     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
     * Lesser General Public License for more details.
     * 
     * $Id$
     */
    
    package net.noderunner.xmlrpc;
    
    import java.io.InputStream;
    import java.io.InputStreamReader;
    
    import junit.framework.TestCase;
    
    public class XmlRpcReaderTest extends TestCase {
    	
    	public void testReader() throws Exception {
    		InputStream is = getClass().getResourceAsStream("/test.xml");
    		InputStreamReader reader = new InputStreamReader(is);
    		XmlRpcReaderImpl ri = new XmlRpcReaderImpl(reader);
    		assertEquals("generic_handler.unpack_pack", ri.readMethodName());
    		ParamIterator i = ri.readMethodRequest();
    		iterate(i);
    		i.close();
    	}
    	
    	private void iterate(ParamIterator i) throws Exception {
    		while (i.hasNext()) {
    			Object object = i.next();
    			if (object instanceof ParamIterator)
    				iterate((ParamIterator)object);
    			System.out.println(object);
    		}
    	}
    
    }
    
    libexml-java-0.0.20080703.orig/xmlrpc/src/test/java/net/noderunner/xmlrpc/IteratorAdapterTest.java0000644000175000017500000000373110762067376032610 0ustar  twernertwerner/* 
     * E-XML Library:  For XML, XML-RPC, HTTP, and related.
     * Copyright (C) 2002-2008  Elias Ross
     * 
     * genman@noderunner.net
     * http://noderunner.net/~genman
     * 
     * 1025 NE 73RD ST
     * SEATTLE WA 98115
     * USA
     *
     * This library is free software; you can redistribute it and/or
     * modify it under the terms of the GNU Lesser General Public
     * License as published by the Free Software Foundation; either
     * version 2.1 of the License, or (at your option) any later version.
     *
     * This library is distributed in the hope that it will be useful,
     * but WITHOUT ANY WARRANTY; without even the implied warranty of
     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
     * Lesser General Public License for more details.
     * 
     * $Id$
     */
    
    package net.noderunner.xmlrpc;
    
    import java.util.List;
    import java.util.Vector;
    
    /**
     * This class uses tests the IteratorAdapter for proper behavior.
     *
     * @author Elias Ross
     * @version 1.0
     */
    public class IteratorAdapterTest
    	extends junit.framework.TestCase
    {
    	public IteratorAdapterTest(String name) {
    		super(name);
    	}
    
    	public static void main(String[] args) {
    		junit.textui.TestRunner.run(IteratorAdapterTest.class);
    	}
    
    	public void testToList() 
    		throws Exception
    	{
    		Vector v = new Vector();
    		Vector v2 = new Vector();
    		v.add("object");
    		v.add("object1");
    		v2.add("one");
    		v2.add("two");
    		v.add(v2);
    		IteratorAdapter ia = new IteratorAdapter(v.iterator());
    		List l = IteratorAdapter.toList(ia);
    		assertTrue("Both equal", v.equals(l));
    	}
    
    	public void test() 
    		throws Exception
    	{
    		Vector v = new Vector();
    		v.add("object");
    		v.add("object1");
    		IteratorAdapter ia = new IteratorAdapter(v.iterator());
    		assertEquals(ia.getIteratorType(), ParamIterator.ARRAY_ITERATOR);
    		assertEquals(ia.hasNext(), true);
    		assertEquals(ia.next(), "object");
    		assertEquals(ia.next(), "object1");
    		assertEquals(ia.hasNext(), false);
    		ia.close();
    		try {
    			ia.next();
    			fail("Should throw NullPointerException");
    		} catch (Exception e) { }
    	}
    }
    libexml-java-0.0.20080703.orig/xmlrpc/src/test/java/net/noderunner/xmlrpc/MapAdapterTest.java0000644000175000017500000000514410762067376031534 0ustar  twernertwerner/* 
     * E-XML Library:  For XML, XML-RPC, HTTP, and related.
     * Copyright (C) 2002-2008  Elias Ross
     * 
     * genman@noderunner.net
     * http://noderunner.net/~genman
     * 
     * 1025 NE 73RD ST
     * SEATTLE WA 98115
     * USA
     *
     * This library is free software; you can redistribute it and/or
     * modify it under the terms of the GNU Lesser General Public
     * License as published by the Free Software Foundation; either
     * version 2.1 of the License, or (at your option) any later version.
     *
     * This library is distributed in the hope that it will be useful,
     * but WITHOUT ANY WARRANTY; without even the implied warranty of
     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
     * Lesser General Public License for more details.
     * 
     * $Id$
     */
    
    package net.noderunner.xmlrpc;
    
    import java.util.HashMap;
    import java.util.Map;
    
    /**
     * This class uses tests the MapAdapter for proper behavior.
     *
     * @author Elias Ross
     * @version 1.0
     */
    public class MapAdapterTest
    	extends junit.framework.TestCase
    {
    
    	public MapAdapterTest(String name) {
    		super(name);
    	}
    
    	public static void main(String[] args) {
    		junit.textui.TestRunner.run(MapAdapterTest.class);
    	}
    
    	public void testBadKey() 
    		throws Exception
    	{
    		HashMap m = new HashMap();
    		m.put(new Integer(0), "value");
    		MapAdapter ma = new MapAdapter(m);
    		assertEquals(ma.hasNext(), true);
    		try {
    			ma.next();
    			fail("Should throw XmlRpcException, since next value is not a string");
    		} catch (XmlRpcException e) { }
    	}
    
    	public void testToMap() 
    		throws Exception
    	{
    		HashMap m = new HashMap();
    		m.put(new Integer(0).toString(), "value");
    		m.put("string", "value2");
    		HashMap m2 = new HashMap();
    		m2.put("i", "watashi");
    		m2.put("you", "anata");
    		m.put("japanese", m2);
    
    		MapAdapter ma = new MapAdapter(m);
    		Map mout = MapAdapter.toMap(ma);
    		assertEquals("should get 0", "value", mout.get("0"));
    		assertEquals("should get string", "value2", mout.get("string"));
    		assertEquals("should be identical maps", mout, m);
    	}
    
    	public void testGeneral() 
    		throws Exception
    	{
    		HashMap m = new HashMap();
    		m.put("key", "value");
    		m.put("key2", "value");
    		MapAdapter ma = new MapAdapter(m);
    		assertEquals(ma.getIteratorType(), ParamIterator.STRUCT_ITERATOR);
    		assertEquals(ma.hasNext(), true);
    		// test if returning good object
    		assertTrue(ma.next() instanceof StructPair);
    		// test value of next object
    		StructPair sp = (StructPair)ma.next();
    		assertEquals(sp.getValue(), "value");
    		// test if we ran out
    		assertEquals(ma.hasNext(), false);
    		// test that close works
    		ma.close();
    		try {
    			ma.next();
    			fail("Should throw NullPointerException");
    		} catch (Exception e) { }
    	}
    }
    libexml-java-0.0.20080703.orig/xmlrpc/src/test/java/net/noderunner/xmlrpc/InvokerTest.java0000644000175000017500000000510210762067376031125 0ustar  twernertwerner/* 
     * E-XML Library:  For XML, XML-RPC, HTTP, and related.
     * Copyright (C) 2002-2008  Elias Ross
     * 
     * genman@noderunner.net
     * http://noderunner.net/~genman
     * 
     * 1025 NE 73RD ST
     * SEATTLE WA 98115
     * USA
     *
     * This library is free software; you can redistribute it and/or
     * modify it under the terms of the GNU Lesser General Public
     * License as published by the Free Software Foundation; either
     * version 2.1 of the License, or (at your option) any later version.
     *
     * This library is distributed in the hope that it will be useful,
     * but WITHOUT ANY WARRANTY; without even the implied warranty of
     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
     * Lesser General Public License for more details.
     * 
     * $Id$
     */
    
    package net.noderunner.xmlrpc;
    
    import java.util.Date;
    import java.util.Vector;
    
    /**
     * This class uses tests the Invoker for proper behavior.
     *
     * @author Elias Ross
     * @version 1.0
     * @see Invoker
     */
    public class InvokerTest
    	extends junit.framework.TestCase
    {
    
    	public InvokerTest(String name) {
    		super(name);
    	}
    
    	public static void main(String[] args) {
    		junit.textui.TestRunner.run(InvokerTest.class);
    	}
    
    	public String badOne(String a, String b, String c)
    		throws Exception
    	{
    		throw new Exception("I hate this; " + a);
    	}
    	
    	public String printThree(String a, String b, String c)
    		throws Exception
    	{
    		assertEquals(a, A);
    		assertEquals(b, B);
    		assertEquals(c, C);
    		return a + b + c;
    	}
    	
    	public Vector printTwo(int i, Date b)
    	{
    		Vector stuff = new Vector();
    		stuff.add(new Integer(i)); stuff.add(b); 
    		return stuff;
    	}
    
    	public static String A = "Apples";
    	public static String B = "Bannanas";
    	public static String C = "Cherries";
    
    	public void test() 
    		throws XmlRpcException
    	{
    		Vector fruits = new Vector();
    		fruits.add(A); fruits.add(B); fruits.add(C);
    
    		Vector stuff = new Vector();
    		stuff.add(new Integer(1)); stuff.add(new Date(0)); 
    
    		Invoker i = new Invoker(this);
    		ParamIterator pi;
    		pi = i.execute("printThree", new IteratorAdapter(fruits.iterator()));
    		assertTrue(pi.hasNext());
    		assertEquals(pi.next(), A + B + C);
    		pi = i.execute("printTwo", new IteratorAdapter(stuff.iterator()));
    		assertTrue(pi.hasNext());
    		assertEquals(pi.next(), new Integer(1));
    		assertEquals(pi.next(), new Date(0));
    		try {
    			i.execute("notHere", new IteratorAdapter(stuff.iterator()));
    			fail("Should fail calling notHere");
    		} catch (XmlRpcException xre) {
    			// xre.printStackTrace();
    		}
    		try {
    			i.execute("badOne", new IteratorAdapter(fruits.iterator()));
    			fail("Should fail calling badOne");
    		} catch (XmlRpcException xre) {
    		}
    	}
    
    }
    libexml-java-0.0.20080703.orig/xmlrpc/src/test/resources/0000755000175000017500000000000011111351372022603 5ustar  twernertwernerlibexml-java-0.0.20080703.orig/xmlrpc/src/test/resources/test.xml0000644000175000017500000000506410674337112024322 0ustar  twernertwerner
      generic_handler.unpack_pack
      
        
          
            
              
                
                  <Apples>
                
                
                  &Bananas&
                
                
                  _Cherries_
                
              
            
          
        
        
          
            
              
                
                  Potato
                
                
                  Tomato
                
                
                  Brocolli
                
              
            
          
        
        
          
            
              
                
                  
                
                
                  42
                
                
                  1
                
                
                  1.0
                
                
                  19691231T16:00:00
                
                
                  AQIDBA==
                
                
                  
                    
                      
                        <Apples>
                      
                      
                        &Bananas&
                      
                      
                        _Cherries_
                      
                    
                  
                
              
            
          
        
        
          
            
              
                favorite fruits
                
                  
                    
                      
                        <Apples>
                      
                      
                        &Bananas&
                      
                      
                        _Cherries_
                      
                    
                  
                
              
            
          
        
      
    
    libexml-java-0.0.20080703.orig/xmlrpc/src/main/0000755000175000017500000000000011111351372020536 5ustar  twernertwernerlibexml-java-0.0.20080703.orig/xmlrpc/src/main/java/0000755000175000017500000000000011111351372021457 5ustar  twernertwernerlibexml-java-0.0.20080703.orig/xmlrpc/src/main/java/net/0000755000175000017500000000000011111351372022245 5ustar  twernertwernerlibexml-java-0.0.20080703.orig/xmlrpc/src/main/java/net/noderunner/0000755000175000017500000000000011111351372024424 5ustar  twernertwernerlibexml-java-0.0.20080703.orig/xmlrpc/src/main/java/net/noderunner/xmlrpc/0000755000175000017500000000000011111351376025735 5ustar  twernertwernerlibexml-java-0.0.20080703.orig/xmlrpc/src/main/java/net/noderunner/xmlrpc/XmlRpcWriter.java0000644000175000017500000000531610762067376031226 0ustar  twernertwerner/* 
     * E-XML Library:  For XML, XML-RPC, HTTP, and related.
     * Copyright (C) 2002-2008  Elias Ross
     * 
     * genman@noderunner.net
     * http://noderunner.net/~genman
     * 
     * 1025 NE 73RD ST
     * SEATTLE WA 98115
     * USA
     *
     * This library is free software; you can redistribute it and/or
     * modify it under the terms of the GNU Lesser General Public
     * License as published by the Free Software Foundation; either
     * version 2.1 of the License, or (at your option) any later version.
     *
     * This library is distributed in the hope that it will be useful,
     * but WITHOUT ANY WARRANTY; without even the implied warranty of
     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
     * Lesser General Public License for more details.
     * 
     * $Id$
     */
    
    package net.noderunner.xmlrpc;
    
    import java.io.Writer;
    
    /**
     * This interfaces describes the basic interface for writing
     * data to an Xml-Rpc server or client.
     * Methods that take a ParamIterator instance should be able to accept a
     * variety of objects returned by the next() method.  A
     * class that implements this interface should be able to output the
     * Xml-Rpc representation of these supported Java objects:
     * 
      *
    • java.lang.Integer, as int *
    • java.lang.Boolean, as boolean *
    • java.lang.Double, as double *
    • java.lang.Float, as double *
    • java.util.Date, as iso8601 *
    • byte[], as base64 *
    • null, as nil *
    • java.util.Collection, as array *
    • java.util.Map, as struct *
    • java.util.Enumeration, as array *
    • java.util.Iterator, as array *
    • net.noderunner.xmlrpc.ParamIterator, as array or struct *
    * Additional object types can be supported. * * @see XmlRpcReader */ public interface XmlRpcWriter { /** * Write an Xml-Rpc request from a method name and a parameter * iterator. * @throws XmlRpcException if ParamIterator throws an exception or * serializing the object fails */ void writeRequest(String method, ParamIterator iterator) throws XmlRpcException; /** * Write an Xml-Rpc response using a parameter * iterator. * @throws XmlRpcException if ParamIterator throws an exception or * serializing the object fails */ void writeResponse(ParamIterator i) throws XmlRpcException; /** * Writes an Xml-Rpc error response to the Xml writer. * @throws XmlRpcException if serializing the error failed */ void writeError(XmlRpcException xre) throws XmlRpcException; /** * Sets the output stream (writer) to be used. Allows an instance to be * re-used. * @param writer writer to wrap */ void setWriter(Writer writer); } libexml-java-0.0.20080703.orig/xmlrpc/src/main/java/net/noderunner/xmlrpc/StructPair.java0000644000175000017500000000233210762067376030717 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.xmlrpc; /** * This interface defines an Xml-Rpc struct object. This is being used, * since Java does not (for some reason) have a java.util.Pair or somesuch * object. * * @author Elias Ross * @version 1.0 */ public interface StructPair { /** * Gets the name, as it appears between the <name> tags. * @return name */ String getName(); /** * Gets the value. * @return value, which can be of any valid Xml-Rpc type */ Object getValue(); } libexml-java-0.0.20080703.orig/xmlrpc/src/main/java/net/noderunner/xmlrpc/example/0000755000175000017500000000000011111351372027364 5ustar twernertwerner././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootlibexml-java-0.0.20080703.orig/xmlrpc/src/main/java/net/noderunner/xmlrpc/example/XmlRpcInputAdapter.javalibexml-java-0.0.20080703.orig/xmlrpc/src/main/java/net/noderunner/xmlrpc/example/XmlRpcInputAdapter0000644000175000017500000000512110762067376033057 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.xmlrpc.example; import java.util.Map; import net.noderunner.xmlrpc.ParamIterator; import net.noderunner.xmlrpc.XmlRpcException; /** * For inputting from XmlRpc. */ public class XmlRpcInputAdapter implements ProvIterator { ParamIterator pi; public XmlRpcInputAdapter(ParamIterator pi) { this.pi = pi; } public boolean hasNext() throws ProvException { try { return pi.hasNext(); } catch (XmlRpcException xre) { throw new ProvException("hasNext() failed", xre); } } static ProvEntity toEntity(Map map) throws ProvException, XmlRpcException { String obj = (String)map.get("object"); if (obj == null) throw new ProvException("null entity in " + map); if (obj.equals(ProvResult.class.getName())) { return new ProvResult((String)map.get("message"), toEntity((Map)map.get("entity"))); } if (obj.equals(Subscriber.class.getName())) { return new SubscriberImpl((String)map.get("name"), (String)map.get("password")); } if (obj.equals(SubscriberSearch.class.getName())) { return new SubscriberSearchImpl((String)map.get("matchName")); } throw new ProvException("unknown entity in " + map); } static ProvEntity toEntity(ParamIterator o) throws ProvException, XmlRpcException { java.util.Map map = net.noderunner.xmlrpc.MapAdapter.toMap(o); return toEntity(map); } /** * Returns a MapAdapter per object. */ public ProvEntity next() throws ProvException { try { Object o = pi.next(); if (o instanceof ParamIterator) { return toEntity((ParamIterator)o); } throw new ProvException("Unknown underlying object " + o); } catch (XmlRpcException xre) { throw new ProvException("next() failed", xre); } } public void close() throws ProvException { try { pi.close(); } catch (XmlRpcException xre) { throw new ProvException("close() failed", xre); } } } libexml-java-0.0.20080703.orig/xmlrpc/src/main/java/net/noderunner/xmlrpc/example/ProvIterator.java0000644000175000017500000000332410762067376032714 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.xmlrpc.example; /** * Iterates over the parameters passed in (or out) of a call. * These are used in this Xml-Rpc package for input and output. *

    * @see IteratorAdapter How to wrap an existing Iterator */ public interface ProvIterator { /** * This will return an entity, such as a Subscriber. * @return next parameter * @throws ProvException if there is some problem retrieving the next * parameter. */ ProvEntity next() throws ProvException; /** * @return true if an additional object is available for reading. * @throws ProvException if there is some problem checking for the next * parameter from the stream. */ boolean hasNext() throws ProvException; /** * This method closes underlying input/output stream. * Calling close() is required, since it will release underlying * resources. * @throws ProvException if the close operation could not be * completed. */ void close() throws ProvException; } libexml-java-0.0.20080703.orig/xmlrpc/src/main/java/net/noderunner/xmlrpc/example/ProvEntity.java0000644000175000017500000000157210762067376032402 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.xmlrpc.example; /** * A signature class, for all entity objects in this package. */ public interface ProvEntity { } libexml-java-0.0.20080703.orig/xmlrpc/src/main/java/net/noderunner/xmlrpc/example/Subscriber.java0000644000175000017500000000156510762067376032364 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.xmlrpc.example; public interface Subscriber extends ProvEntity { String getName(); String getPassword(); } ././@LongLink0000000000000000000000000000014500000000000011565 Lustar rootrootlibexml-java-0.0.20080703.orig/xmlrpc/src/main/java/net/noderunner/xmlrpc/example/ProvException.javalibexml-java-0.0.20080703.orig/xmlrpc/src/main/java/net/noderunner/xmlrpc/example/ProvException.java0000644000175000017500000000372410762067376033065 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.xmlrpc.example; /** * This is thrown on various errors. This exception may contain a * wrapped Throwable object. *

    * @author Elias Ross * @version 1.0 */ public class ProvException extends Exception { /** * */ private static final long serialVersionUID = 7811246520895540002L; /** * Root cause. */ Throwable cause; /** * Construct an XmlRpcException with a message. * @param message message to display. */ public ProvException(String message) { super(message); this.cause = this; } /** * Construct an ProvException with a wrapped Throwable. * @param cause reason for this XmlRpcException */ public ProvException(Throwable cause) { this("ProvException -- ", cause); } /** * Construct an ProvException with a message and code and wrapped * Throwable. * @param message message to display. * @param cause reason for this XmlRpcException */ public ProvException(String message, Throwable cause) { super(message + " -- " + cause); this.cause = cause; } /** * Gets the root cause of the exception, if any. May return * this if no cause. * @return the root cause */ public Throwable getCause() { return cause; } } ././@LongLink0000000000000000000000000000016000000000000011562 Lustar rootrootlibexml-java-0.0.20080703.orig/xmlrpc/src/main/java/net/noderunner/xmlrpc/example/XmlRpcProvisioningServer.javalibexml-java-0.0.20080703.orig/xmlrpc/src/main/java/net/noderunner/xmlrpc/example/XmlRpcProvisioning0000644000175000017500000000363510762067376033155 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.xmlrpc.example; import net.noderunner.xmlrpc.Invoker; import net.noderunner.xmlrpc.NoHandlerException; import net.noderunner.xmlrpc.ParamIterator; import net.noderunner.xmlrpc.XmlRpcException; import net.noderunner.xmlrpc.XmlRpcHandler; public class XmlRpcProvisioningServer implements XmlRpcHandler { Invoker i; ProvisioningInterface client; XmlRpcProvisioningServer(ProvisioningInterface client) { this.client = client; i = new Invoker(client); } public ParamIterator execute(String methodName, ParamIterator params) throws XmlRpcException { ProvIterator in = new XmlRpcInputAdapter(params); try { ProvIterator out = null; if (methodName.equals("addSubscribers")) { out = client.addSubscribers(in); } else if (methodName.equals("deleteSubscribers")) { out = client.deleteSubscribers(in); } else if (methodName.equals("findSubscribers")) { out = client.findSubscribers((SubscriberSearch)in.next()); } else { throw new NoHandlerException("unknown method " + methodName); } return new XmlRpcOutputAdapter(out); } catch (ProvException pe) { throw new XmlRpcException(0, "execute failure", pe); } } } libexml-java-0.0.20080703.orig/xmlrpc/src/main/java/net/noderunner/xmlrpc/example/ProvResult.java0000644000175000017500000000331210762067376032376 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.xmlrpc.example; /** * This is returned on various errors (or successes). This contains a * message and a source object which failed or succeeded. *

    * @author Elias Ross * @version 1.0 */ public class ProvResult implements ProvEntity { /** * Failed entity. */ Object entity; /** * Explaination. */ String message; /** * Construct a ProvResult with a message and entity. * @param message message to display. */ public ProvResult(String message, Object entity) { this.message = message; this.entity = entity; } /** * Gets the entity related to the result. * @return an entity */ public Object getEntity() { return entity; } /** * Gets the message of the result. * @return a message */ public String getMessage() { return message; } /** * Gets a debug message representation of this object. */ public String toString() { return "ProvResult: " + message + " -- For: " + entity; } } ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootlibexml-java-0.0.20080703.orig/xmlrpc/src/main/java/net/noderunner/xmlrpc/example/SubscriberImpl.javalibexml-java-0.0.20080703.orig/xmlrpc/src/main/java/net/noderunner/xmlrpc/example/SubscriberImpl.jav0000644000175000017500000000223510762067376033040 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.xmlrpc.example; public class SubscriberImpl implements Subscriber { String name; String password; public SubscriberImpl(String name, String password) { this.name = name; this.password = password; } public String getName() { return name; } public String getPassword() { return password; } public String toString() { return "SubscriberImpl [name=" + name + " password=" + password + "]"; } } ././@LongLink0000000000000000000000000000015500000000000011566 Lustar rootrootlibexml-java-0.0.20080703.orig/xmlrpc/src/main/java/net/noderunner/xmlrpc/example/SqlProvisioningClient.javalibexml-java-0.0.20080703.orig/xmlrpc/src/main/java/net/noderunner/xmlrpc/example/SqlProvisioningCli0000644000175000017500000000457710762067376033145 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.xmlrpc.example; import java.sql.SQLException; /** * This interface is used for provisioning names in a database. */ public class SqlProvisioningClient implements ProvisioningInterface { /** * Construct a new SqlProvisioningClient. */ public SqlProvisioningClient() { } public ProvIterator addSubscribers(ProvIterator i) throws ProvException { java.util.Stack v = new java.util.Stack(); while (i.hasNext()) { Subscriber s = (Subscriber)i.next(); String sql = "insert into subscribers values (name, password)"; try { execute(sql); } catch (SQLException se) { v.push(new ProvResult("" + se, s)); } if (v.size() > 100) { v.push(new ProvResult("*** TOO MANY ERRORS, ABORT ***", s)); break; } } return new IteratorAdapter(v.iterator()); } void execute(String sql) throws SQLException { throw new SQLException("not done yet"); } public ProvIterator deleteSubscribers(ProvIterator i) throws ProvException { java.util.Stack v = new java.util.Stack(); while (i.hasNext()) { Subscriber s = (Subscriber)i.next(); String sql = "delete from subscribers where name = " + s.getName(); try { execute(sql); } catch (SQLException se) { v.push(new ProvResult("" + se, s)); } if (v.size() > 100) { v.push(new ProvResult("*** TOO MANY ERRORS, ABORT ***", s)); break; } } return new IteratorAdapter(v.iterator()); } public ProvIterator findSubscribers(SubscriberSearch nameLike) throws ProvException { // String sql = "select * from subscribers where name like " + nameLike; // kind of fancy here throw new ProvException("Not done yet"); } } ././@LongLink0000000000000000000000000000016000000000000011562 Lustar rootrootlibexml-java-0.0.20080703.orig/xmlrpc/src/main/java/net/noderunner/xmlrpc/example/XmlRpcProvisioningClient.javalibexml-java-0.0.20080703.orig/xmlrpc/src/main/java/net/noderunner/xmlrpc/example/XmlRpcProvisioning0000644000175000017500000000371310762067376033152 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.xmlrpc.example; import net.noderunner.xmlrpc.ParamIterator; import net.noderunner.xmlrpc.XmlRpcClient; import net.noderunner.xmlrpc.XmlRpcException; /** * This interface is used for provisioning names in a database. */ public class XmlRpcProvisioningClient implements ProvisioningInterface { XmlRpcClient client; /** * Construct a new XmlRpcProvisioningClient. */ public XmlRpcProvisioningClient(XmlRpcClient client) { this.client = client; } ProvIterator call(String method, ProvIterator out) throws ProvException { try { ParamIterator pi = client.execute(INTERFACE_NAME + "." + method, new XmlRpcOutputAdapter(out)); return new XmlRpcInputAdapter(pi); } catch (XmlRpcException xre) { throw new ProvException(xre); } } public ProvIterator addSubscribers(ProvIterator i) throws ProvException { return call("addSubscribers", i); } public ProvIterator deleteSubscribers(ProvIterator i) throws ProvException { return call("deleteSubscribers", i); } public ProvIterator findSubscribers(SubscriberSearch ss) throws ProvException { java.util.Vector v = new java.util.Vector(); v.add(ss); return call("findSubscribers", new IteratorAdapter(v.iterator())); } } ././@LongLink0000000000000000000000000000015500000000000011566 Lustar rootrootlibexml-java-0.0.20080703.orig/xmlrpc/src/main/java/net/noderunner/xmlrpc/example/ProvisioningInterface.javalibexml-java-0.0.20080703.orig/xmlrpc/src/main/java/net/noderunner/xmlrpc/example/ProvisioningInterf0000644000175000017500000000361110762067376033171 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.xmlrpc.example; /** * This interface is used for provisioning names in a database. */ public interface ProvisioningInterface { String INTERFACE_NAME = "ProvisioningInterface"; /** * Add subscribers. * @param s interator containing instances of Subscriber * objects. * @return failures, if existant * @throws ProvException if the subscriber could not be added. */ ProvIterator addSubscribers(ProvIterator i) throws ProvException; /** * Deletes subscribers by name. * @param u interator containing instances of Subscriber * objects. * @return failures, if existant * @throws ProvException if the subscriber could not be deleted. */ ProvIterator deleteSubscribers(ProvIterator i) throws ProvException; /** * Finds matching subscribers. ProvIterator contains a list * of names, which are instances of Subscriber objects. * @param ss refer to SubscriberSearch for matching names * @return matching names * @throws ProvException if the names could not be retrieved */ ProvIterator findSubscribers(SubscriberSearch ss) throws ProvException; } ././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootlibexml-java-0.0.20080703.orig/xmlrpc/src/main/java/net/noderunner/xmlrpc/example/XmlRpcOutputAdapter.javalibexml-java-0.0.20080703.orig/xmlrpc/src/main/java/net/noderunner/xmlrpc/example/XmlRpcOutputAdapte0000644000175000017500000000507110762067376033102 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.xmlrpc.example; import net.noderunner.xmlrpc.ParamIterator; import net.noderunner.xmlrpc.XmlRpcException; /** * For outputting to XmlRpc. */ public class XmlRpcOutputAdapter implements ParamIterator { ProvIterator pi; public XmlRpcOutputAdapter(ProvIterator pi) { this.pi = pi; } /** * Returns ARRAY_ITERATOR as its type. */ public int getIteratorType() { return ARRAY_ITERATOR; } public boolean hasNext() throws XmlRpcException { try { return pi.hasNext(); } catch (ProvException pe) { throw new XmlRpcException(0, "hasNext() failed", pe); } } static ParamIterator toParamIterator(Object o) throws ProvException { java.util.Map m = new java.util.HashMap(); if (o instanceof Subscriber) { Subscriber u = (Subscriber)o; m.put("object", Subscriber.class.getName()); m.put("name", u.getName()); m.put("password", u.getPassword()); } else if (o instanceof SubscriberSearch) { SubscriberSearch ss = (SubscriberSearch)o; m.put("object", SubscriberSearch.class.getName()); m.put("matchName", ss.getMatchName()); } else if (o instanceof ProvResult) { ProvResult p = (ProvResult)o; m.put("object", ProvResult.class.getName()); m.put("message", p.getMessage()); m.put("entity", toParamIterator(p.getEntity())); } else { throw new ProvException("Unknown underlying object " + o); } return new net.noderunner.xmlrpc.MapAdapter(m); } /** * Returns a MapAdapter per object. */ public Object next() throws XmlRpcException { try { Object o = pi.next(); return toParamIterator(o); } catch (ProvException pe) { throw new XmlRpcException(0, "next() failed", pe); } } public void close() throws XmlRpcException { try { pi.close(); } catch (ProvException pe) { throw new XmlRpcException(0, "close() failed", pe); } } } ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootlibexml-java-0.0.20080703.orig/xmlrpc/src/main/java/net/noderunner/xmlrpc/example/SubscriberSearch.javalibexml-java-0.0.20080703.orig/xmlrpc/src/main/java/net/noderunner/xmlrpc/example/SubscriberSearch.j0000644000175000017500000000162710762067376033021 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.xmlrpc.example; public interface SubscriberSearch extends ProvEntity { /** * @return null if not to match this */ String getMatchName(); } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootlibexml-java-0.0.20080703.orig/xmlrpc/src/main/java/net/noderunner/xmlrpc/example/IteratorAdapter.javalibexml-java-0.0.20080703.orig/xmlrpc/src/main/java/net/noderunner/xmlrpc/example/IteratorAdapter.ja0000644000175000017500000000321110762067376033012 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.xmlrpc.example; import java.util.Iterator; /** * An "Adapter" or "Wrapper", constructed over an underlying Iterator * object. This allows for the java.util package Iterator to be used. * @author Elias Ross * @version 1.0 */ public class IteratorAdapter implements ProvIterator { Iterator i; /** * Create a IteratorAdapter around an Iterator. * @param i Iterator to wrap. */ public IteratorAdapter(Iterator i) { this.i = i; } /** * Calls next() on underlying Iterator. */ public ProvEntity next() { return (ProvEntity)i.next(); } /** * Calls hasNext() on underlying Iterator. * @return true if hasNext returned true */ public boolean hasNext() { return i.hasNext(); } /** * Removes the reference to the underlying Iterator, by setting it * to null. Then, no more methods can be called on this object. */ public void close() { i = null; } } ././@LongLink0000000000000000000000000000015400000000000011565 Lustar rootrootlibexml-java-0.0.20080703.orig/xmlrpc/src/main/java/net/noderunner/xmlrpc/example/SubscriberSearchImpl.javalibexml-java-0.0.20080703.orig/xmlrpc/src/main/java/net/noderunner/xmlrpc/example/SubscriberSearchIm0000644000175000017500000000176310762067376033060 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.xmlrpc.example; public class SubscriberSearchImpl implements SubscriberSearch { String matchName; public SubscriberSearchImpl(String matchName) { this.matchName = matchName; } public String getMatchName() { return matchName; } } libexml-java-0.0.20080703.orig/xmlrpc/src/main/java/net/noderunner/xmlrpc/Invoker.java0000644000175000017500000001130310762067376030232 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.xmlrpc; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; /** * This class uses Java Reflection to call methods matching an Xml-Rpc call. * This class uses the Adapter pattern. * * @author Elias Ross * @version 1.0 */ public class Invoker implements XmlRpcHandler { private Object target; private Class targetClass; /** * For converting the method return objects into Xml-Rpc recognized types. public static interface OutputAdapter extends ParamIterator { void setParamIterator(ParamIterator i) throws InvokerException; boolean hasNext() throws InvokerException; Object next() throws InvokerException; } */ /** * For converting the method return objects into Xml-Rpc recognized types. public static interface InputAdapter { void setParamIterator(ParamIterator i) throws InvokerException; boolean hasNext() throws InvokerException; Object next() throws InvokerException; } */ /** * Construct an Invoker, wrapping an Object, adapting it for use * with XmlRpcServer. * @param target to invoke * @see XmlRpcServer */ public Invoker(Object target) { this.target = target; targetClass = target.getClass(); } /** * Sets the optional input adapter, which will translate parameters * from. public void setInputAdapter(InputAdapter a); */ /** * This method copies the first level of parameters to a * List for calling a named method on the wrapped Object. * The advantages of streaming input are lost, unfortunately, to * prepare the parameter list for execution. The results of the * invocation, if a Collection or Iterator * object, are wrapped. * * @throws InvokerException if the invocation call failed on the wrapped * object * @throws XmlRpcException if the ParamIterator failed * to iterate */ public ParamIterator execute(String methodName, ParamIterator params) throws XmlRpcException { // Need to copy params (at least first level) to List List l = null; if (params != null) { l = new ArrayList(); while (params.hasNext()) l.add(params.next()); } // Array and Classtype: Value building Class[] argClasses = null; Object[] argValues = null; if (l != null) { argClasses = new Class[l.size()]; argValues = new Object[l.size()]; for (int i = 0; i < l.size(); i++) { argValues[i] = l.get(i); if (argValues[i] instanceof Integer) argClasses[i] = Integer.TYPE; else if (argValues[i] instanceof Double) argClasses[i] = Double.TYPE; else if (argValues[i] instanceof Boolean) argClasses[i] = Boolean.TYPE; else argClasses[i] = argValues[i].getClass(); } } // Method to invoke Method method = null; try { method = targetClass.getMethod(methodName, argClasses); } catch (NoSuchMethodException nsme) { throw new InvokerException(nsme); } catch (SecurityException se) { throw new InvokerException(se); } // Call invoke Object returnValue = null; try { returnValue = method.invoke(target, argValues); } catch (IllegalAccessException iacce){ throw new InvokerException(iacce); } catch (IllegalArgumentException iarge){ throw new InvokerException(iarge); } catch (InvocationTargetException ite) { throw new InvokerException(ite.getTargetException()); } return toParamIterator(returnValue); } private ParamIterator toParamIterator(Object o) { // Try to package return as Iterator, if possible if (o instanceof ParamIterator) { return (ParamIterator)o; } else if (o instanceof Iterator) { return new IteratorAdapter((Iterator)o); } else if (o instanceof Collection) { Collection c = (Collection)o; return new IteratorAdapter(c.iterator()); } // We don't know what it is List l = new ArrayList(); l.add(o); return toParamIterator(l.iterator()); } } libexml-java-0.0.20080703.orig/xmlrpc/src/main/java/net/noderunner/xmlrpc/XmlRpcParamIterator.java0000644000175000017500000001317010762067376032521 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.xmlrpc; import java.io.IOException; import net.noderunner.exml.Element; import net.noderunner.exml.XmlException; import net.noderunner.exml.XmlParser; /** * This class provides a layer over a XmlParser object. It has methods * appropriate for reading method invocations and responses from a * data stream. * * @see XmlRpcWriter */ public class XmlRpcParamIterator implements ParamIterator, XmlRpcTags { XmlParser parser; Element startTag; // should be a tag Element current; // should be a tag int depth; // for remembering where we were... int type; XmlRpcDateFormat dateFormat; /** * Returns the data being iterated over. */ public int getIteratorType() { return type; } /** * Start this at the <params> element, or <data> * element of arrays or <struct> element for structs. * @param type one of PARAMS_ITERATOR, ARRAY_ITERATOR, or STRUCT_ITERATOR */ public XmlRpcParamIterator(XmlParser parser, int type) throws XmlRpcException { this.dateFormat = new XmlRpcDateFormat(); this.parser = parser; this.type = type; try { if (type != STRUCT_ITERATOR) { startTag = parser.startTag(); if (startTag.getName() == ELEM_FAULT.getName()) { this.type = FAULT_ITERATOR; } } depth = parser.getDepth(); } catch (XmlException xre) { // try { // close(); // } catch (XmlRpcException e) {} throw new XmlRpcException(0, "Could not parse start of parameters", xre); } catch (IOException ioe) { close(); throw new XmlRpcException(0, "Could not read parameters from stream", ioe); } } /** * Call this when located past the <params> element (or * <data> element) first. The constructor will take care * of that. * @return some sort of Object. This must be checked using * instanceOf expressions. * @see XmlRpcWriter#writeResponse(ParamIterator) */ public Object next() throws XmlRpcException { try { if (current == null) throw new XmlRpcException("Must call hasNext() first"); Object o = getObject(); current = null; return o; } catch (Exception e) { throw new XmlRpcException(0, "Error reading Xml element", e); } } public boolean hasNext() throws XmlRpcException { try { // go back to our correct tree depth parser.up(depth); current = parser.startTag(); return (current != null); } catch (Exception e) { throw new XmlRpcException(0, "Error reading Xml element", e); } } public void close() throws XmlRpcException { try { if (type == PARAMS_ITERATOR || type == FAULT_ITERATOR) { // ensure whole document is completely read try { parser.up(0); parser.skipMisc(); } catch (XmlException xre) { throw new XmlRpcException(0, "Error closing XmlParser", xre); } // Don't close the stream // parser.close(); } } catch (IOException e) { throw new XmlRpcException(0, "Error closing XmlParser", e); } } /** * Expects <value> tag to be read. Does not read * </value> tag. * @throws Exception which might be anything to do with the * parse value or input stream. We defer exception handling to the * caller. */ Object getObject() throws Exception { if (type == PARAMS_ITERATOR) parser.startTag(); Element what = parser.startTag(); String kind = what.getName(); if (kind == ELEM_STRING.getName()) { parser.getContent(); return what.getCharacterData(); } if (kind == ELEM_NAME.getName()) { parser.getContent(); String name = what.getCharacterData().trim(); parser.endTag(); parser.startTag(); return new StructPairImpl(name, getObject()); } if (kind == ELEM_NIL.getName()) { parser.emptyContent(); return null; } if (kind == ELEM_INT.getName()) { parser.getContent(); return new Integer(what.getCharacterData().trim()); } if (kind == ELEM_BOOLEAN.getName()) { parser.getContent(); return new Boolean(what.getCharacterData().trim().equals("1")); } if (kind == ELEM_DOUBLE.getName()) { parser.getContent(); return new Double(what.getCharacterData().trim()); } if (kind == ELEM_DATE.getName()) { parser.getContent(); String dateString = what.getCharacterData().trim(); return dateFormat.parse(dateString); } if (kind == ELEM_BASE64.getName()) { parser.getContent(); char [] stuff = what.getCharacterData().trim().toCharArray(); return Base64.getInstance().decode(stuff); } if (kind == ELEM_ARRAY.getName()) { XmlRpcParamIterator pi = new XmlRpcParamIterator(parser, ARRAY_ITERATOR); return pi; } if (kind == ELEM_STRUCT.getName()) { XmlRpcParamIterator pi = new XmlRpcParamIterator(parser, STRUCT_ITERATOR); return pi; } throw new XmlRpcException("Unknown element type '" + kind + "'"); } public String toString() { return "XmlRpcParamIterator [parser=" + parser + " startTag="+startTag + " current="+current + " depth="+depth + "]"; } } libexml-java-0.0.20080703.orig/xmlrpc/src/main/java/net/noderunner/xmlrpc/Base64Exception.java0000644000175000017500000000223410762067376031523 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.xmlrpc; /** * Exception for the Base64 encoding and decoding class. * * @author Elias Ross * @version 1.0 */ class Base64Exception extends Exception { /** * */ private static final long serialVersionUID = 5906136353186462557L; /** * Create a new Base64Exception with a message. * @param message message to display. */ public Base64Exception(String message) { super(message); } } libexml-java-0.0.20080703.orig/xmlrpc/src/main/java/net/noderunner/xmlrpc/XmlRpcHandler.java0000644000175000017500000000314010762067376031320 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.xmlrpc; /** * The Xml-Rpc server uses this interface to call a method of an Rpc * handler. This should be implemented by any class that wants to * directly take control when it is called over Rpc. Classes not * implementing this interface will be wrapped into an Invoker object * that tries to find the matching method for an Xml-Rpc request. *

    * @author Elias Ross * @version 1.0 * @see Invoker Using Invoker to wrap an existing object */ public interface XmlRpcHandler { /** * Handle a Xml-Rpc request. * @param method Method name * @param params Iterator over the parameters * @return parameter(s) to return * @throws XmlRpcException with Xml-Rpc specific exception, or a * wrapped exception */ ParamIterator execute(String method, ParamIterator params) throws XmlRpcException; } libexml-java-0.0.20080703.orig/xmlrpc/src/main/java/net/noderunner/xmlrpc/XmlRpcClient.java0000644000175000017500000000434310762067376031167 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.xmlrpc; /** * This interface is used for calling methods on a Xml-Rpc server. * * @author Elias Ross * @version 1.0 */ public interface XmlRpcClient extends XmlRpcHandler { /** * Set the Xml-Rpc URL to connect to. This server should support * HTTP/1.1 to handle chunked output. This must be called before a * request is made, using execute. */ void setServerURL(java.net.URL url); /** * Generate an Xml-Rpc request and send it to the server. This * method parses the results and return the corresponding Java object. * If setBasicAuthentication was called, it sends this * header. *

    * Any sort of IO exception should be be wrapped in an * XmlRpcException, but it may be useful to trap for just an IO * failure conditions. Use the getCause method for * finding out the specific problem. *

    * @param method This is the method to execute on the remote server. * For Xml-Rpc, this should be in the form handler.method. * @param params This will be closed by this method caller. It * will be closed, even on exceptions being thrown. * @exception XmlRpcException If the call could not be made because of * higher level problems, which may result from a ParamIterator * failure. * @return ParamIterator, which contains the return parameter list. * This must be closed by the caller when done. */ ParamIterator execute(String method, ParamIterator params) throws XmlRpcException; } libexml-java-0.0.20080703.orig/xmlrpc/src/main/java/net/noderunner/xmlrpc/XmlRpcReaderImpl.java0000644000175000017500000001303110762067376031767 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.xmlrpc; import java.io.IOException; import java.io.Reader; import net.noderunner.exml.Dtd; import net.noderunner.exml.Element; import net.noderunner.exml.NullReader; import net.noderunner.exml.XmlException; import net.noderunner.exml.XmlParser; import net.noderunner.exml.XmlReader; /** * This class provides a layer over a XmlParser object to read XML-RPC * data. * * @author Elias Ross * @version 1.0 * @see XmlRpcWriter */ public class XmlRpcReaderImpl implements XmlRpcReader, XmlRpcTags { /** Underlying reader object. */ private XmlParser parser; /** Dtd for reading XmlRpc. */ private static final Dtd dtd = makeDtd(); /** * Construct a dummy XmlRpcReaderImpl. */ public XmlRpcReaderImpl() { this(NullReader.getInstance()); } /** * Construct an XmlRpcReader object over a Reader. * Also, adds in the DTD to the underlying XmlReader object. * @param reader reader to wrap */ public XmlRpcReaderImpl(Reader r) { XmlReader xr = new XmlReader(r, dtd); this.parser = new XmlParser(xr); } public void setReader(Reader reader) { parser.setReader(reader); /* try { parser.startTag(); Element content = parser.getContent(); System.out.println(content); } catch (IOException e) { throw new RuntimeException(e); } catch (XmlException e) { throw new RuntimeException(e); } */ } public ParamIterator readMethodResponse() throws XmlRpcException { try { parser.skipProlog(); Element e; e = parser.startTag(); if (e == null || e.getName() != ELEM_METHOD_RESPONSE.getName()) { throw new XmlRpcException("Expected " + ELEM_METHOD_RESPONSE + ", got " + e); } } catch (XmlException xre) { throw new XmlRpcException(0, "Xml could not be parsed", xre); } catch (IOException ioe) { throw new XmlRpcException(0, "Xml could not be read", ioe); } return readMethodRequest(); } public String readMethodName() throws XmlRpcException { try { parser.skipProlog(); Element e; e = parser.startTag(); if (e.getName() != ELEM_METHOD_CALL.getName()) { throw new XmlRpcException("Expected " + ELEM_METHOD_CALL + ", got " + e); } e = parser.startTag(); if (e.getName() != ELEM_METHOD_NAME.getName()) { throw new XmlRpcException("Expected " + ELEM_METHOD_NAME + ", got " + e); } String methodName = parser.getContent().getCharacterData(); if (methodName.length() == 0) { throw new XmlRpcException(ELEM_METHOD_NAME + " has no length, got " + e); } parser.endTag(); return methodName; } catch (XmlException xre) { throw new XmlRpcException(0, "Xml could not be parsed", xre); } catch (IOException ioe) { throw new XmlRpcException(0, "Xml could not be read", ioe); } } public ParamIterator readMethodRequest() throws XmlRpcException { return new XmlRpcParamIterator(parser, ParamIterator.PARAMS_ITERATOR); } /** * This was taken and edited from the location * http://www.ontosys.com/xml-rpc/xml-rpc.dtd. * Note that, for now, the document element name is not * methodCall or methodResponse, it is instead xmlrpc. */ private static Dtd makeDtd() { String dtdString = "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "]>"; XmlReader r = new XmlReader(); r.setReadString(dtdString); // Populates the string pool java.util.Collection c = r.getStringPool(); c.add(ELEM_METHOD_CALL.getName()); c.add(ELEM_METHOD_RESPONSE.getName()); c.add(ELEM_FAULT.getName()); c.add(ELEM_METHOD_NAME.getName()); c.add(ELEM_PARAMS.getName()); c.add(ELEM_PARAM.getName()); c.add(ELEM_STRING.getName()); c.add(ELEM_INT.getName()); c.add(ELEM_BOOLEAN.getName()); c.add(ELEM_DOUBLE.getName()); c.add(ELEM_DATE.getName()); c.add(ELEM_BASE64.getName()); c.add(ELEM_NIL.getName()); c.add(ELEM_VALUE.getName()); c.add(ELEM_ARRAY.getName()); c.add(ELEM_DATA.getName()); c.add(ELEM_STRUCT.getName()); c.add(ELEM_MEMBER.getName()); c.add(ELEM_NAME.getName()); try { r.doctypedecl(); } catch (Exception e) { throw new RuntimeException("IOException", e); } return r.getDtd(); } } libexml-java-0.0.20080703.orig/xmlrpc/src/main/java/net/noderunner/xmlrpc/ParamIterator.java0000644000175000017500000000575310762067376031403 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.xmlrpc; /** * Iterates over the parameters passed in (or out) of a call. * These are used in this Xml-Rpc package for input and output. * * @author Elias Ross * @version 1.0 * @see IteratorAdapter How to wrap an existing Iterator * @see MapAdapter How to wrap an existing Map * @see XmlRpcHandler An example of how it is being used for input * and output. */ public interface ParamIterator { /** * This indicates a top-level ParamIterator, used for iterating over * the top-level <param> tags. */ int PARAMS_ITERATOR = 1; /** * This is indicates a secondary or deeper <array> is being * iterated over. */ int ARRAY_ITERATOR = 2; /** * This is indicates a secondary or deeper <struct> is being * iterated over. next() should return a StructPair. */ int STRUCT_ITERATOR = 3; /** * This is indicates parameters are being supplied from a * <fault> result. */ int FAULT_ITERATOR = 4; /** * The iterator type is used for hinting the kinds of data to * expect from the next() call. This is used primarily for * clarifying the Xml-Rpc to Java datatype conversion upon data * input, however, it is also useful for passing data out. In * the case of passing out structures, it makes it clear to * format input data as a structure not an array. */ int getIteratorType(); /** * This will return a basic java type, or possibly another * ParamIterator. Iterators returned in this way affect the * underlying input/output stream. * @see XmlRpcParamIterator#next() * @see XmlRpcWriter#writeResponse(ParamIterator) * @return next parameter * @throws XmlRpcException if there is some problem retreiving the next * parameter. */ Object next() throws XmlRpcException; /** * @return true if an additional object is available for reading. * @throws XmlRpcException if there is some problem checking for the next * parameter from the stream. */ boolean hasNext() throws XmlRpcException; /** * This method closes underlying input/output stream. * Calling close() is required, since it will release underlying * resources. * @throws XmlRpcException if the close operation could not be * completed. */ void close() throws XmlRpcException; } libexml-java-0.0.20080703.orig/xmlrpc/src/main/java/net/noderunner/xmlrpc/XmlRpcDateFormat.java0000644000175000017500000000207710762067376032001 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.xmlrpc; import java.text.SimpleDateFormat; /** * Contains methods to parse and format XML-RPC dates. */ public class XmlRpcDateFormat extends SimpleDateFormat { /** * */ private static final long serialVersionUID = 7817973356513962588L; public XmlRpcDateFormat() { super("yyyyMMdd'T'HH:mm:ss"); } } libexml-java-0.0.20080703.orig/xmlrpc/src/main/java/net/noderunner/xmlrpc/package.html0000644000175000017500000000134707477076020030235 0ustar twernertwerner

    Provides classes for XML-RPC reading and writing, as well as a server and client implementation.

    There are no suitable alternatives at this time for reading XML as a stream.

    Package Specification

    Related Documentation

    For overviews, tutorials, examples, guides, and tool documentation, please see:
    • xmlrpc.com has the specification for this standard.
    libexml-java-0.0.20080703.orig/xmlrpc/src/main/java/net/noderunner/xmlrpc/XmlRpcServerImpl.java0000644000175000017500000000552210762067376032041 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.xmlrpc; import java.io.Reader; import java.io.Writer; import java.util.HashMap; import java.util.Map; /** * This class defines a concrete XmlRpcServer. */ public class XmlRpcServerImpl implements XmlRpcServer { /** * Registered handlers. */ private Map handlers; private XmlRpcReader reader; private XmlRpcWriter writer; /** * Construct a new Xml-Rpc server. */ public XmlRpcServerImpl() { handlers = new HashMap(); reader = new XmlRpcReaderImpl(); writer = new XmlRpcWriterImpl(); } public void addHandler(String handlerName, XmlRpcHandler handler) { handlers.put(handlerName, handler); } public void removeHandler(String handlerName) { handlers.remove(handlerName); } /** * Shows debug information. */ public String toString() { return "XmlRpcServerImpl [handlers=" + handlers + "]"; } public void accept(Reader in, Writer out) throws XmlRpcException { reader.setReader(in); String methodName = reader.readMethodName(); // find a handler by name XmlRpcHandler handler = null; int dot = methodName.indexOf("."); if (dot > -1) { String handlerName = methodName.substring(0, dot); handler = (XmlRpcHandler)handlers.get(handlerName); methodName = methodName.substring(dot+1); } if (handler == null) { handler = (XmlRpcHandler)handlers.get(DEFAULT_HANDLER); } if (handler == null) { throw new NoHandlerException("Rpc handler object not found for \""+methodName+"\": no default handler registered."); } writer.setWriter(out); ParamIterator inParam = null; ParamIterator outParam = null; try { inParam = reader.readMethodRequest(); outParam = handler.execute(methodName, inParam); // This ensures that inParam is completely read and valid. // Otherwise, we would assume the rest of the Xml has valid // closing tags. inParam.close(); writer.writeResponse(outParam); } catch (XmlRpcException xre) { xre.printStackTrace(); writer.writeError(xre); } finally { // This insures that the outParam resources will be // released. if (outParam != null) outParam.close(); } } } libexml-java-0.0.20080703.orig/xmlrpc/src/main/java/net/noderunner/xmlrpc/MapAdapter.java0000644000175000017500000000566510762067376030651 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.xmlrpc; import java.util.Iterator; import java.util.Map; /** * An "Adapter" or "Wrapper", constructed over an underlying Map * object. This allows for the java.util package Map to be used. * If exceptions should be thrown, it is best to create a different * wrapper implementation that throws wrapped exceptions. * @author Elias Ross * @version 1.0 */ public class MapAdapter implements ParamIterator { Map map; Iterator i; /** * Create a MapAdapter around an Map. * @param i Iterator to wrap. */ public MapAdapter(Map map) { this.map = map; i = map.keySet().iterator(); } /** * Returns STRUCT_ITERATOR as its type. */ public int getIteratorType() { return STRUCT_ITERATOR; } /** * Calls next() on underlying key iterator for the Map. * @return a StructPair object * @throws XmlRpcException if the current key is not a String object */ public Object next() throws XmlRpcException { Object o = i.next(); if (!(o instanceof String)) throw new XmlRpcException("Expected a String object, not " + o); return new StructPairImpl((String)o, map.get(o)); } /** * Calls hasNext() on underlying Iterator. * @return true if hasNext returned true */ public boolean hasNext() { return i.hasNext(); } /** * Removes the reference to the underlying Iterator, by setting it * to null. Then, no more methods can be called on this object. */ public void close() { i = null; } /** * Creates a Map object out of a ParamIterator. This method works * only if the ParamIterator is a STRUCT_ITERATOR. */ public static Map toMap(ParamIterator pi) throws XmlRpcException { Map m = new java.util.HashMap(); while (pi.hasNext()) { Object o = pi.next(); if (o instanceof StructPair) { StructPair sp = (StructPair)o; Object value = sp.getValue(); if (value instanceof ParamIterator) { ParamIterator sub = (ParamIterator)value; if (sub.getIteratorType() == STRUCT_ITERATOR) { value = MapAdapter.toMap(sub); } else if (sub.getIteratorType() == ARRAY_ITERATOR) { value = IteratorAdapter.toList(sub); } } m.put(sp.getName(), value); } } pi.close(); return m; } } libexml-java-0.0.20080703.orig/xmlrpc/src/main/java/net/noderunner/xmlrpc/StructPairImpl.java0000644000175000017500000000301410762067376031537 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.xmlrpc; /** * This class holds a Xml-Rpc struct object. * * @author Elias Ross * @version 1.0 */ public class StructPairImpl implements StructPair { String name; Object value; /** * Construct a StructPairImpl object with a name and value. * @param name name belonging to this struct member * @param value value belonging to this struct member. May be of * any Xml-Rpc type, or possibly a ParamIterator. */ public StructPairImpl(String name, Object value) { this.name = name; this.value = value; } public String getName() { return name; } public Object getValue() { return value; } /** * Returns a string for viewing its contents. * @return a string */ public String toString() { return "name=" + name + " value=" + value; } } libexml-java-0.0.20080703.orig/xmlrpc/src/main/java/net/noderunner/xmlrpc/XmlRpcException.java0000644000175000017500000000366410762067376031714 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.xmlrpc; /** * This is thrown on various errors. This exception may contain a * wrapped Throwable object. *

    * @author Elias Ross * @version 1.0 */ public class XmlRpcException extends Exception { private static final long serialVersionUID = 3881836903351454422L; /** * The fault code of the exception. For servers based on this * library, this will always be 0. (If there are predefined error * codes, they should be in the Xml-Rpc spec.) */ int code; /** * Root cause. */ Throwable cause; /** * Construct an XmlRpcException with a message. * @param message message to display. */ public XmlRpcException(String message) { super(message); this.code = 0; } /** * Construct an XmlRpcException with a message and code and wrapped * Throwable. * @param message message to display. * @param code this should be zero, unless a standard code was assigned * @param cause reason for this XmlRpcException */ public XmlRpcException(int code, String message, Throwable cause) { super(message, cause); this.code = code; } /** * Gets the code of this exception, if any. * @return code */ public int getCode() { return code; } } libexml-java-0.0.20080703.orig/xmlrpc/src/main/java/net/noderunner/xmlrpc/Base64.java0000644000175000017500000001013010762067376027636 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.xmlrpc; /** * Provides encoding of raw bytes to base64-encoded characters, and * decoding of base64 characters to raw bytes. *

    * This class is implemented as a singleton. There is no storage in * this class, so it is thread-safe. * * @author Elias Ross * @version 1.0 */ class Base64 { static Base64 base64 = new Base64(); /** * Code characters for values 0 to 63. */ static final char[] alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=" .toCharArray(); /** * Fast lookup table for converting to 0 to 63. */ static final byte[] codes = new byte[256]; static { for (int i = 0; i < 256; i++) codes[i] = -1; for (int i = 'A'; i <= 'Z'; i++) codes[i] = (byte)(i - 'A'); for (int i = 'a'; i <= 'z'; i++) codes[i] = (byte)(26 + i - 'a'); for (int i = '0'; i <= '9'; i++) codes[i] = (byte)(52 + i - '0'); codes['+'] = 62; codes['/'] = 63; } protected Base64() { } public static Base64 getInstance() { return base64; } /** * Returns an array of base64-encoded characters to represent the * passed data array. * * @param data the array of bytes to encode * @return base64-coded character array. */ public char[] encode(byte[] data) { char[] out = new char[((data.length + 2) / 3) * 4]; // // 3 bytes encode to 4 chars. Output is always an even // multiple of 4 characters. // for (int i = 0, index = 0; i < data.length; i += 3, index += 4) { boolean quad = false; boolean trip = false; int val = (0xFF & data[i]); val <<= 8; if ((i + 1) < data.length) { val |= (0xFF & data[i + 1]); trip = true; } val <<= 8; if ((i + 2) < data.length) { val |= (0xFF & data[i + 2]); quad = true; } out[index + 3] = alphabet[(quad ? (val & 0x3F) : 64)]; val >>= 6; out[index + 2] = alphabet[(trip ? (val & 0x3F) : 64)]; val >>= 6; out[index + 1] = alphabet[val & 0x3F]; val >>= 6; out[index + 0] = alphabet[val & 0x3F]; } return out; } /** * Returns an array of bytes which were encoded in the passed * character array. * * @param data the array of base64-encoded characters, no whitespace * allowed. * @return decoded data array * @throws Base64Exception if the array-size was miscalculated, * perhaps due to invalid characters read on input. */ public byte[] decode(char[] data) throws Base64Exception { int len = ((data.length + 3) / 4) * 3; if (data.length > 0 && data[data.length - 1] == '=') --len; if (data.length > 1 && data[data.length - 2] == '=') --len; byte[] out = new byte[len]; int shift = 0; // # of excess bits stored in accum int accum = 0; // excess bits int index = 0; for (int ix = 0; ix < data.length; ix++) { int value = codes[data[ix] & 0xFF]; // ignore high byte of char if (value >= 0) { // skip over non-code accum <<= 6; // bits shift up by 6 each time thru shift += 6; // loop, with new bits being put in accum |= value; // at the bottom. if (shift >= 8) { // whenever there are 8 or more shifted in, shift -= 8; // write them out (from the top, leaving any // excess at the bottom for next iteration. out[index++] = (byte)((accum >> shift) & 0xff); } } } if (index != out.length) throw new Base64Exception("Error decoding BASE64 element: miscalculated data length!"); return out; } } libexml-java-0.0.20080703.orig/xmlrpc/src/main/java/net/noderunner/xmlrpc/XmlRpcTags.java0000644000175000017500000000364610762067376030654 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.xmlrpc; import net.noderunner.exml.Element; /** * This interface contains all the element tags used in Xml-Rpc calls. * * @author Elias Ross * @version 1.0 */ interface XmlRpcTags { Element ELEM_METHOD_RESPONSE = new Element("methodResponse"); Element ELEM_METHOD_CALL = new Element("methodCall"); Element ELEM_METHOD_NAME = new Element("methodName"); Element ELEM_FAULT = new Element("fault"); String FAULT_CODE = "faultCode"; String FAULT_STRING = "faultString"; Element ELEM_PARAMS = new Element("params"); Element ELEM_PARAM = new Element("param"); Element ELEM_VALUE = new Element("value"); // encoded values Element ELEM_NIL = new Element("nil", null, false); Element ELEM_STRING = new Element("string"); Element ELEM_INT = new Element("int"); Element ELEM_BOOLEAN = new Element("boolean"); Element ELEM_DOUBLE = new Element("double"); Element ELEM_DATE = new Element("dateTime.iso8601"); Element ELEM_BASE64 = new Element("base64"); Element ELEM_ARRAY = new Element("array"); Element ELEM_DATA = new Element("data"); Element ELEM_STRUCT = new Element("struct"); Element ELEM_MEMBER = new Element("member"); Element ELEM_NAME = new Element("name"); } libexml-java-0.0.20080703.orig/xmlrpc/src/main/java/net/noderunner/xmlrpc/XmlRpcWriterImpl.java0000644000175000017500000001475110762067376032053 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.xmlrpc; import java.io.IOException; import java.io.Writer; import java.util.Collection; import java.util.Date; import java.util.Enumeration; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import net.noderunner.exml.NullWriter; import net.noderunner.exml.XmlWriter; /** * This class provides basic capabilities for writing * data to an Xml-Rpc server or client. Output is automatically * flushed when completely written out. * * @see XmlRpcReader */ public class XmlRpcWriterImpl implements XmlRpcWriter, XmlRpcTags { /** * Wrapper around "Writer" class */ XmlWriter writer; /** * Date formatter. */ XmlRpcDateFormat dateFormat; /** * Construct a dummy XmlRpcWriterImpl. */ public XmlRpcWriterImpl() { this(NullWriter.getInstance()); } /** * Construct a XmlRpcWriterImpl which will wrap a Writer output stream. * Should be a buffered stream for better performance. */ public XmlRpcWriterImpl(Writer w) { this.writer = new XmlWriter(w); this.dateFormat = new XmlRpcDateFormat(); } /** * Sets the writer to output with. * @param writer writer to wrap */ public void setWriter(Writer writer) { this.writer.setWriter(writer); } public void writeRequest(String method, ParamIterator i) throws XmlRpcException { try { writer.startElement(ELEM_METHOD_CALL); writer.startElement(ELEM_METHOD_NAME); writer.write(method); writer.endElement(); writer.startElement(ELEM_PARAMS); while (i.hasNext()) { writer.startElement(ELEM_PARAM); writeObject(i.next()); writer.endElement(); } doneWriting(); } catch (IOException ioe) { throw new XmlRpcException(0, "Could not writeRequest " + method + " " + i, ioe); } } private void doneWriting() throws IOException { writer.up(0); writer.write("\r\n"); writer.flush(); } public void writeResponse(ParamIterator i) throws XmlRpcException { try { writer.startElement(ELEM_METHOD_RESPONSE); if (i != null) { writer.startElement(ELEM_PARAMS); while (i.hasNext()) { writer.startElement(ELEM_PARAM); writeObject(i.next()); writer.endElement(); } writer.endElement(); } doneWriting(); } catch (IOException ioe) { throw new XmlRpcException(0, "Could not writeResponse " + i, ioe); } } public void writeError(XmlRpcException xre) throws XmlRpcException { try { HashMap h = new HashMap(); h.put(FAULT_CODE, new Integer(xre.getCode())); h.put(FAULT_STRING, xre.getMessage()); // anything else is not Xml-Rpc compliant // h.put("faultException", xre.getCause().toString()); writer.startElement(ELEM_METHOD_RESPONSE); writer.startElement(ELEM_FAULT); writeObject(h); doneWriting(); } catch (IOException ioe) { throw new XmlRpcException(0, "Could not writeError " + xre, ioe); } } /** * Writes the Xml-Rpc representation of a supported Java object to * the Xml writer. * @see ParamIterator * @throws XmlRpcException if a ParamIterator was passed in and a * call failed; an unknown object type was found * @throws IOException if an error occured writing with XmlWriter */ void writeObject(Object what) throws IOException, XmlRpcException { // don't want the start and end value tags for these objects if (what instanceof Collection) { Collection c = (Collection) what; writeObject(c.iterator()); return; } if (what instanceof Map) { writeObject(new MapAdapter((Map)what)); return; } if (what instanceof Iterator) { writeObject(new IteratorAdapter((Iterator)what)); return; } if (what instanceof StructPair) { writer.startElement(ELEM_MEMBER); writer.startElement(ELEM_NAME); StructPair sp = (StructPair)what; writer.write(sp.getName()); writer.endElement(); writeObject(sp.getValue()); writer.endElement(); return; } writer.startElement(ELEM_VALUE); if (what == null) { writer.emptyElement (ELEM_NIL); } else if (what instanceof String) { writer.startElement(ELEM_STRING); writer.writeCData(what.toString()); writer.endElement(); } else if (what instanceof Integer) { writer.startElement(ELEM_INT); writer.write(what.toString()); writer.endElement(); } else if (what instanceof Boolean) { writer.startElement(ELEM_BOOLEAN); writer.write(((Boolean) what).booleanValue () ? "1" : "0"); writer.endElement(); } else if (what instanceof Double || what instanceof Float) { writer.startElement(ELEM_DOUBLE); writer.write(what.toString()); writer.endElement(); } else if (what instanceof Date) { writer.startElement(ELEM_DATE); Date d = (Date) what; writer.write(dateFormat.format(d)); writer.endElement(); } else if (what instanceof byte[]) { writer.startElement(ELEM_BASE64); writer.write(Base64.getInstance().encode((byte[]) what)); writer.endElement(); } else if (what instanceof ParamIterator) { ParamIterator i = (ParamIterator) what; int type = i.getIteratorType(); if (type == ParamIterator.PARAMS_ITERATOR || type == ParamIterator.ARRAY_ITERATOR) { writer.startElement(ELEM_ARRAY); writer.startElement(ELEM_DATA); while (i.hasNext()) writeObject(i.next()); writer.endElement(); writer.endElement(); } else if (type == ParamIterator.STRUCT_ITERATOR) { writer.startElement(ELEM_STRUCT); while (i.hasNext()) writeObject(i.next()); writer.endElement(); } } else if (what instanceof Enumeration) { writer.startElement(ELEM_ARRAY); writer.startElement(ELEM_DATA); Enumeration e = (Enumeration) what; while (e.hasMoreElements()) writeObject(e.nextElement()); writer.endElement(); writer.endElement(); } else { throw new XmlRpcException("Unsupported Java type: " + what.getClass()); } writer.endElement(); } } libexml-java-0.0.20080703.orig/xmlrpc/src/main/java/net/noderunner/xmlrpc/XmlRpcClientImpl.java0000644000175000017500000001376310762067376032017 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.xmlrpc; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.StringWriter; import java.net.URL; import java.util.Vector; import net.noderunner.http.ChunkedOutputStream; import net.noderunner.http.ClientRequest; import net.noderunner.http.ClientResponse; import net.noderunner.http.HttpClient; import net.noderunner.http.HttpException; import net.noderunner.http.HttpUtil; import net.noderunner.http.MessageHeader; import net.noderunner.http.MessageHeaders; import net.noderunner.http.Method; import net.noderunner.http.RequestLine; import net.noderunner.http.RetryHttpClient; /** * This is the implementation of XmlRpcClient. Use one instance per thread. It * does not use the URLConnection class, which does not support chunking. It * does support HTTP keep-alive. */ public class XmlRpcClientImpl implements XmlRpcClient { private URL url; private String encoding = "UTF-8"; // this is re-used per send private XmlRpcReader reader; // this is re-used per send private XmlRpcHttpClient httpClient; /** * Constructs a new Xml-Rpc client. */ public XmlRpcClientImpl() { reader = new XmlRpcReaderImpl(); } public void setServerURL(URL url) { this.url = url; } /* * public void setBasicAuthentication(String user, String password) { char[] * basicAuth = Base64.getInstance().encode((user+":"+password).getBytes()); * auth = new String (basicAuth).trim(); } */ private static class XmlRpcHttpClient { HttpClient client; RequestLine requestLine; MessageHeaders headers; ChunkedOutputStream cos; public XmlRpcHttpClient(URL url) { this.client = new RetryHttpClient(url); requestLine = RequestLine.create(url, Method.POST); headers = MessageHeaders.defaultHeaders(url); headers.add(MessageHeader.MH_TRANSFER_ENCODING_CHUNKED); headers.add(MessageHeader.FN_CONTENT_TYPE, "text/xml"); } public void writeRequest() throws IOException { client.writeRequest(new ClientRequest(requestLine, headers)); } public OutputStream getOutputStream() { cos = new ChunkedOutputStream(client.getOutputStream()); return cos; } public InputStream readResponse() throws IOException { cos.doneOutput(); ClientResponse r = client.readResponse(); if (r.getStatusLine().getStatusCode() != 200) throw new HttpException("Bad HTTP Status, expected 200 OK " + r); MessageHeaders hl = r.getHeaders(); return HttpUtil.wrapInputStream(r.getInputStream(), hl); } } /** * This does not use URLConnection, but instead uses raw sockets. * Apparently, URLConnection does not support sending chunked data, which is * needed for streaming Xml support. The server must support * HTTP/1.1, but even without a streaming response, this * implementation will still function correctly. *

    * Note that this implementation does not support HTTP redirects or possibly * proxy servers as well. The supplied ParamIterator will be * closed regardless of any exceptions. *

    */ public ParamIterator execute(String method, ParamIterator params) throws XmlRpcException { if (httpClient == null) httpClient = new XmlRpcHttpClient(url); try { httpClient.writeRequest(); OutputStream out = httpClient.getOutputStream(); OutputStreamWriter outw = new OutputStreamWriter(out, encoding); XmlRpcWriter writer = new XmlRpcWriterImpl(outw); writer.writeRequest(method, params); } catch (IOException ioe) { throw new XmlRpcException(0, "IOException sending HTTP request", ioe); } finally { params.close(); } try { InputStream in = httpClient.readResponse(); reader.setReader(new InputStreamReader(in)); ParamIterator i = reader.readMethodResponse(); return i; } catch (IOException ioe) { throw new XmlRpcException(0, "IOException reading HTTP response", ioe); } } private static void iterate(ParamIterator pi) throws XmlRpcException { while (pi.hasNext()) { Object o = pi.next(); System.out.println("Parameter: " + o); if (o instanceof ParamIterator) { iterate((ParamIterator) o); } } } /** * Tests the XmlRpcClientImpl class by connecting to a server. */ public static void main(String[] args) throws Exception { if (args.length < 2) { System.err .println("Usage: net.noderunner.xmlrpc.XmlRpcClientImpl URL method.sub"); return; } // create client and message XmlRpcClient client = new XmlRpcClientImpl(); client.setServerURL(new java.net.URL(args[0])); String method = args[1]; ParamIterator pia; Vector v = new Vector(); for (int i = 2; i < args.length; i++) { try { v.add(Integer.valueOf(args[i])); } catch (NumberFormatException nfe) { v.add(args[i]); } } pia = new IteratorAdapter(v.iterator()); // format message StringWriter out = new StringWriter(); XmlRpcWriter writer = new XmlRpcWriterImpl(out); writer.writeRequest(method, pia); // print message System.out.println("Client will write this message:"); System.out.println(out); System.out.println(); // do actual call pia = new IteratorAdapter(v.iterator()); ParamIterator result = client.execute(method, pia); System.out.println("Got result:"); iterate(result); System.out.println(); result.close(); } } libexml-java-0.0.20080703.orig/xmlrpc/src/main/java/net/noderunner/xmlrpc/XmlRpcReader.java0000644000175000017500000000530010762067376031145 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.xmlrpc; import java.io.Reader; /** * This interfaces describes methods used for reading method invocations * and responses from a XML-RPC data stream. *

    * The users of this interface, when returning a ParamIterator, * must be careful that its next only returns objects of expected * classes. *

    *

    * The Objects returned might consist of instances of these types: *

      *
    • java.lang.String
    • *
    • java.lang.Integer
    • *
    • java.lang.Boolean
    • *
    • java.lang.Double
    • *
    • java.util.Date
    • *
    • byte[]
    • *
    • net.noderunner.xmlrpc.ParamIterator
    • *
    • null (Null value)
    • *
    *

    * * @author Elias Ross * @version 1.0 * @see XmlRpcWriter */ public interface XmlRpcReader { /** * This is the first method to call after receiving a method call * on the server. * * @return method name to invoke * @throws XmlRpcException if the method name could not be parsed */ String readMethodName() throws XmlRpcException; /** * This returns an iterator used for reading the Xml-Rpc response data * sent by the XML-RPC server. * * @return response parameters readable by an iterator * @throws XmlRpcException if the method response could not be parsed */ ParamIterator readMethodResponse() throws XmlRpcException; /** * This returns an iterator used for reading the XML-RPC request data * received by the XML-RPC server. * It may be required that {@link #readMethodName} be * called before this method is invoked. * * @throws XmlRpcException if the method response could not be parsed */ ParamIterator readMethodRequest() throws XmlRpcException; /** * Sets the input stream (reader) to be used. This allows the * reader to be re-used without having to re-construct it. */ void setReader(Reader reader); } libexml-java-0.0.20080703.orig/xmlrpc/src/main/java/net/noderunner/xmlrpc/NoHandlerException.java0000644000175000017500000000233510762067376032353 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.xmlrpc; /** * This exception is returned if a XmlRpcHandler was not found. * * @author Elias Ross * @version 1.0 * @see XmlRpcHandler */ public class NoHandlerException extends XmlRpcException { /** * */ private static final long serialVersionUID = 5064087626776330631L; /** * Construct a NoHandlerException with a message. * @param message explaination. */ public NoHandlerException(String message) { super(message); } } libexml-java-0.0.20080703.orig/xmlrpc/src/main/java/net/noderunner/xmlrpc/IteratorAdapter.java0000644000175000017500000000513510762067376031715 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.xmlrpc; import java.util.Iterator; import java.util.List; /** * An "Adapter" or "Wrapper", constructed over an underlying Iterator * object. This allows for the java.util package Iterator to be used. * If exceptions should be thrown, it is best to create a different * wrapper implementation that throws wrapped exceptions. * * @author Elias Ross * @version 1.0 */ public class IteratorAdapter implements ParamIterator { private Iterator i; /** * Returns ARRAY_ITERATOR, indicating an array is being * wrapped. */ public int getIteratorType() { return ARRAY_ITERATOR; } /** * Create a IteratorAdapter around an Iterator. * @param i Iterator to wrap. */ public IteratorAdapter(Iterator i) { if (i == null) throw new IllegalArgumentException("Null Iterator"); this.i = i; } /** * Calls next() on underlying Iterator. */ public Object next() { return i.next(); } /** * Calls hasNext() on underlying Iterator. * @return true if hasNext returned true */ public boolean hasNext() { return i.hasNext(); } /** * Removes the reference to the underlying Iterator, by setting it * to null. Then, no more methods can be called on this object. */ public void close() { i = null; } /** * Creates a List object out of a ParamIterator. This method works * only if the ParamIterator is a ARRAY_ITERATOR. */ public static List toList(ParamIterator pi) throws XmlRpcException { List al = new java.util.ArrayList(); while (pi.hasNext()) { Object o = pi.next(); if (o instanceof ParamIterator) { ParamIterator sub = (ParamIterator)o; if (sub.getIteratorType() == ARRAY_ITERATOR) { o = IteratorAdapter.toList(sub); } else if (sub.getIteratorType() == STRUCT_ITERATOR) { o = MapAdapter.toMap(sub); } } al.add(o); } return al; } } libexml-java-0.0.20080703.orig/xmlrpc/src/main/java/net/noderunner/xmlrpc/InvokerException.java0000644000175000017500000000241310762067376032113 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.xmlrpc; /** * This exception is returned if a call on an Invoker failed. * This will contain the thrown exception of the invoked method. * * @author Elias Ross * @version 1.0 */ public class InvokerException extends XmlRpcException { /** * */ private static final long serialVersionUID = -340413137044228628L; /** * Create an InvokerException which contains a Throwable object as * its cause. */ public InvokerException(Throwable t) { super(0, t.getMessage(), t); } } libexml-java-0.0.20080703.orig/xmlrpc/src/main/java/net/noderunner/xmlrpc/XmlRpcServer.java0000644000175000017500000000512010762067376031211 0ustar twernertwerner/* * E-XML Library: For XML, XML-RPC, HTTP, and related. * Copyright (C) 2002-2008 Elias Ross * * genman@noderunner.net * http://noderunner.net/~genman * * 1025 NE 73RD ST * SEATTLE WA 98115 * USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * $Id$ */ package net.noderunner.xmlrpc; import java.io.Reader; import java.io.Writer; /** * This interfaces defines how an XmlRpcServer should handle reading * the method name from a socket and invoking it with a ParamIterator. * Register handlers to make it do something useful. The implementation * should be thread-safe, meaning that multiple threads can call any * method and not create a race-condition. */ public interface XmlRpcServer { /** * This constant is used to register a default handler. A handler, * if registered under this name, should handle all requests that do * not have a known method name. It is of course optional that a * implementing class use this constant. */ String DEFAULT_HANDLER = ""; /** * Register a handler object with this name. * Methods of this object will be callable over Xml-Rpc as * handlername.methodname. * Use the Invoker adapter to register a generic object. * @see Invoker * @param handlerName handler name that will invoke this handler * @param handler object which will handle the requests */ void addHandler(String handlerName, XmlRpcHandler handler); /** * Remove a handler object that was previously registered with this * server. * @param handlerName registered handler to remove */ void removeHandler(String handlerName); /** * From your servlet, or other locality, call this method to handle * an Xml-Rpc request. The input and output streams should * buffer data sent and received for better performance. * The streams do not need to be closed after this method is called. * * @throws XmlRpcException if sort of exceptional condition occured * @throws NoHandlerException if no appropriate handler is available * @param in input stream * @param out output stream */ void accept(Reader in, Writer out) throws XmlRpcException; } // XmlRpcServer libexml-java-0.0.20080703.orig/xmlrpc/.classpath0000644000175000017500000000073610731634071021023 0ustar twernertwerner libexml-java-0.0.20080703.orig/xmlrpc/.project0000644000175000017500000000106010731634071020476 0ustar twernertwerner xmlrpc org.eclipse.jdt.core.javabuilder org.maven.ide.eclipse.maven2Builder org.eclipse.jdt.core.javanature org.maven.ide.eclipse.maven2Nature libexml-java-0.0.20080703.orig/xmlrpc/pom.xml0000644000175000017500000000162710731634071020355 0ustar twernertwerner 4.0.0 net.noderunner exmlrpc jar 1.0 XMLRPC client and server http://e-xml.sourceforge.net junit junit 3.8.1 test net.noderunner http 1.0.1 net.noderunner exml 1.0 javax.servlet servlet-api 2.5 provided libexml-java-0.0.20080703.orig/header.pl0000755000175000017500000000166210762101215017313 0ustar twernertwerner#!/usr/bin/perl -ni.bak BEGIN { my $start; } while (<>) { if ($ARGV ne $oldargv) { print < entries = listBucketResponse.getEntries(); assertEquals("didn't get back the right number of entries", 2, entries.size()); // depends on weirdKey < $key assertEquals("first key isn't right", weirdKey, ((Entry)entries.get(0)).getKey()); assertEquals("second key isn't right", key, ((Entry)entries.get(1)).getKey()); verifyBucketResponseParameters(listBucketResponse, bucket, "", "", UnspecifiedMaxKeys, null, false, null); listBucketResponse = conn.list(bucket, null, null, 1, null); assertEquals( "couldn't list bucket", HttpURLConnection.HTTP_OK, listBucketResponse.getResponseCode()); assertEquals( "didn't get back the right number of entries", 1, listBucketResponse.getEntries().size()); verifyBucketResponseParameters(listBucketResponse, bucket, "", "", 1, null, true, null); for (Entry entry : entries) { response = conn.delete(bucket, entry.getKey(), null); assertEquals( "couldn't delete entry", HttpURLConnection.HTTP_NO_CONTENT, response.getResponseCode()); } /* TODO ListAllBucketsResponse listAllMyBucketsResponse = conn.listAllBuckets(); assertEquals( "couldn't list all my buckets", HttpURLConnection.HTTP_OK, listAllMyBucketsResponse.getResponseCode()); List buckets = listAllMyBucketsResponse.getEntries(); response = conn.delete(bucket); assertEquals( "couldn't delete bucket", HttpURLConnection.HTTP_NO_CONTENT, response.getResponseCode()); listAllMyBucketsResponse = conn.listAllBuckets(); assertEquals( "couldn't list all my buckets", HttpURLConnection.HTTP_OK, listAllMyBucketsResponse.getResponseCode()); assertEquals( "bucket count is incorrect", buckets.size() - 1, listAllMyBucketsResponse.getEntries().size()); */ } private static void verifyBucketResponseParameters( ListResponse listBucketResponse, Bucket bucket, String prefix, String marker, int maxKeys, String delimiter, boolean isTruncated, String nextMarker ) { assertEquals("Bucket name should match.", bucket.getName(), listBucketResponse.getName()); assertEquals("Bucket prefix should match.", prefix, listBucketResponse.getPrefix()); assertEquals("Bucket marker should match.", marker, listBucketResponse.getMarker()); assertEquals("Bucket delimiter should match.", delimiter, listBucketResponse.getDelimiter()); if ( UnspecifiedMaxKeys != maxKeys ) { assertEquals("Bucket max-keys should match.", maxKeys, listBucketResponse.getMaxKeys()); } assertEquals("Bucket should not be truncated.", isTruncated, listBucketResponse.isTruncated()); assertEquals("Bucket nextMarker should match.", nextMarker, listBucketResponse.getNextMarker()); } private static void assertEquals(String message, int expected, int actual) { if (expected != actual) { throw new RuntimeException(message + ": expected " + expected + " but got " + actual); } } private static void assertEquals(String message, byte[] expected, byte[] actual) { if (! Arrays.equals(expected, actual)) { throw new RuntimeException( message + ": expected " + new String(expected) + " but got " + new String(actual)); } } private static void assertEquals(String message, Object expected, Object actual) { if (expected != actual && (actual == null || ! actual.equals(expected))) { throw new RuntimeException(message + ": expected " + expected + " but got " + actual); } } private static void assertEquals(String message, boolean expected, boolean actual) { if (expected != actual) { throw new RuntimeException(message + ": expected " + expected + " but got " + actual); } } } libexml-java-0.0.20080703.orig/amazon-s3/src/test/java/net/noderunner/amazon/s3/EntryTest.java0000644000175000017500000000076210770423301031407 0ustar twernertwernerpackage net.noderunner.amazon.s3; import static org.junit.Assert.*; import org.junit.Test; public class EntryTest { @Test public void testEntry() { Entry a = new Entry("A"); Entry b = new Entry("B"); Entry a1 = new Entry("A"); assertEquals(a, a1); assertEquals(a.hashCode(), a1.hashCode()); assertEquals("A", a1.getKey()); assertEquals("A", a1.toString()); assertEquals(false, a.equals(b)); assertEquals(-1, a.compareTo(b)); assertEquals(null, a.getStorageClass()); } } libexml-java-0.0.20080703.orig/amazon-s3/src/test/java/net/noderunner/amazon/s3/S3Test.java0000644000175000017500000006313610772111125030577 0ustar twernertwernerpackage net.noderunner.amazon.s3; // This software code is made available "AS IS" without warranties of any // kind. You may copy, display, modify and redistribute the software // code either by itself or as incorporated into your code; provided that // you do not remove any proprietary notices. Your use of this software // code is at your own risk and you waive any claim against Amazon // Digital Services, Inc. or its affiliates with respect to your use of // this software code. (c) 2006-2007 Amazon Digital Services, Inc. or its // affiliates. import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.util.Arrays; import java.util.List; import net.noderunner.amazon.s3.Bucket; import net.noderunner.amazon.s3.CallingFormat; import net.noderunner.amazon.s3.Connection; import net.noderunner.amazon.s3.Entry; import net.noderunner.amazon.s3.GetResponse; import net.noderunner.amazon.s3.GetStreamResponse; import net.noderunner.amazon.s3.Headers; import net.noderunner.amazon.s3.ListAllBucketsResponse; import net.noderunner.amazon.s3.ListResponse; import net.noderunner.amazon.s3.Method; import net.noderunner.amazon.s3.QueryGenerator; import net.noderunner.amazon.s3.Response; import net.noderunner.amazon.s3.S3Object; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpMethod; import org.apache.commons.httpclient.URI; import org.apache.commons.httpclient.methods.EntityEnclosingMethod; import org.apache.commons.httpclient.methods.StringRequestEntity; import org.junit.Before; import org.junit.Test; public class S3Test { String awsAccessKeyId = System.getProperty("accessKey"); String awsSecretAccessKey = System.getProperty("secretKey"); boolean emulated = Boolean.valueOf(System.getProperty("emulated", "true")); Bucket bucket; static final int UnspecifiedMaxKeys = -1; @Before public void setUp() { if (emulated) return; if (awsAccessKeyId == null) throw new IllegalStateException("accessKey system propery null"); if (awsSecretAccessKey == null) throw new IllegalStateException("secretKey system propery null"); // for subdomains (bucket.s3.amazonaws.com), // the bucket name must be lowercase since DNS is case-insensitive bucket = new Bucket(awsAccessKeyId.toLowerCase() + "-test-bucket"); } @Test public void testMe() throws Exception { if (emulated) return; // test all operation for both regular and vanity domains // regular: http://s3.amazonaws.com/key // subdomain: http://bucket.s3.amazonaws.com/key // testing pure vanity domains (http:///key) is not covered here // but is possible with some assitional setup test(CallingFormat.SUBDOMAIN, Connection.LOCATION_DEFAULT, false, Connection.DEFAULT_HOST); test(CallingFormat.PATH, Connection.LOCATION_DEFAULT, true, Connection.DEFAULT_HOST); test(CallingFormat.SUBDOMAIN, Connection.LOCATION_EU, true, Connection.DEFAULT_HOST); } private void test(CallingFormat format, String location, boolean secure, String server) throws Exception { System.out.println((secure ? "http" : "https") + " / " + server + " / " + ((location == null) ? "" : location) + " / " + format.getClass().getName()); Connection conn = new Connection(awsAccessKeyId, awsSecretAccessKey, secure, server, format); QueryGenerator generator = new QueryGenerator(awsAccessKeyId, awsSecretAccessKey, secure, server, format); Response response = conn.create(bucket, location, null); response.assertOk(); ListResponse listBucketResponse = conn.list(bucket); listBucketResponse.assertOk(); for (Entry entry : listBucketResponse.getEntries()) { Response delete = conn.delete(bucket, entry.getKey()); System.out.println("DEL " + delete); delete.assertOk(); } listBucketResponse = conn.list(bucket); assertEquals("list wasn't empty " + listBucketResponse, 0, listBucketResponse.getEntries().size()); System.out.println(listBucketResponse); verifyBucketResponseParameters(listBucketResponse, bucket, "", "", UnspecifiedMaxKeys, null, false, null); // start delimiter tests final String text = "this is a test"; final String key = "example.txt"; final String innerKey = "test/inner.txt"; final String lastKey = "z-last-key.txt"; response = conn.put(bucket, key, new S3Object(text)); response.assertOk(); response = conn.put(bucket, innerKey, new S3Object(text)); response.assertOk(); response = conn.put(bucket, lastKey, new S3Object(text)); response.assertOk(); // plain list listBucketResponse = conn.list(bucket); listBucketResponse.assertOk(); assertEquals("Unexpected list size", 3, listBucketResponse.getEntries().size()); assertEquals("Unexpected common prefix size", 0, listBucketResponse.getCommonPrefixEntries().size()); verifyBucketResponseParameters(listBucketResponse, bucket, "", "", UnspecifiedMaxKeys, null, false, null); System.out.println("LIST " + listBucketResponse.getEntries()); // root "directory" listBucketResponse = conn.list(bucket, null, null, null, "/", null); listBucketResponse.assertOk(); assertEquals("Unexpected list size " + listBucketResponse, 2, listBucketResponse.getEntries().size()); assertEquals("Unexpected common prefix size", 1, listBucketResponse.getCommonPrefixEntries().size()); verifyBucketResponseParameters(listBucketResponse, bucket, "", "", UnspecifiedMaxKeys, "/", false, null); // root "directory" with a max-keys of "1" listBucketResponse = conn.list(bucket, null, null, 1, "/", null); listBucketResponse.assertOk(); assertEquals("Unexpected list size", 1, listBucketResponse.getEntries().size()); assertEquals("Unexpected common prefix size", 0, listBucketResponse.getCommonPrefixEntries().size()); verifyBucketResponseParameters(listBucketResponse, bucket, "", "", 1, "/", true, "example.txt"); // root "directory" with a max-keys of "2" listBucketResponse = conn.list(bucket, null, null, 2, "/", null); listBucketResponse.assertOk(); assertEquals("Unexpected list size", 1, listBucketResponse.getEntries().size()); assertEquals("Unexpected common prefix size", 1, listBucketResponse.getCommonPrefixEntries().size()); verifyBucketResponseParameters(listBucketResponse, bucket, "", "", 2, "/", true, "test/"); String marker = listBucketResponse.getNextMarker(); listBucketResponse = conn.list(bucket, null, marker, 2, "/", null); listBucketResponse.assertOk(); assertEquals("Unexpected list size", 1, listBucketResponse.getEntries().size()); assertEquals("Unexpected common prefix size", 0, listBucketResponse.getCommonPrefixEntries().size()); verifyBucketResponseParameters(listBucketResponse, bucket, "", marker, 2, "/", false, null); // test "directory" listBucketResponse = conn.list(bucket, "test/", null, null, "/", null); listBucketResponse.assertOk(); assertEquals("Unexpected list size", 1, listBucketResponse.getEntries().size()); assertEquals("Unexpected common prefix size", 0, listBucketResponse.getCommonPrefixEntries().size()); verifyBucketResponseParameters(listBucketResponse, bucket, "test/", "", UnspecifiedMaxKeys, "/", false, null); // remove innerkey response = conn.delete(bucket, innerKey, null); assertEquals( "couldn't delete entry", HttpURLConnection.HTTP_NO_CONTENT, response.getResponseCode()); // remove last key response = conn.delete(bucket, lastKey, null); assertEquals( "couldn't delete entry", HttpURLConnection.HTTP_NO_CONTENT, response.getResponseCode()); // end delimiter tests response = conn.put(bucket, key, new S3Object(text.getBytes(), null), null); response.assertOk(); Headers metadata = new Headers(); metadata.put("title", "title"); response = conn.put(bucket, key, new S3Object(text.getBytes(), metadata), null); response.assertOk(); GetResponse getResponse = conn.get(bucket, key, null); getResponse.assertOk(); assertEquals("didn't get the right data back", text.getBytes(), getResponse.getObject().getData()); assertEquals("didn't get the right metadata back", 1, getResponse.getObject().getMetadata().size()); assertEquals( "didn't get the right metadata back", "title", getResponse.getObject().getMetadata().getValue("title")); assertEquals( "didn't get the right content-length", ""+text.length(), getResponse.getHeaderField("Content-Length")); GetStreamResponse streamResponse = conn.getStream(bucket, key); InputStream is = streamResponse.getInputStream(); byte b[] = new byte[text.length()]; int len = is.read(b); assertEquals("didn't get the right data back " + len, text.getBytes(), b); streamResponse.release(); String titleWithSpaces = " \t title with leading and trailing spaces "; Headers h = new Headers(); h.put("title", titleWithSpaces); response = conn.put(bucket, key, new S3Object(text.getBytes(), h), null); assertEquals( "couldn't put metadata with leading and trailing spaces", HttpURLConnection.HTTP_OK, response.getResponseCode()); getResponse = conn.get(bucket, key, null); assertEquals( "couldn't get object", HttpURLConnection.HTTP_OK, getResponse.getResponseCode()); assertEquals("didn't get the right metadata back", getResponse.getObject().getMetadata().size(), 1); assertEquals( "didn't get the right metadata back", titleWithSpaces.trim(), getResponse.getObject().getMetadata().getValue("title")); String weirdKey = "&=//%# ++++"; response = conn.put(bucket, weirdKey, new S3Object(text.getBytes())); assertEquals( "couldn't put weird key", HttpURLConnection.HTTP_OK, response.getResponseCode()); getResponse = conn.get(bucket, weirdKey, null); assertEquals( "couldn't get weird key", HttpURLConnection.HTTP_OK, getResponse.getResponseCode()); // start acl test getResponse = conn.getACL(bucket, key, null); assertEquals( "couldn't get acl", HttpURLConnection.HTTP_OK, getResponse.getResponseCode()); byte[] acl = getResponse.getObject().getData(); response = conn.putACL(bucket, key, new String(acl), null); assertEquals( "couldn't put acl", HttpURLConnection.HTTP_OK, response.getResponseCode()); getResponse = conn.getACL(bucket, null); assertEquals( "couldn't get bucket acl", HttpURLConnection.HTTP_OK, getResponse.getResponseCode()); byte[] bucketACL = getResponse.getObject().getData(); response = conn.putACL(bucket, new String(bucketACL), null); assertEquals( "couldn't put bucket acl", HttpURLConnection.HTTP_OK, response.getResponseCode()); // end acl test // bucket logging tests getResponse = conn.getBucketLogging(bucket, null); assertEquals( "couldn't get bucket logging config", HttpURLConnection.HTTP_OK, getResponse.getResponseCode()); byte[] bucketLogging = getResponse.getObject().getData(); response = conn.putBucketLogging(bucket, new String(bucketLogging), null); assertEquals( "couldn't put bucket logging config", HttpURLConnection.HTTP_OK, response.getResponseCode()); // end bucket logging tests listBucketResponse = conn.list(bucket, null, null, null, null); assertEquals( "couldn't list bucket", HttpURLConnection.HTTP_OK, listBucketResponse.getResponseCode()); List entries = listBucketResponse.getEntries(); assertEquals("didn't get back the right number of entries", 2, entries.size()); // depends on weirdKey < $key assertEquals("first key isn't right", weirdKey, ((Entry)entries.get(0)).getKey()); assertEquals("second key isn't right", key, ((Entry)entries.get(1)).getKey()); verifyBucketResponseParameters(listBucketResponse, bucket, "", "", UnspecifiedMaxKeys, null, false, null); listBucketResponse = conn.list(bucket, null, null, 1, null); assertEquals( "couldn't list bucket", HttpURLConnection.HTTP_OK, listBucketResponse.getResponseCode()); assertEquals( "didn't get back the right number of entries", 1, listBucketResponse.getEntries().size()); verifyBucketResponseParameters(listBucketResponse, bucket, "", "", 1, null, true, null); for (Entry entry : entries) { response = conn.delete(bucket, entry.getKey(), null); assertEquals( "couldn't delete entry", HttpURLConnection.HTTP_NO_CONTENT, response.getResponseCode()); } ListAllBucketsResponse listAllMyBucketsResponse = conn.listAllBuckets(); assertEquals( "couldn't list all my buckets", HttpURLConnection.HTTP_OK, listAllMyBucketsResponse.getResponseCode()); List buckets = listAllMyBucketsResponse.getEntries(); response = conn.delete(bucket); assertEquals( "couldn't delete bucket", HttpURLConnection.HTTP_NO_CONTENT, response.getResponseCode()); listAllMyBucketsResponse = conn.listAllBuckets(); assertEquals( "couldn't list all my buckets", HttpURLConnection.HTTP_OK, listAllMyBucketsResponse.getResponseCode()); assertEquals( "bucket count is incorrect", buckets.size() - 1, listAllMyBucketsResponse.getEntries().size()); checkURI( generator.create(bucket, null), Method.PUT, HttpURLConnection.HTTP_OK, "couldn't create bucket"); checkURI( generator.put(bucket, key, new S3Object("test data".getBytes(), null), null), Method.PUT, HttpURLConnection.HTTP_OK, "put object", "test data"); checkURI( generator.get(bucket, key, null), Method.GET, HttpURLConnection.HTTP_OK, "get object"); checkURI( generator.list(bucket, null, null, null, null), Method.GET, HttpURLConnection.HTTP_OK, "list bucket"); checkURI( generator.listAllBuckets(), Method.GET, HttpURLConnection.HTTP_OK, "list all my buckets"); checkURI( generator.getACL(bucket, key, null), Method.GET, HttpURLConnection.HTTP_OK, "get acl"); checkURI( generator.putACL(bucket, key, null), Method.PUT, HttpURLConnection.HTTP_OK, "put acl", new String(acl)); checkURI( generator.getACL(bucket, null), Method.GET, HttpURLConnection.HTTP_OK, "get bucket acl"); checkURI( generator.putACL(bucket, null), Method.PUT, HttpURLConnection.HTTP_OK, "put bucket acl", new String(bucketACL)); checkURI( generator.getBucketLogging(bucket, null), Method.GET, HttpURLConnection.HTTP_OK, "get bucket logging"); checkURI( generator.putBucketLogging(bucket, null), Method.PUT, HttpURLConnection.HTTP_OK, "put bucket logging", new String(bucketLogging)); checkURI( generator.delete(bucket, key, null), Method.DELETE, HttpURLConnection.HTTP_NO_CONTENT, "delete object"); checkURI( generator.delete(bucket, null), Method.DELETE, HttpURLConnection.HTTP_NO_CONTENT, "delete bucket"); } private static void verifyBucketResponseParameters( ListResponse listBucketResponse, Bucket bucket, String prefix, String marker, int maxKeys, String delimiter, boolean isTruncated, String nextMarker ) { assertEquals("Bucket name should match.", bucket.getName(), listBucketResponse.getName()); assertEquals("Bucket prefix should match.", prefix, listBucketResponse.getPrefix()); assertEquals("Bucket marker should match.", marker, listBucketResponse.getMarker()); assertEquals("Bucket delimiter should match.", delimiter, listBucketResponse.getDelimiter()); if ( UnspecifiedMaxKeys != maxKeys ) { assertEquals("Bucket max-keys should match.", maxKeys, listBucketResponse.getMaxKeys()); } assertEquals("Bucket should not be truncated.", isTruncated, listBucketResponse.isTruncated()); assertEquals("Bucket nextMarker should match.", nextMarker, listBucketResponse.getNextMarker()); } private static void assertEquals(String message, int expected, int actual) { if (expected != actual) { throw new RuntimeException(message + ": expected " + expected + " but got " + actual); } } private static void assertEquals(String message, byte[] expected, byte[] actual) { if (! Arrays.equals(expected, actual)) { throw new RuntimeException( message + ": expected " + new String(expected) + " but got " + new String(actual)); } } private static void assertEquals(String message, Object expected, Object actual) { if (expected != actual && (actual == null || ! actual.equals(expected))) { throw new RuntimeException(message + ": expected " + expected + " but got " + actual); } } private static void assertEquals(String message, boolean expected, boolean actual) { if (expected != actual) { throw new RuntimeException(message + ": expected " + expected + " but got " + actual); } } private static void checkURI(URI uri, Method method, int code, String message) throws MalformedURLException, IOException { checkURI(uri, method, code, message, null); } private static void checkURI(URI uri, Method method, int code, String message, String data) throws MalformedURLException, IOException { if (data == null) data = ""; HttpClient client = new HttpClient(); HttpMethod httpMethod = method.createHttpMethod(); if (method == Method.PUT) { ((EntityEnclosingMethod) httpMethod).setRequestEntity(new StringRequestEntity(data)); } httpMethod.setURI(uri); int response = client.executeMethod(httpMethod); httpMethod.releaseConnection(); assertEquals(message, code, response); } private void readline() throws IOException { // TODO // System.in.read(); } @Test public void testDriver() throws Exception { if (emulated) return; Bucket bucket = new Bucket(awsAccessKeyId.toLowerCase() + "-test-bucket"); String keyName = "KEY"; Connection conn = new Connection(awsAccessKeyId, awsSecretAccessKey); QueryGenerator generator = new QueryGenerator(awsAccessKeyId, awsSecretAccessKey); // Check if the bucket exists. The high availability engineering of // Amazon S3 is focused on get, put, list, and delete operations. // Because bucket operations work against a centralized, global // resource space, it is not appropriate to make bucket create or // delete calls on the high availability code path of your application. // It is better to create or delete buckets in a separate initialization // or setup routine that you run less often. if (!conn.exists(bucket)) { System.out.println("----- creating bucket -----"); System.out.println(conn.create(bucket, Connection.LOCATION_DEFAULT, null).getResponseMessage()); // sample creating an EU located bucket. // (note path-style urls will not work with location-constrained buckets) //System.out.println(conn.createBucket(bucketName, AWSAuthConnection.LOCATION_EU, null).connection.getResponseMessage()); } System.out.println("----- listing bucket -----"); System.out.println(conn.list(bucket).getEntries()); System.out.println("----- bucket location -----"); System.out.println(conn.getLocation(bucket).getLocation()); System.out.println("----- putting object -----"); S3Object object = new S3Object("this is a test".getBytes(), null); Headers headers = new Headers(); headers.put("Content-Type", "text/plain"); System.out.println( conn.put(bucket, keyName, object, headers).getResponseMessage() ); System.out.println("----- listing bucket -----"); System.out.println(conn.list(bucket, null, null, null, null).getEntries()); System.out.println("----- getting object -----"); System.out.println( new String(conn.get(bucket, keyName, null).getObject().getData()) ); System.out.println("----- query string auth example -----"); generator.setExpiresIn(60 * 1000); System.out.println("Try this url in your web browser (it will only work for 60 seconds)\n"); System.out.println(generator.get(bucket, keyName, null)); System.out.print("\npress enter> "); readline(); System.out.println("\nNow try just the url without the query string arguments. It should fail.\n"); System.out.println(generator.makeBareURI(bucket, keyName)); System.out.print("\npress enter> "); readline(); System.out.println("----- putting object with metadata and public read acl -----"); Headers metadata = new Headers(); metadata.put("blah", "foo"); object = new S3Object("this is a publicly readable test".getBytes(), new Headers(metadata)); headers = new Headers(); headers.put("x-amz-acl", "public-read"); headers.put("Content-Type", "text/plain"); System.out.println( conn.put(bucket, keyName + "-public", object, headers).getResponseMessage() ); System.out.println("----- anonymous read test -----"); System.out.println("\nYou should be able to try this in your browser\n"); System.out.println(generator.makeBareURI(bucket, keyName + "-public")); System.out.print("\npress enter> "); readline(); System.out.println("----- path style url example -----"); System.out.println("\nNon-location-constrained buckets can also be specified as part of the url path. (This was the original url style supported by S3.)"); System.out.println("\nTry this url out in your browser (it will only be valid for 60 seconds)\n"); generator.setCallingFormat(CallingFormat.PATH); // could also have been done like this: // generator = new QueryStringAuthGenerator(awsAccessKeyId, awsSecretAccessKey, true, Utils.DEFAULT_HOST, CallingFormat.getPathCallingFormat()); generator.setExpiresIn(60 * 1000); System.out.println(generator.get(bucket, keyName, null)); System.out.print("\npress enter> "); readline(); System.out.println("----- getting object's acl -----"); System.out.println(new String(conn.getACL(bucket, keyName, null).getObject().getData())); System.out.println("----- deleting objects -----"); System.out.println( conn.delete(bucket, keyName, null).getResponseMessage() ); System.out.println( conn.delete(bucket, keyName + "-public", null).getResponseMessage() ); System.out.println("----- listing bucket -----"); System.out.println(conn.list(bucket, null, null, null, null).getEntries()); System.out.println("----- listing all my buckets -----"); System.out.println(conn.listAllBuckets().getEntries()); System.out.println("----- deleting bucket -----"); System.out.println( conn.delete(bucket).getResponseMessage() ); } } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootlibexml-java-0.0.20080703.orig/amazon-s3/src/test/java/net/noderunner/amazon/s3/CallingFormatTest.javalibexml-java-0.0.20080703.orig/amazon-s3/src/test/java/net/noderunner/amazon/s3/CallingFormatTest.ja0000644000175000017500000000152510770333236032506 0ustar twernertwernerpackage net.noderunner.amazon.s3; import static org.junit.Assert.assertEquals; import java.util.HashMap; import java.util.Map; import net.noderunner.amazon.s3.Bucket; import net.noderunner.amazon.s3.CallingFormat; import org.apache.commons.httpclient.URI; import org.junit.Test; public class CallingFormatTest { @Test public void testCalling() throws Exception { Bucket bucket = new Bucket("bucket"); String key = "/HI"; Map args = new HashMap(); args.put("one", "1"); URI uri; uri = CallingFormat.PATH.getURI(true, "foo", 444, bucket, key, args); assertEquals("https://foo:444/bucket/%2FHI?one=1", uri.toString()); uri = CallingFormat.SUBDOMAIN.getURI(true, "foo", 444, bucket, key, args); assertEquals("https://bucket.foo:444/%2FHI?one=1", uri.toString()); } } libexml-java-0.0.20080703.orig/amazon-s3/src/test/java/net/noderunner/amazon/s3/HeadersTest.java0000644000175000017500000000064410770423301031660 0ustar twernertwernerpackage net.noderunner.amazon.s3; import static org.junit.Assert.assertEquals; import org.junit.Test; public class HeadersTest { @Test public void testHeaders() { Headers h = new Headers(); h.put("x", "x1"); h.put("x", "x2"); assertEquals(null, h.getValue("y")); assertEquals("x1", h.getValue("x")); Headers h2 = new Headers(h); assertEquals("x1", h2.getValue("x")); h2.mergeMetadata(h2); } } libexml-java-0.0.20080703.orig/amazon-s3/src/test/java/net/noderunner/amazon/s3/BucketTest.java0000644000175000017500000000224710770423301031523 0ustar twernertwernerpackage net.noderunner.amazon.s3; import static org.junit.Assert.assertEquals; import java.util.Date; import org.junit.Test; public class BucketTest { @Test public void testBucket() { Bucket bucket = new Bucket("name"); assertEquals(true, bucket.specified()); Date d = new Date(); bucket.setCreationDate(d); assertEquals(d, bucket.getCreationDate()); assertEquals(true, Bucket.validateBucketName("0Az._A", CallingFormat.PATH)); assertEquals(false, Bucket.validateBucketName("0A#._A", CallingFormat.PATH)); assertEquals(false, Bucket.validateBucketName("F", CallingFormat.PATH)); assertEquals(false, Bucket.validateBucketName(null, CallingFormat.PATH)); assertEquals(false, Bucket.validateBucketName("0Az._A", CallingFormat.SUBDOMAIN)); assertEquals(true, Bucket.validateBucketName("foo.00", CallingFormat.SUBDOMAIN)); assertEquals(true, Bucket.validateBucketName("jo.jo.jo", CallingFormat.SUBDOMAIN)); assertEquals(false, Bucket.validateBucketName("0A#._A", CallingFormat.SUBDOMAIN)); assertEquals(false, Bucket.validateBucketName("F", CallingFormat.SUBDOMAIN)); assertEquals(false, Bucket.validateBucketName(null, CallingFormat.SUBDOMAIN)); } } ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootlibexml-java-0.0.20080703.orig/amazon-s3/src/test/java/net/noderunner/amazon/s3/CanonicalStringTest.javalibexml-java-0.0.20080703.orig/amazon-s3/src/test/java/net/noderunner/amazon/s3/CanonicalStringTest.0000644000175000017500000000273010770333236032526 0ustar twernertwernerpackage net.noderunner.amazon.s3; import static org.junit.Assert.assertEquals; import java.security.Key; import java.util.Collections; import java.util.Map; import net.noderunner.amazon.s3.Bucket; import net.noderunner.amazon.s3.CanonicalString; import net.noderunner.amazon.s3.Headers; import net.noderunner.amazon.s3.Method; import org.junit.Test; public class CanonicalStringTest { @Test public void testMacOlder() throws Exception { String access = "213321324ksadjfkasjfdasfdjksadf"; String canon = "XXYasfajkjaslkfdjalksjflkasjflkajskfjasjflksadjflksajfdkljsadlkfjaslkfd"; Key key = CanonicalString.key(access); String encode = CanonicalString.encode(key, canon); assertEquals("hAu+ibd/CZIw6/5OR69i2+40bfc=", encode); } @Test public void testMac2() throws Exception { String access = "213321324ksadjfkasjfdasfdjksadf"; String canon = "XXYasfajkjaslkfdjalksjflkasjflkajskfjasjflksadjflksajfdkljsadlkfjaslkfd"; Key key = CanonicalString.key(access); String encode = CanonicalString.encode(key, canon); assertEquals("hAu+ibd/CZIw6/5OR69i2+40bfc=", encode); } @Test public void testMake() throws Exception { Map path = Collections.singletonMap("auth", ""); Headers h = new Headers(); h.put("x", "y"); String expires = "whenever"; String make = CanonicalString.make(Method.PUT, new Bucket("xyz"), "key", path, h, expires); assertEquals("PUT\n\n\nwhenever\n/xyz/key", make); } } libexml-java-0.0.20080703.orig/amazon-s3/src/test/resources/0000755000175000017500000000000011111351376023112 5ustar twernertwernerlibexml-java-0.0.20080703.orig/amazon-s3/src/test/resources/log4j.xml0000644000175000017500000000304610770333236024663 0ustar twernertwerner libexml-java-0.0.20080703.orig/amazon-s3/src/main/0000755000175000017500000000000011111351376021045 5ustar twernertwernerlibexml-java-0.0.20080703.orig/amazon-s3/src/main/java/0000755000175000017500000000000011111351376021766 5ustar twernertwernerlibexml-java-0.0.20080703.orig/amazon-s3/src/main/java/net/0000755000175000017500000000000011111351376022554 5ustar twernertwernerlibexml-java-0.0.20080703.orig/amazon-s3/src/main/java/net/noderunner/0000755000175000017500000000000011111351376024733 5ustar twernertwernerlibexml-java-0.0.20080703.orig/amazon-s3/src/main/java/net/noderunner/amazon/0000755000175000017500000000000011111351376026220 5ustar twernertwernerlibexml-java-0.0.20080703.orig/amazon-s3/src/main/java/net/noderunner/amazon/s3/0000755000175000017500000000000011111351376026545 5ustar twernertwernerlibexml-java-0.0.20080703.orig/amazon-s3/src/main/java/net/noderunner/amazon/s3/emulator/0000755000175000017500000000000011111351376030375 5ustar twernertwerner././@LongLink0000000000000000000000000000014500000000000011565 Lustar rootrootlibexml-java-0.0.20080703.orig/amazon-s3/src/main/java/net/noderunner/amazon/s3/emulator/Server.javalibexml-java-0.0.20080703.orig/amazon-s3/src/main/java/net/noderunner/amazon/s3/emulator/Server.java0000644000175000017500000001632510772111125032513 0ustar twernertwernerpackage net.noderunner.amazon.s3.emulator; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.PrintWriter; import java.net.HttpURLConnection; import java.net.URI; import java.net.URISyntaxException; import java.util.Collections; import java.util.Date; import java.util.Enumeration; import java.util.List; import java.util.Map; import java.util.SortedMap; import java.util.TreeMap; import javax.servlet.ServletException; import javax.servlet.ServletInputStream; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import net.noderunner.amazon.s3.Entry; import net.noderunner.amazon.s3.Headers; import net.noderunner.amazon.s3.Owner; import net.noderunner.amazon.s3.S3Object; import net.noderunner.http.servlet.ServletServer; /** * Amazon S3 emulator that stores data in an internal sorted map. * Not highly scalable or reliable, but may be fine for testing your application. * * Some browse methods are not complete. * Get Data/Put/Head are mostly complete. * What's supported is in the test suite. * * @author Elias Ross */ public class Server extends HttpServlet { private static final long serialVersionUID = 1L; private transient Log log = LogFactory.getLog(getClass()); private transient ServletServer ss; private boolean bucket = false; private SortedMap map = Collections.synchronizedSortedMap(new TreeMap()); public Server() throws IOException { ss = new ServletServer(this); log.info("Server created " + this); } /** * Closes socket, stops accepting requests. */ public void close() throws IOException { log("close"); ss.close(); } @Override protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Entry e = entry(req); S3Object remove = map.remove(e); if (remove == null) { resp.sendError(404, "Not found " + e); } else { resp.sendError(HttpURLConnection.HTTP_NO_CONTENT, "Deleted"); } } private Entry entry(HttpServletRequest req) { return new Entry(key(uri(req))); } /** * Listening port. */ public int getPort() { return ss.getPort(); } /** * Starts accepting requests. */ public void start() { ss.start(); } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { URI uri = uri(req); boolean debug = log.isDebugEnabled(); if (debug) log("doGet " + uri); if ("/".equals(uri.getPath())) { list(req, resp); } else { String key = uri.getPath().substring(1); Entry e = new Entry(key); S3Object obj = map.get(e); if (debug) log("map.get(" + key + ") = " + obj); if (obj == null) { resp.sendError(404, "Not here: " + e); return; } Headers h = new Headers(); h = h.mergeMetadata(obj.getMetadata()); for (Map.Entry> me : h.getHeaders().entrySet()) { for (String v : me.getValue()) { resp.setHeader(me.getKey(), v); } } resp.getOutputStream().write(obj.getData()); } } private void list(HttpServletRequest req, HttpServletResponse resp) throws IOException { String prefix = req.getParameter("prefix"); String marker = req.getParameter("marker"); String delimiter = req.getParameter("delimiter"); String maxKeysStr = req.getParameter("max-keys"); if (log.isDebugEnabled()) log("list prefix=" + prefix + " delimiter=" + delimiter); int maxKeys = Integer.MAX_VALUE; if (maxKeysStr != null) maxKeys = Integer.parseInt(maxKeysStr); Writer w = new Writer(); SortedMap submap = new TreeMap(map); if (prefix != null) submap = submap.tailMap(new Entry(prefix)); int keyCount = 0; boolean truncated = false; String nextMarker = null; for (Entry e : submap.keySet()) { if (++keyCount > maxKeys) { truncated = true; break; } String key = e.getKey(); String remain = key; nextMarker = key; if (prefix != null) { if (!key.startsWith(prefix)) break; remain = key.substring(prefix.length()); } if (delimiter != null && remain.indexOf(delimiter) != -1) continue; if (log.isDebugEnabled()) log("include key=" + key); w.start("Contents"); w.start("Key").write(key).end(); w.start("LastModified").write(e.getLastModified()).end(); w.start("Size").write(e.getSize()).end(); w.start("Owner"); w.start("ID").write(e.getOwner().getId()).end() .start("DisplayName").write(e.getOwner().getDisplayName()) .end(); w.end(); w.end(); } Writer hw = new Writer(); hw.start("ListBucketResult"); hw.start("Name").write("localhost").end(); hw.start("Prefix").write(s(prefix)).end(); hw.start("Marker").write(s(marker)).end(); if (delimiter != null) { hw.start("Delimiter").write(delimiter).end(); if (truncated) { hw.start("NextMarker").write(nextMarker).end(); } } hw.start("IsTruncated").write(String.valueOf(truncated)).end(); if (maxKeysStr != null) hw.start("MaxKeys").write(maxKeysStr).end(); hw.write(w); hw.end(); PrintWriter pw = resp.getWriter(); pw.write(hw.toString()); pw.flush(); bucket = true; } private String s(String s) { if (s == null) return ""; return s; } @Override protected void doHead(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { URI uri = uri(req); if (log.isDebugEnabled()) log("doHead " + uri); if (map.containsKey(entry(req))) { log("found"); resp.sendError(HttpURLConnection.HTTP_OK, "Found URI"); } else { log("not found"); resp.sendError(404, "Not found"); } } private URI uri(HttpServletRequest req) { try { return new URI(req.getRequestURI()); } catch (URISyntaxException e1) { throw new RuntimeException(e1); } } private String key(URI uri) { return uri.getPath().substring(1); } @Override protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { URI uri = uri(req); log("doPut " + uri); if ("/".equals(uri.getPath())) { log("create bucket"); bucket = true; } else { Entry e = new Entry(key(uri)); e.setLastModified(new Date()); e.setSize(req.getContentLength()); e.setOwner(new Owner("id", "name")); ByteArrayOutputStream os = new ByteArrayOutputStream(); ServletInputStream is = req.getInputStream(); byte b[] = new byte[128]; while (true) { int len = is.read(b); if (len == -1) break; os.write(b, 0, len); } S3Object s3 = new S3Object(os.toByteArray()); map.put(e, s3); Headers h = new Headers(); @SuppressWarnings("unchecked") Enumeration names = req.getHeaderNames(); for (String n : Collections.list(names)) h.put(n, req.getHeader(n)); s3.setMetadata(h.extractMetadata()); log("put '" + e + "' as: " + s3); } } @Override public void log(String s) { log.debug(s); } /** * Returns a debug String. */ @Override public String toString() { return super.toString() + " bucket=" + this.bucket + " ss=" + this.ss + " map=" + this.map + ""; } } ././@LongLink0000000000000000000000000000014500000000000011565 Lustar rootrootlibexml-java-0.0.20080703.orig/amazon-s3/src/main/java/net/noderunner/amazon/s3/emulator/Writer.javalibexml-java-0.0.20080703.orig/amazon-s3/src/main/java/net/noderunner/amazon/s3/emulator/Writer.java0000644000175000017500000000237510772111125032521 0ustar twernertwernerpackage net.noderunner.amazon.s3.emulator; import java.util.Date; import java.util.Stack; import net.noderunner.amazon.s3.ISO801DateFormat; /** * Outputs XML. Not thread safe. * * @author Elias Ross */ public class Writer { private Stack tags = new Stack(); private StringBuilder sb = new StringBuilder(); /** * Starts an XML tag. */ public Writer start(String tag) { sb.append("<").append(tag).append(">"); tags.push(tag); return this; } /** * Ends an XML tag. */ public Writer end() { String tag = tags.pop(); sb.append(""); return this; } /** * Writes character data. */ public Writer write(String s) { s = s.replaceAll("&", "&"); s = s.replaceAll("<", "<"); sb.append(s); return this; } /** * Writes to a writer. */ public Writer write(Writer w) { sb.append(w.toString()); return this; } /** * Converts to a string. */ @Override public String toString() { return sb.toString(); } /** * Writes an ISO801 date. */ public Writer write(Date lastModified) { return write(new ISO801DateFormat().format(lastModified)); } /** * Writes a Long value. */ public Writer write(long size) { return write(String.valueOf(size)); } } libexml-java-0.0.20080703.orig/amazon-s3/src/main/java/net/noderunner/amazon/s3/Connection.java0000644000175000017500000006462210770333236031526 0ustar twernertwerner// This software code is made available "AS IS" without warranties of any // kind. You may copy, display, modify and redistribute the software // code either by itself or as incorporated into your code; provided that // you do not remove any proprietary notices. Your use of this software // code is at your own risk and you waive any claim against Amazon // Digital Services, Inc. or its affiliates with respect to your use of // this software code. (c) 2006-2007 Amazon Digital Services, Inc. or its // affiliates. package net.noderunner.amazon.s3; import java.io.IOException; import java.security.Key; import java.text.SimpleDateFormat; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.TimeZone; import org.apache.commons.httpclient.HostConfiguration; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpMethod; import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager; import org.apache.commons.httpclient.URI; import org.apache.commons.httpclient.methods.ByteArrayRequestEntity; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.methods.PutMethod; import org.apache.commons.httpclient.methods.StringRequestEntity; import org.apache.commons.httpclient.params.HttpMethodParams; /** * A stateless connection to the Amazon S3 system which uses the REST API. *

    * It is initially configured with authentication and connection parameters and * exposes methods to access and manipulate S3 data. */ public class Connection { /** * Location default. */ public static final String LOCATION_DEFAULT = null; /** * Location in Europe. */ public static final String LOCATION_EU = "EU"; /** * Default hostname. */ public static final String DEFAULT_HOST = "s3.amazonaws.com"; /** * HTTP port. */ public static final int INSECURE_PORT = 80; /** * HTTPS port. */ public static final int SECURE_PORT = 443; /** * Data larger than 1024 bytes will use expect headers. * See: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html 14.20 */ public static final int EXPECT_SIZE = 1024; private String awsAccessKeyId; private Key awsSecretAccessKey; private boolean isSecure; private String server; private int port; private CallingFormat callingFormat; private MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager(); private HostConfiguration config; private HttpClient client; static { String charset = URI.getDefaultProtocolCharset(); if (!charset.equals("UTF-8")) throw new Error("URI charset must be UTF-8: " + charset); } /** * Constructs a new Connection. */ public Connection(String awsAccessKeyId, String awsSecretAccessKey) { this(awsAccessKeyId, awsSecretAccessKey, true); } /** * Constructs a new Connection. */ public Connection(String awsAccessKeyId, String awsSecretAccessKey, boolean isSecure) { this(awsAccessKeyId, awsSecretAccessKey, isSecure, DEFAULT_HOST); } /** * Constructs a new Connection. */ public Connection(String awsAccessKeyId, String awsSecretAccessKey, boolean isSecure, String server) { this(awsAccessKeyId, awsSecretAccessKey, isSecure, server, isSecure ? SECURE_PORT : INSECURE_PORT); } /** * Constructs a new Connection. */ public Connection(String awsAccessKeyId, String awsSecretAccessKey, boolean isSecure, String server, int port) { this(awsAccessKeyId, awsSecretAccessKey, isSecure, server, port, CallingFormat.SUBDOMAIN); } /** * Constructs a new Connection. */ public Connection(String awsAccessKeyId, String awsSecretAccessKey, boolean isSecure, String server, CallingFormat format) { this(awsAccessKeyId, awsSecretAccessKey, isSecure, server, isSecure ? SECURE_PORT : INSECURE_PORT, format); } /** * Create a new interface to interact with S3 with the given credential and connection * parameters * * @param awsAccessKeyId Your user key into AWS * @param awsSecretAccessKey The secret string used to generate signatures for authentication. * @param isSecure use SSL encryption * @param server Which host to connect to. Usually, this will be s3.amazonaws.com * @param port Which port to use. * @param callingFormat Type of request Regular/Vanity or Pure Vanity domain */ public Connection(String awsAccessKeyId, String awsSecretAccessKey, boolean isSecure, String server, int port, CallingFormat format) { this.awsAccessKeyId = awsAccessKeyId; this.awsSecretAccessKey = CanonicalString.key(awsSecretAccessKey); this.isSecure = isSecure; this.server = server; this.port = port; this.callingFormat = format; config = new HostConfiguration(); config.setHost(server, port, isSecure ? "http" : "https"); client = new HttpClient(connectionManager); client.setHostConfiguration(config); } /** * Creates a new bucket. * @param bucket The name of the bucket to create. * @param location Desired location ("EU") (or null for default). * @param headers A Map of String to List of Strings representing the http * headers to pass (can be null). * @param metadata A Map of String to List of Strings representing the s3 * metadata for this bucket (can be null). * @throws IllegalArgumentException on invalid location */ public Response create(Bucket bucket, String location, Headers headers) throws IOException { String body; if (location == null) { body = null; } else if (LOCATION_EU.equals(location)) { if (!callingFormat.supportsLocatedBuckets()) throw new IllegalArgumentException("Creating location-constrained bucket with unsupported calling-format"); body = "" + location + ""; } else throw new IllegalArgumentException("Invalid Location: "+location); // validate bucket name if (!bucket.validateName(callingFormat)) throw new IllegalArgumentException("Invalid Bucket Name: "+bucket); PutMethod method = (PutMethod) makeRequest(Method.PUT, bucket, headers); if (body != null) { StringRequestEntity sre = new StringRequestEntity(body, "text/xml", "UTF-8"); method.setRequestEntity(sre); } executeRelease(method); return new Response(method); } private int execute(HttpMethod method) throws IOException { return client.executeMethod(method); } private int executeRelease(HttpMethod method) throws IOException { try { return client.executeMethod(method); } finally { method.releaseConnection(); } } /** * Creates a new bucket with a location. */ public Response create(Bucket bucket, String location) throws IOException { return create(bucket, location, null); } /** * Creates a new bucket. */ public Response create(Bucket bucket) throws IOException { return create(bucket, null); } /** * Check if the specified bucket exists (via a HEAD request) * @param bucket The name of the bucket to check * @return true if HEAD access returned success * @see #head(Bucket, String) */ public boolean exists(Bucket bucket) throws IOException { HttpMethod method = makeRequest(Method.HEAD, bucket); int httpCode = executeRelease(method); return httpCode >= 200 && httpCode < 300; } /** * Lists the contents of a bucket. * @param bucket The name of the bucket * @param prefix All returned keys will start with this string (can be null). * @param marker All returned keys will be lexographically greater than * this string (can be null). * @param maxKeys The maximum number of keys to return (can be null). * @param headers A Map of String to List of Strings representing the http * headers to pass (can be null). */ public ListResponse list(Bucket bucket, String prefix, String marker, Integer maxKeys, Headers headers) throws IOException { return list(bucket, prefix, marker, maxKeys, null, headers); } /** * Lists the contents of a bucket. */ public ListResponse list(Bucket bucket, String prefix, String marker, Integer maxKeys) throws IOException { return list(bucket, prefix, marker, maxKeys, null); } /** * Lists the contents of a bucket. */ public ListResponse list(Bucket bucket, Integer maxKeys) throws IOException { return list(bucket, null, null, maxKeys); } /** * Lists the contents of a bucket. */ public ListResponse list(Bucket bucket) throws IOException { return list(bucket, null, null, null, null); } /** * Lists the contents of a bucket by prefix. */ public ListResponse list(Bucket bucket, String prefix) throws IOException { return list(bucket, prefix, null, null); } /** * Lists the contents of a bucket. * @param bucket The name of the bucket to list. * @param prefix All returned keys will start with this string (can be null). * @param marker All returned keys will be lexographically greater than * this string (can be null). * @param maxKeys The maximum number of keys to return (can be null). * @param delimiter Keys that contain a string between the prefix and the first * occurrence of the delimiter will be rolled up into a single element. * @param headers A Map of String to List of Strings representing the http * headers to pass (can be null). */ public ListResponse list(Bucket bucket, String prefix, String marker, Integer maxKeys, String delimiter, Headers headers) throws IOException { Map pathArgs = paramsForListOptions(prefix, marker, maxKeys, delimiter); HttpMethod method = makeRequest(Method.GET, bucket, pathArgs, headers); try { execute(method); return new ListResponse(method); } finally { method.releaseConnection(); } } private static Map paramsForListOptions(String prefix, String marker, Integer maxKeys, String delimiter) { Map argParams = new HashMap(); if (prefix != null) argParams.put("prefix", prefix); if (marker != null) argParams.put("marker", marker); if (delimiter != null) argParams.put("delimiter", delimiter); if (maxKeys != null) argParams.put("max-keys", Integer.toString(maxKeys.intValue())); return argParams; } /** * Deletes a bucket. * @param bucket The name of the bucket to delete. * @param headers A Map of String to List of Strings representing the http * headers to pass (can be null). */ public Response delete(Bucket bucket, Headers headers) throws IOException { HttpMethod method = makeRequest(Method.DELETE, bucket, "", null, headers); executeRelease(method); return new Response(method); } /** * Deletes a bucket. */ public Response delete(Bucket bucket) throws IOException { return delete(bucket, (Headers)null); } /** * Writes an object to S3. * @param bucket The name of the bucket to which the object will be added. * @param key The name of the key to use. * @param object An S3Object containing the data to write. * @param headers A Map of String to List of Strings representing the http * headers to pass (can be null). */ public Response put(Bucket bucket, String key, S3Object object, Headers headers) throws IOException { PutMethod request = (PutMethod) makeRequest(Method.PUT, bucket, key, null, headers, object); return execute(request, object); } /** * Writes an object to S3. */ public Response put(Bucket bucket, String key, S3Object object) throws IOException { return put(bucket, key, object, null); } /** * Reads an object from S3. * @param bucket The name of the bucket where the object lives. * @param key The name of the key to use. * @param headers HTTP headers to pass (can be null). */ public GetResponse get(Bucket bucket, String key, Headers headers) throws IOException { HttpMethod method = makeRequest(Method.GET, bucket, key, null, headers); try { execute(method); return new GetResponse(method); } finally { method.releaseConnection(); } } /** * Reads an object from S3. */ public GetResponse get(Bucket bucket, String key) throws IOException { return get(bucket, key, null); } /** * Reads an object from S3, returning a stream to access the data. * This is preferable when dealing with large objects. * * @param bucket The name of the bucket where the object lives. * @param key The name of the key to use. * @param headers HTTP headers to pass (can be null). */ public GetStreamResponse getStream(Bucket bucket, String key, Headers headers) throws IOException { HttpMethod method = makeRequest(Method.GET, bucket, key, null, headers); boolean ok = false; try { execute(method); ok = true; return new GetStreamResponse((GetMethod)method); } finally { if (!ok) method.releaseConnection(); } } /** * Reads an object from S3, returning a stream to access the data. * This is preferable when dealing with large objects. */ public GetStreamResponse getStream(Bucket bucket, String key) throws IOException { return getStream(bucket, key, null); } /** * Returns information about an S3 object without loading it. * Check {@link Response#isOk()} or {@link Response#isNotFound()} to see if the object exists. */ public Response head(Bucket bucket, String key) throws IOException { return head(bucket, key, null); } /** * Returns information about an S3 object without loading it. */ public Response head(Bucket bucket, String key, Headers headers) throws IOException { HttpMethod method = makeRequest(Method.HEAD, bucket, key, null, headers); executeRelease(method); return new Response(method); } /** * Deletes an object from S3. * @param bucket The name of the bucket where the object lives. * @param key The name of the key to use. * @param headers A Map of String to List of Strings representing the http * headers to pass (can be null). */ public Response delete(Bucket bucket, String key, Headers headers) throws IOException { HttpMethod method = makeRequest(Method.DELETE, bucket, key, null, headers); executeRelease(method); return new Response(method); } /** * Deletes an object from S3. */ public Response delete(Bucket bucket, String key) throws IOException { return delete(bucket, key, null); } /** * Get the logging xml document for a given bucket * @param bucket The name of the bucket * @param headers A Map of String to List of Strings representing the http * headers to pass (can be null). */ public GetResponse getBucketLogging(Bucket bucket, Headers headers) throws IOException { Map pathArgs = Collections.singletonMap("logging", ""); HttpMethod method = makeRequest(Method.GET, bucket, "", pathArgs, headers); try { execute(method); return new GetResponse(method); } finally { method.releaseConnection(); } } /** * Write a new logging xml document for a given bucket * @param loggingXMLDoc The xml representation of the logging configuration as a String * @param bucket The name of the bucket * @param headers A Map of String to List of Strings representing the http * headers to pass (can be null). */ public Response putBucketLogging(Bucket bucket, String loggingXMLDoc, Headers headers) throws IOException { Map pathArgs = Collections.singletonMap("logging", ""); S3Object object = new S3Object(loggingXMLDoc.getBytes(), null); PutMethod request = (PutMethod) makeRequest(Method.PUT, bucket, "", pathArgs, headers, object); return execute(request, object); } private Response execute(PutMethod request, S3Object object) throws IOException { if (object.getLength() > EXPECT_SIZE) request.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true); // request.setContentChunked(true); request.setRequestEntity(new ByteArrayRequestEntity(object.getData())); executeRelease(request); return new Response(request); } /** * Get the ACL for a given bucket * @param bucket The name of the bucket where the object lives. * @param headers A Map of String to List of Strings representing the http * headers to pass (can be null). */ public GetResponse getACL(Bucket bucket, Headers headers) throws IOException { return getACL(bucket, "", headers); } /** * Get the ACL for a given object (or bucket, if key is null). * @param bucket The name of the bucket where the object lives. * @param key The name of the key to use. * @param headers A Map of String to List of Strings representing the http * headers to pass (can be null). */ public GetResponse getACL(Bucket bucket, String key, Headers headers) throws IOException { if (key == null) key = ""; Map pathArgs = Collections.singletonMap("acl", ""); HttpMethod method = makeRequest(Method.GET, bucket, key, pathArgs, headers); try { execute(method); return new GetResponse(method); } finally { method.releaseConnection(); } } /** * Write a new ACL for a given bucket * @param aclXMLDoc The xml representation of the ACL as a String * @param bucket The name of the bucket where the object lives. * @param headers A Map of String to List of Strings representing the http * headers to pass (can be null). */ public Response putACL(Bucket bucket, String aclXMLDoc, Headers headers) throws IOException { return putACL(bucket, "", aclXMLDoc, headers); } /** * Write a new ACL for a given object * @param aclXMLDoc The xml representation of the ACL as a String * @param bucket The name of the bucket where the object lives. * @param key The name of the key to use. * @param headers A Map of String to List of Strings representing the http * headers to pass (can be null). */ public Response putACL(Bucket bucket, String key, String aclXMLDoc, Headers headers) throws IOException { S3Object object = new S3Object(aclXMLDoc); Map pathArgs = Collections.singletonMap("acl", ""); PutMethod request = (PutMethod) makeRequest(Method.PUT, bucket, key, pathArgs, headers, object); return execute(request, object); } /** * Returns the bucket location. */ public LocationResponse getLocation(Bucket bucket) throws IOException { Map pathArgs = Collections.singletonMap("location", ""); HttpMethod method = makeRequest(Method.GET, bucket, "", pathArgs, null); try { execute(method); return new LocationResponse(method); } finally { method.releaseConnection(); } } /** * Lists all the buckets created by this account. */ public ListAllBucketsResponse listAllBuckets(Headers headers) throws IOException { HttpMethod method = makeRequest(Method.GET, null, "", null, headers); try { execute(method); return new ListAllBucketsResponse(method); } finally { method.releaseConnection(); } } /** * Lists all the buckets created by this account. */ public ListAllBucketsResponse listAllBuckets() throws IOException { return listAllBuckets(null); } /** * Make a new HttpMethod without passing an S3Object parameter. * Use this method for key operations that do require arguments * @param method The method to invoke * @param bucketName the bucket this request is for * @param key the key this request is for * @param pathArgs the * @param headers * @return * @throws IOException */ private HttpMethod makeRequest(Method method, Bucket bucket, String key, Map pathArgs, Headers headers) throws IOException { return makeRequest(method, bucket, key, pathArgs, headers, null); } private HttpMethod makeRequest(Method method, Bucket bucket) throws IOException { return makeRequest(method, bucket, null); } private HttpMethod makeRequest(Method method, Bucket bucket, Headers headers) throws IOException { return makeRequest(method, bucket, null, headers); } private HttpMethod makeRequest(Method method, Bucket bucket, Map pathArgs, Headers headers) throws IOException { return makeRequest(method, bucket, "", pathArgs, headers); } /** * Make a new HttpMethod. * @param method The HTTP method to use (GET, PUT, DELETE) * @param bucketNamePattern The bucket name this request affects * @param key The key this request is for, not encoded * @param pathArgs parameters if any to be sent along this request * @param headers A Map of String to List of Strings representing the http * headers to pass (can be null). * @param object The S3Object that is to be written (can be null). */ private HttpMethod makeRequest(Method method, Bucket bucket, String key, Map pathArgs, Headers headers, S3Object object) throws IOException { HttpMethod httpMethod = method.createHttpMethod(); URI uri = this.callingFormat.getURI(this.isSecure, server, this.port, bucket, key, pathArgs); httpMethod.setURI(uri); addHeaders(httpMethod, headers); if (object != null) addMetadataHeaders(httpMethod, object.getMetadata()); addAuthHeader(httpMethod, method, bucket, key, pathArgs); return httpMethod; } /** * Add the given headers to the HttpMethod. * @param httpMethod The HttpMethod to which the headers will be added. * @param headers A Map of String to List of Strings representing the http * headers to pass (can be null). */ private void addHeaders(HttpMethod httpMethod, Headers headers) { addHeaders(httpMethod, headers, ""); } /** * Add the given metadata fields to the HttpMethod. * @param httpMethod The HttpMethod to which the headers will be added. * @param metadata A Map of String to List of Strings representing the s3 * metadata for this resource. */ private void addMetadataHeaders(HttpMethod httpMethod, Headers metadata) { addHeaders(httpMethod, metadata, Headers.METADATA_PREFIX); } /** * Add the given headers to the HttpMethod with a prefix before the keys. * @param httpMethod The HttpMethod to which the headers will be added. * @param headers A Map of String to List of Strings representing the http * headers to pass (can be null). * @param prefix The string to prepend to each key before adding it to the connection. */ private void addHeaders(HttpMethod httpMethod, Headers headers, String prefix) { if (headers != null) { for (Map.Entry> me : headers.getHeaders().entrySet()) { String key = me.getKey(); for (String value : me.getValue()) { httpMethod.addRequestHeader(prefix + key, value); } } } } /** * Add the appropriate Authorization header to the HttpMethod. * @param httpMethod The HttpMethod to which the header will be added. * @param method The HTTP method to use (GET, PUT, DELETE) * @param bucket the bucket name this request is for * @param key the key this request is for (not URL encoded) * @param pathArgs path arguments which are part of this request */ private void addAuthHeader(HttpMethod httpMethod, Method method, Bucket bucket, String key, Map pathArgs) { if (httpMethod.getRequestHeader("Date") == null) { httpMethod.setRequestHeader("Date", httpDate()); } if (httpMethod.getRequestHeader("Content-Type") == null) { httpMethod.setRequestHeader("Content-Type", ""); } Headers prop = new Headers(httpMethod.getRequestHeaders()); String enckey = UrlEncoder.encode(key); String canonicalString = CanonicalString.make(method, bucket, enckey, pathArgs, prop); String encodedCanonical = CanonicalString.encode(this.awsSecretAccessKey, canonicalString); httpMethod.setRequestHeader("Authorization", "AWS " + this.awsAccessKeyId + ":" + encodedCanonical); } /** * Generate an rfc822 date for use in the Date HTTP header. */ private static String httpDate() { final String DateFormat = "EEE, dd MMM yyyy HH:mm:ss "; SimpleDateFormat format = new SimpleDateFormat( DateFormat, Locale.US ); format.setTimeZone( TimeZone.getTimeZone( "UTC" ) ); return format.format( new Date() ) + "GMT"; } /** * Shuts down any managed or pooled connections. */ public void shutdown() { connectionManager.shutdown(); } /** * Returns a debug string. */ @Override public String toString() { return "Connection id=" + awsAccessKeyId + " isSecure=" + isSecure + " server=" + server + " port=" + port + " format=" + callingFormat; } } libexml-java-0.0.20080703.orig/amazon-s3/src/main/java/net/noderunner/amazon/s3/Entry.java0000644000175000017500000000546110772111125030515 0ustar twernertwerner// This software code is made available "AS IS" without warranties of any // kind. You may copy, display, modify and redistribute the software // code either by itself or as incorporated into your code; provided that // you do not remove any proprietary notices. Your use of this software // code is at your own risk and you waive any claim against Amazon // Digital Services, Inc. or its affiliates with respect to your use of // this software code. (c) 2006 Amazon Digital Services, Inc. or its // affiliates. package net.noderunner.amazon.s3; import java.util.Date; /** * A structure representing a single object stored in S3. */ public class Entry implements Comparable { private String key; private Date lastModified; private String eTag; private long size; private String storageClass; private Owner owner; /** * Constructs a new Entry. */ Entry() { } /** * Constructs a new Entry. */ public Entry(String key) { setKey(key); } /** * Sets lastModified. */ public void setLastModified(Date lastModified) { this.lastModified = lastModified; } /** * The date at which the object was last modified. */ public Date getLastModified() { return (Date) lastModified.clone(); } /** * Returns the key */ @Override public String toString() { return getKey(); } /** * Sets key. */ void setKey(String key) { this.key = key; } /** * Returns the name of the object */ public String getKey() { return key; } /** * Sets eTag. */ void setETag(String eTag) { this.eTag = eTag; } /** * Returns the object's ETag, which can be used for conditional GETs. */ public String getETag() { return eTag; } /** * Sets owner. */ public void setOwner(Owner owner) { this.owner = owner; } /** * Returns the object's owner */ public Owner getOwner() { return owner; } /** * Sets size. */ public void setSize(long size) { this.size = size; } /** * Returns the size of the object in bytes. */ public long getSize() { return size; } /** * Sets storageClass. */ void setStorageClass(String storageClass) { this.storageClass = storageClass; } /** * The object's storage class */ public String getStorageClass() { return storageClass; } /** * Returns true if other is an entry with the same key. */ @Override public boolean equals(Object other) { if (!(other instanceof Entry)) return false; Entry entry = (Entry)other; return key.equals(entry.key); } /** * Calculates hash using the key. */ @Override public int hashCode() { return key.hashCode(); } /** * Compares by key name. */ public int compareTo(Entry other) { return key.compareTo(other.key); } } libexml-java-0.0.20080703.orig/amazon-s3/src/main/java/net/noderunner/amazon/s3/UrlEncoder.java0000644000175000017500000000171310770333236031461 0ustar twernertwerner// This software code is made available "AS IS" without warranties of any // kind. You may copy, display, modify and redistribute the software // code either by itself or as incorporated into your code; provided that // you do not remove any proprietary notices. Your use of this software // code is at your own risk and you waive any claim against Amazon // Digital Services, Inc. or its affiliates with respect to your use of // this software code. (c) 2006-2007 Amazon Digital Services, Inc. or its // affiliates. package net.noderunner.amazon.s3; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; class UrlEncoder { private UrlEncoder() {} static String encode(String unencoded) { try { return URLEncoder.encode(unencoded, "UTF-8"); } catch (UnsupportedEncodingException e) { // should never happen throw new RuntimeException("Could not url encode to UTF-8", e); } } } ././@LongLink0000000000000000000000000000015400000000000011565 Lustar rootrootlibexml-java-0.0.20080703.orig/amazon-s3/src/main/java/net/noderunner/amazon/s3/ListAllBucketsResponse.javalibexml-java-0.0.20080703.orig/amazon-s3/src/main/java/net/noderunner/amazon/s3/ListAllBucketsRespon0000644000175000017500000000524710772111125032552 0ustar twernertwerner// This software code is made available "AS IS" without warranties of any // kind. You may copy, display, modify and redistribute the software // code either by itself or as incorporated into your code; provided that // you do not remove any proprietary notices. Your use of this software // code is at your own risk and you waive any claim against Amazon // Digital Services, Inc. or its affiliates with respect to your use of // this software code. (c) 2006 Amazon Digital Services, Inc. or its // affiliates. package net.noderunner.amazon.s3; import java.io.IOException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.apache.commons.httpclient.HttpMethod; import org.xml.sax.Attributes; import org.xml.sax.helpers.DefaultHandler; /** * Response for listing all buckets. */ public class ListAllBucketsResponse extends Response { private List entries; ListAllBucketsResponse(HttpMethod method) throws IOException { super(method); if (isOk()) { entries = new ArrayList(); parse(new ListAllMyBucketsHandler()); } } /** * Returns the bucket entries, unmodifiable. */ public List getEntries() { return Collections.unmodifiableList(entries); } class ListAllMyBucketsHandler extends DefaultHandler { private Bucket currBucket = null; private StringBuilder currText = null; private SimpleDateFormat iso8601Parser = null; public ListAllMyBucketsHandler() { super(); this.iso8601Parser = new ISO801DateFormat(); this.currText = new StringBuilder(); } @Override public void startElement(String uri, String name, String qName, Attributes attrs) { if (name.equals("Bucket")) { this.currBucket = new Bucket(); } } @Override public void endElement(String uri, String name, String qName) { if (name.equals("Bucket")) { entries.add(this.currBucket); } else if (name.equals("Name")) { if (currBucket == null) throw new IllegalStateException(); this.currBucket.setName(this.currText.toString()); } else if (name.equals("CreationDate")) { try { this.currBucket.setCreationDate(this.iso8601Parser .parse(this.currText.toString())); } catch (ParseException e) { throw new RuntimeException( "Unexpected date format in list bucket output", e); } } this.currText = new StringBuilder(); } @Override public void characters(char ch[], int start, int length) { this.currText.append(ch, start, length); } } @Override public String toString() { return super.toString() + " entries=" + entries; } } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootlibexml-java-0.0.20080703.orig/amazon-s3/src/main/java/net/noderunner/amazon/s3/GetStreamResponse.javalibexml-java-0.0.20080703.orig/amazon-s3/src/main/java/net/noderunner/amazon/s3/GetStreamResponse.ja0000644000175000017500000000336710770333236032511 0ustar twernertwerner// This software code is made available "AS IS" without warranties of any // kind. You may copy, display, modify and redistribute the software // code either by itself or as incorporated into your code; provided that // you do not remove any proprietary notices. Your use of this software // code is at your own risk and you waive any claim against Amazon // Digital Services, Inc. or its affiliates with respect to your use of // this software code. (c) 2006 Amazon Digital Services, Inc. or its // affiliates. package net.noderunner.amazon.s3; import java.io.IOException; import java.io.InputStream; import org.apache.commons.httpclient.methods.GetMethod; /** * A Response object returned from Connection.getStream(). * This response, once read, must be released by calling {@link #release()}. */ public class GetStreamResponse extends Response { private GetMethod method; /** * Pulls a representation of an S3Object out of the HttpURLConnection * response. */ GetStreamResponse(GetMethod method) throws IOException { super(method); this.method = method; } /** * Returns an input stream for the content. * Call {@link #release}) after done reading. * @throws IOException */ public InputStream getInputStream() throws IOException { InputStream body = method.getResponseBodyAsStream(); if (body == null) throw new IllegalStateException("body null"); return body; } /** * Returns the content length, if known. */ public long getLength() { return method.getResponseContentLength(); } /** * Releases this connection. */ public void release() { method.releaseConnection(); } /** * Returns a debug string. */ @Override public String toString() { return super.toString() + " method=" + method; } } libexml-java-0.0.20080703.orig/amazon-s3/src/main/java/net/noderunner/amazon/s3/Headers.java0000644000175000017500000000637210770333236031000 0ustar twernertwernerpackage net.noderunner.amazon.s3; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TreeMap; import org.apache.commons.httpclient.Header; /** * HTTP header wrapper. * * @author Elias Ross */ public class Headers { public static final String METADATA_PREFIX = "x-amz-meta-"; private Map> headers; /** * Constructs a new Headers object. */ public Headers(Map> headers) { this.headers = headers; } /** * Copy-constructs new Headers. */ public Headers(Headers headers) { this(); for (Map.Entry> me : headers.headers.entrySet()) { for (String v : me.getValue()) put(me.getKey(), v); } } /** * Constructs a new Headers object. */ public Headers() { this(new HashMap>()); } /** * Constructs a new Headers object. */ public Headers(Header[] requestHeaders) { this(); for (Header h : requestHeaders) { put(h.getName(), h.getValue()); } } /** * Adds a header. */ public void put(String header, String value) { if (headers.containsKey(header)) { headers.get(header).add(value); } else { headers.put(header, new ArrayList(Collections.singletonList(value))); } } /** * Returns headers. */ public Map> getHeaders() { return headers; } /** * Returns a list of values. */ public List getValues(String header) { return headers.get(header); } public String getValue(String header) { List values = getValues(header); if (values == null || values.isEmpty()) return null; return values.get(0); } /** * Returns the number of headers. */ public int size() { return headers.size(); } /** * Returns a new Headers object with metadata from this object. */ public Headers extractMetadata() { TreeMap> metadata = new TreeMap>(); for (Map.Entry> me : headers.entrySet()) { String key = me.getKey(); if (key == null) continue; if (key.startsWith(METADATA_PREFIX)) { metadata.put(key.substring(METADATA_PREFIX.length()), me.getValue()); } } return new Headers(metadata); } /** * Returns new headers with metadata. */ public Headers mergeMetadata(Headers metadata) { if (metadata == null) return this; Map> merged = new TreeMap>(this.headers); for (Map.Entry> me : metadata.headers.entrySet()) { String key = me.getKey(); String metadataKey = METADATA_PREFIX + key; if (merged.containsKey(metadataKey)) { merged.get(metadataKey).addAll(me.getValue()); } else { merged.put(metadataKey, me.getValue()); } } return new Headers(merged); } /** * Returns a debug string. */ @Override public String toString() { return "headers=" + headers; } } libexml-java-0.0.20080703.orig/amazon-s3/src/main/java/net/noderunner/amazon/s3/S3Object.java0000644000175000017500000000342610770333236031036 0ustar twernertwerner// This software code is made available "AS IS" without warranties of any // kind. You may copy, display, modify and redistribute the software // code either by itself or as incorporated into your code; provided that // you do not remove any proprietary notices. Your use of this software // code is at your own risk and you waive any claim against Amazon // Digital Services, Inc. or its affiliates with respect to your use of // this software code. (c) 2006 Amazon Digital Services, Inc. or its // affiliates. package net.noderunner.amazon.s3; /** * A representation of a single object stored in S3. */ public class S3Object { /** * Data itself. */ private byte[] data; /** * Meta-data headers. */ private Headers metadata; /** * Constructs a new S3Object. * @param data * @param metadata */ public S3Object(byte[] data, Headers metadata) { this.data = data; this.metadata = metadata; } /** * Constructs a new S3Object. */ public S3Object(byte[] data) { this(data, null); } /** * Constructs a new S3Object; data is converted to bytes. */ public S3Object(String data) { this(data.getBytes()); } /** * Returns data. */ public byte[] getData() { return data; } /** * Returns the length of data. */ public int getLength() { return data.length; } /** * Returns metadata, unmodifiable. */ public Headers getMetadata() { return metadata; } /** * Sets the metadata. */ public void setMetadata(Headers metadata) { this.metadata = metadata; } /** * Returns a debug string. */ @Override public String toString() { return "S3Object[" + " data.length=" + this.data.length + " metadata=" + this.metadata + "]"; } } libexml-java-0.0.20080703.orig/amazon-s3/src/main/java/net/noderunner/amazon/s3/QueryGenerator.java0000644000175000017500000002004610770333236032373 0ustar twernertwerner// This software code is made available "AS IS" without warranties of any // kind. You may copy, display, modify and redistribute the software // code either by itself or as incorporated into your code; provided that // you do not remove any proprietary notices. Your use of this software // code is at your own risk and you waive any claim against Amazon // Digital Services, Inc. or its affiliates with respect to your use of // this software code. (c) 2006-2007 Amazon Digital Services, Inc. or its // affiliates. package net.noderunner.amazon.s3; import java.io.IOException; import java.security.Key; import java.util.HashMap; import java.util.Map; import org.apache.commons.httpclient.URI; /** * Generates URL Query Strings that can be used to perform operations. * These parameters include an expiration date, so that * if you hand them off to someone else, they will only work for a limited amount of time. */ public class QueryGenerator { private String awsAccessKeyId; private Key awsSecretAccessKey; private boolean isSecure; private String server; private int port; private CallingFormat callingFormat; private Long expiresIn = null; private Long expires = null; // by default, expire in 1 minute. private static final Long DEFAULT_EXPIRES_IN = new Long(60 * 1000); public QueryGenerator(String awsAccessKeyId, String awsSecretAccessKey) { this(awsAccessKeyId, awsSecretAccessKey, true); } public QueryGenerator(String awsAccessKeyId, String awsSecretAccessKey, boolean isSecure) { this(awsAccessKeyId, awsSecretAccessKey, isSecure, Connection.DEFAULT_HOST); } public QueryGenerator(String awsAccessKeyId, String awsSecretAccessKey, boolean isSecure, String server) { this(awsAccessKeyId, awsSecretAccessKey, isSecure, server, isSecure ? Connection.SECURE_PORT : Connection.INSECURE_PORT); } public QueryGenerator(String awsAccessKeyId, String awsSecretAccessKey, boolean isSecure, String server, int port) { this(awsAccessKeyId, awsSecretAccessKey, isSecure, server, port, CallingFormat.SUBDOMAIN); } public QueryGenerator(String awsAccessKeyId, String awsSecretAccessKey, boolean isSecure, String server, CallingFormat callingFormat) { this(awsAccessKeyId, awsSecretAccessKey, isSecure, server, isSecure ? Connection.SECURE_PORT : Connection.INSECURE_PORT, callingFormat); } public QueryGenerator(String awsAccessKeyId, String awsSecretAccessKey, boolean isSecure, String server, int port, CallingFormat callingFormat) { this.awsAccessKeyId = awsAccessKeyId; this.awsSecretAccessKey = CanonicalString.key(awsSecretAccessKey); this.isSecure = isSecure; this.server = server; this.port = port; this.callingFormat = callingFormat; this.expiresIn = DEFAULT_EXPIRES_IN; this.expires = null; } public void setCallingFormat(CallingFormat format) { this.callingFormat = format; } public void setExpires(long millisSinceEpoch) { expires = new Long(millisSinceEpoch); expiresIn = null; } public void setExpiresIn(long millis) { expiresIn = new Long(millis); expires = null; } public URI create(Bucket bucket, Headers headers) { // validate bucket name if (!bucket.validateName(callingFormat)) throw new IllegalArgumentException("Invalid Bucket Name: "+bucket); return generateURI(Method.PUT, bucket, "", headers); } public URI list(Bucket bucket, String prefix, String marker, Integer maxKeys, Headers headers){ return list(bucket, prefix, marker, maxKeys, null, headers); } public URI list(Bucket bucket, String prefix, String marker, Integer maxKeys, String delimiter, Headers headers) { return generateURI(Method.GET, bucket, headers); } public URI delete(Bucket bucket, Headers headers) { return generateURI(Method.DELETE, bucket, headers); } public URI put(Bucket bucket, String key, S3Object object, Headers headers) { Headers metadata = null; if (object != null) { metadata = object.getMetadata(); } if (headers == null) { headers = new Headers(); } return generateURI(Method.PUT, bucket, key, headers.mergeMetadata(metadata)); } public URI get(Bucket bucket, String key, Headers headers) { return generateURI(Method.GET, bucket, key, headers); } public URI delete(Bucket bucket, String key, Headers headers) { return generateURI(Method.DELETE, bucket, key, headers); } private Map map(String name) { HashMap map = new HashMap(); map.put(name, ""); return map; } public URI getBucketLogging(Bucket bucket, Headers headers) { return generateURI(Method.GET, bucket, "", map("logging"), headers); } public URI putBucketLogging(Bucket bucket, Headers headers) { return generateURI(Method.PUT, bucket, "", map("logging"), headers); } public URI getACL(Bucket bucket, Headers headers) { return getACL(bucket, "", headers); } public URI getACL(Bucket bucket, String key, Headers headers) { return generateURI(Method.GET, bucket, key, map("acl"), headers); } public URI putACL(Bucket bucket, Headers headers) { return putACL(bucket, "", headers); } public URI putACL(Bucket bucket, String key, Headers headers) { return generateURI(Method.PUT, bucket, key, map("acl"), headers); } public URI listAllBuckets(Headers headers) { return generateURI(Method.GET, headers); } public URI listAllBuckets() { return listAllBuckets(null); } public String makeBareURI(Bucket bucket, String key) { StringBuilder buffer = new StringBuilder(); if (this.isSecure) { buffer.append("https://"); } else { buffer.append("http://"); } buffer.append(this.server).append(":").append(this.port).append("/").append(bucket); buffer.append("/").append(UrlEncoder.encode(key)); return buffer.toString(); } @SuppressWarnings("unchecked") private URI generateURI(Method method, Bucket bucket, String key, Headers headers) { return generateURI(method, bucket, key, new HashMap(), headers); } private URI generateURI(Method method, Bucket bucket, Headers headers) { return generateURI(method, bucket, "", headers); } private URI generateURI(Method method, Headers headers) { return generateURI(method, null, headers); } private URI generateURI(Method method, Bucket bucket, String key, Map pathArgs, Headers headers) { long expires = 0L; if (this.expiresIn != null) { expires = System.currentTimeMillis() + this.expiresIn.longValue(); } else if (this.expires != null) { expires = this.expires.longValue(); } else { throw new RuntimeException("Illegal expires state"); } // convert to seconds expires /= 1000; String enckey = UrlEncoder.encode(key); String canonicalString = CanonicalString.make(method, bucket, enckey, pathArgs, headers, ""+expires); String encodedCanonical = CanonicalString.encode(this.awsSecretAccessKey, canonicalString); pathArgs.put("Signature", encodedCanonical); pathArgs.put("Expires", Long.toString(expires)); pathArgs.put("AWSAccessKeyId", this.awsAccessKeyId); try { return this.callingFormat.getURI(this.isSecure, server, port, bucket, key, pathArgs); } catch (IOException e) { throw new IllegalStateException("Unable to generate URI " + e); } } } libexml-java-0.0.20080703.orig/amazon-s3/src/main/java/net/noderunner/amazon/s3/Bucket.java0000644000175000017500000000635210770333236030640 0ustar twernertwerner// This software code is made available "AS IS" without warranties of any // kind. You may copy, display, modify and redistribute the software // code either by itself or as incorporated into your code; provided that // you do not remove any proprietary notices. Your use of this software // code is at your own risk and you waive any claim against Amazon // Digital Services, Inc. or its affiliates with respect to your use of // this software code. (c) 2006 Amazon Digital Services, Inc. or its // affiliates. package net.noderunner.amazon.s3; import java.util.Date; import java.util.regex.Pattern; /** * A class representing a single bucket. */ public class Bucket { /** * The name of the bucket. */ private String name; /** * The bucket's creation date. */ private Date creationDate; Bucket() { } /** * Constructs a new Bucket. * * @param name non-null name */ public Bucket(String name) { if (name == null) throw new NullPointerException(); this.name = name; } /** * Returns name. */ public String getName() { return name; } /** * Returns true if specified; length is non-zero. */ public boolean specified() { return name.length() != 0; } /** * Sets name. */ void setName(String name) { this.name = name; } /** * Returns creationDate. */ public Date getCreationDate() { return creationDate; } /** * Sets creationDate. */ void setCreationDate(Date creationDate) { this.creationDate = creationDate; } /** * Returns the name. */ @Override public String toString() { return name; } static Pattern bucketPath = Pattern.compile("^[0-9A-Za-z\\.\\-_]*$"); static Pattern ipv4Pattern = Pattern.compile("^[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+$"); static Pattern bucketNamePattern = Pattern.compile("^[a-z0-9]([a-z0-9\\-]*[a-z0-9])?(\\.[a-z0-9]([a-z0-9\\-]*[a-z0-9])?)*$"); /** * Returns true if the bucket name is valid for the calling format. */ public static boolean validateBucketName(String bucketName, CallingFormat callingFormat) { if (callingFormat == CallingFormat.PATH) { final int MIN_BUCKET_LENGTH = 3; final int MAX_BUCKET_LENGTH = 255; return null != bucketName && bucketName.length() >= MIN_BUCKET_LENGTH && bucketName.length() <= MAX_BUCKET_LENGTH && bucketPath.matcher(bucketName).matches(); } else { final int MIN_BUCKET_LENGTH = 3; final int MAX_BUCKET_LENGTH = 63; // If there wasn't a location-constraint, then the current actual // restriction is just that no 'part' of the name (i.e. sequence // of characters between any 2 '.'s has to be 63) but the recommendation // is to keep the entire bucket name under 63. return null != bucketName && bucketName.length() >= MIN_BUCKET_LENGTH && bucketName.length() <= MAX_BUCKET_LENGTH && !ipv4Pattern.matcher(bucketName).matches() && bucketNamePattern.matcher(bucketName).matches(); } } /** * Returns true if the bucket name is valid for the calling format. */ public boolean validateName(CallingFormat callingFormat) { return validateBucketName(name, callingFormat); } } ././@LongLink0000000000000000000000000000014500000000000011565 Lustar rootrootlibexml-java-0.0.20080703.orig/amazon-s3/src/main/java/net/noderunner/amazon/s3/CanonicalString.javalibexml-java-0.0.20080703.orig/amazon-s3/src/main/java/net/noderunner/amazon/s3/CanonicalString.java0000644000175000017500000001436010770333236032477 0ustar twernertwernerpackage net.noderunner.amazon.s3; import java.nio.charset.Charset; import java.security.InvalidKeyException; import java.security.Key; import java.security.NoSuchAlgorithmException; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.SortedMap; import java.util.TreeMap; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import org.apache.commons.codec.binary.Base64; import org.apache.commons.httpclient.util.EncodingUtil; /** * Creates canonical strings for authorization purposes by hashing * the request against an authorization key. * * @author Elias Ross */ public class CanonicalString { private static final String AMAZON_HEADER_PREFIX = "x-amz-"; private static final String ALTERNATIVE_DATE_HEADER = "x-amz-date"; private static final Charset UTF8 = Charset.forName("UTF-8"); /** * HMAC/SHA1 Algorithm per RFC 2104. */ private static final String HMAC_SHA1_ALGORITHM = "HmacSHA1"; private CanonicalString() { } /** * Returns a canonical string used in authentication. */ public static String make(Method method, Bucket bucket, String key, Map pathArgs, Headers headers) { return make(method, bucket, key, pathArgs, headers, null); } /** * Returns a canonical string used in authentication. * * @param expires When non-null, it will be used instead of the Date header. * @param key URL-encoded string */ public static String make(Method method, Bucket bucket, String key, Map pathArgs, Headers headers, String expires) { StringBuilder buf = new StringBuilder(128); buf.append(method.name()).append("\n"); // Add all interesting headers to a list, then sort them. "Interesting" // is defined as Content-MD5, Content-Type, Date, and x-amz- SortedMap interestingHeaders = new TreeMap(); if (headers != null) { for (Map.Entry> me : headers.getHeaders().entrySet()) { String hashKey = me.getKey(); if (hashKey == null) continue; String lk = hashKey.toLowerCase(Locale.US); // Ignore any headers that are not particularly interesting. if (lk.equals("content-type") || lk.equals("content-md5") || lk.equals("date") || lk.startsWith(AMAZON_HEADER_PREFIX)) { interestingHeaders.put(lk, concatenateList(me.getValue())); } } } if (interestingHeaders.containsKey(ALTERNATIVE_DATE_HEADER)) { interestingHeaders.put("date", ""); } // if the expires is non-null, use that for the date field. this // trumps the x-amz-date behavior. if (expires != null) { interestingHeaders.put("date", expires); } // these headers require that we still put a new line in after them, // even if they don't exist. if (! interestingHeaders.containsKey("content-type")) { interestingHeaders.put("content-type", ""); } if (! interestingHeaders.containsKey("content-md5")) { interestingHeaders.put("content-md5", ""); } // Finally, add all the interesting headers (i.e.: all that startwith x-amz- ;-)) for (Map.Entry me : interestingHeaders.entrySet()) { String headerKey = me.getKey(); if (headerKey.startsWith(AMAZON_HEADER_PREFIX)) { buf.append(headerKey).append(':').append(me.getValue()); } else { buf.append(me.getValue()); } buf.append("\n"); } // build the path using the bucket and key if (bucket != null && bucket.specified()) { buf.append("/" + bucket.getName() ); } // append the key (it might be an empty string) // append a slash regardless buf.append("/"); if (key != null) { buf.append(key); } // if there is an acl, logging or torrent parameter // add them to the string if (pathArgs != null ) { if (pathArgs.containsKey("acl")) { buf.append("?acl"); } else if (pathArgs.containsKey("torrent")) { buf.append("?torrent"); } else if (pathArgs.containsKey("logging")) { buf.append("?logging"); } else if (pathArgs.containsKey("location")) { buf.append("?location"); } } return buf.toString(); } /** * Concatenates a bunch of header values, separating them with a comma. * @param values List of header values. * @return String of all headers, with commas. */ private static String concatenateList(List values) { StringBuilder buf = new StringBuilder(); for (int i = 0, size = values.size(); i < size; ++ i) { buf.append(values.get(i).replaceAll("\n", "").trim()); if (i != (size - 1)) { buf.append(","); } } return buf.toString(); } /** * Returns an encrypted key for the access key. */ static Key key(String awsSecretAccessKey) { // The following HMAC/SHA1 code for the signature is taken from the // AWS Platform's implementation of RFC2104 (amazon.webservices.common.Signature) // // Acquire an HMAC/SHA1 from the raw key bytes. SecretKeySpec signingKey = new SecretKeySpec(awsSecretAccessKey.getBytes(), HMAC_SHA1_ALGORITHM); return signingKey; } /** * Calculate the HMAC/SHA1 on a string. * @return Signature */ static String encode(Key signingKey, String canonicalString) { Mac mac; try { mac = Mac.getInstance(HMAC_SHA1_ALGORITHM); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("Could not find sha1 algorithm", e); } try { mac.init(signingKey); } catch (InvalidKeyException e) { throw new RuntimeException("Could not initialize the MAC algorithm", e); } mac.update(UTF8.encode(canonicalString)); byte[] encode = Base64.encodeBase64(mac.doFinal()); return EncodingUtil.getAsciiString(encode); } } libexml-java-0.0.20080703.orig/amazon-s3/src/main/java/net/noderunner/amazon/s3/Method.java0000644000175000017500000000136110770333236030636 0ustar twernertwernerpackage net.noderunner.amazon.s3; import org.apache.commons.httpclient.HttpMethod; import org.apache.commons.httpclient.methods.DeleteMethod; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.methods.HeadMethod; import org.apache.commons.httpclient.methods.PutMethod; /** * HTTP Methods. * * @author Elias Ross */ public enum Method { GET, PUT, DELETE, HEAD; /** * Returns a new HTTP method for processing. */ HttpMethod createHttpMethod() { switch (this) { case PUT: return new PutMethod(); case GET: return new GetMethod(); case DELETE: return new DeleteMethod(); case HEAD: return new HeadMethod(); } throw new Error(); } }libexml-java-0.0.20080703.orig/amazon-s3/src/main/java/net/noderunner/amazon/s3/CallingFormat.java0000644000175000017500000001102610772111125032130 0ustar twernertwerner// This software code is made available "AS IS" without warranties of any // kind. You may copy, display, modify and redistribute the software // code either by itself or as incorporated into your code; provided that // you do not remove any proprietary notices. Your use of this software // code is at your own risk and you waive any claim against Amazon // Digital Services, Inc. or its affiliates with respect to your use of // this software code. (c) 2006-2007 Amazon Digital Services, Inc. or its // affiliates. package net.noderunner.amazon.s3; import java.util.Map; import org.apache.commons.httpclient.HttpURL; import org.apache.commons.httpclient.HttpsURL; import org.apache.commons.httpclient.URI; import org.apache.commons.httpclient.URIException; /** * Calling formats. * * @author Elias Ross */ public abstract class CallingFormat { /** * Call by using a path. */ public final static CallingFormat PATH = new PathCallingFormat(); /** * Call by using a sub-domain of the bucket name. */ public final static CallingFormat SUBDOMAIN = new SubdomainCallingFormat(); /** * Call using a "vanity" or user-provided hostname. * The bucket name is in fact the domain name. */ public final static CallingFormat VANITY = new VanityCallingFormat(); public abstract boolean supportsLocatedBuckets(); public abstract String getEndpoint(String server, int port, Bucket bucket); public abstract String getPathBase(Bucket bucket, String key); public abstract URI getURI(boolean isSecure, String server, int port, Bucket bucket, String key, Map pathArgs) throws URIException; /** * Adds query parameters to the URL. */ private static URI addQuery(HttpURL uri, Map pathArgs) throws URIException { if (pathArgs == null || pathArgs.isEmpty()) return uri; int size = pathArgs.size(); String[] name = new String[size]; String[] value = new String[size]; int i = 0; for (Map.Entry me : pathArgs.entrySet()) { name[i] = me.getKey(); value[i] = me.getValue(); if (value[i] == null) throw new NullPointerException("query cannot contain null " + pathArgs); i++; } uri.setQuery(name, value); return uri; } private static URI url(boolean isSecure, String host, int port, String path, Map pathArgs) throws URIException { HttpURL url = isSecure ? new HttpsURL(host, port, "/") : new HttpURL(host, port, "/"); url.setEscapedPath(path); return addQuery(url, pathArgs); } static private class PathCallingFormat extends CallingFormat { @Override public boolean supportsLocatedBuckets() { return false; } @Override public String getPathBase(Bucket bucket, String key) { return isBucketSpecified(bucket) ? "/" + bucket + "/" + UrlEncoder.encode(key) : "/"; } @Override public String getEndpoint(String server, int port, Bucket bucket) { return server + ":" + port; } @Override public URI getURI(boolean isSecure, String server, int port, Bucket bucket, String key, Map pathArgs) throws URIException { String pathBase = isBucketSpecified(bucket) ? "/" + bucket + "/" + UrlEncoder.encode(key) : "/"; return url(isSecure, server, port, pathBase, pathArgs); } private boolean isBucketSpecified(Bucket bucket) { if (bucket == null) return false; if (bucket.getName().length() == 0) return false; return true; } } static private class SubdomainCallingFormat extends CallingFormat { @Override public boolean supportsLocatedBuckets() { return true; } public String getServer(String server, Bucket bucket) { return bucket + "." + server; } @Override public String getEndpoint(String server, int port, Bucket bucket) { return getServer(server, bucket) + ":" + port; } @Override public String getPathBase(Bucket bucket, String key) { return "/" + UrlEncoder.encode(key); } @Override public URI getURI(boolean isSecure, String server, int port, Bucket bucket, String key, Map pathArgs) throws URIException { if (bucket == null || !bucket.specified()) { return url(isSecure, server, port, "", pathArgs); } else { String serverToUse = getServer(server, bucket); String pathBase = getPathBase(bucket, key); return url(isSecure, serverToUse, port, pathBase, pathArgs); } } } static private class VanityCallingFormat extends SubdomainCallingFormat { @Override public String getServer(String server, Bucket bucket) { return bucket.getName(); } } } ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootlibexml-java-0.0.20080703.orig/amazon-s3/src/main/java/net/noderunner/amazon/s3/LocationResponse.javalibexml-java-0.0.20080703.orig/amazon-s3/src/main/java/net/noderunner/amazon/s3/LocationResponse.jav0000644000175000017500000000473710772111125032547 0ustar twernertwerner// This software code is made available "AS IS" without warranties of any // kind. You may copy, display, modify and redistribute the software // code either by itself or as incorporated into your code; provided that // you do not remove any proprietary notices. Your use of this software // code is at your own risk and you waive any claim against Amazon // Digital Services, Inc. or its affiliates with respect to your use of // this software code. (c) 2006-2007 Amazon Digital Services, Inc. or its // affiliates. package net.noderunner.amazon.s3; import java.io.IOException; import org.apache.commons.httpclient.HttpMethod; import org.xml.sax.Attributes; import org.xml.sax.helpers.DefaultHandler; /** * A Response object returned from AWSAuthConnection.getBucketLocation(). * Parses the response XML and exposes the location constraint * via the {@link #getLocation()} method. */ public class LocationResponse extends Response { private String location; /** * Parse the response to a ?location query. */ LocationResponse(HttpMethod method) throws IOException { super(method); if (isOk()) { parse(new LocationResponseHandler()); } } /** * Report the location-constraint for a bucket. * A value of null indicates an error; * the empty string indicates no constraint; * and any other value is an actual location constraint value. */ public String getLocation() { return location; } /** * Helper class to parse LocationConstraint response XML */ class LocationResponseHandler extends DefaultHandler { private StringBuilder currText = null; @Override public void startElement(String uri, String name, String qName, Attributes attrs) { if (name.equals("LocationConstraint")) { this.currText = new StringBuilder(); } } @Override public void endElement(String uri, String name, String qName) { if (name.equals("LocationConstraint")) { location = this.currText.toString(); this.currText = null; } } @Override public void characters(char ch[], int start, int length) { if (currText != null) this.currText.append(ch, start, length); } } @Override public String toString() { return super.toString() + " location=" + location; } } libexml-java-0.0.20080703.orig/amazon-s3/src/main/java/net/noderunner/amazon/s3/ListResponse.java0000644000175000017500000001722310772111125032045 0ustar twernertwerner// This software code is made available "AS IS" without warranties of any // kind. You may copy, display, modify and redistribute the software // code either by itself or as incorporated into your code; provided that // you do not remove any proprietary notices. Your use of this software // code is at your own risk and you waive any claim against Amazon // Digital Services, Inc. or its affiliates with respect to your use of // this software code. (c) 2006 Amazon Digital Services, Inc. or its // affiliates. package net.noderunner.amazon.s3; import java.io.IOException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.List; import org.apache.commons.httpclient.HttpMethod; import org.xml.sax.Attributes; import org.xml.sax.helpers.DefaultHandler; /** * Returned by {@link Connection#list}. */ public class ListResponse extends Response { private String name = null; private String prefix = null; private String marker = null; private String delimiter = null; private int maxKeys = 0; private boolean isTruncated = false; private String nextMarker = null; private List entries = null; private List commonPrefixEntries = null; ListResponse(HttpMethod method) throws IOException { super(method); if (isOk()) { parse(new ListBucketHandler()); } } /** * A List of CommonPrefixEntry objects representing the common prefixes of the * keys that matched up to the delimiter. Null if the request fails. */ public List getCommonPrefixEntries() { return commonPrefixEntries; } /** * Returns delimiter. */ public String getDelimiter() { return delimiter; } /** * A List of ListEntry objects representing the objects in the given bucket. */ public List getEntries() { return entries; } /** * Indicates if there are more results to the list. True if the current * list results have been truncated. false if request fails. */ public boolean isTruncated() { return isTruncated; } /** * Prefix entry. */ public static class CommonPrefixEntry { /** * The prefix common to the delimited keys it represents */ private String prefix; CommonPrefixEntry() { } /** * Returns prefix. */ public String getPrefix() { return prefix; } } class ListBucketHandler extends DefaultHandler { private boolean isEchoedPrefix = false; private Entry keyEntry = null; private CommonPrefixEntry commonPrefixEntry = null; private StringBuilder currText = null; private SimpleDateFormat iso8601Parser = null; public ListBucketHandler() { super(); entries = new ArrayList(); commonPrefixEntries = new ArrayList(); this.iso8601Parser = new ISO801DateFormat(); this.currText = new StringBuilder(); } @Override public void startDocument() { this.isEchoedPrefix = true; } @Override public void startElement(String uri, String name, String qName, Attributes attrs) { if (name.equals("Contents")) { this.keyEntry = new Entry(); } else if (name.equals("Owner")) { this.keyEntry.setOwner(new Owner()); } else if (name.equals("CommonPrefixes")){ this.commonPrefixEntry = new CommonPrefixEntry(); } this.currText = new StringBuilder(); } @Override public void endElement(String uri, String name, String qName) { if (name.equals("Name")) { ListResponse.this.name = this.currText.toString(); } // this prefix is the one we echo back from the request else if (name.equals("Prefix") && this.isEchoedPrefix) { prefix = this.currText.toString(); this.isEchoedPrefix = false; } else if (name.equals("Marker")) { marker = this.currText.toString(); } else if (name.equals("MaxKeys")) { maxKeys = Integer.parseInt(this.currText.toString()); } else if (name.equals("Delimiter")) { delimiter = this.currText.toString(); } else if (name.equals("IsTruncated")) { isTruncated = Boolean.valueOf(this.currText.toString()); } else if (name.equals("NextMarker")) { nextMarker = this.currText.toString(); } else if (name.equals("Contents")) { entries.add(this.keyEntry); } else if (name.equals("Key")) { this.keyEntry.setKey(this.currText.toString()); } else if (name.equals("LastModified")) { try { this.keyEntry.setLastModified(this.iso8601Parser.parse(this.currText.toString())); } catch (ParseException e) { throw new RuntimeException("Unexpected date format in list bucket output", e); } } else if (name.equals("ETag")) { this.keyEntry.setETag(this.currText.toString()); } else if (name.equals("Size")) { this.keyEntry.setSize(Long.parseLong(this.currText.toString())); } else if (name.equals("StorageClass")) { this.keyEntry.setStorageClass(this.currText.toString()); } else if (name.equals("ID")) { this.keyEntry.getOwner().setId(this.currText.toString()); } else if (name.equals("DisplayName")) { this.keyEntry.getOwner().setDisplayName(this.currText.toString()); } else if (name.equals("CommonPrefixes")) { commonPrefixEntries.add(this.commonPrefixEntry); } // this is the common prefix for keys that match up to the delimiter else if (name.equals("Prefix")) { this.commonPrefixEntry.prefix = this.currText.toString(); } } @Override public void characters(char ch[], int start, int length) { this.currText.append(ch, start, length); } } /** * The name of the bucket being listed. Null if request fails. */ public String getName() { return this.name; } /** * The prefix echoed back from the request. Null if request fails. */ public String getPrefix() { return this.prefix; } /** * The marker echoed back from the request. Null if request fails. */ public String getMarker() { return this.marker; } /** * The maxKeys echoed back from the request if specified. 0 if request fails. */ public int getMaxKeys(){ return this.maxKeys; } /** * The delimiter echoed back from the request. Null if not specified in * the request, or if it fails. */ public boolean getIsTruncated() { return this.isTruncated; } /** * Indicates what to use as a marker for subsequent list requests in the event * that the results are truncated. Present only when a delimiter is specified. * Null if request fails. */ public String getNextMarker() { return this.nextMarker; } @Override public String toString() { return super.toString() + " entries=" + entries + " name=" + name + " prefix=" + prefix + " marker=" + marker + " maxKeys=" + maxKeys + " isTruncated=" + isTruncated + " nextMarker=" + nextMarker + " prefix=" + commonPrefixEntries; } } libexml-java-0.0.20080703.orig/amazon-s3/src/main/java/net/noderunner/amazon/s3/Owner.java0000644000175000017500000000253210770333236030511 0ustar twernertwerner// This software code is made available "AS IS" without warranties of any // kind. You may copy, display, modify and redistribute the software // code either by itself or as incorporated into your code; provided that // you do not remove any proprietary notices. Your use of this software // code is at your own risk and you waive any claim against Amazon // Digital Services, Inc. or its affiliates with respect to your use of // this software code. (c) 2006 Amazon Digital Services, Inc. or its // affiliates. package net.noderunner.amazon.s3; /** * A structure representing the owner of an object, used as a part of ListEntry. */ public class Owner { private String id; private String displayName; Owner() { } /** * Constructs a new Owner. */ public Owner(String id, String displayName) { this.id = id; this.displayName = displayName; } /** * Sets displayName. */ void setDisplayName(String displayName) { this.displayName = displayName; } /** * Returns displayName. */ public String getDisplayName() { return displayName; } /** * Sets id. */ void setId(String id) { this.id = id; } /** * Returns id. */ public String getId() { return id; } /** * Returns a debug string. */ @Override public String toString() { return "Owner id=" + id + " displayName=" + displayName; } } ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootlibexml-java-0.0.20080703.orig/amazon-s3/src/main/java/net/noderunner/amazon/s3/ISO801DateFormat.javalibexml-java-0.0.20080703.orig/amazon-s3/src/main/java/net/noderunner/amazon/s3/ISO801DateFormat.jav0000644000175000017500000000056110770333236032110 0ustar twernertwernerpackage net.noderunner.amazon.s3; import java.text.SimpleDateFormat; import java.util.TimeZone; /** * Date format used by Amazon S3. * @author Elias Ross */ @SuppressWarnings("serial") public class ISO801DateFormat extends SimpleDateFormat { public ISO801DateFormat() { super("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); setTimeZone(TimeZone.getTimeZone("UTC")); } } libexml-java-0.0.20080703.orig/amazon-s3/src/main/java/net/noderunner/amazon/s3/Response.java0000644000175000017500000001011310770333236031207 0ustar twernertwerner// This software code is made available "AS IS" without warranties of any // kind. You may copy, display, modify and redistribute the software // code either by itself or as incorporated into your code; provided that // you do not remove any proprietary notices. Your use of this software // code is at your own risk and you waive any claim against Amazon // Digital Services, Inc. or its affiliates with respect to your use of // this software code. (c) 2006 Amazon Digital Services, Inc. or its // affiliates. package net.noderunner.amazon.s3; import java.io.IOException; import java.io.InputStream; import org.apache.commons.httpclient.Header; import org.apache.commons.httpclient.HttpMethod; import org.xml.sax.ContentHandler; import org.xml.sax.ErrorHandler; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.XMLReaderFactory; /** * The parent class of all other Responses.

    Returns status codes that * should be checked. */ public class Response { private HttpMethod method; Response(HttpMethod method) { this.method = method; } /** * Returns the HTTP response code. */ public int getResponseCode() throws IOException { return method.getStatusCode(); } /** * Returns the HTTP response message. */ public String getResponseMessage() throws IOException { return method.getStatusText(); } /** * Returns content length of the response. */ public int getContentLength() { return -1; // TODO } /** * Throws an IllegalStateException if not 200-level OK. */ public void assertOk() { if (isOk()) return; String msg; try { msg = method.getResponseBodyAsString(); } catch (IOException e) { msg = "?"; } throw new IllegalStateException("Unexpected response: " + this + " Message: " + msg); } /** * Returns an HTTP header field from the response. */ public String getHeaderField(String field) { Header header = method.getResponseHeader(field); if (header == null) return null; return header.getValue(); } /** * Returns all HTTP headers. * Prefer caching the return value. */ public Headers getHeaders() { return new Headers(method.getResponseHeaders()); } /** * Returns true if processing was 200-level OK. */ public boolean isOk() { try { int code = getResponseCode(); return code == 200 || code == 204; } catch (IOException e) { return false; } } /** * Returns true if processing returned 404. */ public boolean isNotFound() { try { return getResponseCode() == 404; } catch (IOException e) { return false; } } /** * Returns a string representation. */ @Override public String toString() { try { return "Response code=" + getResponseCode() + " msg='" + getResponseMessage() + "'"; } catch (IOException e) { throw new RuntimeException(e); } } /** * Parses the response. */ protected void parse(ContentHandler handler) throws IOException { try { XMLReader xr = createXMLReader(); xr.setContentHandler(handler); ErrorHandler eh = new ErrorHandler() { public void error(SAXParseException e) throws SAXException { throw e; } public void fatalError(SAXParseException e) throws SAXException { throw e; } public void warning(SAXParseException e) throws SAXException { throw e; } }; xr.setErrorHandler(eh); InputStream is = method.getResponseBodyAsStream(); xr.parse(new InputSource(is)); is.close(); } catch (SAXException e) { throw new RuntimeException("Unexpected error parsing ListBucket xml", e); } } static XMLReader createXMLReader() { try { return XMLReaderFactory.createXMLReader(); } catch (SAXException e) { // oops, lets try doing this (needed in 1.4) System.setProperty("org.xml.sax.driver", "org.apache.crimson.parser.XMLReaderImpl"); } try { // try once more return XMLReaderFactory.createXMLReader(); } catch (SAXException e) { throw new RuntimeException( "Couldn't initialize a sax driver for the XMLReader"); } } } libexml-java-0.0.20080703.orig/amazon-s3/src/main/java/net/noderunner/amazon/s3/GetResponse.java0000644000175000017500000000363110770333236031656 0ustar twernertwerner// This software code is made available "AS IS" without warranties of any // kind. You may copy, display, modify and redistribute the software // code either by itself or as incorporated into your code; provided that // you do not remove any proprietary notices. Your use of this software // code is at your own risk and you waive any claim against Amazon // Digital Services, Inc. or its affiliates with respect to your use of // this software code. (c) 2006 Amazon Digital Services, Inc. or its // affiliates. package net.noderunner.amazon.s3; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import org.apache.commons.httpclient.HttpMethod; import org.apache.commons.httpclient.HttpMethodBase; /** * Returned by the {@link Connection#get(Bucket, String)} methods. */ public class GetResponse extends Response { private S3Object object; GetResponse(HttpMethod method) throws IOException { super(method); if (getResponseCode() < 400) { long len = ((HttpMethodBase)method).getResponseContentLength(); byte[] body = toByteArray(method.getResponseBodyAsStream(), len); object = new S3Object(body, getHeaders().extractMetadata()); } } /** * Read the input stream and dump it all into a big byte array */ private static byte[] toByteArray(InputStream stream, long len) throws IOException { final int chunkSize = 4 * 1024; byte[] buf = new byte[chunkSize]; ByteArrayOutputStream baos; if (len != -1) { baos = new ByteArrayOutputStream((int)len); } else { baos = new ByteArrayOutputStream(chunkSize); } int count; while ((count = stream.read(buf)) != -1) baos.write(buf, 0, count); return baos.toByteArray(); } /** * Returns the S3 object. */ public S3Object getObject() { return object; } /** * Returns a debug string. */ @Override public String toString() { return super.toString() + " object=" + object; } } libexml-java-0.0.20080703.orig/amazon-s3/.classpath0000644000175000017500000000066610770333236021332 0ustar twernertwerner libexml-java-0.0.20080703.orig/amazon-s3/.project0000644000175000017500000000106110770333236021004 0ustar twernertwerner s3-rest org.maven.ide.eclipse.maven2Builder org.eclipse.jdt.core.javabuilder org.eclipse.jdt.core.javanature org.maven.ide.eclipse.maven2Nature libexml-java-0.0.20080703.orig/amazon-s3/pom.xml0000644000175000017500000000531010770414520020647 0ustar twernertwerner 4.0.0 net.noderunner amazon-s3 1.0.0.0 Cleaned-up version of the Amazon S3 REST access layer maven-compiler-plugin 1.5 1.5 maven-surefire-plugin accessKey TODO secretKey TODO org.apache.maven.wagon wagon-ssh-external 1.0-beta-2 e-xml.sourceforge.net http://e-xml.sourceforge.net/maven2/repository e-xml.sourceforge.net scp://e-xml.sourceforge.net/home/users/g/ge/genman/htdocs/maven2/repository junit junit 4.1 test commons-httpclient commons-httpclient 3.1 log4j log4j 1.2.14 test net.noderunner http 1.0 true javax.servlet servlet-api 2.3 true commons-httpclient commons-httpclient 3.0.1 commons-httpclient commons-httpclient 3.0.1 libexml-java-0.0.20080703.orig/pom.xml0000644000175000017500000000106610762101215017036 0ustar twernertwerner 4.0.0 e-xml net.noderunner 1.0.0.0 pom e-xml libraries and others e-xml http xmlrpc