Example usage for javax.xml.transform SourceLocator getSystemId

List of usage examples for javax.xml.transform SourceLocator getSystemId

Introduction

In this page you can find the example usage for javax.xml.transform SourceLocator getSystemId.

Prototype

public String getSystemId();

Source Link

Document

Return the system identifier for the current document event.

Usage

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

/**
 * Entry point//from w  ww . j ava 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

public static void xsl(String inFilename, String outFilename, String xslFilename) {
    try {//from w ww. j  a v  a  2  s .  c om
        TransformerFactory factory = TransformerFactory.newInstance();
        Templates template = factory.newTemplates(new StreamSource(new FileInputStream(xslFilename)));
        Transformer xformer = template.newTransformer();
        Source source = new StreamSource(new FileInputStream(inFilename));
        Result result = new StreamResult(new FileOutputStream(outFilename));
        xformer.transform(source, result);
    } catch (FileNotFoundException e) {
    } catch (TransformerConfigurationException e) {
    } catch (TransformerException e) {
        SourceLocator locator = e.getLocator();
        int col = locator.getColumnNumber();
        int line = locator.getLineNumber();
        String publicId = locator.getPublicId();
        String systemId = locator.getSystemId();
    }
}

From source file:nl.nn.adapterframework.core.IbisException.java

public String getExceptionSpecificDetails(Throwable t) {
    String result = null;/*from w ww. ja  v a 2  s .com*/
    if (t instanceof AddressException) {
        AddressException ae = (AddressException) t;
        String parsedString = ae.getRef();
        if (StringUtils.isNotEmpty(parsedString)) {
            result = addPart(result, " ", "[" + parsedString + "]");
        }
        int column = ae.getPos() + 1;
        if (column > 0) {
            result = addPart(result, " ", "at column [" + column + "]");
        }
    }
    if (t instanceof SAXParseException) {
        SAXParseException spe = (SAXParseException) t;
        int line = spe.getLineNumber();
        int col = spe.getColumnNumber();
        String sysid = spe.getSystemId();

        String locationInfo = null;
        if (StringUtils.isNotEmpty(sysid)) {
            locationInfo = "SystemId [" + sysid + "]";
        }
        if (line >= 0) {
            locationInfo = addPart(locationInfo, " ", "line [" + line + "]");
        }
        if (col >= 0) {
            locationInfo = addPart(locationInfo, " ", "column [" + col + "]");
        }
        result = addPart(locationInfo, ": ", result);
    }
    if (t instanceof TransformerException) {
        TransformerException te = (TransformerException) t;
        SourceLocator locator = te.getLocator();
        if (locator != null) {
            int line = locator.getLineNumber();
            int col = locator.getColumnNumber();
            String sysid = locator.getSystemId();

            String locationInfo = null;
            if (StringUtils.isNotEmpty(sysid)) {
                locationInfo = "SystemId [" + sysid + "]";
            }
            if (line >= 0) {
                locationInfo = addPart(locationInfo, " ", "line [" + line + "]");
            }
            if (col >= 0) {
                locationInfo = addPart(locationInfo, " ", "column [" + col + "]");
            }
            result = addPart(locationInfo, ": ", result);
        }
    }
    if (t instanceof SQLException) {
        SQLException sqle = (SQLException) t;
        int errorCode = sqle.getErrorCode();
        String sqlState = sqle.getSQLState();
        if (errorCode != 0) {
            result = addPart("errorCode [" + errorCode + "]", ", ", result);
        }
        if (StringUtils.isNotEmpty(sqlState)) {
            result = addPart("SQLState [" + sqlState + "]", ", ", result);
        }
    }
    return result;
}

From source file:org.apache.cocoon.components.notification.DefaultNotifyingBuilder.java

/**
 * Builds a Notifying object (SimpleNotifyingBean in this case)
 * that tries to explain what the Object o can reveal.
 *
 * @param sender who sent this Object./*  w w w.  j  a v  a2  s . com*/
 * @param o the object to use when building the SimpleNotifyingBean
 * @return the  Notifying Object that was build
 * @see org.apache.cocoon.components.notification.Notifying
 */
