Example usage for org.xml.sax InputSource getCharacterStream

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

Introduction

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

Prototype

public Reader getCharacterStream() 

Source Link

Document

Get the character stream for this input source.

Usage

From source file:org.apache.xmlgraphics.image.loader.util.ImageUtil.java

/**
 * Indicates whether the Source object has a Reader instance.
 * @param src the Source object//from   w ww. j av  a 2s.c  o  m
 * @return true if an Reader is available
 */
public static boolean hasReader(Source src) {
    if (src instanceof StreamSource) {
        Reader reader = ((StreamSource) src).getReader();
        return (reader != null);
    } else if (src instanceof SAXSource) {
        InputSource is = ((SAXSource) src).getInputSource();
        if (is != null) {
            return (is.getCharacterStream() != null);
        }
    }
    return false;
}

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 w  w . j  a  v a2  s . com
 * @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.//from  w  ww .j  av a2s.  c  o  m
 * @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.cobra_grendel.html.parser.DocumentBuilderImpl.java

/**
 * Creates a document without parsing it so it can be used for incremental rendering.
 * //from  w  ww.  j  av  a2  s.  c o m
 * @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  www .j a  v  a2s .c  om*/
    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  w  w  w.j a  v  a 2s .  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.");
    }//w ww .ja va2  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.");
    }// w  w w  .  j  av a 2  s .  co  m
    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.dhatim.yaml.YamlReader.java

public void parse(InputSource yamlInputSource) throws IOException, SAXException {
    if (contentHandler == null) {
        throw new IllegalStateException("'contentHandler' not set.  Cannot parse YAML stream.");
    }//from  ww w . j  a v a 2  s .com
    if (executionContext == null) {
        throw new IllegalStateException(
                "Smooks container 'executionContext' not set.  Cannot parse YAML stream.");
    }

    try {
        // Get a reader for the YAML source...
        Reader yamlStreamReader = yamlInputSource.getCharacterStream();
        if (yamlStreamReader == null) {
            throw new SmooksException(
                    "The InputSource doesn't provide a Reader character stream. Make sure that you supply a reader to the Smooks.filterSource method.");
        }
        YamlToSaxHandler yamlToSaxHandler = new YamlToSaxHandler(contentHandler, anchorAttributeName,
                aliasAttributeName, indent);

        EventHandler eventHandler;
        if (aliasStrategy == AliasStrategy.REFER) {
            eventHandler = new AliasReferencingEventHandler(yamlToSaxHandler);
        } else {
            eventHandler = new AliasResolvingEventHandler(yamlEventStreamParser, yamlToSaxHandler,
                    aliasStrategy == AliasStrategy.REFER_RESOLVE);
        }

        if (logger.isTraceEnabled()) {
            logger.trace("Starting YAML parsing");
        }

        Iterable<Event> yamlEventStream = yaml.parse(yamlStreamReader);

        // Start the document and add the root  element...
        contentHandler.startDocument();

        yamlToSaxHandler.startElementStructure(rootName, null, false);

        yamlEventStreamParser.handle(eventHandler, yamlEventStream);

        yamlToSaxHandler.endElementStructure(rootName);

        contentHandler.endDocument();

    } finally {
        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  .j  a v  a 2 s.  c  om
        } else {
            final Reader w = input.getCharacterStream();
            if (w != null) {
                w.close();
            }
        }
    }
}