Example usage for org.xml.sax InputSource setSystemId

List of usage examples for org.xml.sax InputSource setSystemId

Introduction

In this page you can find the example usage for org.xml.sax InputSource setSystemId.

Prototype

public void setSystemId(String systemId) 

Source Link

Document

Set the system identifier for this input source.

Usage

From source file:SAXDemo.java

/** The main method sets things up for parsing */
public static void main(String[] args) throws IOException, SAXException, ParserConfigurationException {
    // Create a JAXP "parser factory" for creating SAX parsers
    javax.xml.parsers.SAXParserFactory spf = SAXParserFactory.newInstance();

    // Configure the parser factory for the type of parsers we require
    spf.setValidating(false); // No validation required

    // Now use the parser factory to create a SAXParser object
    // Note that SAXParser is a JAXP class, not a SAX class
    javax.xml.parsers.SAXParser sp = spf.newSAXParser();

    // Create a SAX input source for the file argument
    org.xml.sax.InputSource input = new InputSource(new FileReader(args[0]));

    // Give the InputSource an absolute URL for the file, so that
    // it can resolve relative URLs in a <!DOCTYPE> declaration, e.g.
    input.setSystemId("file://" + new File(args[0]).getAbsolutePath());

    // Create an instance of this class; it defines all the handler methods
    SAXDemo handler = new SAXDemo();

    // Finally, tell the parser to parse the input and notify the handler
    sp.parse(input, handler);//from   w  ww .  ja  v a2s . com

    // Instead of using the SAXParser.parse() method, which is part of the
    // JAXP API, we could also use the SAX1 API directly. Note the
    // difference between the JAXP class javax.xml.parsers.SAXParser and
    // the SAX1 class org.xml.sax.Parser
    //
    // org.xml.sax.Parser parser = sp.getParser(); // Get the SAX parser
    // parser.setDocumentHandler(handler); // Set main handler
    // parser.setErrorHandler(handler); // Set error handler
    // parser.parse(input); // Parse!
}

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