public Notifying build(Object sender, Object o) {
    if (o instanceof Notifying) {
        return (Notifying) o;
    } else if (o instanceof Throwable) {
        Throwable t = (Throwable) o;
        SimpleNotifyingBean n = new SimpleNotifyingBean(sender);
        n.setType(Notifying.ERROR_NOTIFICATION);
        n.setTitle("An Error Occurred");

        if (t != null) {
            Throwable rootCause = getRootCause(t);

            n.setSource(t.getClass().getName());

            // NullPointerException usually does not have a message
            if (rootCause.getMessage() != null) {
                n.setMessage(rootCause.getMessage());
            } else {
                n.setMessage(t.getMessage());
            }

            n.setDescription(t.toString());
            n.addExtraDescription(Notifying.EXTRA_CAUSE, rootCause.toString());

            if (rootCause instanceof SAXParseException) {
                SAXParseException saxParseException = (SAXParseException) rootCause;

                n.addExtraDescription(Notifying.EXTRA_LOCATION,
                        String.valueOf(saxParseException.getSystemId()));
                n.addExtraDescription(Notifying.EXTRA_LINE, String.valueOf(saxParseException.getLineNumber()));
                n.addExtraDescription(Notifying.EXTRA_COLUMN,
                        String.valueOf(saxParseException.getColumnNumber()));
            } else if (rootCause instanceof TransformerException) {
                TransformerException transformerException = (TransformerException) rootCause;
                SourceLocator sourceLocator = transformerException.getLocator();

                if (null != sourceLocator) {
                    n.addExtraDescription(Notifying.EXTRA_LOCATION,
                            String.valueOf(sourceLocator.getSystemId()));
                    n.addExtraDescription(Notifying.EXTRA_LINE, String.valueOf(sourceLocator.getLineNumber()));
                    n.addExtraDescription(Notifying.EXTRA_COLUMN,
                            String.valueOf(sourceLocator.getColumnNumber()));
                }
            }

            // Add root cause exception stacktrace
            StringWriter sw = new StringWriter();
            rootCause.printStackTrace(new PrintWriter(sw));
            n.addExtraDescription(Notifying.EXTRA_STACKTRACE, sw.toString());

            // Add full exception chain
            sw = new StringWriter();
            appendTraceChain(sw, t);
            n.addExtraDescription(Notifying.EXTRA_FULLTRACE, sw.toString());
        }

        return n;
    } else {
        SimpleNotifyingBean n = new SimpleNotifyingBean(sender);
        n.setType(Notifying.UNKNOWN_NOTIFICATION);
        n.setTitle("Object Notification");
        n.setMessage(String.valueOf(o));
        n.setDescription("No details available.");
        return n;
    }
}

From source file:org.apache.cocoon.util.TraxErrorHandler.java

private String getMessage(TransformerException exception) {
    SourceLocator locator = exception.getLocator();
    if (locator != null) {
        String id = (!locator.getPublicId().equals(locator.getPublicId())) ? locator.getPublicId()
                : (null != locator.getSystemId()) ? locator.getSystemId() : "SystemId Unknown";
        return "File " + id + "; Line " + locator.getLineNumber() + "; Column " + locator.getColumnNumber()
                + "; " + exception.getMessage();
    }//from   w ww .  j  ava  2 s  . com
    return exception.getMessage();
}

From source file:org.directwebremoting.drapgen.generate.gi.GiType.java

/**
 * @param preprocXslt The preprocessor XSLT
 *
 *//*from w  ww. j  ava  2 s  .co  m*/
public void cloneForOverloading(String preprocXslt) {
    try {
        // Read the XSLT
        if (preprocessTemplate == null) {
            Source xslSource = new StreamSource(new File(preprocXslt));
            preprocessTemplate = factory.newTemplates(xslSource);
        }

        Source xmlSource = new DOMSource(document);

        DocumentBuilder builder = builderFactory.newDocumentBuilder();
        Document newDocument = builder.newDocument();
        Result result = new DOMResult(newDocument);

        Transformer preprocessor = preprocessTemplate.newTransformer();
        preprocessor.transform(xmlSource, result);
        document = newDocument;
    } catch (TransformerException ex) {
        SourceLocator locator = ex.getLocator();
        log.warn("Line: " + locator.getLineNumber() + ", Column: " + locator.getColumnNumber());
        log.warn("PublicId: " + locator.getPublicId());
        log.warn("SystemId: " + locator.getSystemId());
        log.error("Failed to transform", ex);
    } catch (Exception ex) {
        log.warn("Processing Error for " + xmlFile.getAbsolutePath(), ex);
    }
}

