Example usage for javax.xml.transform TransformerException getMessage

List of usage examples for javax.xml.transform TransformerException getMessage

Introduction

In this page you can find the example usage for javax.xml.transform TransformerException getMessage.

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:net.sf.joost.Main.java

/**
 * Entry point// w  w  w .ja v  a  2 s  .c o m
 * @param args array of strings containing the parameter for Joost and
 * at least two URLs addressing xml-source and stx-sheet
 */
public static void main(String[] args) {
    // input filename
    String xmlFile = null;

    // the currently last processor (as XMLFilter)
    Processor processor = null;

    // output filename (optional)
    String outFile = null;

    // custom message emitter class name (optional)
    String meClassname = null;

    // log4j properties filename (optional)
    String log4jProperties = null;

    // log4j message level (this is an object of the class Level)
    Level log4jLevel = null;

    // set to true if a command line parameter was wrong
    boolean wrongParameter = false;

    // set to true if -help was specified on the command line
    boolean printHelp = false;

    // set to true if -pdf was specified on the command line
    boolean doFOP = false;

    // set to true if -nodecl was specified on the command line
    boolean nodecl = false;

    // set to true if -noext was specified on the command line
    boolean noext = false;

    // set to true if -doe was specified on the command line
    boolean doe = false;

    // debugging
    boolean dontexit = false;

    // timings
    boolean measureTime = false;
    long timeStart = 0, timeEnd = 0;

    // needed for evaluating parameter assignments
    int index;

    // serializer SAX -> XML text
    StreamEmitter emitter = null;

    // filenames for the usage and version info
    final String USAGE = "usage.txt", VERSION = "version.txt";

    try {

        // parse command line argument list
        for (int i = 0; i < args.length; i++) {
            if (args[i].trim().length() == 0) {
                // empty parameter? ingore
            }
            // all options start with a '-', but a single '-' means stdin
            else if (args[i].charAt(0) == '-' && args[i].length() > 1) {
                if ("-help".equals(args[i])) {
                    printHelp = true;
                    continue;
                } else if ("-version".equals(args[i])) {
                    printResource(VERSION);
                    logInfoAndExit();
                } else if ("-pdf".equals(args[i])) {
                    doFOP = true;
                    continue;
                } else if ("-nodecl".equals(args[i])) {
                    nodecl = true;
                    continue;
                } else if ("-noext".equals(args[i])) {
                    noext = true;
                    continue;
                } else if ("-doe".equals(args[i])) {
                    doe = true;
                    continue;
                } else if ("-wait".equals(args[i])) {
                    dontexit = true; // undocumented
                    continue;
                } else if ("-time".equals(args[i])) {
                    measureTime = true;
                    continue;
                } else if ("-o".equals(args[i])) {
                    // this option needs a parameter
                    if (++i < args.length && args[i].charAt(0) != '-') {
                        if (outFile != null) {
                            System.err.println("Option -o already specified with " + outFile);
                            wrongParameter = true;
                        } else
                            outFile = args[i];
                        continue;
                    } else {
                        if (outFile != null)
                            System.err.println("Option -o already specified with " + outFile);
                        else
                            System.err.println("Option -o requires a filename");
                        i--;
                        wrongParameter = true;
                    }
                } else if ("-m".equals(args[i])) {
                    // this option needs a parameter
                    if (++i < args.length && args[i].charAt(0) != '-') {
                        if (meClassname != null) {
                            System.err.println("Option -m already specified with " + meClassname);
                            wrongParameter = true;
                        } else
                            meClassname = args[i];
                        continue;
                    } else {
                        if (meClassname != null)
                            System.err.println("Option -m already specified with " + meClassname);
                        else
                            System.err.println("Option -m requires a classname");
                        i--;
                        wrongParameter = true;
                    }
                } else if (DEBUG && "-log-properties".equals(args[i])) {
                    // this option needs a parameter
                    if (++i < args.length && args[i].charAt(0) != '-') {
                        log4jProperties = args[i];
                        continue;
                    } else {
                        System.err.println("Option -log-properties requires " + "a filename");
                        wrongParameter = true;
                    }
                } else if (DEBUG && "-log-level".equals(args[i])) {
                    // this option needs a parameter
                    if (++i < args.length && args[i].charAt(0) != '-') {
                        if ("off".equals(args[i])) {
                            log4jLevel = Level.OFF;
                            continue;
                        } else if ("debug".equals(args[i])) {
                            log4jLevel = Level.DEBUG;
                            continue;
                        } else if ("info".equals(args[i])) {
                            log4jLevel = Level.INFO;
                            continue;
                        } else if ("warn".equals(args[i])) {
                            log4jLevel = Level.WARN;
                            continue;
                        } else if ("error".equals(args[i])) {
                            log4jLevel = Level.ERROR;
                            continue;
                        } else if ("fatal".equals(args[i])) {
                            log4jLevel = Level.FATAL;
                            continue;
                        } else if ("all".equals(args[i])) {
                            log4jLevel = Level.ALL;
                            continue;
                        } else {
                            System.err.println("Unknown parameter for -log-level: " + args[i]);
                            wrongParameter = true;
                            continue;
                        }
                    } else {
                        System.err.println("Option -log-level requires a " + "parameter");
                        wrongParameter = true;
                    }
                } else {
                    System.err.println("Unknown option " + args[i]);
                    wrongParameter = true;
                }
            }
            // command line argument is not an option with a leading '-'
            else if ((index = args[i].indexOf('=')) != -1) {
                // parameter assignment
                if (processor != null)
                    processor.setParameter(args[i].substring(0, index), args[i].substring(index + 1));
                else {
                    System.err.println("Assignment " + args[i] + " must follow an stx-sheet parameter");
                    wrongParameter = true;
                }
                continue;
            } else if (xmlFile == null) {
                xmlFile = args[i];
                continue;
            } else {
                // xmlFile != null, i.e. this is an STX sheet
                ParseContext pContext = new ParseContext();
                pContext.allowExternalFunctions = !noext;
                if (measureTime)
                    timeStart = System.currentTimeMillis();
                Processor proc = new Processor(new InputSource(args[i]), pContext);
                if (nodecl)
                    proc.outputProperties.setProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
                if (measureTime) {
                    timeEnd = System.currentTimeMillis();
                    System.err.println("Parsing " + args[i] + ": " + (timeEnd - timeStart) + " ms");
                }

                if (processor != null)
                    proc.setParent(processor); // XMLFilter chain
                processor = proc;
            }
        }

        // PDF creation requested
        if (doFOP && outFile == null) {
            System.err.println("Option -pdf requires option -o");
            wrongParameter = true;
        }

        // missing filenames
        if (!printHelp && processor == null) {
            if (xmlFile == null)
                System.err.println("Missing filenames for XML source and " + "STX transformation sheet");
            else
                System.err.println("Missing filename for STX transformation " + "sheet");
            wrongParameter = true;
        }

        if (meClassname != null && !wrongParameter) {
            // create object
            StxEmitter messageEmitter = null;
            try {
                messageEmitter = (StxEmitter) Class.forName(meClassname).newInstance();
            } catch (ClassNotFoundException ex) {
                System.err.println("Class not found: " + ex.getMessage());
                wrongParameter = true;
            } catch (InstantiationException ex) {
                System.err.println("Instantiation failed: " + ex.getMessage());
                wrongParameter = true;
            } catch (IllegalAccessException ex) {
                System.err.println("Illegal access: " + ex.getMessage());
                wrongParameter = true;
            } catch (ClassCastException ex) {
                System.err.println(
                        "Wrong message emitter: " + meClassname + " doesn't implement the " + StxEmitter.class);
                wrongParameter = true;
            }
            if (messageEmitter != null) { // i.e. no exception occurred
                // set message emitter for all processors in the filter chain
                Processor p = processor;
                do {
                    p.setMessageEmitter(messageEmitter);
                    Object o = p.getParent();
                    if (o instanceof Processor)
                        p = (Processor) o;
                    else
                        p = null;
                } while (p != null);
            }
        }

        if (printHelp) {
            printResource(VERSION);
            printResource(USAGE);
            logInfoAndExit();
        }

        if (wrongParameter) {
            System.err.println("Specify -help to get a detailed help message");
            System.exit(1);
        }

        if (DEBUG) {
            // use specified log4j properties file
            if (log4jProperties != null)
                PropertyConfigurator.configure(log4jProperties);

            // set log level specified on the the command line
            if (log4jLevel != null)
                Logger.getRootLogger().setLevel(log4jLevel);
        }

        // The first processor re-uses its XMLReader for parsing the input
        // xmlFile.
        // For a real XMLFilter usage you have to call
        // processor.setParent(yourXMLReader)

        // Connect a SAX consumer
        if (doFOP) {
            // pass output events to FOP
            //              // Version 1: use a FOPEmitter object as XMLFilter
            //              processor.setContentHandler(
            //                 new FOPEmitter(
            //                    new java.io.FileOutputStream(outFile)));

            // Version 2: use a static method to retrieve FOP's content
            // handler and use it directly
            processor.setContentHandler(FOPEmitter.getFOPContentHandler(new java.io.FileOutputStream(outFile)));
        } else {
            // Create XML output
            if (outFile != null) {
                emitter = StreamEmitter.newEmitter(outFile, processor.outputProperties);
                emitter.setSystemId(new File(outFile).toURI().toString());
            } else
                emitter = StreamEmitter.newEmitter(System.out, processor.outputProperties);
            processor.setContentHandler(emitter);
            processor.setLexicalHandler(emitter);
            // the previous line is a short-cut for
            // processor.setProperty(
            //    "http://xml.org/sax/properties/lexical-handler", emitter);

            emitter.setSupportDisableOutputEscaping(doe);
        }

        InputSource is;
        if (xmlFile.equals("-")) {
            is = new InputSource(System.in);
            is.setSystemId("<stdin>");
            is.setPublicId("");
        } else
            is = new InputSource(xmlFile);

        // Ready for take-off
        if (measureTime)
            timeStart = System.currentTimeMillis();

        processor.parse(is);

        if (measureTime) {
            timeEnd = System.currentTimeMillis();
            System.err.println("Processing " + xmlFile + ": " + (timeEnd - timeStart) + " ms");
        }

        //           // check if the Processor copy constructor works
        //           Processor pr = new Processor(processor);
        //           java.util.Properties props = new java.util.Properties();
        //           props.put("encoding", "ISO-8859-2");
        //           StreamEmitter em =
        //              StreamEmitter.newEmitter(System.err, props);
        //           pr.setContentHandler(em);
        //           pr.setLexicalHandler(em);
        //           pr.parse(is);
        //           // end check

        // this is for debugging with the Java Memory Profiler
        if (dontexit) {
            System.err.println("Press Enter to exit");
            System.in.read();
        }

    } catch (java.io.IOException ex) {
        System.err.println(ex.toString());
        System.exit(1);
    } catch (SAXException ex) {
        if (emitter != null) {
            try {
                // flushes the internal BufferedWriter, i.e. outputs
                // the intermediate result
                emitter.endDocument();
            } catch (SAXException exx) {
                // ignore
            }
        }
        Exception embedded = ex.getException();
        if (embedded != null) {
            if (embedded instanceof TransformerException) {
                TransformerException te = (TransformerException) embedded;
                SourceLocator sl = te.getLocator();
                String systemId;
                // ensure that systemId is not null; is this a bug?
                if (sl != null && (systemId = sl.getSystemId()) != null) {
                    // remove the "file://" scheme prefix if it is present
                    if (systemId.startsWith("file://"))
                        systemId = systemId.substring(7);
                    else if (systemId.startsWith("file:"))
                        // bug in JDK 1.4 / Crimson? (see rfc1738)
                        systemId = systemId.substring(5);
                    System.err.println(systemId + ":" + sl.getLineNumber() + ":" + sl.getColumnNumber() + ": "
                            + te.getMessage());
                } else
                    System.err.println(te.getMessage());
            } else {
                // Fatal: this mustn't happen
                embedded.printStackTrace(System.err);
            }
        } else
            System.err.println(ex.toString());
        System.exit(1);
    }
}