/**
 * Entry point//ww w  .java 2s.  co  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:com.bytelightning.opensource.pokerface.PokerFaceApp.java

public static void main(String[] args) {
    if (JavaVersionAsFloat() < (1.8f - Float.MIN_VALUE)) {
        System.err.println("PokerFace requires at least Java v8 to run.");
        return;/*from ww  w .ja v a2 s . co  m*/
    }
    // Configure the command line options parser
    Options options = new Options();
    options.addOption("h", false, "help");
    options.addOption("listen", true, "(http,https,secure,tls,ssl,CertAlias)=Address:Port for https.");
    options.addOption("keystore", true, "Filepath for PokerFace certificate keystore.");
    options.addOption("storepass", true, "The store password of the keystore.");
    options.addOption("keypass", true, "The key password of the keystore.");
    options.addOption("target", true, "Remote Target requestPattern=targetUri"); // NOTE: targetUri may contain user-info and if so will be interpreted as the alias of a cert to be presented to the remote target
    options.addOption("servercpu", true, "Number of cores the server should use.");
    options.addOption("targetcpu", true, "Number of cores the http targets should use.");
    options.addOption("trustany", false, "Ignore certificate identity errors from target servers.");
    options.addOption("files", true, "Filepath to a directory of static files.");
    options.addOption("config", true, "Path for XML Configuration file.");
    options.addOption("scripts", true, "Filepath for root scripts directory.");
    options.addOption("library", true, "JavaScript library to load into global context.");
    options.addOption("watch", false, "Dynamically watch scripts directory for changes.");
    options.addOption("dynamicTargetScripting", false,
            "WARNING! This option allows scripts to redirect requests to *any* other remote server.");

    CommandLine cmdLine = null;
    // parse the command line.
    try {
        CommandLineParser parser = new PosixParser();
        cmdLine = parser.parse(options, args);
        if (args.length == 0 || cmdLine.hasOption('h')) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.setWidth(120);
            formatter.printHelp(PokerFaceApp.class.getSimpleName(), options);
            return;
        }
    } catch (ParseException exp) {
        System.err.println("Parsing failed.  Reason: " + exp.getMessage());
        return;
    } catch (Exception ex) {
        ex.printStackTrace(System.err);
        return;
    }

    XMLConfiguration config = new XMLConfiguration();
    try {
        if (cmdLine.hasOption("config")) {
            Path tmp = Utils.MakePath(cmdLine.getOptionValue("config"));
            if (!Files.exists(tmp))
                throw new FileNotFoundException("Configuration file does not exist.");
            if (Files.isDirectory(tmp))
                throw new FileNotFoundException("'config' path is not a file.");
            // This is a bit of a pain, but but let's make sure we have a valid configuration file before we actually try to use it.
            config.setEntityResolver(new DefaultEntityResolver() {
                @Override
                public InputSource resolveEntity(String publicId, String systemId) throws SAXException {
                    InputSource retVal = super.resolveEntity(publicId, systemId);
                    if ((retVal == null) && (systemId != null)) {
                        try {
                            URL entityURL;
                            if (systemId.endsWith("/PokerFace_v1Config.xsd"))
                                entityURL = PokerFaceApp.class.getResource("/PokerFace_v1Config.xsd");
                            else
                                entityURL = new URL(systemId);
                            URLConnection connection = entityURL.openConnection();
                            connection.setUseCaches(false);
                            InputStream stream = connection.getInputStream();
                            retVal = new InputSource(stream);
                            retVal.setSystemId(entityURL.toExternalForm());
                        } catch (Throwable e) {
                            return retVal;
                        }
                    }
                    return retVal;
                }

            });
            config.setSchemaValidation(true);
            config.setURL(tmp.toUri().toURL());
            config.load();
            if (cmdLine.hasOption("listen"))
                System.out.println("IGNORING 'listen' option because a configuration file was supplied.");
            if (cmdLine.hasOption("target"))
                System.out.println("IGNORING 'target' option(s) because a configuration file was supplied.");
            if (cmdLine.hasOption("scripts"))
                System.out.println("IGNORING 'scripts' option because a configuration file was supplied.");
            if (cmdLine.hasOption("library"))
                System.out.println("IGNORING 'library' option(s) because a configuration file was supplied.");
        } else {
            String[] serverStrs;
            String[] addr = { null };
            String[] port = { null };
            serverStrs = cmdLine.getOptionValues("listen");
            if (serverStrs == null)
                throw new MissingOptionException("No listening addresses specified specified");
            for (int i = 0; i < serverStrs.length; i++) {
                String addrStr;
                String alias = null;
                String protocol = null;
                Boolean https = null;
                int addrPos = serverStrs[i].indexOf('=');
                if (addrPos >= 0) {
                    if (addrPos < 2)
                        throw new IllegalArgumentException("Invalid http argument.");
                    else if (addrPos + 1 >= serverStrs[i].length())
                        throw new IllegalArgumentException("Invalid http argument.");
                    addrStr = serverStrs[i].substring(addrPos + 1, serverStrs[i].length());
                    String[] types = serverStrs[i].substring(0, addrPos).split(",");
                    for (String type : types) {
                        if (type.equalsIgnoreCase("http"))
                            break;
                        else if (type.equalsIgnoreCase("https") || type.equalsIgnoreCase("secure"))
                            https = true;
                        else if (type.equalsIgnoreCase("tls") || type.equalsIgnoreCase("ssl"))
                            protocol = type.toUpperCase();
                        else
                            alias = type;
                    }
                } else
                    addrStr = serverStrs[i];
                ParseAddressString(addrStr, addr, port, alias != null ? 443 : 80);
                config.addProperty("server.listen(" + i + ")[@address]", addr[0]);
                config.addProperty("server.listen(" + i + ")[@port]", port[0]);
                if (alias != null)
                    config.addProperty("server.listen(" + i + ")[@alias]", alias);
                if (protocol != null)
                    config.addProperty("server.listen(" + i + ")[@protocol]", protocol);
                if (https != null)
                    config.addProperty("server.listen(" + i + ")[@secure]", https);
            }
            String servercpu = cmdLine.getOptionValue("servercpu");
            if (servercpu != null)
                config.setProperty("server[@cpu]", servercpu);
            String clientcpu = cmdLine.getOptionValue("targetcpu");
            if (clientcpu != null)
                config.setProperty("targets[@cpu]", clientcpu);

            // Configure static files
            if (cmdLine.hasOption("files")) {
                Path tmp = Utils.MakePath(cmdLine.getOptionValue("files"));
                if (!Files.exists(tmp))
                    throw new FileNotFoundException("Files directory does not exist.");
                if (!Files.isDirectory(tmp))
                    throw new FileNotFoundException("'files' path is not a directory.");
                config.setProperty("files.rootDirectory", tmp.toAbsolutePath().toUri());
            }

            // Configure scripting
            if (cmdLine.hasOption("scripts")) {
                Path tmp = Utils.MakePath(cmdLine.getOptionValue("scripts"));
                if (!Files.exists(tmp))
                    throw new FileNotFoundException("Scripts directory does not exist.");
                if (!Files.isDirectory(tmp))
                    throw new FileNotFoundException("'scripts' path is not a directory.");
                config.setProperty("scripts.rootDirectory", tmp.toAbsolutePath().toUri());
                config.setProperty("scripts.dynamicWatch", cmdLine.hasOption("watch"));
                String[] libraries = cmdLine.getOptionValues("library");
                if (libraries != null) {
                    for (int i = 0; i < libraries.length; i++) {
                        Path lib = Utils.MakePath(libraries[i]);
                        if (!Files.exists(lib))
                            throw new FileNotFoundException(
                                    "Script library does not exist [" + libraries[i] + "].");
                        if (Files.isDirectory(lib))
                            throw new FileNotFoundException(
                                    "Script library is not a file [" + libraries[i] + "].");
                        config.setProperty("scripts.library(" + i + ")", lib.toAbsolutePath().toUri());
                    }
                }
            } else if (cmdLine.hasOption("watch"))
                System.out.println("IGNORING 'watch' option as no 'scripts' directory was specified.");
            else if (cmdLine.hasOption("library"))
                System.out.println("IGNORING 'library' option as no 'scripts' directory was specified.");
        }
        String keyStorePath = cmdLine.getOptionValue("keystore");
        if (keyStorePath != null)
            config.setProperty("keystore", keyStorePath);
        String keypass = cmdLine.getOptionValue("keypass");
        if (keypass != null)
            config.setProperty("keypass", keypass);
        String storepass = cmdLine.getOptionValue("storepass");
        if (storepass != null)
            config.setProperty("storepass", keypass);
        if (cmdLine.hasOption("trustany"))
            config.setProperty("targets[@trustAny]", true);

        config.setProperty("scripts.dynamicTargetScripting", cmdLine.hasOption("dynamicTargetScripting"));

        String[] targetStrs = cmdLine.getOptionValues("target");
        if (targetStrs != null) {
            for (int i = 0; i < targetStrs.length; i++) {
                int uriPos = targetStrs[i].indexOf('=');
                if (uriPos < 2)
                    throw new IllegalArgumentException("Invalid target argument.");
                else if (uriPos + 1 >= targetStrs[i].length())
                    throw new IllegalArgumentException("Invalid target argument.");
                String patternStr = targetStrs[i].substring(0, uriPos);
                String urlStr = targetStrs[i].substring(uriPos + 1, targetStrs[i].length());
                String alias;
                try {
                    URL url = new URL(urlStr);
                    alias = url.getUserInfo();
                    String scheme = url.getProtocol();
                    if ((!"http".equals(scheme)) && (!"https".equals(scheme)))
                        throw new IllegalArgumentException("Invalid target uri scheme.");
                    int port = url.getPort();
                    if (port < 0)
                        port = url.getDefaultPort();
                    urlStr = scheme + "://" + url.getHost() + ":" + port + url.getPath();
                    String ref = url.getRef();
                    if (ref != null)
                        urlStr += "#" + ref;
                } catch (MalformedURLException ex) {
                    throw new IllegalArgumentException("Malformed target uri");
                }
                config.addProperty("targets.target(" + i + ")[@pattern]", patternStr);
                config.addProperty("targets.target(" + i + ")[@url]", urlStr);
                if (alias != null)
                    config.addProperty("targets.target(" + i + ")[@alias]", alias);
            }
        }
        //         config.save(System.out);
    } catch (Throwable e) {
        e.printStackTrace(System.err);
        return;
    }
    // If we get here, we have a possibly valid configuration.
    try {
        final PokerFace p = new PokerFace();
        p.config(config);
        if (p.start()) {
            PokerFace.Logger.warn("Started!");
            Runtime.getRuntime().addShutdownHook(new Thread() {
                public void run() {
                    try {
                        PokerFace.Logger.warn("Initiating shutdown...");
                        p.stop();
                        PokerFace.Logger.warn("Shutdown completed!");
                    } catch (Throwable e) {
                        PokerFace.Logger.error("Failed to shutdown cleanly!");
                        e.printStackTrace(System.err);
                    }
                }
            });
        } else {
            PokerFace.Logger.error("Failed to start!");
            System.exit(-1);
        }
    } catch (Throwable e) {
        e.printStackTrace(System.err);
    }
}

