Example usage for javax.xml.stream XMLInputFactory newInstance

List of usage examples for javax.xml.stream XMLInputFactory newInstance

Introduction

In this page you can find the example usage for javax.xml.stream XMLInputFactory newInstance.

Prototype

public static XMLInputFactory newInstance() throws FactoryConfigurationError 

Source Link

Document

Creates a new instance of the factory in exactly the same manner as the #newFactory() method.

Usage

From source file:org.apache.axis2.saaj.SOAPPartImpl.java

public void setContent(Source source) throws SOAPException {
    try {//from  w  w w. j  a  va2s  . c o  m
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        XMLInputFactory inputFactory = XMLInputFactory.newInstance();
        XMLStreamReader reader;

        if (source instanceof StreamSource) {
            reader = inputFactory.createXMLStreamReader(source);
        } else {
            Result result = new StreamResult(baos);
            Transformer xformer = TransformerFactory.newInstance().newTransformer();
            xformer.transform(source, result);
            InputStream is = new ByteArrayInputStream(baos.toByteArray());
            reader = inputFactory.createXMLStreamReader(is);
        }

        StAXSOAPModelBuilder builder1 = null;
        if (this.envelope.element.getOMFactory() instanceof SOAP11Factory) {
            builder1 = new StAXSOAPModelBuilder(reader, (SOAP11Factory) this.envelope.element.getOMFactory(),
                    null);
        } else if (this.envelope.element.getOMFactory() instanceof SOAP12Factory) {
            builder1 = new StAXSOAPModelBuilder(reader, (SOAP12Factory) this.envelope.element.getOMFactory(),
                    null);
        }

        org.apache.axiom.soap.SOAPEnvelope soapEnvelope = builder1.getSOAPEnvelope();
        envelope = new SOAPEnvelopeImpl((org.apache.axiom.soap.impl.dom.SOAPEnvelopeImpl) soapEnvelope);
        envelope.element.build();
        this.document = envelope.getOwnerDocument();
        envelope.setSOAPPartParent(this);
    } catch (TransformerFactoryConfigurationError e) {
        log.error(e);
        throw new SOAPException(e);
    } catch (Exception e) {
        log.error(e);
        throw new SOAPException(e);
    }
}

From source file:org.apache.ddlutils.io.DatabaseIO.java

/**
 * Creates a new, initialized XML input factory object.
 * /*from  w  ww .  ja va2s  . co m*/
 * @return The factory object
 */
private XMLInputFactory getXMLInputFactory() {
    XMLInputFactory factory = XMLInputFactory.newInstance();

    factory.setProperty("javax.xml.stream.isCoalescing", Boolean.TRUE);
    factory.setProperty("javax.xml.stream.isNamespaceAware", Boolean.TRUE);
    return factory;
}

From source file:org.apache.ddlutils.io.DataReader.java

/**
 * Creates a new, initialized XML input factory object.
 * //from   w  w w  . j  a  v  a2  s .com
 * @return The factory object
 */
private XMLInputFactory getXMLInputFactory() {
    XMLInputFactory factory = XMLInputFactory.newInstance();

    factory.setProperty("javax.xml.stream.isCoalescing", Boolean.TRUE);
    factory.setProperty("javax.xml.stream.isNamespaceAware", Boolean.FALSE);
    return factory;
}

From source file:org.apache.hadoop.hdfs.tools.offlineImageViewer.OfflineImageReconstructor.java

private OfflineImageReconstructor(CountingOutputStream out, InputStreamReader reader)
        throws XMLStreamException {
    this.out = out;
    XMLInputFactory factory = XMLInputFactory.newInstance();
    this.events = factory.createXMLEventReader(reader);
    this.sections = new HashMap<>();
    this.sections.put(NameSectionProcessor.NAME, new NameSectionProcessor());
    this.sections.put(INodeSectionProcessor.NAME, new INodeSectionProcessor());
    this.sections.put(SecretManagerSectionProcessor.NAME, new SecretManagerSectionProcessor());
    this.sections.put(CacheManagerSectionProcessor.NAME, new CacheManagerSectionProcessor());
    this.sections.put(SnapshotDiffSectionProcessor.NAME, new SnapshotDiffSectionProcessor());
    this.sections.put(INodeReferenceSectionProcessor.NAME, new INodeReferenceSectionProcessor());
    this.sections.put(INodeDirectorySectionProcessor.NAME, new INodeDirectorySectionProcessor());
    this.sections.put(FilesUnderConstructionSectionProcessor.NAME,
            new FilesUnderConstructionSectionProcessor());
    this.sections.put(SnapshotSectionProcessor.NAME, new SnapshotSectionProcessor());
    this.isoDateFormat = PBImageXmlWriter.createSimpleDateFormat();
}

