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.wso2.carbon.governance.registry.extensions.executors.utils.Utils.java

public static OMElement getServiceOMElement(Resource newResource) {
    try {//w w w. j  a v a 2 s. c om
        String content = getResourceContent(newResource);
        XMLStreamReader reader = XMLInputFactory.newInstance().createXMLStreamReader(new StringReader(content));
        StAXOMBuilder builder = new StAXOMBuilder(reader);
        OMElement serviceElement = builder.getDocumentElement();
        serviceElement.build();
        return serviceElement;
    } catch (Exception e) {
        log.error("Error in parsing the resource content");
    }
    return null;
}

From source file:HTTPChunkLocator.java

@Override
public ChunkLocation[] getChunkLocations(final File file, final String virtualFsName)
        throws ChunkStorageException {
    final long inode = getInode(file);
    final long fileSizeInBytes = getFileSizeInBytes(file);

    final XMLInputFactory factory = XMLInputFactory.newInstance();
    XMLEventReader reader = null;
    try {//from  w  ww  . ja v  a2s .  c o m
        final URI uri = new URI(endpoint.getScheme(), endpoint.getUserInfo(), endpoint.getHost(),
                endpoint.getPort(), endpoint.getPath(), "inum=" + inode, null);
        reader = factory.createXMLEventReader(openStream(uri));
        final List<ChunkLocation> parseChunks = parseChunks(reader, fileSizeInBytes);
        return parseChunks.toArray(new ChunkLocation[0]);
    } catch (final Exception e) {
        throw new ChunkStorageException(e);
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (final XMLStreamException e) {
                // ignore
            }
        }
    }
}

From source file:eu.peppol.document.PayloadParserTest.java

/**
 * Takes a file holding an SBD/SBDH with an ASiC archive in base64 as payload and extracts the ASiC archive in binary format, while
 * calculating the message digest.//from   w w w .j  a  v  a  2 s  .c o  m
 *
 * @throws Exception
 */
@Test
public void parseSampleSbdWithAsic() throws Exception {

    InputStream resourceAsStream = PayloadParserTest.class.getClassLoader()
            .getResourceAsStream("sample-sbd-with-asic.xml");
    assertNotNull(resourceAsStream);

    Path xmlFile = Files.createTempFile("unit-test", ".xml");

    XMLEventReader xmlEventReader = XMLInputFactory.newInstance().createXMLEventReader(resourceAsStream,
            "UTF-8");
    FileOutputStream outputStream = new FileOutputStream(xmlFile.toFile());
    XMLEventWriter xmlEventWriter = XMLOutputFactory.newInstance().createXMLEventWriter(outputStream, "UTF-8");

    Path asicFile = Files.createTempFile("unit-test", ".asice");
    OutputStream asicOutputStream = Files.newOutputStream(asicFile);
    MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");

    DigestOutputStream digestOutputStream = new DigestOutputStream(asicOutputStream, messageDigest);
    Base64OutputStream base64OutputStream = new Base64OutputStream(digestOutputStream, false);

    boolean insideAsicElement = false;

    while (xmlEventReader.hasNext()) {
        XMLEvent xmlEvent = xmlEventReader.nextEvent();

        switch (xmlEvent.getEventType()) {
        case XMLEvent.START_ELEMENT:
            String localPart = xmlEvent.asStartElement().getName().getLocalPart();
            if ("asic".equals(localPart)) {
                insideAsicElement = true;
            }
            break;
        case XMLEvent.END_ELEMENT:
            localPart = xmlEvent.asEndElement().getName().getLocalPart();
            if ("asic".equals(localPart)) {
                insideAsicElement = false;
            }
            break;

        case XMLEvent.CHARACTERS:
            // Whenever we are inside the ASiC XML element, spit
            // out the base64 encoded data into the base64 decoding output stream.
            if (insideAsicElement) {
                Characters characters = xmlEvent.asCharacters();
                base64OutputStream.write(characters.getData().getBytes("UTF-8"));
            }
            break;
        }
        xmlEventWriter.add(xmlEvent);
    }

    asicOutputStream.close();
    outputStream.close();
    log.debug("Wrote xml output to: " + xmlFile);
    log.debug("Wrote ASiC to:" + asicFile);
    log.debug("Digest: " + new String(Base64.getEncoder().encode(messageDigest.digest())));
}

From source file:de.tuebingen.uni.sfs.germanet.api.IliLoader.java

