Example usage for org.xml.sax InputSource getByteStream

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

Introduction

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

Prototype

public InputStream getByteStream() 

Source Link

Document

Get the byte stream for this input source.

Usage

From source file:sapience.injectors.impl.AbstractInjector.java

public byte[] annotate(Serializable docID, byte[] in) throws IOException {

    // copy the byte array, will be returned if exception is thrown
    byte[] copy = in.clone();

    // the stream the result is written to. With original length as initial
    // length//from ww  w  . j a  va2  s . c om
    ByteArrayOutputStream baos = new ByteArrayOutputStream(in.length);

    /*
     * procedure
     * 
     * We have - unique document id (UDI) - access to a lookup component to
     * get references - a list of definitions telling us where
     * modelreferences can exist in the current document type
     * 
     * 1. we call the check method with the UDI, which returns a list of
     * references for the UDI (LookUpList) 2. we delegate it to the sax
     * handler of the extending packages a. for each line, we first check if
     * it is valid location (comparing the first bytes) a.+: check if
     * current line (constructed Xpath) is in LookUpList a.+.+ check if
     * current line contains a model reference a.+.+.+ call put of lookup
     * component a.+.+.- inject annotation a.+.- continue a.-: continue
     * 
     * 3. return the bytearray with the injected annotations
     */

    // if doc type is not configured, we throw an exception and return the
    // input stream unchanged
    try {

        InputSource is = new InputSource(new String(copy));

        // we let the extending classes handle the actual content
        this.annotate(docID, is.getByteStream(), baos);

    } catch (Exception e) {
        return copy;
    } finally {
        baos.flush();
    }

    byte[] res = baos.toByteArray();
    baos.close();
    return res;
}

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

@Override
public StreamSource resolve(String href, String base) throws TransformerException {
    try {/*from  ww  w. ja  va  2 s  .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:de.ii.xtraplatform.ogc.csw.parser.CSWCapabilitiesParser.java

public void parse(InputSource is) {

    SMInputCursor root = null;/*from w w  w.  j  a v  a2 s . com*/

    try {
        root = staxFactory.rootElementCursor(is.getByteStream()).advance();

        if (checkForExceptionReport(root)) {
            return;
        }

        parseNamespaces(root);

        //analyzer.analyzeVersion(root.getAttrValue(WFS.getWord(WFS.VOCABULARY.VERSION)));

        SMInputCursor recordsResponseChild = root.childElementCursor().advance();

        while (recordsResponseChild.readerAccessible()) {

            switch (CSW.findKey(recordsResponseChild.getLocalName())) {
            case SEARCH_RESULTS:
                parseSearchResults(recordsResponseChild);
                break;
            }

            recordsResponseChild = recordsResponseChild.advance();
        }
    } catch (XMLStreamException ex) {
        // TODO: move to analyzer for XtraProxy
        //LOGGER.error(FrameworkMessages.ERROR_PARSING_WFS_CAPABILITIES);
        //throw new ParseError(FrameworkMessages.ERROR_PARSING_WFS_CAPABILITIES);

        analyzer.analyzeFailed(ex);
    } finally {
        if (root != null) {
            try {
                root.getStreamReader().closeCompletely();
            } catch (XMLStreamException ex) {
                // ignore
            }
        }
    }
}

From source file:com.googlecode.android_scripting.ZipExtractorTask.java

private long unzip() throws Exception {
    long extractedSize = 0l;
    Enumeration<? extends ZipEntry> entries;
    if (mInput.isFile() && mInput.getName().contains(".gz")) {
        InputStream stream = new FileInputStream(mInput);
        GZIPInputStream gzipStream = new GZIPInputStream(stream);
        InputSource is = new InputSource(gzipStream);
        InputStream input = new BufferedInputStream(is.getByteStream());
        File destination = new File(mOutput, "php");
        ByteArrayBuffer baf = new ByteArrayBuffer(255000);
        int current = 0;
        while ((current = input.read()) != -1) {
            baf.append((byte) current);
        }/*from   w  w  w .  ja v a  2 s . c  om*/

        FileOutputStream output = new FileOutputStream(destination);
        output.write(baf.toByteArray());
        output.close();
        Log.d("written!");
        return baf.toByteArray().length;
    }
    ZipFile zip = new ZipFile(mInput);
    long uncompressedSize = getOriginalSize(zip);

    publishProgress(0, (int) uncompressedSize);

    entries = zip.entries();

    try {
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            if (entry.isDirectory()) {
                // Not all zip files actually include separate directory entries.
                // We'll just ignore them
                // and create them as necessary for each actual entry.
                continue;
            }
            File destination = new File(mOutput, entry.getName());
            if (!destination.getParentFile().exists()) {
                destination.getParentFile().mkdirs();
            }
            if (destination.exists() && mContext != null && !mReplaceAll) {
                Replace answer = showDialog(entry.getName());
                switch (answer) {
                case YES:
                    break;
                case NO:
                    continue;
                case YESTOALL:
                    mReplaceAll = true;
                    break;
                default:
                    return extractedSize;
                }
            }
            ProgressReportingOutputStream outStream = new ProgressReportingOutputStream(destination);
            extractedSize += IoUtils.copy(zip.getInputStream(entry), outStream);
            outStream.close();
        }
    } finally {
        try {
            zip.close();
        } catch (Exception e) {
            // swallow this exception, we are only interested in the original one
        }
    }
    Log.v("Extraction is complete.");
    return extractedSize;
}

