import java.io.*;
import java.net.*;
import gnu.xml.util.Resolver;
import gnu.xml.util.XMLWriter;
import org.xml.sax.*;
import org.xml.sax.helpers.XMLReaderFactory;
public class CallFile
{
// argv [0] == in.xml (filename)
// argv [1] == url for posting service
public static void main (String argv [])
{
try {
XMLReader in;
Caller caller;
XMLWriter out;
out = new XMLWriter (System.out);
caller = new CallWriter (new URL (argv [1]), out);
in = XMLReaderFactory.createXMLReader ();
in.setFeature (featurePrefix + "namespace-prefixes", true);
bindAll (in, caller);
in.parse (Resolver.fileNameToURL (argv [0]));
} catch (Exception e) {
e.printStackTrace ();
System.exit (1);
}
}
private static void bindAll (XMLReader in, Object out)
throws SAXException
{
if (out instanceof ContentHandler)
in.setContentHandler ((ContentHandler) out);
if (out instanceof DTDHandler)
in.setDTDHandler ((DTDHandler) out);
try {
if (out instanceof DeclHandler)
in.setProperty
("http://xml.org/sax/properties/
declaration-handler", out);
} catch (SAXNotRecognizedException e) { /* IGNORE */ }
try {
if (out instanceof LexicalHandler)
in.setProperty
("http://xml.org/sax/properties/
lexical-handler", out);
} catch (SAXNotRecognizedException e) { /* IGNORE */ }
}
// print input to server
// block till response
// print output as XML text to stdout
private static class CallWriter extends XMLWriter
{
private URL target;
private URLConnection conn;
private XMLWriter next;
CallWriter (URL url, XMLWriter out)
{
super ((Writer)null);
target = url;
next = out;
}
// Connect to remote object and set up to send it XML text
public synchronized void startDocument () throws SAXException
{
try {
conn = target.openConnection ();
conn.setDoOutput (true);
// "text/*" expects DOS-style EOL
next.setEOL ("\r\n");
conn.setRequestProperty ("Content-Type",
"text/xml;charset=UTF-8");
setWriter (new OutputStreamWriter (
conn.getOutputStream (),
"UTF8"), "UTF-8");
} catch (IOException e) {
fatal ("can't write (POST) to URI: " + target, e);
}
super.startDocument ();
}
// finish sending request
// receive the POST response
public void endDocument () throws SAXException
{
super.endDocument ();
try {
InputSource source = new InputSource
(conn.getInputStream ());
XMLReader producer = XMLReaderFactory.createXMLReader ();
String encoding;
producer.setFeature (featurePrefix +
"namespace-prefixes", true);
encoding = Resolver.getEncoding (conn.getContentType ());
if (encoding != null)
source.setEncoding (encoding);
bindAll (producer, next);
producer.parse (source);
} catch (IOException e) {
fatal ("I/O Exception reading response, "
+ e.getMessage (), e);
}
}
}
}