/**
 * Loads <code>IliRecords</code> from the specified file into this
 * <code>IliLoader</code>'s <code>GermaNet</code> object.
 * @param iliFile the file containing <code>IliRecords</code> data
 * @throws java.io.FileNotFoundException
 * @throws javax.xml.stream.XMLStreamException
 *///from www. java  2s  .co  m
protected void loadILI(File iliFile) throws FileNotFoundException, XMLStreamException {
    InputStream in = new FileInputStream(iliFile);
    XMLInputFactory factory = XMLInputFactory.newInstance();
    XMLStreamReader parser = factory.createXMLStreamReader(in);
    int event;
    String nodeName;
    logger.debug("Loading " + iliFile.getName() + "...");

    //Parse entire file, looking for ili record start elements
    while (parser.hasNext()) {
        event = parser.next();
        switch (event) {
        case XMLStreamConstants.START_DOCUMENT:
            namespace = parser.getNamespaceURI();
            break;
        case XMLStreamConstants.START_ELEMENT:
            nodeName = parser.getLocalName();
            if (nodeName.equals(GermaNet.XML_ILI_RECORD)) {
                IliRecord ili = processIliRecord(parser);
                germaNet.addIliRecord(ili);
            }
            break;
        }
    }
    parser.close();
    logger.debug("Done.");
}

From source file:com.msopentech.odatajclient.testservice.utils.XMLUtilities.java

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

From source file:edu.harvard.i2b2.eclipse.login.LoginHelper.java

/**
 * Function to convert pm request to OMElement
 * //  ww w .j a  va  2  s  .  c  om
 * @param requestVdo   String request to send to pm web service
 * @return An OMElement containing the pm web service request
 */
public static OMElement getPmPayLoad(String requestVdo) throws Exception {
    OMElement method = null;
    try {
        StringReader strReader = new StringReader(requestVdo);
        XMLInputFactory xif = XMLInputFactory.newInstance();
        XMLStreamReader reader = xif.createXMLStreamReader(strReader);

        StAXOMBuilder builder = new StAXOMBuilder(reader);
        method = builder.getDocumentElement();

        /*
        OMFactory fac = OMAbstractFactory.getOMFactory();
        OMNamespace omNs = fac.createOMNamespace("http://www.i2b2.org/xsd/hive/msg",
        "i2b2");
                
        method = fac.createOMElement("request", omNs);
                
        StringReader strReader = new StringReader(requestVdo);
        XMLInputFactory xif = XMLInputFactory.newInstance();
        XMLStreamReader reader = xif.createXMLStreamReader(strReader);
                
        StAXOMBuilder builder = new StAXOMBuilder(reader);
        //method = builder.getDocumentElement();
        OMElement lineItem = builder.getDocumentElement();
        method.addChild(lineItem);
        */
    } catch (FactoryConfigurationError e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        log.error(e.getMessage());
        throw new Exception(e);
    }
    return method;
}

From source file:io.cloudslang.content.xml.utils.XmlUtils.java

/**
 * Returns the Namespaces context from an xml.
 *
 * @param xmlString   xml as string//from   w ww . jav  a 2 s .co m
 * @param xmlFilePath path to xml file
 * @return the Namespaces context from an xml.
 * @throws IOException        file reading exception
 * @throws XMLStreamException parsing exception
 */
public static NamespaceContext getNamespaceContext(String xmlString, String xmlFilePath) throws Exception {
    InputStream inputXML = getStream(xmlString, xmlFilePath);
    XMLInputFactory inputFactory = XMLInputFactory.newInstance();
    XMLStreamReader reader = inputFactory.createXMLStreamReader(inputXML);
    Map<String, String> namespaces = new HashMap<>();
    while (reader.hasNext()) {
        int evt = reader.next();
        if (evt == XMLStreamConstants.START_ELEMENT) {
            QName qName = reader.getName();
            if (qName != null) {
                if (qName.getPrefix() != null && qName.getPrefix().compareTo("") != 0)
                    namespaces.put(qName.getPrefix(), qName.getNamespaceURI());
            }
        }
    }
    return new SimpleNamespaceContext(namespaces);
}

From source file:com.vistatec.ocelot.xliff.okapi.OkapiXLIFFFactory.java