From source file:net.sf.eclipsecs.core.config.CheckConfigurationTester.java

/**
 * Tests a configuration if there are unresolved properties.
 * /*  w w  w.ja  va2 s  .co m*/
 * @return the list of unresolved properties as ResolvableProperty values.
 * @throws CheckstylePluginException
 *             most likely the configuration file could not be found
 */
public List<ResolvableProperty> getUnresolvedProperties() throws CheckstylePluginException {

    CheckstyleConfigurationFile configFile = mCheckConfiguration.getCheckstyleConfiguration();

    PropertyResolver resolver = configFile.getPropertyResolver();

    // set the project context if the property resolver needs the
    // context
    if (mContextProject != null && resolver instanceof IContextAware) {
        ((IContextAware) resolver).setProjectContext(mContextProject);
    }

    MissingPropertyCollector collector = new MissingPropertyCollector();

    if (resolver instanceof MultiPropertyResolver) {
        ((MultiPropertyResolver) resolver).addPropertyResolver(collector);
    } else {
        MultiPropertyResolver multiResolver = new MultiPropertyResolver();
        multiResolver.addPropertyResolver(resolver);
        multiResolver.addPropertyResolver(collector);
        resolver = multiResolver;
    }

    InputSource in = null;
    try {
        in = configFile.getCheckConfigFileInputSource();
        ConfigurationLoader.loadConfiguration(in, resolver, false);
    } catch (CheckstyleException e) {
        CheckstylePluginException.rethrow(e);
    } finally {
        IOUtils.closeQuietly(in.getByteStream());
    }

    return collector.getUnresolvedProperties();
}

From source file:com.netspective.commons.xml.ParseContext.java

public void doExternalTransformations() throws TransformerConfigurationException, TransformerException,
        ParserConfigurationException, SAXException, IOException {
    // re-create the input source because the original stream is already closed
    InputSource inputSource = recreateInputSource();

    Source activeSource = inputSource.getByteStream() != null ? new StreamSource(inputSource.getByteStream())
            : new StreamSource(inputSource.getCharacterStream());
    activeSource.setSystemId(inputSource.getSystemId());

    Writer activeResultBuffer = new StringWriter();
    Result activeResult = new StreamResult(activeResultBuffer);
    activeResult.setSystemId(activeResultBuffer.getClass().getName());

    TransformerFactory factory = TransformerFactory.newInstance();
    int lastTransformer = transformSources.length - 1;
    for (int i = 0; i <= lastTransformer; i++) {
        Transformer transformer = factory.newTransformer(transformSources[i]);
        transformer.transform(activeSource, activeResult);

        if (i < lastTransformer) {
            activeSource = new StreamSource(new StringReader(activeResultBuffer.toString()));
            activeResultBuffer = new StringWriter();
            activeResult = new StreamResult(activeResultBuffer);
        }/*w  w w . ja va2  s  .c om*/
    }

    // now that all the transformations have been performed, we want to reset our input source to the final
    // transformation
    init(createInputSource(activeResultBuffer.toString()));
}

From source file:net.sf.eclipsecs.core.jobs.TransformCheckstyleRulesJob.java

/**
 * {@inheritDoc}//  w  ww  .jav  a2  s  .  c om
 */
