Example usage for org.xml.sax InputSource setPublicId

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

Introduction

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

Prototype

public void setPublicId(String publicId) 

Source Link

Document

Set the public identifier for this input source.

Usage

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

/**
 * Entry point//www .  j ava2 s  .c  om
 * @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

/**
 * Utility to get the bytes uri//from  w w  w  .java 2  s.c  o  m
 *
 * @param source the resource to get
 */
public static InputSource sourceToInputSource(Source source) {
    if (source instanceof SAXSource) {
        return ((SAXSource) source).getInputSource();
    } else if (source instanceof DOMSource) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        Node node = ((DOMSource) source).getNode();
        if (node instanceof Document) {
            node = ((Document) node).getDocumentElement();
        }
        Element domElement = (Element) node;
        ElementToStream(domElement, baos);
        InputSource isource = new InputSource(source.getSystemId());
        isource.setByteStream(new ByteArrayInputStream(baos.toByteArray()));
        return isource;
    } else if (source instanceof StreamSource) {
        StreamSource ss = (StreamSource) source;
        InputSource isource = new InputSource(ss.getSystemId());
        isource.setByteStream(ss.getInputStream());
        isource.setCharacterStream(ss.getReader());
        isource.setPublicId(ss.getPublicId());
        return isource;
    } else {
        return getInputSourceFromURI(source.getSystemId());
    }
}

From source file:com.janoz.tvapilib.support.XmlParsingObject.java

protected void parse(AbstractSaxParser parser, InputStream inputStream) {
    try {/*from   w  w  w . j a va 2s. c o m*/
        InputSource input = new InputSource(inputStream);
        input.setPublicId("");
        input.setSystemId("");
        XMLReader reader = XMLReaderFactory.createXMLReader();
        reader.setContentHandler(parser);
        reader.parse(input);
    } catch (SAXException e) {
        LOG.info("Error parsing XML data.", e);
        throw new TvApiException(e.getMessage(), e);
    } catch (IOException e) {
        LOG.info("IO error while parsing XML data.", e);
        throw new TvApiException("IO error while parsing XML data.", e);
    }
}

From source file:channellistmaker.listmaker.XmlTvDtdResolver.java

/**
 * ???????xmltv.dtd????????DocumentBuilder?????????xmltv.dtd???
 * ????????null?/*from   w ww .jav a2s.c  o  m*/
 */
@Override
public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
    if (this.DTD_FILE == null) {
        LOG.warn("DTD???????");
        return null;
    } else {
        LOG.trace("DTD????");
    }
    if ((publicId != null && publicId.contains(DTD_NAME))
            || (systemId != null && systemId.contains(DTD_NAME))) {
        LOG.trace("??????");
        InputSource source = new InputSource(new FileInputStream(this.DTD_FILE));
        source.setPublicId(publicId);
        source.setSystemId(systemId);
        return source;
    } else {
        LOG.trace("?????" + DTD_NAME
                + " ?????????");
        return null;
    }
}

From source file:org.data.support.beans.factory.xml.QueryDTDResolver.java

@Override
public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
    if (logger.isTraceEnabled()) {
        logger.trace("Trying to resolve XML entity with public ID [" + publicId + "] and system ID [" + systemId
                + "]");
    }/*from  w ww .  ja  v  a2s. c  o  m*/
    if (systemId != null && systemId.endsWith(DTD_EXTENSION)) {
        int lastPathSeparator = systemId.lastIndexOf("/");
        for (String DTD_NAME : DTD_NAMES) {
            int dtdNameStart = systemId.indexOf(DTD_NAME);
            if (dtdNameStart > lastPathSeparator) {
                String dtdFile = systemId.substring(dtdNameStart);
                if (logger.isTraceEnabled()) {
                    logger.trace("Trying to locate [" + dtdFile + "] in Spring jar");
                }
                try {
                    Resource resource = new ClassPathResource(dtdFile, getClass());
                    InputSource source = new InputSource(resource.getInputStream());
                    source.setPublicId(publicId);
                    source.setSystemId(systemId);
                    if (logger.isDebugEnabled()) {
                        logger.debug("Found queries DTD [" + systemId + "] in classpath: " + dtdFile);
                    }
                    return source;
                } catch (IOException ex) {
                    if (logger.isDebugEnabled()) {
                        logger.debug(
                                "Could not resolve queries DTD [" + systemId + "]: not found in class path",
                                ex);
                    }
                }

            }
        }
    }

    // Use the default behavior -> download from website or wherever.
    return null;
}

