Example usage for org.xml.sax InputSource getSystemId

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

Introduction

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

Prototype

public String getSystemId() 

Source Link

Document

Get the system identifier for this input source.

Usage

From source file:XMLUtils.java

public static Document parse(InputSource is) throws ParserConfigurationException, SAXException, IOException {
    return getParser().parse(is.getSystemId());
}

From source file:Main.java

private static void transformInternal(final URIResolver xslResolver, final StreamSource xml,
        final InputSource xsl, final Map<String, Object> parameters, final StreamResult result)
        throws IOException, ParserConfigurationException, SAXException, TransformerConfigurationException,
        TransformerException {//from w ww .  j  ava 2  s . c  om
    final TransformerFactory tfactory = TransformerFactory.newInstance();
    tfactory.setURIResolver(xslResolver);

    // Does this factory support SAX features?
    if (tfactory.getFeature(SAXSource.FEATURE)) {
        // if so, we can safely cast
        final SAXTransformerFactory stfactory = ((SAXTransformerFactory) tfactory);

        // create a Templates ContentHandler to handle parsing of the
        // stylesheet
        final javax.xml.transform.sax.TemplatesHandler templatesHandler = stfactory.newTemplatesHandler();
        templatesHandler.setDocumentLocator(emptyDocumentLocator);

        final XMLFilter filter = new XMLFilterImpl();
        filter.setParent(makeXMLReader());
        filter.setContentHandler(templatesHandler);

        // parse the stylesheet
        templatesHandler.setSystemId(xsl.getSystemId());
        filter.parse(xsl);

        // set xslt parameters
        final Transformer autobot = templatesHandler.getTemplates().newTransformer();
        if (parameters != null) {
            final Iterator<String> keys = parameters.keySet().iterator();
            while (keys.hasNext()) {
                final String name = keys.next();
                final Object value = parameters.get(name);
                autobot.setParameter(name, value);
            }
        }

        // set saxon parameters
        if (parameters != null) {
            final Iterator<String> keys = parameters.keySet().iterator();
            while (keys.hasNext()) {
                String name = keys.next();
                if (name.startsWith("saxon-")) {
                    final String value = parameters.get(name).toString();
                    name = name.replaceFirst("saxon\\-", "");
                    autobot.setOutputProperty(name, value);
                }
            }
        }

        // do the transform
        // logger.debug("SAX resolving systemIDs relative to: " +
        // templatesHandler.getSystemId());
        autobot.transform(xml, result);

    } else {
        throw new IllegalStateException("Factory doesn't implement SAXTransformerFactory");
    }
}

From source file:net.sf.joost.trax.TemplatesImpl.java

/**
 * Configures the <code>Templates</code> - initializing by parsing the
 * stylesheet.//  w w  w . ja  va 2 s  .  c  o m
 * @param reader The <code>XMLReader</code> for parsing the stylesheet
 * @param isource The <code>InputSource</code> of the stylesheet
 * @throws TransformerConfigurationException When an error occurs while
 *  initializing the <code>Templates</code>.
 */
private void init(XMLReader reader, InputSource isource) throws TransformerConfigurationException {

    if (DEBUG)
        log.debug("init with InputSource " + isource.getSystemId());
    try {
        /**
         * Register ErrorListener from
         * {@link TransformerFactoryImpl#getErrorListener()}
         * if available.
         */
        // check if transformerfactory is in debug mode
        boolean debugmode = ((Boolean) this.factory.getAttribute(DEBUG_FEATURE)).booleanValue();

        ParseContext pContext = new ParseContext();
        pContext.allowExternalFunctions = factory.allowExternalFunctions;
        pContext.setErrorListener(factory.getErrorListener());
        pContext.uriResolver = factory.getURIResolver();
        if (debugmode) {
            if (DEBUG)
                log.info("init transformer in debug mode");
            pContext.parserListener = factory.getParserListenerMgr();
            processor = new DebugProcessor(reader, isource, pContext, factory.getMessageEmitter());
        } else {
            processor = new Processor(reader, isource, pContext);
        }
        processor.setTransformerHandlerResolver(factory.thResolver);
        processor.setOutputURIResolver(factory.outputUriResolver);
    } catch (java.io.IOException iE) {
        if (DEBUG)
            log.debug(iE);
        throw new TransformerConfigurationException(iE.getMessage(), iE);
    } catch (org.xml.sax.SAXException sE) {
        Exception emb = sE.getException();
        if (emb instanceof TransformerConfigurationException)
            throw (TransformerConfigurationException) emb;
        if (DEBUG)
            log.debug(sE);
        throw new TransformerConfigurationException(sE.getMessage(), sE);
    } catch (java.lang.NullPointerException nE) {
        if (DEBUG)
            log.debug(nE);
        nE.printStackTrace(System.err);
        throw new TransformerConfigurationException(
                "could not found value for property javax.xml.parsers.SAXParser ", nE);
    }
}