From source file:Utils.java

public static Document readXml(StreamSource is) throws SAXException, IOException, ParserConfigurationException {

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

    dbf.setValidating(false);//from w  w w  .  j  av a 2  s.c  om
    dbf.setIgnoringComments(false);
    dbf.setIgnoringElementContentWhitespace(true);
    dbf.setNamespaceAware(true);
    // dbf.setCoalescing(true);
    // dbf.setExpandEntityReferences(true);

    DocumentBuilder db = null;
    db = dbf.newDocumentBuilder();
    db.setEntityResolver(new NullResolver());

    // db.setErrorHandler( new MyErrorHandler());
    InputSource is2 = new InputSource();
    is2.setSystemId(is.getSystemId());
    is2.setByteStream(is.getInputStream());
    is2.setCharacterStream(is.getReader());

    return db.parse(is2);
}

From source file:XMLUtilities.java

/**
 * Convenience method for parsing an XML file. This method will
 * wrap the resource in an InputSource and set the source's
 * systemId to "jedit.jar" (so the source should be able to
 * handle any external entities by itself).
 *
 * <p>SAX Errors are caught and are not propagated to the caller;
 * instead, an error message is printed to jEdit's activity
 * log. So, if you need custom error handling, <b>do not use
 * this method</b>.//  ww w . j av  a2  s .c om
 *
 * <p>The given stream is closed before the method returns,
 * regardless whether there were errors or not.</p>
 *
 * @return true if any error occured during parsing, false if success.
 */