From source file:de.tudarmstadt.ukp.dkpro.core.io.xml.XmlReaderText.java

@Override
public void getNext(CAS aCAS) throws IOException, CollectionException {
    Resource res = nextFile();/*www .  j  a va 2s.c  o m*/
    initCas(aCAS, res);

    InputStream is = null;

    try {
        JCas jcas = aCAS.getJCas();

        is = res.getInputStream();

        // Create handler
        Handler handler = newSaxHandler();
        handler.setJCas(jcas);
        handler.setLogger(getLogger());

        // Parser XML
        SAXParserFactory pf = SAXParserFactory.newInstance();
        SAXParser parser = pf.newSAXParser();

        InputSource source = new InputSource(is);
        source.setPublicId(res.getLocation());
        source.setSystemId(res.getLocation());
        parser.parse(source, handler);

        // Set up language
        if (getConfigParameterValue(PARAM_LANGUAGE) != null) {
            aCAS.setDocumentLanguage((String) getConfigParameterValue(PARAM_LANGUAGE));
        }
    } catch (CASException e) {
        throw new CollectionException(e);
    } catch (ParserConfigurationException e) {
        throw new CollectionException(e);
    } catch (SAXException e) {
        throw new IOException(e);
    } finally {
        closeQuietly(is);
    }
}

From source file:com.knitml.core.xml.PluggableSchemaResolver.java

public InputSource resolveEntity(String publicId, String systemId) throws IOException {
    if (logger.isTraceEnabled()) {
        logger.trace("Trying to resolve XML entity with public id [" + publicId + "] and system id [" + systemId
                + "]");
    }//from  ww w. j  av a2 s  .  co m
    if (systemId != null) {
        String resourceLocation = getSchemaMapping(systemId);
        if (resourceLocation != null) {
            Resource resource = new ClassPathResource(resourceLocation, this.classLoader);
            InputSource source = new InputSource(resource.getInputStream());
            source.setPublicId(publicId);
            source.setSystemId(systemId);
            if (logger.isDebugEnabled()) {
                logger.debug("Found XML schema [" + systemId + "] in classpath: " + resourceLocation);
            }
            return source;
        }
    }
    return null;
}

From source file:org.data.support.beans.factory.xml.SchemaResolver.java

public InputSource resolveEntity(String publicId, String systemId) throws IOException {
    if (logger.isTraceEnabled()) {
        logger.trace("Trying to resolve XML entity with public id [" + publicId + "] and system id [" + systemId
                + "]");
    }/*w ww.j  a  v  a  2 s  . co  m*/

    if (systemId != null) {
        String resourceLocation = getSchemaMappings().get(systemId);
        if (resourceLocation != null) {
            Resource resource = new ClassPathResource(resourceLocation, this.classLoader);
            try {
                InputSource source = new InputSource(resource.getInputStream());
                source.setPublicId(publicId);
                source.setSystemId(systemId);
                if (logger.isDebugEnabled()) {
                    logger.debug("Found XML schema [" + systemId + "] in classpath: " + resourceLocation);
                }
                return source;
            } catch (FileNotFoundException ex) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Couldn't find XML schema [" + systemId + "]: " + resource, ex);
                }
            }
        }
    }
    return null;
}

From source file:com.adaptris.util.text.xml.Resolver.java

