Example usage for javax.xml.stream XMLInputFactory newFactory

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

Introduction

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

Prototype

public static XMLInputFactory newFactory() throws FactoryConfigurationError 

Source Link

Document

Create a new instance of the factory.

Usage

From source file:Main.java

public static <T> T unmarshal(Reader r, Class<T> clazz)
        throws JAXBException, XMLStreamException, FactoryConfigurationError {
    JAXBContext context = s_contexts.get(clazz);
    if (context == null) {
        context = JAXBContext.newInstance(clazz);
        s_contexts.put(clazz, context);/*from ww w . j  a  v a 2  s  .  co  m*/
    }

    ValidationEventCollector valEventHndlr = new ValidationEventCollector();
    XMLStreamReader xmlsr = XMLInputFactory.newFactory().createXMLStreamReader(r);
    Unmarshaller unmarshaller = context.createUnmarshaller();
    unmarshaller.setSchema(null);
    unmarshaller.setEventHandler(valEventHndlr);

    JAXBElement<T> elem = null;
    try {
        elem = unmarshaller.unmarshal(xmlsr, clazz);
    } catch (Exception e) {
        if (e instanceof JAXBException) {
            throw (JAXBException) e;
        } else {
            throw new UnmarshalException(e.getMessage(), e);
        }
    }

    if (valEventHndlr.hasEvents()) {
        for (ValidationEvent valEvent : valEventHndlr.getEvents()) {
            if (valEvent.getSeverity() != ValidationEvent.WARNING) {
                // throw a new Unmarshall Exception if there is a parsing error
                String msg = MessageFormat.format("Line {0}, Col: {1}: {2}",
                        valEvent.getLocator().getLineNumber(), valEvent.getLocator().getColumnNumber(),
                        valEvent.getLinkedException().getMessage());
                throw new UnmarshalException(msg, valEvent.getLinkedException());
            }
        }
    }
    return elem.getValue();
}

From source file:lille.iagl.python_bucket.PythonBucketter.java

