Example usage for org.xml.sax.helpers XMLReaderFactory createXMLReader

List of usage examples for org.xml.sax.helpers XMLReaderFactory createXMLReader

Introduction

In this page you can find the example usage for org.xml.sax.helpers XMLReaderFactory createXMLReader.

Prototype

public static XMLReader createXMLReader() throws SAXException 

Source Link

Document

Obtains a new instance of a org.xml.sax.XMLReader .

Usage

From source file:org.eclipse.swordfish.plugins.compression.CompressorImpl.java

public Source asUncompressedSource(Source src) {
    try {// ww  w .j  av  a 2s  .c o  m
        String encoded = null;
        if (src instanceof DOMSource) {
            Node root = ((DOMSource) src).getNode();
            if (root instanceof Document) {
                root = ((Document) root).getDocumentElement();
            }
            Element rootElement = (Element) root;
            String qName = rootElement.getNodeName();
            String localName = qName.substring(qName.indexOf(":") + 1, qName.length());
            if (localName.equalsIgnoreCase(CompressionConstants.COMPRESSED_ELEMENT)) {
                Node node = rootElement.getFirstChild();
                if (node != null && node.getNodeType() == Node.TEXT_NODE) {
                    encoded = node.getNodeValue();
                }
            }
            if (null != encoded && encoded.length() > 0) {
                byte[] decoded = new Base64().decode(encoded.getBytes());
                InputStream is = new GZIPInputStream(new ByteArrayInputStream(decoded));
                DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
                Document doc = builder.parse(is);
                return new DOMSource(doc);
            } else {
                return src;
            }
        } else if (src instanceof StreamSource) {
            XMLReader xmlReader = XMLReaderFactory.createXMLReader();
            CompressedContentHandler ch = new CompressedContentHandler();
            xmlReader.setContentHandler(ch);
            xmlReader.parse(new InputSource(((StreamSource) src).getInputStream()));
            encoded = ch.getContent();
            if (null != encoded && encoded.length() > 0) {
                byte[] decoded = new Base64().decode(encoded.getBytes());
                InputStream is = new GZIPInputStream(new ByteArrayInputStream(decoded));
                return new StreamSource(is);
            } else {
                throw new SwordfishException("Payload is empty, cannot uncompress.");
            }
        } else {
            return asUncompressedSource(new SourceTransformer().toDOMSource(src));
        }
    } catch (Exception e) {
        LOG.error("Couldn't decompress source", e);
        throw new SwordfishException("Couldn't decompress source", e);
    }
}

From source file:org.entcore.feeder.aaf.BaseImportProcessing.java

protected void parse(final Handler<Message<JsonObject>> handler, final ImportProcessing importProcessing) {
    final String[] files = vertx.fileSystem().readDirSync(path, getFileRegex());
    final VoidHandler[] handlers = new VoidHandler[files.length + 1];
    handlers[handlers.length - 1] = new VoidHandler() {
        @Override// w ww  .java  2  s . c  o  m
        protected void handle() {
            next(handler, importProcessing);
        }
    };
    Arrays.sort(files);
    for (int i = files.length - 1; i >= 0; i--) {
        final int j = i;
        handlers[i] = new VoidHandler() {
            @Override
            protected void handle() {
                try {
                    String file = files[j];
                    log.info("Parsing file : " + file);
                    byte[] encoded = Files.readAllBytes(Paths.get(file));
                    String content = UNESCAPE_AAF.translate(new String(encoded, "UTF-8"));
                    InputSource in = new InputSource(new StringReader(content));
                    AAFHandler sh = new AAFHandler(BaseImportProcessing.this);
                    XMLReader xr = XMLReaderFactory.createXMLReader();
                    xr.setContentHandler(sh);
                    xr.setEntityResolver(new EntityResolver2() {
                        @Override
                        public InputSource getExternalSubset(String name, String baseURI)
                                throws SAXException, IOException {
                            return null;
                        }

                        @Override
                        public InputSource resolveEntity(String name, String publicId, String baseURI,
                                String systemId) throws SAXException, IOException {
                            return resolveEntity(publicId, systemId);
                        }

                        @Override
                        public InputSource resolveEntity(String publicId, String systemId)
                                throws SAXException, IOException {
                            if (systemId.equals("ficAlimMENESR.dtd")) {
                                Reader reader = new FileReader(path + File.separator + "ficAlimMENESR.dtd");
                                return new InputSource(reader);
                            } else {
                                return null;
                            }
                        }
                    });
                    xr.parse(in);
                    importer.flush(new Handler<Message<JsonObject>>() {
                        @Override
                        public void handle(Message<JsonObject> message) {
                            if ("ok".equals(message.body().getString("status"))) {
                                handlers[j + 1].handle(null);
                            } else {
                                error(message, handler);
                            }
                        }
                    });
                } catch (Exception e) {
                    error(e, handler);
                }
            }
        };
    }
    handlers[0].handle(null);
}

