List of usage examples for org.xml.sax InputSource setSystemId
public void setSystemId(String systemId)
From source file:org.exolab.castor.mapping.Mapping.java
/** * Loads the mapping from the specified URL. * * @param url The URL of the mapping file. * @param type The source type.//from ww w . j a v a 2s .c o m * @throws IOException An error occured when reading the mapping file. * @throws MappingException The mapping file is invalid. */ public void loadMapping(final URL url, final String type) throws IOException, MappingException { try { if (_resolver.getBaseURL() == null) { _resolver.setBaseURL(url); } InputSource source = _resolver.resolveEntity(null, url.toExternalForm()); if (source == null) { source = new InputSource(url.toExternalForm()); source.setByteStream(url.openStream()); } else source.setSystemId(url.toExternalForm()); LOG.info(Messages.format("mapping.loadingFrom", url.toExternalForm())); loadMapping(source, type); } catch (SAXException ex) { throw new MappingException(ex); } }
From source file:org.geoserver.wms.WMSTestSupport.java
/** * Utility method to run the transformation on tr with the provided request and returns the * result as a DOM/*from w w w . ja v a 2 s .c o m*/ * * @param req * , the Object to run the xml transformation against with {@code tr}, usually an * instance of a {@link Request} subclass * @param tr * , the transformer to run the transformation with and produce the result as a DOM * @param namespaceAware * whether to use a namespace aware parser for the response or not */ public static Document transform(Object req, TransformerBase tr, boolean namespaceAware) throws Exception { ByteArrayOutputStream out = new ByteArrayOutputStream(); tr.transform(req, out); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(namespaceAware); DocumentBuilder db = dbf.newDocumentBuilder(); /** * Resolves everything to an empty xml document, useful for skipping errors due to missing * dtds and the like * * @author Andrea Aime - TOPP */ class EmptyResolver implements org.xml.sax.EntityResolver { public InputSource resolveEntity(String publicId, String systemId) throws org.xml.sax.SAXException, IOException { StringReader reader = new StringReader("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); InputSource source = new InputSource(reader); source.setPublicId(publicId); source.setSystemId(systemId); return source; } } db.setEntityResolver(new EmptyResolver()); // System.out.println(out.toString()); Document doc = db.parse(new ByteArrayInputStream(out.toByteArray())); return doc; }
From source file:org.hisp.dhis.webwork.configuration.UrlXmlConfigurationProvider.java
private void loadConfigurationFile(String fileName, Element includeElement) { if (!includedFileNames.contains(fileName)) { if (LOG.isDebugEnabled()) { LOG.debug("Loading xwork configuration from: " + fileName); }/*from w ww.ja v a2s .c om*/ includedFileNames.add(fileName); Document doc = null; InputStream is = null; try { is = getInputStream(fileName); if (is == null) { throw new Exception("Could not open file " + fileName); } InputSource in = new InputSource(is); // FIXME: we shouldn't be doing this lookup twice try { in.setSystemId(ClassLoaderUtil.getResource(fileName, getClass()).toString()); } catch (Exception e) { in.setSystemId(fileName); } Map dtdMappings = new HashMap(); dtdMappings.put("-//OpenSymphony Group//XWork 1.1.1//EN", "xwork-1.1.1.dtd"); dtdMappings.put("-//OpenSymphony Group//XWork 1.1//EN", "xwork-1.1.dtd"); dtdMappings.put("-//OpenSymphony Group//XWork 1.0//EN", "xwork-1.0.dtd"); doc = DomHelper.parse(in, dtdMappings); } catch (XworkException e) { // WTF!!?? if (includeElement != null) { System.out.println(e); throw new ConfigurationException(e, includeElement); } else { throw new ConfigurationException(e); } } catch (Exception e) { final String s = "Caught exception while loading file " + fileName; LOG.error(s, e); // throw new ConfigurationException(s, e, includeElement); throw new ConfigurationException(s, e); } finally { if (is != null) { try { is.close(); } catch (IOException e) { LOG.error("Unable to close input stream", e); } } } Element rootElement = doc.getDocumentElement(); NodeList children = rootElement.getChildNodes(); int childSize = children.getLength(); for (int i = 0; i < childSize; i++) { Node childNode = children.item(i); if (childNode instanceof Element) { Element child = (Element) childNode; final String nodeName = child.getNodeName(); if (nodeName.equals("package")) { addPackage(child); } else if (nodeName.equals("include")) { String includeFileName = child.getAttribute("file"); loadConfigurationFile(includeFileName, child); } } } if (LOG.isDebugEnabled()) { LOG.debug("Loaded xwork configuration from: " + fileName); } } }
From source file:org.impalaframework.xml.schema.ClassPathSchemaResolver.java
public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException { if (systemId != null) { 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 for system id in '" + systemId + "' in classpath: " + resourceLocation); }//from w w w . ja v a 2 s .c o m return source; } } return null; }
From source file:org.infoscoop.web.InitializeServlet.java
/** * get the resource on the same context as InputSource. * @param config//from ww w.jav a 2 s .c om * @param path * @return * @throws ServletException */ public static InputSource getResource(ServletConfig config, String path) throws ServletException { try { URL url = config.getServletContext().getResource(path); InputStream input = config.getServletContext().getResourceAsStream(path); InputSource is = new InputSource(url.toExternalForm()); is.setByteStream(input); is.setSystemId(config.getServletContext().getRealPath(path)); return is; } catch (MalformedURLException e) { throw new ServletException(e); } }
From source file:org.infosec.ismp.collectd.snmp.castor.CastorUtils.java
/** * Unmarshal a Castor XML configuration file. Uses Java 5 generics for * return type. //from w w w. j av a 2 s . c om * * @param <T> the class representing the marshalled XML configuration * file. This will be the return time form the method. * @param clazz the class representing the marshalled XML configuration * file * @param resource the marshalled XML configuration file to unmarshal * @return Unmarshalled object representing XML file * @throws MarshalException if the underlying Castor * Unmarshaller.unmarshal() call throws a MarshalException * @throws ValidationException if the underlying Castor * Unmarshaller.unmarshal() call throws a ValidationException * @throws IOException if the resource could not be opened */ public static <T> T unmarshal(Class<T> clazz, Resource resource) throws MarshalException, ValidationException, IOException { InputStream in; try { in = resource.getInputStream(); } catch (IOException e) { IOException newE = new IOException( "Failed to open XML configuration file for resource '" + resource + "': " + e); newE.initCause(e); throw newE; } try { InputSource source = new InputSource(in); try { source.setSystemId(resource.getURL().toString()); } catch (Throwable t) { // ignore } return unmarshal(clazz, source); } finally { IOUtils.closeQuietly(in); } }
From source file:org.infosec.ismp.collectd.snmp.castor.CastorUtils.java
/** * Unmarshal a Castor XML configuration file. Uses Java 5 generics for * return type and throws DataAccessExceptions. * // www . j av a 2s . c o m * @param <T> the class representing the marshalled XML configuration * file. This will be the return time form the method. * @param clazz the class representing the marshalled XML configuration * file * @param resource the marshalled XML configuration file to unmarshal * @return Unmarshalled object representing XML file * @throws DataAccessException if the resource could not be opened or the * underlying Castor * Unmarshaller.unmarshal() call throws a MarshalException or * ValidationException. The underlying exception will be translated * using CastorExceptionTranslator and will include information about * the resource from its {@link Resource#toString() toString()} method. */ public static <T> T unmarshalWithTranslatedExceptions(Class<T> clazz, Resource resource) { // TODO It might be useful to add code to test for readability on real files; the code below is from DefaultManualProvisioningDao - dj@opennms.org // if (!importFile.canRead()) { // throw new PermissionDeniedDataAccessException("Unable to read file "+importFile, null); // } InputStream in; try { in = resource.getInputStream(); } catch (IOException e) { throw CASTOR_EXCEPTION_TRANSLATOR .translate("opening XML configuration file for resource '" + resource + "'", e); } try { InputSource source = new InputSource(in); try { source.setSystemId(resource.getURL().toString()); } catch (Throwable t) { /* * resource.getURL() might throw an IOException * (or maybe a DataAccessException, since it's a * RuntimeException), indicating that the resource can't be * represented as a URL. We don't really care so much--we'll * only lose the ability for Castor to include the resource URL * in error messages and for it to directly resolve relative * URLs (which we don't currently use), so we just ignore it. */ } return unmarshal(clazz, source); } catch (MarshalException e) { throw CASTOR_EXCEPTION_TRANSLATOR.translate("unmarshalling XML file for resource '" + resource + "'", e); } catch (ValidationException e) { throw CASTOR_EXCEPTION_TRANSLATOR.translate("unmarshalling XML file for resource '" + resource + "'", e); } finally { IOUtils.closeQuietly(in); } }
From source file:org.jboss.confluence.plugin.docbook_tools.docbookimport.DocbookImporter.java
/** * Process XSLT transformation./*from w w w. j a va2 s . co m*/ * * @param xsltTemplate input stream with XSLT template file used to transform (closed inside this method) * @param xmlToTransform input stream with XML file to transform (closed inside this method) * @param xmlToTransformURL URL of <code>xmlToTransform</code> file (may be <code>file://</code> too). We need it to * correctly evaluate relative paths. * @param output stream to write transformed output to * @throws javax.xml.transform.TransformerException */ protected void processXslt(final InputStream xsltTemplate, final InputStream xmlToTransform, final String xmlToTransformURL, final OutputStream output) throws Exception { final XSLTErrorListener errorListener = new XSLTErrorListener(); final SAXErrorHandler eh = new SAXErrorHandler(); Thread th = new Thread(new Runnable() { public void run() { try { org.xml.sax.InputSource xmlSource = new org.xml.sax.InputSource(xmlToTransform); xmlSource.setSystemId(xmlToTransformURL); javax.xml.transform.Source xsltSource = new javax.xml.transform.stream.StreamSource( xsltTemplate); javax.xml.transform.Result result = new javax.xml.transform.stream.StreamResult(output); // prepare XInclude aware parser which resolves necessary entities correctly XMLReader reader = new ParserAdapter(saxParserFactory.newSAXParser().getParser()); reader.setEntityResolver(new JDGEntityResolver(reader.getEntityResolver())); reader.setErrorHandler(eh); SAXSource xmlSAXSource = new SAXSource(reader, xmlSource); javax.xml.transform.Transformer trans = transformerFact.newTransformer(xsltSource); trans.setErrorListener(errorListener); trans.transform(xmlSAXSource, result); } catch (Exception e) { if (e instanceof TransformerException) { errorListener.setException((TransformerException) e); } else { errorListener.setException(new TransformerException(e)); } } finally { FileUtils.closeInputStream(xmlToTransform); FileUtils.closeInputStream(xsltTemplate); } } }); th.setName("DocbookImporter XSLT transformation thread"); th.setDaemon(true); th.setContextClassLoader(DocbookImporter.class.getClassLoader()); th.start(); th.join(); if (eh.getException() != null) { throw eh.getException(); } if (errorListener.getException() != null) { throw errorListener.getException(); } }
From source file:org.jboss.elasticsearch.river.remote.sitemap.SiteMapParser.java
/** * Decompress the gzipped content and process the resulting XML Sitemap. * //from w ww . ja v a 2s. c o m * @param url - URL of the gzipped content * @param response - Gzipped content * @throws MalformedURLException * @throws IOException * @throws UnknownFormatException */ private AbstractSiteMap processGzip(URL url, byte[] response) throws MalformedURLException, IOException, UnknownFormatException { logger.debug("Processing gzip"); AbstractSiteMap smi; InputStream is = new ByteArrayInputStream(response); // Remove .gz ending String xmlUrl = url.toString().replaceFirst("\\.gz$", ""); logger.debug("XML url = " + xmlUrl); BOMInputStream decompressed = new BOMInputStream(new GZIPInputStream(is)); InputSource in = new InputSource(decompressed); in.setSystemId(xmlUrl); smi = processXml(url, in); decompressed.close(); return smi; }
From source file:org.kuali.core.db.torque.KualiXmlToAppData.java
/** * Parses a XML input file and returns a newly created and * populated Database structure.//from w ww . j a va2 s .com * * @param xmlFile The input file to parse. * @return Database populated by <code>xmlFile</code>. */ public KualiDatabase parseFile(String xmlFile) throws EngineException { try { // in case I am missing something, make it obvious if (!firstPass) { throw new Error("No more double pass"); } // check to see if we alread have parsed the file if ((alreadyReadFiles != null) && alreadyReadFiles.contains(xmlFile)) { return database; } else if (alreadyReadFiles == null) { alreadyReadFiles = new Vector(3, 1); } // remember the file to avoid looping alreadyReadFiles.add(xmlFile); currentXmlFile = xmlFile; saxFactory.setValidating(false); SAXParser parser = saxFactory.newSAXParser(); FileInputStream fileInputStream = null; try { fileInputStream = new FileInputStream(xmlFile); } catch (FileNotFoundException fnfe) { throw new FileNotFoundException(new File(xmlFile).getAbsolutePath()); } BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream); try { log.info("Parsing file: '" + (new File(xmlFile)).getName() + "'"); InputSource is = new InputSource(bufferedInputStream); is.setSystemId(xmlFile); parser.parse(is, this); } finally { bufferedInputStream.close(); } } catch (SAXParseException e) { throw new EngineException("Sax error on line " + e.getLineNumber() + " column " + e.getColumnNumber() + " : " + e.getMessage(), e); } catch (Exception e) { throw new EngineException(e); } if (!isExternalSchema) { firstPass = false; } database.doFinalInitialization(); return database; }