From source file:org.callimachusproject.xml.XdmNodeFactory.java

private XdmNode parse(InputSource isource) throws SAXException {
    // Make sure the builder uses our entity resolver
    XMLReader reader = XMLReaderFactory.createXMLReader();
    reader.setEntityResolver(xmlResolver);
    SAXSource source = new SAXSource(reader, isource);
    if (isource.getSystemId() != null) {
        source.setSystemId(isource.getSystemId());
    }/*from   w w  w.  j a  v  a2  s  .  co m*/
    return parse(source);
}

From source file:net.sf.joost.trax.TrAXFilter.java

/**
 * Parses the <code>InputSource</code>
 * @param input A <code>InputSource</code> object.
 * @throws SAXException/*from  www.j  av  a  2  s .c  om*/
 * @throws IOException
 */
public void parse(InputSource input) throws SAXException, IOException {

    Transformer transformer = null;
    if (DEBUG) {
        if (log.isDebugEnabled())
            log.debug("parsing InputSource " + input.getSystemId());
    }

    try {
        // get a new Transformer
        transformer = this.templates.newTransformer();
        if (transformer instanceof TransformerImpl) {
            this.processor = ((TransformerImpl) transformer).getStxProcessor();
        } else {
            String msg = "An error is occured, because the given transformer is "
                    + "not an instance of TransformerImpl";
            if (log != null)
                log.fatal(msg);
            else
                System.err.println("Fatal error - " + msg);

        }
        XMLReader parent = this.getParent();

        if (parent == null) {
            parent = XMLReaderFactory.createXMLReader();
            setParent(parent);
        }
        ContentHandler handler = this.getContentHandler();

        if (handler == null) {
            handler = parent.getContentHandler();
        }
        if (handler == null) {
            throw new SAXException("no ContentHandler registered");
        }
        //init StxEmitter
        StxEmitter out = null;

        //SAX specific Implementation
        out = new SAXEmitter(handler);

        if (this.processor != null) {
            this.processor.setContentHandler(out);
            this.processor.setLexicalHandler(out);
        } else {
            throw new SAXException("Joost-Processor is not correct configured.");
        }
        if (parent == null) {
            throw new SAXException("No parent for filter");
        }
        parent.setContentHandler(this.processor);
        parent.setProperty("http://xml.org/sax/properties/lexical-handler", this.processor);
        parent.setEntityResolver(this);
        parent.setDTDHandler(this);
        parent.setErrorHandler(this);
        parent.parse(input);

    } catch (TransformerConfigurationException tE) {
        try {
            configErrListener.fatalError(tE);
        } catch (TransformerConfigurationException innerE) {
            throw new SAXException(innerE.getMessage(), innerE);
        }
    } catch (SAXException sE) {
        try {
            configErrListener.fatalError(new TransformerConfigurationException(sE.getMessage(), sE));
        } catch (TransformerConfigurationException innerE) {
            throw new SAXException(innerE.getMessage(), innerE);
        }
    } catch (IOException iE) {
        try {
            configErrListener.fatalError(new TransformerConfigurationException(iE.getMessage(), iE));
        } catch (TransformerConfigurationException innerE) {
            throw new IOException(innerE.getMessage());
        }
    }
}

From source file:com.adamrosenfield.wordswithcrosses.net.derstandard.SolutionParser.java

private Reader getReader(InputSource s) throws SAXException, IOException {
    Reader r = s.getCharacterStream();
    InputStream i = s.getByteStream();
    String encoding = s.getEncoding();
    String publicid = s.getPublicId();
    String systemid = s.getSystemId();
    if (r == null) {
        if (i == null)
            i = getInputStream(publicid, systemid);
        // i = new BufferedInputStream(i);
        if (encoding == null) {
            r = theAutoDetector.autoDetectingReader(i);
        } else {//ww  w  . j a  v  a  2  s  .  com
            try {
                r = new InputStreamReader(i, encoding);
            } catch (UnsupportedEncodingException e) {
                r = new InputStreamReader(i);
            }
        }
    }
    // r = new BufferedReader(r);
    return r;
}

From source file:com.runwaysdk.dataaccess.io.RunwayClasspathEntityResolver.java