/**
 * @see EntityResolver#resolveEntity(String, String)
 *//*from  ww w .  ja v  a2  s. c  om*/
@Override
public InputSource resolveEntity(String publicId, String systemId) throws SAXException {
    debugLog("Resolving [{}][{}]", publicId, systemId);
    InputSource result = null;
    try {
        InputSource ret = new InputSource(retrieveAndCache(new URLString(systemId)));
        ret.setPublicId(publicId);
        ret.setSystemId(systemId);
        result = ret;
    } catch (Exception e) {
        debugLog("Couldn't handle [{}][{}], fallback to default parser behaviour", publicId, systemId);
        result = null;
    }
    return result;
}

From source file:de.micromata.genome.gwiki.page.gspt.taglibs.TagLibraryInfoImpl.java

protected void loadTagLibary(String uri) {
    Digester dig = new Digester();
    dig.setClassLoader(Thread.currentThread().getContextClassLoader());
    dig.setValidating(false);//from  www. j  a  v  a  2 s.  c  o  m
    final EntityResolver parentResolver = dig.getEntityResolver();
    dig.setEntityResolver(new EntityResolver() {

        public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {

            InputStream is = null;
            if (StringUtils.equals(systemId, "http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd") == true
                    || StringUtils.equals(publicId,
                            "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN") == true) {
                is = loadLocalDtd("web-jsptaglibrary_1_1.dtd");

            } else if (StringUtils.equals(systemId, "http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd") == true
                    || StringUtils.equals(publicId,
                            "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN") == true) {
                is = loadLocalDtd("web-jsptaglibrary_1_2.dtd");
            }
            if (is == null) {
                if (parentResolver == null) {
                    GWikiLog.error("Cannot resolve entity: " + systemId);
                    return null;
                }
                return parentResolver.resolveEntity(publicId, systemId);
            }
            InputSource source = new InputSource(is);
            source.setPublicId(publicId);
            source.setSystemId(systemId);
            return source;
        }
    });
    dig.addCallMethod("taglib/tlib-version", "setTlibversion", 0);
    dig.addCallMethod("taglib/tlibversion", "setTlibversion", 0);
    dig.addCallMethod("taglib/jsp-version", "setJspversion", 0);
    dig.addCallMethod("taglib/jspversion", "setJspversion", 0);
    dig.addCallMethod("taglib/short-name", "setShortname", 0);
    dig.addCallMethod("taglib/shortname", "setShortname", 0);
    dig.addObjectCreate("taglib/tag", TagTmpInfo.class);
    dig.addCallMethod("taglib/tag/name", "setTagName", 0);
    dig.addCallMethod("taglib/tag/description", "setInfoString", 0);
    dig.addCallMethod("taglib/tag/tag-class", "setTagClassName", 0);
    dig.addCallMethod("taglib/tag/tagclass", "setTagClassName", 0);

    dig.addCallMethod("taglib/tag/body-content", "setBodycontent", 0);
    dig.addCallMethod("taglib/tag/bodycontent", "setBodycontent", 0);

    dig.addObjectCreate("taglib/tag/attribute", TagTmpAttributeInfo.class);
    dig.addCallMethod("taglib/tag/attribute/name", "setName", 0);
    dig.addCallMethod("taglib/tag/attribute/required", "setRequired", 0);
    dig.addCallMethod("taglib/tag/attribute/rtexprvalue", "setRtexprvalue", 0);
    dig.addSetNext("taglib/tag/attribute", "addAttributeInfo");
    dig.addSetNext("taglib/tag", "addTag");

    dig.push(this);
    try {
        InputStream is = loadImpl(uri);
        if (is == null) {
            throw new RuntimeException("could not load tld '" + uri + "'");
        }
        /*
         * ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copy(is, baos); String text =
         * Converter.stringFromBytes(baos.toByteArray()); dig.parse(new StringReader(text));
         */
        dig.parse(is);
        rework();
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}