public static boolean parseXML(InputStream in, DefaultHandler handler) throws IOException {
    try {
        XMLReader parser = XMLReaderFactory.createXMLReader();
        InputSource isrc = new InputSource(new BufferedInputStream(in));
        isrc.setSystemId("jedit.jar");
        parser.setContentHandler(handler);
        parser.setDTDHandler(handler);
        parser.setEntityResolver(handler);
        parser.setErrorHandler(handler);
        parser.parse(isrc);
    } catch (SAXParseException se) {
        int line = se.getLineNumber();
        return true;
    } catch (SAXException e) {
        return true;
    } finally {
        try {
            if (in != null)
                in.close();
        } catch (IOException io) {
        }
    }
    return false;
}

From source file:Main.java

public static InputSource getInputSource(URL url, InputStream is) throws IOException {
    // is = new BufferedInputStream(is);
    // String encoding = getEncoding(is);
    InputSource inputSource = new InputSource(is);
    // inputSource.setEncoding(encoding);
    // [rfeng] Make sure we set the system id as it will be used as the base URI for nested import/include 
    inputSource.setSystemId(url.toString());
    return inputSource;
}

From source file:org.wildfly.extension.camel.SpringCamelContextFactory.java

private static CamelContext createSpringCamelContext(Resource resource, ClassLoader classLoader)
        throws Exception {
    GenericApplicationContext appContext = new GenericApplicationContext();
    appContext.setClassLoader(classLoader);
    XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(appContext) {
        @Override//w  w w  . j a va  2  s  .co m
        protected NamespaceHandlerResolver createDefaultNamespaceHandlerResolver() {
            NamespaceHandlerResolver defaultResolver = super.createDefaultNamespaceHandlerResolver();
            return new CamelNamespaceHandlerResolver(defaultResolver);
        }
    };
    xmlReader.setEntityResolver(new EntityResolver() {
        @Override
        public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
            InputStream inputStream = null;
            if (CAMEL_SPRING_SYSTEM_ID.equals(systemId)) {
                inputStream = SpringCamelContext.class.getResourceAsStream("/camel-spring.xsd");
            } else if (SPRING_BEANS_SYSTEM_ID.equals(systemId)) {
                inputStream = XmlBeanDefinitionReader.class.getResourceAsStream("spring-beans-3.1.xsd");
            }
            InputSource result = null;
            if (inputStream != null) {
                result = new InputSource();
                result.setSystemId(systemId);
                result.setByteStream(inputStream);
            }
            return result;
        }
    });
    xmlReader.loadBeanDefinitions(resource);
    appContext.refresh();
    return SpringCamelContext.springCamelContext(appContext);
}