public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
    if (systemId.startsWith("classpath:")) {
        systemId = systemId.replaceFirst("classpath:", "");
    } else {/*from   w ww  .  j  av a 2 s .  c  om*/
        return null;
    }

    // We're fetching from the root classloader, which means the equivalent of having a / at the beginning of the path
    // For some reason, when you do put a preceeding / the root classloader won't find the resource. This is dumb so I'm
    // going to remove preceeding slashes to stop it from not finding a valid resource.
    if (systemId.startsWith("/")) {
        systemId = systemId.replaceFirst("/", "");
    }

    InputSource inputSource = null;

    try {
        URL url = this.getClass().getClassLoader().getResource(systemId);

        if (url == null) {
            throw new Exception("ClassLoader.getResource returned null.");
        }

        inputSource = new InputSource(url.toURI().toString());

        if (inputSource.getSystemId() == null) {
            throw new Exception(
                    "ClassLoader.getResource returned a url, but inputSource.getSystemId returned null.");
        }

        log.debug("Runway SAX parser successfully resolved resource on classpath [" + systemId + "] to ["
                + inputSource.getSystemId() + "].");

        return inputSource;
    } catch (Exception e) {
        log.fatal("Runway SAX parser unable to resolve resource on classpath [" + systemId + "].", e);
        return null;
    }
}

From source file:net.sf.joost.trax.TemplatesImpl.java

/**
 * Constructor./*from   ww w  .j a v  a2  s  .c  o m*/
 * @param reader The <code>XMLReader</code> for parsing the stylesheet
 * @param isource The <code>InputSource</code> of the stylesheet
 * @param factory A reference on a <code>TransformerFactoryImpl</code>
 * @throws TransformerConfigurationException When an error occurs.
 */
protected TemplatesImpl(XMLReader reader, InputSource isource, TransformerFactoryImpl factory)
        throws TransformerConfigurationException {

    if (DEBUG)
        log.debug("calling constructor with SystemId " + isource.getSystemId());
    this.factory = factory;
    try {
        //configure template
        init(reader, isource);
    } catch (TransformerConfigurationException tE) {
        factory.defaultErrorListener.fatalError(tE);
    }
}

From source file:org.callimachusproject.xml.InputSourceResolver.java

@Override
public StreamSource resolve(String href, String base) throws TransformerException {
    try {//from   w  w  w  . j  av a2s  . c om
        InputSource input = resolve(resolveURI(href, base));
        if (input == null)
            return null;
        InputStream in = input.getByteStream();
        if (in != null) {
            if (input.getSystemId() == null)
                return new StreamSource(in);
            return new StreamSource(in, input.getSystemId());
        }
        Reader reader = input.getCharacterStream();
        if (reader != null) {
            if (input.getSystemId() == null)
                return new StreamSource(reader);
            return new StreamSource(reader, input.getSystemId());
        }
        if (input.getSystemId() == null)
            return new StreamSource();
        return new StreamSource(input.getSystemId());
    } catch (IOException e) {
        throw new TransformerException(e);
    }
}

From source file:net.ontopia.topicmaps.nav2.portlets.pojos.TMRAP.java

/**
 * PUBLIC: Sends a query, returning a model of the result.
 * @param psis a collection of PSIs as strings
 * @return a list of Server objects/*from  ww  w. j a v  a  2 s. c o m*/
 */
public Collection query(Collection psis) throws IOException, InvalidQueryException {
    if (psis.isEmpty())
        return Collections.EMPTY_SET;
    String psikey = makeKey(psis);

    Collection model = new ArrayList();
    Iterator it = servers.iterator();
    while (it.hasNext()) {
        String endpoint = (String) it.next();

        // is it in the cache?
        if (cache.containsKey(endpoint + psikey)) {
            CacheEntry entry = (CacheEntry) cache.get(endpoint + psikey);
            model.add(entry.getObject());
            continue;
        }

        // not in cache, so go look it up
        InputSource src = getInputSource(endpoint, psis);
        TMXMLReader reader = new TMXMLReader(src, new URILocator(src.getSystemId()));
        TopicMapIF topicmap = reader.read();
        QueryWrapper qw = new QueryWrapper(topicmap);
        qw.setDeclarations("using tmrap for i\"http://psi.ontopia.net/tmrap/\" ");
        Server server = (Server) qw.queryForObject("instance-of($S, tmrap:server)?", new Factory());
        model.add(server);
        qw.queryForList("instance-of($TM, tmrap:topicmap)?", new Factory(server));

        // process the topic maps
        Iterator it2 = server.getTopicMaps().iterator();
        while (it2.hasNext()) {
            TopicMap tm = (TopicMap) it2.next();
            Map params = qw.makeParams("tm", tm.getTopic());
            qw.queryForList("tmrap:contained-in(%tm% : tmrap:container, $P : tmrap:containee)?",
                    new Factory(tm), params);
        }

        // update the cache
        cache.put(endpoint + psikey, new CacheEntry(server));
    }
    return model;
}