From source file:org.apache.hadoop.util.ConfTest.java

private static List<NodeInfo> parseConf(InputStream in) throws XMLStreamException {
    QName configuration = new QName("configuration");
    QName property = new QName("property");

    List<NodeInfo> nodes = new ArrayList<NodeInfo>();
    Stack<NodeInfo> parsed = new Stack<NodeInfo>();

    XMLInputFactory factory = XMLInputFactory.newInstance();
    XMLEventReader reader = factory.createXMLEventReader(in);

    while (reader.hasNext()) {
        XMLEvent event = reader.nextEvent();
        if (event.isStartElement()) {
            StartElement currentElement = event.asStartElement();
            NodeInfo currentNode = new NodeInfo(currentElement);
            if (parsed.isEmpty()) {
                if (!currentElement.getName().equals(configuration)) {
                    return null;
                }/*from   w ww. j  a  v  a2 s  .com*/
            } else {
                NodeInfo parentNode = parsed.peek();
                QName parentName = parentNode.getStartElement().getName();
                if (parentName.equals(configuration)
                        && currentNode.getStartElement().getName().equals(property)) {
                    @SuppressWarnings("unchecked")
                    Iterator<Attribute> it = currentElement.getAttributes();
                    while (it.hasNext()) {
                        currentNode.addAttribute(it.next());
                    }
                } else if (parentName.equals(property)) {
                    parentNode.addElement(currentElement);
                }
            }
            parsed.push(currentNode);
        } else if (event.isEndElement()) {
            NodeInfo node = parsed.pop();
            if (parsed.size() == 1) {
                nodes.add(node);
            }
        } else if (event.isCharacters()) {
            if (2 < parsed.size()) {
                NodeInfo parentNode = parsed.pop();
                StartElement parentElement = parentNode.getStartElement();
                NodeInfo grandparentNode = parsed.peek();
                if (grandparentNode.getElement(parentElement) == null) {
                    grandparentNode.setElement(parentElement, event.asCharacters());
                }
                parsed.push(parentNode);
            }
        }
    }

    return nodes;
}

From source file:org.apache.jackrabbit.oak.benchmark.wikipedia.WikipediaImport.java

public int importWikipedia(Session session) throws Exception {
    long start = System.currentTimeMillis();
    int count = 0;
    int code = 0;

    if (doReport) {
        System.out.format("Importing %s...%n", dump);
    }// w  ww.j av a 2 s.  co  m

    String type = "nt:unstructured";
    if (session.getWorkspace().getNodeTypeManager().hasNodeType("oak:Unstructured")) {
        type = "oak:Unstructured";
    }
    Node wikipedia = session.getRootNode().addNode("wikipedia", type);

    int levels = 0;
    if (!flat) {
        // calculate the number of levels needed, based on the rough
        // estimate that the average XML size of a page is about 1kB
        for (long pages = dump.length() / 1024; pages > 256; pages /= 256) {
            levels++;
        }
    }

    String title = null;
    String text = null;
    XMLInputFactory factory = XMLInputFactory.newInstance();
    StreamSource source;
    if (dump.getName().endsWith(".xml")) {
        source = new StreamSource(dump);
    } else {
        CompressorStreamFactory csf = new CompressorStreamFactory();
        source = new StreamSource(
                csf.createCompressorInputStream(new BufferedInputStream(new FileInputStream(dump))));
    }
    haltImport = false;
    XMLStreamReader reader = factory.createXMLStreamReader(source);
    while (reader.hasNext() && !haltImport) {
        switch (reader.next()) {
        case XMLStreamConstants.START_ELEMENT:
            if ("title".equals(reader.getLocalName())) {
                title = reader.getElementText();
            } else if ("text".equals(reader.getLocalName())) {
                text = reader.getElementText();
            }
            break;
        case XMLStreamConstants.END_ELEMENT:
            if ("page".equals(reader.getLocalName())) {
                String name = Text.escapeIllegalJcrChars(title);
                Node parent = wikipedia;
                if (levels > 0) {
                    int n = name.length();
                    for (int i = 0; i < levels; i++) {
                        int hash = name.substring(min(i, n)).hashCode();
                        parent = JcrUtils.getOrAddNode(parent, String.format("%02x", hash & 0xff));
                    }
                }
                Node page = parent.addNode(name);
                page.setProperty("title", title);
                page.setProperty("text", text);
                code += title.hashCode();
                code += text.hashCode();
                count++;
                if (count % 1000 == 0) {
                    batchDone(session, start, count);
                }

                pageAdded(title, text);
            }
            break;
        }
    }

    session.save();

    if (doReport) {
        long millis = System.currentTimeMillis() - start;
        System.out.format("Imported %d pages in %d seconds (%.2fms/page)%n", count, millis / 1000,
                (double) millis / count);
    }

    return code;
}