From source file:org.h2gis.drivers.osm.OSMParser.java

/**
 * Read the OSM file and create its corresponding tables.
 *
 * @param inputFile// w w  w .j av a  2s .co  m
 * @param tableName
 * @param connection
 * @param progress
 * @return
 * @throws SQLException
 */
public boolean read(Connection connection, String tableName, File inputFile, ProgressVisitor progress)
        throws SQLException {
    this.progress = progress.subProcess(100);
    // Initialisation
    final boolean isH2 = JDBCUtilities.isH2DataBase(connection.getMetaData());
    boolean success = false;
    TableLocation requestedTable = TableLocation.parse(tableName, isH2);
    String osmTableName = requestedTable.getTable();
    checkOSMTables(connection, isH2, requestedTable, osmTableName);
    createOSMDatabaseModel(connection, isH2, requestedTable, osmTableName);

    FileInputStream fs = null;
    try {
        fs = new FileInputStream(inputFile);
        this.fc = fs.getChannel();
        this.fileSize = fc.size();
        // Given the file size and an average node file size.
        // Skip how many nodes in order to update progression at a step of 1%
        readFileSizeEachNode = Math.max(1, (this.fileSize / AVERAGE_NODE_SIZE) / 100);
        nodeCountProgress = 0;
        XMLReader parser = XMLReaderFactory.createXMLReader();
        parser.setErrorHandler(this);
        parser.setContentHandler(this);
        if (inputFile.getName().endsWith(".osm")) {
            parser.parse(new InputSource(fs));
        } else if (inputFile.getName().endsWith(".osm.gz")) {
            parser.parse(new InputSource(new GZIPInputStream(fs)));
        } else if (inputFile.getName().endsWith(".osm.bz2")) {
            parser.parse(new InputSource(new BZip2CompressorInputStream(fs)));
        }
        success = true;
    } catch (SAXException ex) {
        throw new SQLException(ex);
    } catch (IOException ex) {
        throw new SQLException("Cannot parse the file " + inputFile.getAbsolutePath(), ex);
    } finally {
        try {
            if (fs != null) {
                fs.close();
            }
        } catch (IOException ex) {
            throw new SQLException("Cannot close the file " + inputFile.getAbsolutePath(), ex);
        }
        // When the reading ends, close() method has to be called
        if (nodePreparedStmt != null) {
            nodePreparedStmt.close();
        }
        if (nodeTagPreparedStmt != null) {
            nodeTagPreparedStmt.close();
        }
        if (wayPreparedStmt != null) {
            wayPreparedStmt.close();
        }
        if (wayTagPreparedStmt != null) {
            wayTagPreparedStmt.close();
        }
        if (wayNodePreparedStmt != null) {
            wayNodePreparedStmt.close();
        }
        if (relationPreparedStmt != null) {
            relationPreparedStmt.close();
        }
        if (relationTagPreparedStmt != null) {
            relationTagPreparedStmt.close();
        }
        if (nodeMemberPreparedStmt != null) {
            nodeMemberPreparedStmt.close();
        }
        if (wayMemberPreparedStmt != null) {
            wayMemberPreparedStmt.close();
        }
        if (relationMemberPreparedStmt != null) {
            relationMemberPreparedStmt.close();
        }
        if (tagPreparedStmt != null) {
            tagPreparedStmt.close();
        }
    }

    return success;
}

From source file:org.h2gis.functions.io.osm.OSMParser.java

/**
 * Read the OSM file and create its corresponding tables.
 *
 * @param inputFile/*www . j a  v  a 2s  . co  m*/
 * @param tableName
 * @param connection
 * @param progress
 * @return
 * @throws SQLException
 */