@Override
public XLIFFVersion detectXLIFFVersion(File detectVersion) throws IOException, XMLStreamException {
    try (BOMInputStream bomInputStream = new BOMInputStream(new FileInputStream(detectVersion),
            ByteOrderMark.UTF_8, ByteOrderMark.UTF_16BE, ByteOrderMark.UTF_16LE, ByteOrderMark.UTF_32BE,
            ByteOrderMark.UTF_32LE)) {//ww  w.  j a  va  2s  .  c  o  m
        String bom = "UTF-8";
        if (bomInputStream.hasBOM()) {
            bom = bomInputStream.getBOMCharsetName();
        }

        XMLInputFactory xml = XMLInputFactory.newInstance();
        XMLEventReader reader = xml.createXMLEventReader(bomInputStream, bom);
        while (reader.hasNext()) {
            XMLEvent event = reader.nextEvent();
            switch (event.getEventType()) {
            case XMLEvent.START_ELEMENT:
                StartElement startElement = (StartElement) event;
                String localPart = startElement.getName().getLocalPart();
                if (localPart.equals("xliff")) {
                    @SuppressWarnings("unchecked")
                    Iterator<Attribute> attrs = startElement.getAttributes();
                    while (attrs.hasNext()) {
                        Attribute attr = attrs.next();
                        if (isXliffVersionAttributeName(attr.getName())) {
                            String value = attr.getValue();
                            reader.close();
                            if ("2.0".equals(value)) {
                                return XLIFFVersion.XLIFF20;
                            } else {
                                return XLIFFVersion.XLIFF12;
                            }
                        }
                    }
                }
                break;

            default:
                break;
            }
        }
        throw new IllegalStateException("Could not detect XLIFF version");
    }
}

From source file:edu.harvard.i2b2.pm.ws.MessageFactory.java

/**
 * Function creates PFT response OMElement from xml string
 * @param xmlString//from   ww  w.  jav a2 s .c  om
 * @return OMElement
 * @throws XMLStreamException
 */
public static OMElement createResponseOMElementFromString(String xmlString) throws XMLStreamException {
    OMElement returnElement = null;

    try {
        StringReader strReader = new StringReader(xmlString);
        XMLInputFactory xif = XMLInputFactory.newInstance();
        XMLStreamReader reader = xif.createXMLStreamReader(strReader);

        StAXOMBuilder builder = new StAXOMBuilder(reader);
        returnElement = builder.getDocumentElement();

    } catch (XMLStreamException xmlStreamEx) {
        log.error("Error while converting PM response ConfigureType to OMElement");
        throw xmlStreamEx;
    }

    return returnElement;
}

From source file:com.gtdfree.test.XMLTest.java

public void testParserEncoding() {

    try {//from  www .j  a  v  a  2s .  com

        File file = new File("./src/test/resources/gtd-free-data_2.1.xml");
        InputStream is = new FileInputStream(file);
        XMLStreamReader r = XMLInputFactory.newInstance().createXMLStreamReader(is);
        System.out.println(r.getEncoding());
        assertEquals("UTF-8", r.getEncoding());
        while (r.hasNext()) {
            r.next();
        }
        r.close();
        is.close();

        file = new File("./src/test/resources/gtd-free-data_WIN1250_2.1.xml");
        is = new FileInputStream(file);
        r = XMLInputFactory.newInstance().createXMLStreamReader(is);
        System.out.println(r.getEncoding());
        assertEquals("UTF-8", r.getEncoding());
        try {
            while (r.hasNext()) {
                r.next();
            }
            fail("This should not happend.");
        } catch (Exception e) {
            //e.printStackTrace();
        }
        r.close();
        is.close();

        file = new File("./src/test/resources/gtd-free-data_2.1_enc.xml");
        is = new FileInputStream(file);
        r = XMLInputFactory.newInstance().createXMLStreamReader(is);
        System.out.println(r.getEncoding());
        assertEquals("UTF-8", r.getEncoding());
        while (r.hasNext()) {
            r.next();
        }
        r.close();
        is.close();

        file = new File("./src/test/resources/gtd-free-data_WIN1250_2.1_enc.xml");
        is = new FileInputStream(file);
        r = XMLInputFactory.newInstance().createXMLStreamReader(is);
        System.out.println(r.getEncoding());
        assertEquals("WINDOWS-1250", r.getEncoding());
        while (r.hasNext()) {
            r.next();
        }
        r.close();
        is.close();

    } catch (Exception e) {

        e.printStackTrace();
        fail(e.getMessage());

    }

}