From source file:Main.java

/**
 * Pretty print an XML. Use with caution as this drains the source if it is
 * a StreamSource./*from  w ww .ja va 2 s.  c  o m*/
 * @param source the XML source
 * @return a String with readable XML
 */
public static String prettyPrint(final Source source) {
    try {
        Transformer serializer = TransformerFactory.newInstance().newTransformer();
        serializer.setOutputProperty(OutputKeys.INDENT, "yes");
        serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
        StringWriter writer = new StringWriter();
        serializer.transform(source, new StreamResult(writer));
        return writer.toString();
    } catch (TransformerException e) {
        return e.getMessage();
    }
}

From source file:Main.java

/**
 * Save a DOM document//from   w w  w  .  j a  va 2  s. com
 */
public static void saveDocument(Document document, OutputStream out, boolean indent) throws IOException {
    try {
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        if (indent) {
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
        }
        transformer.transform(new DOMSource(document), new StreamResult(out));
    } catch (TransformerException e) {
        throw new IOException(e.getMessage());
    }
}

From source file:Main.java

/**
 * Saves a given XML document to the given output stream.
 *///from w ww .j  ava2s. c  o m
public static void writeXML(Document document, OutputStream os) throws IOException {
    DOMSource src = new DOMSource(document);
    StreamResult res = new StreamResult(os);
    TransformerFactory tf = TransformerFactory.newInstance();
    try {
        Transformer t = tf.newTransformer();
        t.transform(src, res);
    } catch (TransformerException e) {
        throw new IOException(e.getMessage());
    }
}