public boolean read(Connection connection, String tableName, File inputFile, ProgressVisitor progress)
        throws SQLException {
    this.progress = progress.subProcess(100);
    // Initialisation
    final boolean isH2 = JDBCUtilities.isH2DataBase(connection.getMetaData());
    boolean success = false;
    TableLocation requestedTable = TableLocation.parse(tableName, isH2);
    String osmTableName = requestedTable.getTable();
    checkOSMTables(connection, isH2, requestedTable, osmTableName);
    createOSMDatabaseModel(connection, isH2, requestedTable, osmTableName);

    FileInputStream fs = null;
    try {
        fs = new FileInputStream(inputFile);
        this.fc = fs.getChannel();
        this.fileSize = fc.size();
        // Given the file size and an average node file size.
        // Skip how many nodes in order to update progression at a step of 1%
        readFileSizeEachNode = Math.max(1, (this.fileSize / AVERAGE_NODE_SIZE) / 100);
        nodeCountProgress = 0;
        XMLReader parser = XMLReaderFactory.createXMLReader();
        parser.setErrorHandler(this);
        parser.setContentHandler(this);
        if (inputFile.getName().endsWith(".osm")) {
            parser.parse(new InputSource(fs));
        } else if (inputFile.getName().endsWith(".osm.gz")) {
            parser.parse(new InputSource(new GZIPInputStream(fs)));
        } else if (inputFile.getName().endsWith(".osm.bz2")) {
            parser.parse(new InputSource(new BZip2CompressorInputStream(fs)));
        } else {
            throw new SQLException("Supported formats are .osm, .osm.gz, .osm.bz2");
        }
        success = true;
    } catch (SAXException ex) {
        throw new SQLException(ex);
    } catch (IOException ex) {
        throw new SQLException("Cannot parse the file " + inputFile.getAbsolutePath(), ex);
    } finally {
        try {
            if (fs != null) {
                fs.close();
            }
        } catch (IOException ex) {
            throw new SQLException("Cannot close the file " + inputFile.getAbsolutePath(), ex);
        }
        // When the reading ends, close() method has to be called
        if (nodePreparedStmt != null) {
            nodePreparedStmt.close();
        }
        if (nodeTagPreparedStmt != null) {
            nodeTagPreparedStmt.close();
        }
        if (wayPreparedStmt != null) {
            wayPreparedStmt.close();
        }
        if (wayTagPreparedStmt != null) {
            wayTagPreparedStmt.close();
        }
        if (wayNodePreparedStmt != null) {
            wayNodePreparedStmt.close();
        }
        if (relationPreparedStmt != null) {
            relationPreparedStmt.close();
        }
        if (relationTagPreparedStmt != null) {
            relationTagPreparedStmt.close();
        }
        if (nodeMemberPreparedStmt != null) {
            nodeMemberPreparedStmt.close();
        }
        if (wayMemberPreparedStmt != null) {
            wayMemberPreparedStmt.close();
        }
        if (relationMemberPreparedStmt != null) {
            relationMemberPreparedStmt.close();
        }
        if (tagPreparedStmt != null) {
            tagPreparedStmt.close();
        }
    }

    return success;
}

From source file:org.intermine.modelviewer.jaxb.ConfigParser.java

/**
 * Unmarshalls an XML document using the very forgiving event driven parser provided
 * by SAX. No issues with namespaces and so forth here.
 *  //from  w  w w.  j  a  v  a  2 s.c  om
 * @param context The type of objects expected from the XML file.
 * @param file The file to load.
 * 
 * @return The Object created as a result of reading the file.
 * Its type will depend on <code>context</code>.
 * 
 * @throws SAXException if there is a problem parsing with SAX.
 * @throws ParserConfigurationException if there is a configuration problem with
 * the SAX system.
 * @throws IOException if there is a low level I/O problem.
 * 
 * @see CoreHandler
 * @see GenomicHandler
 * @see ProjectHandler
 * @see GenomicCoreHandler
 */
private Object saxParse(Context context, File file)
        throws SAXException, ParserConfigurationException, IOException {
    //Schema schema = schemas.get(context);
    //schema.newValidator().validate(new StreamSource(file));

    BackupContentHandler handler;
    switch (context) {
    case CORE:
        handler = new CoreHandler();
        break;

    case GENOMIC:
        handler = new GenomicHandler();
        break;

    case PROJECT:
        handler = new ProjectHandler();
        break;

    default:
        throw new UnsupportedOperationException("Cannot load things of type " + context);
    }

    XMLReader reader = XMLReaderFactory.createXMLReader();
    reader.setContentHandler(handler);
    reader.parse(new InputSource(new FileReader(file)));
    return handler.getResult();
}

From source file:org.itracker.web.util.ImportExportUtilities.java

/**
 * Takes an XML file matching the ITracker import/export DTD and returns an array
 * of AbstractBean objects.  The array will contain all of the projects, components
 * versions, users, custom fields, and issues contained in the XML.
 *
 * @param xmlReader an xml reader to import
 * @throws ImportExportException thrown if the xml can not be parsed into the appropriate objects
 *///from   w  w  w . j a va 2s  .  c  o  m
public static AbstractEntity[] importIssues(Reader xmlReader) throws ImportExportException {
    AbstractEntity[] abstractBeans;

    try {
        logger.debug("Starting XML data import.");

        XMLReader reader = XMLReaderFactory.createXMLReader();
        ImportHandler handler = new ImportHandler();
        reader.setContentHandler(handler);
        reader.setErrorHandler(handler);
        reader.parse(new InputSource(xmlReader));
        abstractBeans = handler.getModels();

        logger.debug("Imported a total of " + abstractBeans.length + " beans.");
    } catch (Exception e) {
        logger.error("Exception.", e);
        throw new ImportExportException(e.getMessage());
    }

    return abstractBeans;
}

