List of usage examples for org.xml.sax InputSource getByteStream
public InputStream getByteStream()
From source file:org.apache.xmlgraphics.image.loader.util.ImageUtil.java
/** * Closes the InputStreams or ImageInputStreams of Source objects. Any exception occurring * while closing the stream is ignored.//w ww . ja v a 2 s. c o m * @param src the Source object */ public static void closeQuietly(Source src) { if (src == null) { return; } else if (src instanceof StreamSource) { StreamSource streamSource = (StreamSource) src; IOUtils.closeQuietly(streamSource.getInputStream()); streamSource.setInputStream(null); IOUtils.closeQuietly(streamSource.getReader()); streamSource.setReader(null); } else if (src instanceof ImageSource) { ImageSource imageSource = (ImageSource) src; if (imageSource.getImageInputStream() != null) { try { imageSource.getImageInputStream().close(); } catch (IOException ioe) { //ignore } imageSource.setImageInputStream(null); } } else if (src instanceof SAXSource) { InputSource is = ((SAXSource) src).getInputSource(); if (is != null) { IOUtils.closeQuietly(is.getByteStream()); is.setByteStream(null); IOUtils.closeQuietly(is.getCharacterStream()); is.setCharacterStream(null); } } }
From source file:org.apache.xmlgraphics.io.XmlSourceUtil.java
/** * Closes the InputStreams or ImageInputStreams of Source objects. Any exception occurring * while closing the stream is ignored.//w w w . j a v a 2s. c om * @param src the Source object */ public static void closeQuietly(Source src) { if (src instanceof StreamSource) { StreamSource streamSource = (StreamSource) src; IOUtils.closeQuietly(streamSource.getReader()); } else if (src instanceof ImageSource) { if (ImageUtil.getImageInputStream(src) != null) { try { ImageUtil.getImageInputStream(src).close(); } catch (IOException ioe) { // ignore } } } else if (src instanceof SAXSource) { InputSource is = ((SAXSource) src).getInputSource(); if (is != null) { IOUtils.closeQuietly(is.getByteStream()); IOUtils.closeQuietly(is.getCharacterStream()); } } removeStreams(src); }
From source file:org.betaconceptframework.astroboa.configuration.W3CRelatedSchemaEntityResolver.java
@Override public LSInput resolveResource(String type, String namespaceURI, String publicId, String systemId, String baseURI) {// ww w. j av a 2s.c om InputSource entity; try { entity = locateEntity(systemId, publicId); } catch (IOException e) { throw new CmsException(e); } if (entity == null || entity.getByteStream() == null) { return null; } DOMImplementationLS domImplementationLS = (DOMImplementationLS) registry.getDOMImplementation("LS"); LSInput lsInput = domImplementationLS.createLSInput(); lsInput.setByteStream(entity.getByteStream()); lsInput.setSystemId(systemId); return lsInput; }
From source file:org.castor.mapping.MappingUnmarshaller.java
/** * Internal recursive loading method. This method will load the mapping document into a mapping * object and load all the included mapping along the way into a single collection. * * @param mapping The mapping instance.// w w w. j av a2s . c o m * @param resolver The entity resolver to use. May be null. * @param source The input source. * @throws MappingException The mapping file is invalid. */ private void loadMappingInternal(final Mapping mapping, final DTDResolver resolver, final InputSource source) throws MappingException { // Clear all the cached resolvers, so they can be reconstructed a // second time based on the new mappings loaded _registry.clear(); Object id = source.getSystemId(); if (id == null) { id = source.getByteStream(); } if (id != null) { // check that the mapping has already been processed if (mapping.processed(id)) { return; } // mark the mapping as being processed mapping.markAsProcessed(id); } MappingRoot root = mapping.getRoot(); _idResolver.setMapping(root); try { // Load the specificed mapping source Unmarshaller unm = new Unmarshaller(MappingRoot.class); unm.setValidation(false); unm.setEntityResolver(resolver); unm.setClassLoader(Mapping.class.getClassLoader()); unm.setIDResolver(_idResolver); unm.setUnmarshalListener(new MappingUnmarshallListener(this, mapping, resolver)); MappingRoot loaded = (MappingRoot) unm.unmarshal(source); // Load all the included mapping by reference // -- note: this is just for processing any // -- includes which may have previously failed // -- using the IncludeListener...and to // -- report any potential errors. Enumeration includes = loaded.enumerateInclude(); while (includes.hasMoreElements()) { Include include = (Include) includes.nextElement(); if (!mapping.processed(include.getHref())) { try { loadMappingInternal(mapping, resolver, include.getHref()); } catch (Exception ex) { throw new MappingException(ex); } } } // gather "class" tags Enumeration<? extends ClassMapping> classMappings = loaded.enumerateClassMapping(); while (classMappings.hasMoreElements()) { root.addClassMapping(classMappings.nextElement()); } // gather "key-generator" tags Enumeration<? extends KeyGeneratorDef> keyGeneratorDefinitions = loaded.enumerateKeyGeneratorDef(); while (keyGeneratorDefinitions.hasMoreElements()) { root.addKeyGeneratorDef(keyGeneratorDefinitions.nextElement()); } // gather "field-handler" tags Enumeration<? extends FieldHandlerDef> fieldHandlerDefinitions = loaded.enumerateFieldHandlerDef(); while (fieldHandlerDefinitions.hasMoreElements()) { root.addFieldHandlerDef(fieldHandlerDefinitions.nextElement()); } } catch (Exception ex) { throw new MappingException(ex); } }
From source file:org.cobra_grendel.html.parser.DocumentBuilderImpl.java
/** * Creates a document without parsing it so it can be used for incremental rendering. * /* ww w.j av a 2 s . c om*/ * @param is * The input source, which may be an instance of {@link org.cobra_grendel.html.parser.InputSourceImpl}. */ public Document createDocument(final InputSource is, final int transactionId) throws SAXException, IOException { String charset = is.getEncoding(); if (charset == null) { charset = "US-ASCII"; } String uri = is.getSystemId(); if (uri == null) { LOGGER.warn("parse(): InputSource has no SystemId (URI); document item URLs will not be resolvable."); } InputStream in = is.getByteStream(); WritableLineReader wis; if (in != null) { wis = new WritableLineReader(new InputStreamReader(in, charset)); } else { Reader reader = is.getCharacterStream(); if (reader != null) { wis = new WritableLineReader(reader); } else { throw new IllegalArgumentException("InputSource has neither a byte stream nor a character stream"); } } HTMLDocumentImpl document = new HTMLDocumentImpl(bcontext, rcontext, wis, uri, transactionId); return document; }
From source file:org.dhatim.csv.CSVReader.java
public void parse(InputSource csvInputSource) throws IOException, SAXException { if (contentHandler == null) { throw new IllegalStateException("'contentHandler' not set. Cannot parse CSV stream."); }/*from w w w . j a va2s.c o m*/ if (execContext == null) { throw new IllegalStateException("'execContext' not set. Cannot parse CSV stream."); } try { Reader csvStreamReader; au.com.bytecode.opencsv.CSVReader csvLineReader; String[] csvRecord; // Get a reader for the CSV source... csvStreamReader = csvInputSource.getCharacterStream(); if (csvStreamReader == null) { csvStreamReader = new InputStreamReader(csvInputSource.getByteStream(), encoding); } // Create the CSV line reader... csvLineReader = new au.com.bytecode.opencsv.CSVReader(csvStreamReader, separator, quoteChar, escapeChar, skipLines); if (validateHeader) { validateHeader(csvLineReader); } // Start the document and add the root "csv-set" element... contentHandler.startDocument(); contentHandler.startElement(XMLConstants.NULL_NS_URI, rootElementName, StringUtils.EMPTY, EMPTY_ATTRIBS); // Output each of the CVS line entries... int lineNumber = 0; int expectedCount = getExpectedColumnsCount(); while ((csvRecord = csvLineReader.readNext()) != null) { lineNumber++; // First line is line "1" if (csvRecord.length < expectedCount && strict) { logger.debug("[CORRUPT-CSV] CSV line #" + lineNumber + " invalid [" + Arrays.asList(csvRecord) + "]. The line should contain number of items at least as in CSV config file " + csvFields.length + " fields [" + csvFields + "], but contains " + csvRecord.length + " fields. Ignoring!!"); continue; } if (indent) { contentHandler.characters(INDENT_LF, 0, 1); contentHandler.characters(INDENT_1, 0, 1); } AttributesImpl attrs = new AttributesImpl(); // If we reached here it means that this line has to be in the sax stream // hence we first add the record number attribute on the csv-record element attrs.addAttribute(XMLConstants.NULL_NS_URI, RECORD_NUMBER_ATTR, RECORD_NUMBER_ATTR, "xs:int", Integer.toString(lineNumber)); // if this line is truncated, we add the truncated attribute onto the csv-record element if (csvRecord.length < expectedCount) attrs.addAttribute(XMLConstants.NULL_NS_URI, RECORD_TRUNCATED_ATTR, RECORD_TRUNCATED_ATTR, "xs:boolean", Boolean.TRUE.toString()); contentHandler.startElement(XMLConstants.NULL_NS_URI, recordElementName, StringUtils.EMPTY, attrs); int recordIt = 0; for (Field field : fields) { String fieldName = field.getName(); if (field.ignore()) { int toSkip = parseIgnoreFieldDirective(fieldName); if (toSkip == Integer.MAX_VALUE) { break; } recordIt += toSkip; continue; } if (indent) { contentHandler.characters(INDENT_LF, 0, 1); contentHandler.characters(INDENT_2, 0, 2); } // Don't insert the element if the csv record does not contain it!! if (recordIt < csvRecord.length) { String value = csvRecord[recordIt]; contentHandler.startElement(XMLConstants.NULL_NS_URI, fieldName, StringUtils.EMPTY, EMPTY_ATTRIBS); StringFunctionExecutor stringFunctionExecutor = field.getStringFunctionExecutor(); if (stringFunctionExecutor != null) { value = stringFunctionExecutor.execute(value); } contentHandler.characters(value.toCharArray(), 0, value.length()); contentHandler.endElement(XMLConstants.NULL_NS_URI, fieldName, StringUtils.EMPTY); } if (indent) { } recordIt++; } if (indent) { contentHandler.characters(INDENT_LF, 0, 1); contentHandler.characters(INDENT_1, 0, 1); } contentHandler.endElement(null, recordElementName, StringUtils.EMPTY); } if (indent) { contentHandler.characters(INDENT_LF, 0, 1); } // Close out the "csv-set" root element and end the document.. contentHandler.endElement(XMLConstants.NULL_NS_URI, rootElementName, StringUtils.EMPTY); contentHandler.endDocument(); } finally { // These properties need to be reset for every execution (e.g. when reader is pooled). contentHandler = null; execContext = null; } }
From source file:org.dhatim.edisax.BufferedSegmentReader.java
/** * Construct the stream reader.//from ww w . java 2 s.c o m * @param ediInputSource EDI Stream input source. * @param rootDelimiters Root currentDelimiters. New currentDelimiters can be pushed and popped. */ public BufferedSegmentReader(InputSource ediInputSource, Delimiters rootDelimiters) { underlyingByteStream = ediInputSource.getByteStream(); reader = ediInputSource.getCharacterStream(); if (reader == null) { readEncoding = Charset.defaultCharset(); reader = new InputStreamReader(underlyingByteStream, readEncoding); } else if (reader instanceof InputStreamReader) { readEncoding = Charset.forName(((InputStreamReader) reader).getEncoding()); } this.currentDelimiters = rootDelimiters; }
From source file:org.dhatim.fixedlength.FixedLengthReader.java
public void parse(InputSource flInputSource) throws IOException, SAXException { if (contentHandler == null) { throw new IllegalStateException("'contentHandler' not set. Cannot parse Fixed Length stream."); }//from ww w . ja v a 2 s. c o m if (execContext == null) { throw new IllegalStateException("'execContext' not set. Cannot parse Fixed Length stream."); } try { Reader flStreamReader; BufferedReader flLineReader; String flRecord; int lineNumber = 0; // Get a reader for the Fixed Length source... flStreamReader = flInputSource.getCharacterStream(); if (flStreamReader == null) { flStreamReader = new InputStreamReader(flInputSource.getByteStream(), encoding); } // Create the Fixed Length line reader... flLineReader = new BufferedReader(flStreamReader); // Start the document and add the root element... contentHandler.startDocument(); contentHandler.startElement(XMLConstants.NULL_NS_URI, rootElementName, StringUtils.EMPTY, EMPTY_ATTRIBS); // Output each of the Fixed Length line entries... while ((flRecord = flLineReader.readLine()) != null) { lineNumber++; // First line is line "1" if (lineNumber <= this.skipLines) { continue; } boolean invalidLength = flRecord.length() < totalFieldLenght; if (invalidLength && strict) { if (logger.isWarnEnabled()) { logger.debug("[WARNING-FIXEDLENGTH] Fixed Length line #" + lineNumber + " is invalid. The line doesn't contain enough characters to fill all the fields. This line is skipped."); } continue; } char[] recordChars = flRecord.toCharArray(); if (indent) { contentHandler.characters(INDENT_LF, 0, 1); contentHandler.characters(INDENT_1, 0, 1); } AttributesImpl attrs = EMPTY_ATTRIBS; // Add a lineNumber ID if (this.lineNumber || invalidLength) { attrs = new AttributesImpl(); if (this.lineNumber) { attrs.addAttribute(XMLConstants.NULL_NS_URI, lineNumberAttributeName, lineNumberAttributeName, "xs:int", Integer.toString(lineNumber)); } if (invalidLength) { attrs.addAttribute(XMLConstants.NULL_NS_URI, truncatedAttributeName, truncatedAttributeName, "xs:boolean", Boolean.TRUE.toString()); } } contentHandler.startElement(XMLConstants.NULL_NS_URI, recordElementName, StringUtils.EMPTY, attrs); // Loops through fields int fieldLengthTotal = 0; for (int i = 0; i < flFields.length; i++) { // Field name local to the loop String fieldName = fields[i].getName(); // Field length local to the loop int fieldLength = fields[i].getLength(); StringFunctionExecutor stringFunctionExecutor = fields[i].getStringFunctionExecutor(); if (!fields[i].ignore()) { if (indent) { contentHandler.characters(INDENT_LF, 0, 1); contentHandler.characters(INDENT_2, 0, 2); } // Check that there are enough characters in the string boolean truncated = fieldLengthTotal + fieldLength > flRecord.length(); AttributesImpl recordAttrs = EMPTY_ATTRIBS; //If truncated then set the truncated attribute if (truncated) { recordAttrs = new AttributesImpl(); recordAttrs.addAttribute(XMLConstants.NULL_NS_URI, truncatedAttributeName, truncatedAttributeName, "xs:boolean", Boolean.TRUE.toString()); } contentHandler.startElement(XMLConstants.NULL_NS_URI, fieldName, StringUtils.EMPTY, recordAttrs); // If not truncated then set the element data if (!truncated) { if (stringFunctionExecutor == null) { contentHandler.characters(recordChars, fieldLengthTotal, fieldLength); } else { String value = flRecord.substring(fieldLengthTotal, fieldLengthTotal + fieldLength); value = stringFunctionExecutor.execute(value); contentHandler.characters(value.toCharArray(), 0, value.length()); } } contentHandler.endElement(XMLConstants.NULL_NS_URI, fieldName, StringUtils.EMPTY); } fieldLengthTotal += fieldLength; } if (indent) { contentHandler.characters(INDENT_LF, 0, 1); contentHandler.characters(INDENT_1, 0, 1); } contentHandler.endElement(null, recordElementName, StringUtils.EMPTY); } if (indent) { contentHandler.characters(INDENT_LF, 0, 1); } // Close out the "fixedlength-set" root element and end the document.. contentHandler.endElement(XMLConstants.NULL_NS_URI, rootElementName, StringUtils.EMPTY); contentHandler.endDocument(); } finally { // These properties need to be reset for every execution (e.g. when reader is pooled). contentHandler = null; execContext = null; } }
From source file:org.dhatim.json.JSONReader.java
public void parse(InputSource csvInputSource) throws IOException, SAXException { if (contentHandler == null) { throw new IllegalStateException("'contentHandler' not set. Cannot parse JSON stream."); }/*www. j a va2 s . c om*/ if (executionContext == null) { throw new IllegalStateException( "Smooks container 'executionContext' not set. Cannot parse JSON stream."); } try { // Get a reader for the JSON source... Reader jsonStreamReader = csvInputSource.getCharacterStream(); if (jsonStreamReader == null) { jsonStreamReader = new InputStreamReader(csvInputSource.getByteStream(), encoding); } // Create the JSON parser... JsonParser jp = null; try { if (logger.isTraceEnabled()) { logger.trace("Creating JSON parser"); } jp = jsonFactory.createJsonParser(jsonStreamReader); // Start the document and add the root "csv-set" element... contentHandler.startDocument(); startElement(rootName, 0); if (logger.isTraceEnabled()) { logger.trace("Starting JSON parsing"); } boolean first = true; Stack<String> elementStack = new Stack<String>(); Stack<Type> typeStack = new Stack<Type>(); JsonToken t; while ((t = jp.nextToken()) != null) { if (logger.isTraceEnabled()) { logger.trace("Token: " + t.name()); } switch (t) { case START_OBJECT: case START_ARRAY: if (!first) { if (!typeStack.empty() && typeStack.peek() == Type.ARRAY) { startElement(arrayElementName, typeStack.size()); } } typeStack.push(t == JsonToken.START_ARRAY ? Type.ARRAY : Type.OBJECT); break; case END_OBJECT: case END_ARRAY: typeStack.pop(); boolean typeStackPeekIsArray = !typeStack.empty() && typeStack.peek() == Type.ARRAY; if (!elementStack.empty() && !typeStackPeekIsArray) { endElement(elementStack.pop(), typeStack.size()); } if (typeStackPeekIsArray) { endElement(arrayElementName, typeStack.size()); } break; case FIELD_NAME: String text = jp.getText(); if (logger.isTraceEnabled()) { logger.trace("Field name: " + text); } String name = getElementName(text); startElement(name, typeStack.size()); elementStack.add(name); break; default: String value; if (t == JsonToken.VALUE_NULL) { value = nullValueReplacement; } else { value = jp.getText(); } if (typeStack.peek() == Type.ARRAY) { startElement(arrayElementName, typeStack.size()); } contentHandler.characters(value.toCharArray(), 0, value.length()); if (typeStack.peek() == Type.ARRAY) { endElement(arrayElementName); } else { endElement(elementStack.pop()); } break; } first = false; } endElement(rootName, 0); contentHandler.endDocument(); } finally { try { jp.close(); } catch (Exception e) { } } } finally { // These properties need to be reset for every execution (e.g. when reader is pooled). contentHandler = null; executionContext = null; } }
From source file:org.dita.dost.util.XMLUtils.java
/** Close input source. */ public static void close(final InputSource input) throws IOException { if (input != null) { final InputStream i = input.getByteStream(); if (i != null) { i.close();// w ww. ja v a2s . co m } else { final Reader w = input.getCharacterStream(); if (w != null) { w.close(); } } } }