From source file:com.pieframework.model.repository.ModelStore.java

/**
 * @param xmlFile/*from w  w  w  .j  a  v  a2 s.  co m*/
 * @param writer
 * @throws ParserConfigurationException
 * @throws SAXException
 * @throws IOException
 * @throws TransformerException
 */
protected static void processXIncludes(File xmlFile, Writer writer)
        throws ParserConfigurationException, SAXException, IOException, TransformerException {

    final InputStream xml = new FileInputStream(xmlFile);

    // This sets the base where XIncludes are resolved
    InputSource i = new InputSource(xml);
    i.setSystemId(xmlFile.toURI().toString());

    // Configure Document Builder
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setXIncludeAware(true);
    factory.setNamespaceAware(true);
    factory.setFeature("http://apache.org/xml/features/xinclude/fixup-base-uris", false);
    DocumentBuilder docBuilder = factory.newDocumentBuilder();

    if (!docBuilder.isXIncludeAware()) {
        throw new IllegalStateException();
    }

    // Parse the InputSource
    Document doc = docBuilder.parse(i);

    // output
    Source source = new DOMSource(doc);
    Result result = new StreamResult(writer);
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    transformer.transform(source, result);
}

From source file:net.sourceforge.dita4publishers.word2dita.Word2DitaValidationHelper.java

/**
 * @return//from  w  w w. ja va  2s. c o m
 * @throws IOException 
 * @throws DomException 
 * @throws BosMemberValidationException 
 */
static Element getCommentTemplate(URL commentsUrl, BosConstructionOptions bosOptions)
        throws IOException, BosMemberValidationException, DomException {
    InputSource commentsTemplateXmlSource = new InputSource(commentsUrl.openStream());
    commentsTemplateXmlSource.setSystemId(DocxConstants.COMMENTS_XML_PATH);
    Document commentsTemplateDom = DomUtil.getDomForSource(commentsTemplateXmlSource, bosOptions, false, false);
    NodeList comments = commentsTemplateDom.getDocumentElement()
            .getElementsByTagNameNS(DocxConstants.nsByPrefix.get("w"), "comment");
    Element commentTemplate = (Element) comments.item(0);
    return commentTemplate;
}

From source file:net.sourceforge.dita4publishers.word2dita.Word2DitaValidationHelper.java

/**
 * @param bosOptions/*from   w  ww  .java  2 s  .  c  o m*/
 * @param docxZip
 * @param commentsTemplateUrl
 * @return
 * @throws Exception 
 */
static Document getCommentsDom(BosConstructionOptions bosOptions, ZipComponents zipComponents,
        URL commentsTemplateUrl) throws Exception {
    Document commentsDom;
    NodeList comments;
    ZipComponent commentsXml = zipComponents.getEntry(DocxConstants.COMMENTS_XML_PATH);
    if (commentsXml == null) {
        System.err.println("No comments.xml file");
        commentsXml = zipComponents.createZipComponent(DocxConstants.COMMENTS_XML_PATH);

        // Use the template as the base for new comments.xml DOM:
        InputSource templateSource = new InputSource(commentsTemplateUrl.openStream());
        templateSource.setSystemId(commentsTemplateUrl.toExternalForm());
        commentsDom = DomUtil.getDomForSource(templateSource, bosOptions, false, false);
        comments = commentsDom.getDocumentElement().getElementsByTagNameNS(DocxConstants.nsByPrefix.get("w"),
                "comment");

        // Remove any existing comments that were in the template:
        for (int i = 0; i < comments.getLength(); i++) {
            Element comment = (Element) comments.item(i);
            commentsDom.getDocumentElement().removeChild(comment);
        }
        zipComponents.createZipComponent(DocxConstants.COMMENTS_XML_PATH, commentsDom);

    } else {
        commentsDom = zipComponents.getDomForZipComponent(bosOptions, DocxConstants.COMMENTS_XML_PATH);
    }
    return commentsDom;
}