From source file:org.jets3t.service.utils.ServiceUtils.java

/**
 * Find a SAX XMLReader by hook or by crook, with work-arounds for
 * non-standard platforms.//from  www . j  av a 2 s .  c  o m
 *
 * @return an initialized XML SAX reader
 */
public static XMLReader loadXMLReader() throws ServiceException {
    // Try loading the default SAX reader
    try {
        return XMLReaderFactory.createXMLReader();
    } catch (SAXException e) {
        // Ignore failure
    }

    // No dice using the standard approach, try loading alternatives...
    String[] altXmlReaderClasspaths = new String[] { "org.apache.crimson.parser.XMLReaderImpl", // JDK 1.4
            "org.xmlpull.v1.sax2.Driver", // Android
    };
    for (int i = 0; i < altXmlReaderClasspaths.length; i++) {
        String xmlReaderClasspath = altXmlReaderClasspaths[i];
        try {
            return XMLReaderFactory.createXMLReader(xmlReaderClasspath);
        } catch (SAXException e) {
            // Ignore failure
        }
    }
    // If we haven't found and returned an XMLReader yet, give up.
    throw new ServiceException("Failed to initialize a SAX XMLReader");
}

From source file:org.kalypso.kalypsomodel1d2d.conv.test.MarshallPolyhedralSurfaceTest.java

@Test
public void testWritePolyhedralSurface() throws Exception {
    final GM_PolygonPatch[] polygons = createPolygons();
    final GM_PolyhedralSurface<GM_PolygonPatch> surface = GeometryFactory.createGM_PolyhedralSurface(polygons,
            crs);//from w  ww . j av a 2 s.c o m

    File polyFile = null;
    OutputStream os = null;
    try {
        polyFile = File.createTempFile("polyTest", ".gml"); //$NON-NLS-1$ //$NON-NLS-2$
        polyFile.deleteOnExit();

        /* Output: to stream */
        os = new BufferedOutputStream(new FileOutputStream(polyFile));
        assertNotNull(os);

        final ToXMLStream xmlStream = new ToXMLStream();
        xmlStream.setOutputStream(os);
        // Configure content handler. IMPORTANT: call after setOutputStream!
        xmlStream.setLineSepUse(true);
        xmlStream.setIndent(true);
        xmlStream.setIndentAmount(1);
        xmlStream.setEncoding("UTF-8"); //$NON-NLS-1$

        final XMLReader xmlReader = XMLReaderFactory.createXMLReader();
        xmlReader.setContentHandler(xmlStream);

        xmlStream.startDocument();

        final PolyhedralSurfaceMarshaller marshaller = new PolyhedralSurfaceMarshaller(xmlReader);
        marshaller.marshall(surface);

        xmlStream.endDocument();

        os.close();

        final String xmlString = FileUtils.readFileToString(polyFile, "UTF-8"); //$NON-NLS-1$
        System.out.println(xmlString);
    } finally {
        polyFile.delete();
        IOUtils.closeQuietly(os);
    }
}

From source file:org.kalypso.kalypsomodel1d2d.conv.test.MarshallTriangulatedSurfaceTest.java

private XMLReader initMarshalling(final OutputStream os) throws SAXException {
    m_xmlStream = new ToXMLStream();
    m_xmlStream.setOutputStream(os);//w  w  w.  j a  v a 2 s. c o  m
    // Configure content handler. IMPORTANT: call after setOutputStream!
    m_xmlStream.setLineSepUse(true);
    m_xmlStream.setIndent(true);
    m_xmlStream.setIndentAmount(1);
    m_xmlStream.setEncoding("UTF-8"); //$NON-NLS-1$

    final XMLReader xmlReader = XMLReaderFactory.createXMLReader();
    xmlReader.setContentHandler(m_xmlStream);

    m_xmlStream.startDocument();

    return xmlReader;
}

From source file:org.kalypsodeegree_impl.io.sax.test.SaxParserTestUtils.java

/**
 * Create an XMLReader that writes all xml into the given {@link OutputStream}.
 *//*from ww  w  .  j a  v a 2  s . c o m*/
public static XMLReader createXMLReader(final OutputStream os) throws SAXException {
    final ToXMLStream xmlStream = new ToXMLStream();
    xmlStream.setOutputStream(os);
    // Configure content handler. IMPORTANT: call after setOutputStream!
    xmlStream.setLineSepUse(true);
    xmlStream.setIndent(true);
    xmlStream.setIndentAmount(1);
    xmlStream.setEncoding(ENCODING);

    final XMLReader reader = XMLReaderFactory.createXMLReader();
    reader.setContentHandler(xmlStream);

    return reader;
}