From source file:Main.java

public static String documentToXmlString(Document document) {
    DOMSource domSource = new DOMSource(document);
    StringWriter writer = new StringWriter();
    StreamResult result = new StreamResult(writer);
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer transformer;/*www.  ja  v a 2  s  .  c o  m*/
    try {
        transformer = tf.newTransformer();
        transformer.transform(domSource, result);
    } catch (TransformerException e) {
        throw new RuntimeException(e.getMessage());
    }
    return writer.toString();
}

From source file:Main.java

/**
 * Serialize an XML document into a String (for debug purpose only!). the
 * returned String could contains an error message instead if a problem as
 * occurred during the serialization. This method is intended for debug /
 * trace purpose because you really don't need to serialize XML at all in
 * your code unless your planing to output it to a file. In this case, use
 * {@link XmlHelper#writeXmlToFile(Document, File)} instead.
 *//*www  .  j a va  2s .com*/
public static String dumpXml(Document document) {
    TransformerFactory factory = TransformerFactory.newInstance();
    try {
        Transformer transformer = factory.newTransformer();
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        StringWriter writer = new StringWriter();
        transformer.transform(new DOMSource(document), new StreamResult(writer));
        return writer.getBuffer().toString();
    } catch (TransformerException e) {
        return "XML dump failed: " + e.getMessage();
    }
}