@Override
public IStatus runInWorkspace(final IProgressMonitor arg0) throws CoreException {

    try {
        final IProjectConfiguration conf = ProjectConfigurationFactory.getConfiguration(mProject);

        final List<Configuration> rules = new ArrayList<Configuration>();

        // collect rules from all configured filesets
        for (FileSet fs : conf.getFileSets()) {

            ICheckConfiguration checkConfig = fs.getCheckConfig();

            CheckstyleConfigurationFile configFile = checkConfig.getCheckstyleConfiguration();

            PropertyResolver resolver = configFile.getPropertyResolver();

            // set the project context if the property resolver needs the
            // context
            if (resolver instanceof IContextAware) {
                ((IContextAware) resolver).setProjectContext(mProject);
            }

            InputSource in = null;
            try {
                in = configFile.getCheckConfigFileInputSource();

                Configuration configuration = ConfigurationLoader.loadConfiguration(in, resolver, true);

                // flatten the nested configuration tree into a list
                recurseConfiguration(configuration, rules);
            } finally {
                IOUtils.closeQuietly(in.getByteStream());
            }
        }

        if (rules.isEmpty()) {
            return Status.CANCEL_STATUS;
        }

        final CheckstyleTransformer transformer = new CheckstyleTransformer(mProject, rules);
        transformer.transformRules();
    } catch (CheckstyleException e) {
        Status status = new Status(IStatus.ERROR, CheckstylePlugin.PLUGIN_ID, IStatus.ERROR, e.getMessage(), e);
        throw new CoreException(status);
    } catch (CheckstylePluginException e) {
        Status status = new Status(IStatus.ERROR, CheckstylePlugin.PLUGIN_ID, IStatus.ERROR, e.getMessage(), e);
        throw new CoreException(status);
    }

    return Status.OK_STATUS;
}

From source file:net.sf.eclipsecs.core.config.CheckConfigurationWorkingCopy.java

/**
 * Reads the Checkstyle configuration file and builds the list of configured modules. Elements are of type
 * <code>net.sf.eclipsecs.core.config.Module</code>.
 *
 * @return the list of configured modules in this Checkstyle configuration
 * @throws CheckstylePluginException/*from w  w w.ja v  a 2 s. com*/
 *             error when reading the Checkstyle configuration file
 */
public List<Module> getModules() throws CheckstylePluginException {
    List<Module> result = null;

    InputSource in = null;

    try {
        in = getCheckstyleConfiguration().getCheckConfigFileInputSource();
        result = ConfigurationReader.read(in);
    } finally {
        IOUtils.closeQuietly(in.getByteStream());
    }

    return result;
}

From source file:main.export.sql.DataImporter.java

/**
 * /*from www  .j  a  v a 2  s .c o m*/
 * @param configFile
 */
private void loadDataConfig(InputSource configFile) {

    try {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

        DocumentBuilder builder = dbf.newDocumentBuilder();
        Document document;
        try {
            document = builder.parse(configFile);
        } finally {
            // some XML parsers are broken and don't close the byte stream
            // (but they should according to spec)
            IOUtils.closeQuietly(configFile.getByteStream());
        }

        config = new DataConfig();
        NodeList elems = document.getElementsByTagName("dataConfig");
        if (elems == null || elems.getLength() == 0) {
            log.error("the root node '<dataConfig>' is missing");
            throw new IOException();
        }
        config.readFromXml((Element) elems.item(0));
        log.info("Data Configuration loaded successfully");
    } catch (Exception e) {
        log.error(e.getStackTrace());
    }

}

From source file:CSVXMLReader.java

/**
 * Parse a CSV file. SAX events are delivered to the ContentHandler
 * that was registered via <code>setContentHandler</code>.
 *
 * @param input the comma separated values file to parse.
 *///from  w  ww  .  j a  va 2  s .  c  o  m
public void parse(InputSource input) throws IOException, SAXException {
    // if no handler is registered to receive events, don't bother
    // to parse the CSV file
    ContentHandler ch = getContentHandler();
    if (ch == null) {
        return;
    }

    // convert the InputSource into a BufferedReader
    BufferedReader br = null;
    if (input.getCharacterStream() != null) {
        br = new BufferedReader(input.getCharacterStream());
    } else if (input.getByteStream() != null) {
        br = new BufferedReader(new InputStreamReader(input.getByteStream()));
    } else if (input.getSystemId() != null) {
        java.net.URL url = new URL(input.getSystemId());
        br = new BufferedReader(new InputStreamReader(url.openStream()));
    } else {
        throw new SAXException("Invalid InputSource object");
    }

    ch.startDocument();

    // emit <csvFile>
    ch.startElement("", "", "csvFile", EMPTY_ATTR);

    // read each line of the file until EOF is reached
    String curLine = null;
    while ((curLine = br.readLine()) != null) {
        curLine = curLine.trim();
        if (curLine.length() > 0) {
            // create the <line> element
            ch.startElement("", "", "line", EMPTY_ATTR);
            // output data from this line
            parseLine(curLine, ch);
            // close the </line> element
            ch.endElement("", "", "line");
        }
    }

    // emit </csvFile>
    ch.endElement("", "", "csvFile");
    ch.endDocument();
}