From source file:org.directwebremoting.drapgen.generate.gi.GiType.java

/**
 * @param templateDir The base directory for the templates
 * @param defaultTemplate The extra path (from templateDir) to the default
 *
 *///from  w  ww.j  a  v a 2 s .co  m
public void transform(String templateDir, String defaultTemplate) {
    try {
        File templateFile = new File(templateDir + xmlClassName.replaceFirst("\\.xml$", ".xslt"));
        if (!templateFile.canRead()) {
            templateFile = new File(templateDir + defaultTemplate);
        }

        // Read the XSLT
        Source xslSource = new StreamSource(templateFile);

        Templates template = templatesCache.get(templateFile);
        if (template == null) {
            template = factory.newTemplates(xslSource);
            templatesCache.put(templateFile, template);
        }

        Source xmlSource = new DOMSource(document);
        Transformer javaTransformer = template.newTransformer();
        javaTransformer.transform(xmlSource, new StreamResult(output));
    } catch (TransformerException ex) {
        SourceLocator locator = ex.getLocator();
        log.fatal("Failed to transform", ex);
        log.warn("Line: " + locator.getLineNumber() + ", Column: " + locator.getColumnNumber());
        log.warn("PublicId: " + locator.getPublicId());
        log.warn("SystemId: " + locator.getSystemId());
    } catch (Exception ex) {
        log.warn("Processing Error for " + xmlFile.getAbsolutePath(), ex);
    }
}

From source file:org.directwebremoting.drapgen.generate.gi.GiType.java

/**
 * @param directory Where to write the xml
 * @throws java.io.IOException If writing fails
 *///  ww w. j  ava  2s .co  m
public void writeDOM(String directory) throws IOException {
    FileWriter out = null;

    try {
        Transformer transformer = factory.newTransformer();
        Source source = new DOMSource(document);

        StringWriter xml = new StringWriter();
        StreamResult result = new StreamResult(xml);

        transformer.transform(source, result);

        xml.flush();

        String domName = xmlClassName.replaceAll("/", ".");
        File domFile = new File(directory + "org.directwebremoting.proxy." + domName);
        out = new FileWriter(domFile);
        out.append(xml.toString());
    } catch (TransformerException ex) {
        SourceLocator locator = ex.getLocator();
        log.fatal("Failed to transform", ex);
        log.warn("Line: " + locator.getLineNumber() + ", Column: " + locator.getColumnNumber());
        log.warn("PublicId: " + locator.getPublicId());
        log.warn("SystemId: " + locator.getSystemId());
    } finally {
        if (out != null) {
            out.close();
        }
    }
}

From source file:org.eclipse.wst.xsl.xalan.debugger.XalanStyleFrame.java

public String getSourceFilename() {
    SourceLocator locator = getSourceLocator();
    if (locator != null)
        return locator.getSystemId();
    return "";
}

From source file:org.geoserver.security.iride.util.xml.transform.ErrorHandlerUtils.java

/**
 *
 * @param locator//from   w w w  .  j av a2s .  c  o m
 * @return
 */
private static String getLocationMessageText(SourceLocator locator) {
    String locMessage = "";
    String systemId = locator.getSystemId();
    String nodeMessage = null;
    int lineNumber = locator.getLineNumber();

    if (locator instanceof DOMLocator) {
        nodeMessage = "at " + ((DOMLocator) locator).getOriginatingNode().getNodeName() + ' ';
    }
    boolean containsLineNumber = lineNumber != -1;
    if (nodeMessage != null) {
        locMessage += nodeMessage;
    }
    if (containsLineNumber) {
        locMessage += "on line " + lineNumber + ' ';
        if (locator.getColumnNumber() != -1) {
            locMessage += "column " + locator.getColumnNumber() + ' ';
        }
    }
    if (StringUtils.length(systemId) > 0) {
        locMessage += (containsLineNumber ? "of " : "in ") + abbreviatePath(systemId) + ':';
    }

    return locMessage;
}