From source file:Main.java

private static void SaveCustomerFile(Document CustomerDoc, JFrame mainFrame) {
    try {// ww w  .j ava 2  s. com
        TransformerFactory Factory = TransformerFactory.newInstance();
        Transformer Trans = Factory.newTransformer();
        DOMSource source = new DOMSource(CustomerDoc);
        File f = new File(".");
        String FilePath = f.getAbsoluteFile().getParent() + "\\Customers.xml";
        f = new File(FilePath);
        if (f.exists()) {
            f.delete();
        }
        StreamResult Result = new StreamResult(f);
        Trans.setOutputProperty(OutputKeys.INDENT, "yes");
        Trans.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "7");
        Trans.transform(source, Result);
    } catch (TransformerException ex) {
        System.out.println(ex.getMessage());
        JOptionPane.showMessageDialog(mainFrame,
                "There Was an Error Saving The File. Please Restart the Application.");
        System.exit(1);
    }
}

From source file:Main.java

public static void writeDocument(Document doc, OutputStream os) throws IOException {
    try {//  ww  w.  j  a  v a2  s . co  m
        TransformerFactory tFactory = TransformerFactory.newInstance();
        Transformer transformer = tFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xalan}indent-amount", "2");

        DOMSource source = new DOMSource(doc);
        CharsetEncoder utf8Encoder = Charset.forName("UTF-8").newEncoder();
        StreamResult result = new StreamResult(new OutputStreamWriter(os, utf8Encoder));
        transformer.transform(source, result);
    } catch (TransformerException e) {
        System.err.println(e.getMessage());
    }
}