public PythonBucketter(String pathFileInput) {
    try {/*from  w  w  w  .j  a va  2 s  . c  o  m*/

        XMLInputFactory xmlIF = XMLInputFactory.newFactory();
        InputStream inputStream = new FileInputStream(pathFileInput);
        this.xmlSR = xmlIF.createXMLEventReader(inputStream);
        this.file_to_list();
        this.makeBucket();
    } catch (XMLStreamException | FileNotFoundException ex) {
        Logger.getLogger(PythonStackTraceRecognizer.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.amalto.core.load.io.XMLStreamUnwrapper.java

public XMLStreamUnwrapper(InputStream stream) {
    try {//  ww w.  j a va2 s  . c o  m
        reader = XMLInputFactory.newFactory().createXMLEventReader(stream);
        // Skip to first record
        while (reader.hasNext() && level < RECORD_LEVEL) {
            final XMLEvent event = reader.nextEvent();
            if (event.isStartElement()) {
                // Declare root element namespaces (if any)
                final StartElement startElement = event.asStartElement();
                Iterator namespaces = startElement.getNamespaces();
                while (namespaces.hasNext()) {
                    rootNamespaceList.add((Namespace) namespaces.next());
                }
                level++;
            }
        }
        xmlOutputFactory = XMLOutputFactory.newFactory();
    } catch (XMLStreamException e) {
        throw new RuntimeException("Unexpected parsing configuration error.", e);
    }
}

From source file:com.adaptris.core.services.UseXmlCharsetAsEncodingService.java

private static XMLInputFactory createInputFactory() {
    XMLInputFactory factory = XMLInputFactory.newFactory();
    factory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, Boolean.FALSE);
    return factory;
}

From source file:org.javelin.sws.ext.bind.SweJaxbUnmarshallerTest.java

/**
 * RI can unmarshal only to {@link XmlRootElement} annotated classes or to classes passed as a second argument to {@link Unmarshaller#unmarshal(javax.xml.stream.XMLEventReader, Class)}
 * /* w w  w.  j ava2 s  . c  o m*/
 * @throws Exception
 */
@Test(expected = UnmarshalException.class)
public void unmarshalVeryComplexContentRI() throws Exception {
    JAXBContext context = ContextFactory.createContext(new Class[] {
            org.javelin.sws.ext.bind.jaxb.context6.ClassWithVeryComplexContent.class, SingleRootElement.class },
            new HashMap<String, Object>());
    Unmarshaller um = context.createUnmarshaller();
    InputStream inputStream = new ClassPathResource("very-complex-content-01.xml", this.getClass())
            .getInputStream();
    // will throw javax.xml.bind.UnmarshalException: unexpected element (uri:"urn:test", local:"root"). Expected elements are <{y}x"
    um.unmarshal(XMLInputFactory.newFactory().createXMLEventReader(inputStream));
}

From source file:net.juniper.titan.JaxbHelper.java

public JaxbHelper(String location, PrDao prDao) {
    try {//from  w  ww .  ja  va2  s.c  o m
        jc = JAXBContext.newInstance("jaxbBindings");
        xmlLocation = location;
        xif = XMLInputFactory.newFactory();
        xif.setProperty(XMLInputFactory.SUPPORT_DTD, false);
        this.prDao = prDao;
        u = jc.createUnmarshaller();

    } catch (JAXBException ex) {
        Logger.getLogger(JaxbHelper.class.getName()).log(Level.SEVERE, "Jaxb context failed to initialise.",
                ex);
    }
}

From source file:net.landora.animeinfo.mylistreader.ListReader.java

public boolean download(InputStream input) throws Throwable {
    TarInputStream is = null;/*from w  ww  . j a  va  2s .  co  m*/
    try {
        is = new TarInputStream(new GZIPInputStream(input));

        TarEntry entry;
        while ((entry = is.getNextEntry()) != null) {
            if (!entry.getName().equalsIgnoreCase("mylist.xml")) {
                continue;
            }

            XMLStreamReader reader = XMLInputFactory.newFactory().createXMLStreamReader(is);
            reader.nextTag();
            reader.require(XMLStreamReader.START_ELEMENT, null, "my_anime_list");
            values = new HashMap<String, String>();
            StringBuilder value = new StringBuilder();

            while (reader.nextTag() != XMLStreamReader.END_ELEMENT) {
                reader.require(XMLStreamReader.START_ELEMENT, null, null);
                String tableName = reader.getLocalName();

                values.clear();

                while (reader.nextTag() != XMLStreamReader.END_ELEMENT) {
                    String valueName = reader.getLocalName();

                    value.setLength(0);
                    while (reader.next() != XMLStreamReader.END_ELEMENT) {
                        switch (reader.getEventType()) {
                        case XMLStreamReader.CDATA:
                        case XMLStreamReader.CHARACTERS:
                        case XMLStreamReader.SPACE:
                            value.append(reader.getText());
                        }
                    }
                    reader.require(XMLStreamReader.END_ELEMENT, null, valueName);
                    values.put(valueName, value.toString());

                }
                reader.require(XMLStreamReader.END_ELEMENT, null, tableName);

                handleTable(tableName);

            }
            reader.require(XMLStreamReader.END_ELEMENT, null, "my_anime_list");

            saveLast();
        }
        return true;
    } finally {
        if (is != null) {
            IOUtils.closeQuietly(is);
        } else if (input != null) {
            IOUtils.closeQuietly(input);
        }
    }
}

From source file:com.github.lindenb.jvarkit.tools.blast.BlastFilterJS.java

@Override
protected Collection<Throwable> call(String inputName) throws Exception {

    final CompiledScript compiledScript;
    Unmarshaller unmarshaller;// www  .  ja  v a  2 s.  com
    Marshaller marshaller;
    try {
        compiledScript = super.compileJavascript();

        JAXBContext jc = JAXBContext.newInstance("gov.nih.nlm.ncbi.blast");

        unmarshaller = jc.createUnmarshaller();
        marshaller = jc.createMarshaller();

        XMLInputFactory xmlInputFactory = XMLInputFactory.newFactory();
        xmlInputFactory.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, Boolean.TRUE);
        xmlInputFactory.setProperty(XMLInputFactory.IS_COALESCING, Boolean.TRUE);
        xmlInputFactory.setProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES, Boolean.TRUE);
        xmlInputFactory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, Boolean.FALSE);
        marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

        PrintWriter pw = openFileOrStdoutAsPrintWriter();
        XMLOutputFactory xof = XMLOutputFactory.newFactory();
        xof.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, Boolean.FALSE);
        XMLEventWriter w = xof.createXMLEventWriter(pw);

        StreamSource src = null;
        if (inputName == null) {
            LOG.info("Reading stdin");
            src = new StreamSource(stdin());
        } else {
            LOG.info("Reading file " + inputName);
            src = new StreamSource(new File(inputName));
        }

        XMLEventReader r = xmlInputFactory.createXMLEventReader(src);

        XMLEventFactory eventFactory = XMLEventFactory.newFactory();

        SimpleBindings bindings = new SimpleBindings();
        while (r.hasNext()) {
            XMLEvent evt = r.peek();
            switch (evt.getEventType()) {
            case XMLEvent.START_ELEMENT: {
                StartElement sE = evt.asStartElement();
                Hit hit = null;
                JAXBElement<Hit> jaxbElement = null;
                if (sE.getName().getLocalPart().equals("Hit")) {
                    jaxbElement = unmarshaller.unmarshal(r, Hit.class);
                    hit = jaxbElement.getValue();
                } else {
                    w.add(r.nextEvent());
                    break;
                }

                if (hit != null) {

                    bindings.put("hit", hit);

                    boolean accept = super.evalJavaScriptBoolean(compiledScript, bindings);

                    if (accept) {
                        marshaller.marshal(jaxbElement, w);
                        w.add(eventFactory.createCharacters("\n"));
                    }
                }

                break;
            }
            case XMLEvent.SPACE:
                break;
            default: {
                w.add(r.nextEvent());
                break;
            }
            }
            r.close();
        }
        w.flush();
        w.close();
        pw.flush();
        pw.close();
        return RETURN_OK;
    } catch (Exception err) {
        return wrapException(err);
    } finally {

    }
}