From source file:org.apache.olingo.fit.metadata.Metadata.java

public Metadata(final InputStream is) {
    DEF_NS = Constants.get(ConstantKey.EDM_NS);
    schemas = new HashMap<String, Schema>();

    try {//from  ww w. ja va 2s .  com
        final XMLInputFactory ifactory = XMLInputFactory.newInstance();
        final XMLEventReader reader = ifactory.createXMLEventReader(is,
                org.apache.olingo.commons.api.Constants.UTF8);

        try {
            while (reader.hasNext()) {
                final XMLEvent event = reader.nextEvent();

                if (event.isStartElement()
                        && event.asStartElement().getName().equals(new QName(DEF_NS, "Schema"))) {
                    final Schema schema = getSchema(event.asStartElement(), reader);
                    schemas.put(schema.getNamespace(), schema);
                }
            }

        } catch (Exception ignore) {
            // ignore
        } finally {
            reader.close();
            IOUtils.closeQuietly(is);
        }
    } catch (Exception e) {
        LOG.error("Error parsing metadata", e);
    }

    for (Map.Entry<String, Schema> schemaEntry : schemas.entrySet()) {
        for (EntityType entityType : schemaEntry.getValue().getEntityTypes()) {
            for (NavigationProperty property : entityType.getNavigationProperties()) {
                property.setFeed(property.getType().startsWith("Collection("));

                final Collection<EntitySet> entitySets = schemaEntry.getValue().getContainers().iterator()
                        .next().getEntitySets(schemaEntry.getKey(), entityType.getName());

                final Iterator<EntitySet> iter = entitySets.iterator();
                boolean found = false;

                while (!found && iter.hasNext()) {
                    final EntitySet entitySet = iter.next();
                    final String target = entitySet.getTarget(property.getName());
                    if (StringUtils.isNotBlank(target)) {
                        property.setTarget(entitySet.getTarget(property.getName()));
                        found = true;
                    }
                }
            }
        }
    }
}

From source file:org.apache.olingo.fit.utils.AbstractXMLUtilities.java

protected XMLEventReader getEventReader(final InputStream is) throws XMLStreamException {
    if (ifactory == null) {
        ifactory = XMLInputFactory.newInstance();
    }/*from w  w w. j av a  2s . c  om*/
    ifactory.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, false);
    return ifactory.createXMLEventReader(is);
}

From source file:org.apache.olingo.fit.utils.XMLEventReaderWrapper.java

public XMLEventReaderWrapper(final InputStream stream) throws IOException, XMLStreamException {
    final StringBuilder startBuilder = new StringBuilder();
    startBuilder.append("<").append(CONTENT).append(" xmlns:m").append("=\"")
            .append(Constants.get(ConstantKey.METADATA_NS)).append("\"").append(" xmlns:d").append("=\"")
            .append(Constants.get(ConstantKey.DATASERVICES_NS)).append("\"").append(" xmlns:georss")
            .append("=\"").append(Constants.get(ConstantKey.GEORSS_NS)).append("\"").append(" xmlns:gml")
            .append("=\"").append(Constants.get(ConstantKey.GML_NS)).append("\"").append(">");

    CONTENT_STAG = startBuilder.toString();

    final XMLInputFactory factory = XMLInputFactory.newInstance();

    final InputStreamReader reader = new InputStreamReader(new ByteArrayInputStream(
            (CONTENT_STAG + IOUtils.toString(stream, ENCODING).replaceAll("^<\\?xml.*\\?>", "")
                    + XMLEventReaderWrapper.CONTENT_ETAG).getBytes(ENCODING)),
            Constants.DECODER);//from w  ww  .j a  v  a 2s . c  om

    wrapped = factory.createXMLEventReader(reader);

    init();
}

From source file:org.apache.olingo.fit.utils.XMLUtilities.java

protected XMLEventReader getEventReader(final InputStream is) throws XMLStreamException {
    if (ifactory == null) {
        ifactory = XMLInputFactory.newInstance();
    }/*from   ww  w  .  j  a va 2  s . c  o  m*/

    return ifactory.createXMLEventReader(new InputStreamReader(is, Constants.DECODER));
}