From source file:Main.java

/**
 * Writes the given {@link Document} to an {@link OutputStream} using
 * UTF-8 encoding.//www  .j ava2 s  .c  o  m
 *
 * @param doc The {@link Document} to write.
 * @param out The {@link OutputStream} to write to.
 * @see #encodeDocument(Document,boolean)
 * @see #writeDocumentTo(Document,File)
 */
public static void writeDocumentTo(Document doc, OutputStream out) throws IOException {
    final DOMSource source = new DOMSource(doc);
    final Writer writer = new OutputStreamWriter(out, "UTF-8");
    final StreamResult result = new StreamResult(writer);
    final Transformer xform = createTransformer();
    try {
        xform.transform(source, result);
    } catch (TransformerException e) {
        throw new IOException("Couldn't write XML: " + e.getMessage());
    }
}

From source file:ddf.util.XSLTUtil.java

/**
 * Performs an xsl transformation against an XML document
 *
 * @param template/*from   www .  j a  v  a  2 s. c o m*/
 *            The compiled XSL template to be run
 * @param xmlDoc
 *            xml document to be transformed
 * @param xslProperties
 *            default classification
 * @return the transformed document.
 * @throws TransformerException
 */
public static Document transform(Templates template, Document xmlDoc, Map<String, Object> parameters)
        throws TransformerException {
    ByteArrayOutputStream baos;
    ByteArrayInputStream bais = null;
    Document resultDoc;
    try {
        Transformer transformer = template.newTransformer();

        DBF.setNamespaceAware(true);
        DocumentBuilder builder = DBF.newDocumentBuilder();
        StreamResult resultOutput = null;
        Source source = new DOMSource(xmlDoc);
        baos = new ByteArrayOutputStream();
        try {
            resultOutput = new StreamResult(baos);
            if (parameters != null && !parameters.isEmpty()) {
                for (Map.Entry<String, Object> entry : parameters.entrySet()) {
                    LOGGER.debug("Adding parameter key: {} value: {}", entry.getKey(), entry.getValue());
                    String key = entry.getKey();
                    Object value = entry.getValue();
                    if (key != null && !key.isEmpty() && value != null) {
                        transformer.setParameter(key, value);
                    } else {
                        LOGGER.debug("Null or empty value for parameter: {}", entry.getKey());

                    }
                }
            } else {
                LOGGER.warn("All properties were null.  Using \"last-resort\" defaults: U, USA, MTS");
            }

            transformer.transform(source, resultOutput);
            bais = new ByteArrayInputStream(baos.toByteArray());
            resultDoc = builder.parse(bais);
        } finally {
            IOUtils.closeQuietly(bais);
            IOUtils.closeQuietly(baos);
        }

        return resultDoc;
    } catch (TransformerException e) {
        LOGGER.warn(e.getMessage(), e);
        throw e;
    } catch (Exception e) {
        LOGGER.warn(e.getMessage(), e);
        throw new TransformerException("Error while transforming document: " + e.getMessage(), e);
    }
}