From source file:org.owasp.webgoat.plugin.XXE.java

private SearchForm parseXml(String xml) throws Exception {
    JAXBContext jc = JAXBContext.newInstance(SearchForm.class);

    XMLInputFactory xif = XMLInputFactory.newFactory();
    xif.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, true);
    xif.setProperty(XMLInputFactory.SUPPORT_DTD, true);
    XMLStreamReader xsr = xif.createXMLStreamReader(new StringReader(xml));

    Unmarshaller unmarshaller = jc.createUnmarshaller();
    return (SearchForm) unmarshaller.unmarshal(xsr);
}

From source file:org.javelin.sws.ext.bind.SweJaxbUnmarshallerTest.java

@Test
public void unmarshalVeryComplexContentExplicitRI() throws Exception {
    JAXBContext context = ContextFactory.createContext(new Class[] {
            org.javelin.sws.ext.bind.jaxb.context6.ClassWithVeryComplexContent.class, SingleRootElement.class },
            new HashMap<String, Object>());
    Unmarshaller um = context.createUnmarshaller();
    InputStream inputStream = new ClassPathResource("very-complex-content-01.xml", this.getClass())
            .getInputStream();/*from w w w  . j a  va  2s . co  m*/
    // will throw javax.xml.bind.UnmarshalException: unexpected element (uri:"urn:test", local:"root"). Expected elements are <{y}x"
    JAXBElement<org.javelin.sws.ext.bind.jaxb.context6.ClassWithVeryComplexContent> je = um.unmarshal(
            XMLInputFactory.newFactory().createXMLEventReader(inputStream),
            org.javelin.sws.ext.bind.jaxb.context6.ClassWithVeryComplexContent.class);
    org.javelin.sws.ext.bind.jaxb.context6.ClassWithVeryComplexContent ob = je.getValue();
    assertThat(ob.getStr(), equalTo("test-1"));
    assertThat(ob.getInside(), equalTo("str"));
    assertThat(ob.getInside2().getNumber(), equalTo(42));
    assertThat(ob.getInside2().getStr(), equalTo("test-2"));
    assertThat(ob.getInside2().getInside(), equalTo("inside"));
}