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:org.flockdata.integration.FileProcessor.java

private int processXMLFile(String file, ExtractProfile extractProfile) throws IOException, FlockException,
        IllegalAccessException, InstantiationException, ClassNotFoundException {
    try {/*from w w  w . j ava 2  s. c  om*/
        int rows = 0;
        StopWatch watch = new StopWatch();
        StreamSource source = new StreamSource(file);
        XMLInputFactory xif = XMLInputFactory.newFactory();
        XMLStreamReader xsr = xif.createXMLStreamReader(source);

        XmlMappable mappable = (XmlMappable) Class.forName(extractProfile.getHandler()).newInstance();
        mappable.positionReader(xsr);

        String dataType = mappable.getDataType();
        watch.start();
        try {
            long then = new DateTime().getMillis();
            while (xsr.getLocalName().equals(dataType)) {
                EntityInputBean entityInputBean = Transformer.toEntity(mappable, xsr,
                        extractProfile.getContentModel());
                rows++;
                xsr.nextTag();
                getPayloadWriter().writeEntity(entityInputBean);

                if (stopProcessing(rows, then)) {
                    break;
                }

            }
        } finally {
            getPayloadWriter().flush();
        }
        return endProcess(watch, rows, 0);

    } catch (XMLStreamException | JAXBException e1) {
        throw new IOException(e1);
    }
}

From source file:org.jabref.logic.importer.fileformat.MedlineImporter.java

@Override
public ParserResult importDatabase(BufferedReader reader) throws IOException {
    Objects.requireNonNull(reader);

    List<BibEntry> bibItems = new ArrayList<>();

    try {/* w  w  w . j a  v  a 2  s . c o  m*/
        JAXBContext context = JAXBContext.newInstance("org.jabref.logic.importer.fileformat.medline");
        XMLInputFactory xmlInputFactory = XMLInputFactory.newFactory();
        XMLStreamReader xmlStreamReader = xmlInputFactory.createXMLStreamReader(reader);

        //go to the root element
        while (!xmlStreamReader.isStartElement()) {
            xmlStreamReader.next();
        }

        Unmarshaller unmarshaller = context.createUnmarshaller();
        Object unmarshalledObject = unmarshaller.unmarshal(xmlStreamReader);

        //check whether we have an article set, an article, a book article or a book article set
        if (unmarshalledObject instanceof PubmedArticleSet) {
            PubmedArticleSet articleSet = (PubmedArticleSet) unmarshalledObject;
            for (Object article : articleSet.getPubmedArticleOrPubmedBookArticle()) {
                if (article instanceof PubmedArticle) {
                    PubmedArticle currentArticle = (PubmedArticle) article;
                    parseArticle(currentArticle, bibItems);
                }
                if (article instanceof PubmedBookArticle) {
                    PubmedBookArticle currentArticle = (PubmedBookArticle) article;
                    parseBookArticle(currentArticle, bibItems);
                }
            }
        } else if (unmarshalledObject instanceof PubmedArticle) {
            PubmedArticle article = (PubmedArticle) unmarshalledObject;
            parseArticle(article, bibItems);
        } else if (unmarshalledObject instanceof PubmedBookArticle) {
            PubmedBookArticle currentArticle = (PubmedBookArticle) unmarshalledObject;
            parseBookArticle(currentArticle, bibItems);
        } else {
            PubmedBookArticleSet bookArticleSet = (PubmedBookArticleSet) unmarshalledObject;
            for (PubmedBookArticle bookArticle : bookArticleSet.getPubmedBookArticle()) {
                parseBookArticle(bookArticle, bibItems);
            }
        }
    } catch (JAXBException | XMLStreamException e) {
        LOGGER.debug("could not parse document", e);
        return ParserResult.fromError(e);
    }
    return new ParserResult(bibItems);
}

From source file:org.jasig.portal.io.xml.AbstractIdentityImportExportTest.java

protected final <T> void testIdentityImportExport(final IDataImporter<T> dataImporter,
        final IDataExporter<?> dataExporter, Resource resource, Function<T, String> getName) throws Exception {

    final String importData = toString(resource);

    final XMLInputFactory xmlInputFactory = XMLInputFactory.newFactory();
    final XMLEventReader xmlEventReader = xmlInputFactory.createXMLEventReader(new StringReader(importData));

    //Unmarshall from XML
    final Unmarshaller unmarshaller = dataImporter.getUnmarshaller();
    final StAXSource source = new StAXSource(xmlEventReader);
    @SuppressWarnings("unchecked")
    final T dataImport = (T) unmarshaller.unmarshal(source);

    //Make sure the data was unmarshalled
    assertNotNull("Unmarshalled import data was null", dataImport);

    //Import the data
    dataImporter.importData(dataImport);

    //Export the data
    final String name = getName.apply(dataImport);
    final Object dataExport = transactionOperations.execute(new TransactionCallback<Object>() {
        /* (non-Javadoc)
         * @see org.springframework.transaction.support.TransactionCallback#doInTransaction(org.springframework.transaction.TransactionStatus)
         *//*from   w w w  . j a  v a  2 s  .  c om*/
        @Override
        public Object doInTransaction(TransactionStatus status) {
            return dataExporter.exportData(name);
        }
    });

    //Make sure the data was exported
    assertNotNull("Exported data was null", dataExport);

    //Marshall to XML
    final Marshaller marshaller = dataExporter.getMarshaller();

    final StringWriter result = new StringWriter();
    marshaller.marshal(dataExport, new StreamResult(result));

    //Compare the exported XML data with the imported XML data, they should match
    final String resultString = result.toString();
    try {
        XMLUnit.setIgnoreWhitespace(true);
        Diff d = new Diff(new StringReader(importData), new StringReader(resultString));
        assertTrue("Export result differs from import" + d, d.similar());
    } catch (Exception e) {
        throw new XmlTestException("Failed to assert similar between import XML and export XML", resultString,
                e);
    } catch (Error e) {
        throw new XmlTestException("Failed to assert similar between import XML and export XML", resultString,
                e);
    }
}

From source file:org.jasig.portal.io.xml.PortalDataKeyFileProcessor.java

PortalDataKeyFileProcessor(Map<PortalDataKey, IPortalDataType> dataKeyTypes, BatchImportOptions options) {
    this.dataKeyTypes = dataKeyTypes;
    this.options = options;

    this.xmlInputFactory = XMLInputFactory.newFactory();

    //Set the input buffer to 2k bytes. This appears to work for reading just enough to get the start element event for
    //all of the data files in a single read operation.
    this.xmlInputFactory.setProperty(WstxInputProperties.P_INPUT_BUFFER_LENGTH, 2000);
    this.xmlInputFactory.setProperty(XMLInputFactory2.P_LAZY_PARSING, true); //Do as little parsing as possible, just want basic info
    this.xmlInputFactory.setProperty(XMLInputFactory.IS_VALIDATING, false); //Don't do any validation here
    this.xmlInputFactory.setProperty(XMLInputFactory.SUPPORT_DTD, false); //Don't load referenced DTDs here
}

From source file:org.jboss.loom.migrators.logging.LoggingMigrator.java

@Override
public void loadSourceServerConfig(MigrationContext ctx) throws LoadMigrationException {
    try {/*from w  w  w . j  av  a 2 s .  c  o  m*/
        File log4jConfFile = Utils.createPath(
                //super.getGlobalConfig().getAS5Config().getDir(),  "server",
                //super.getGlobalConfig().getAS5Config().getProfileName(),
                //"conf", "jboss-log4j.xml");
                super.getGlobalConfig().getAS5Config().getConfDir(), "jboss-log4j.xml");

        XMLInputFactory xif = XMLInputFactory.newFactory();
        xif.setProperty(XMLInputFactory.SUPPORT_DTD, false);
        XMLStreamReader xsr = xif.createXMLStreamReader(new StreamSource(log4jConfFile));

        //if( ! log4jConfFile.canRead())
        //    throw new LoadMigrationException("Cannot find/open file: " + log4jConfFile.getAbsolutePath());

        Unmarshaller unmarshaller = JAXBContext.newInstance(LoggingAS5Bean.class).createUnmarshaller();
        LoggingAS5Bean loggingAS5 = (LoggingAS5Bean) unmarshaller.unmarshal(xsr);

        MigratorData mData = new MigratorData();

        if (loggingAS5.getCategories() != null) {
            mData.getConfigFragments().addAll(loggingAS5.getCategories());
        }

        if (loggingAS5.getLoggers() != null) {
            mData.getConfigFragments().addAll(loggingAS5.getLoggers());
        }

        mData.getConfigFragments().addAll(loggingAS5.getAppenders());
        mData.getConfigFragments().add(loggingAS5.getRootLoggerAS5());

        ctx.getMigrationData().put(LoggingMigrator.class, mData);
    } catch (JAXBException | XMLStreamException e) {
        throw new LoadMigrationException(e);
    }
}

From source file:org.netbeans.jbatch.modeler.spec.core.Definitions.java

public static Definitions load(ModelerFile file, String definitionId) {
    File savedFile = file.getFile();
    Definitions definition_Load = null;//from  w w  w .j  av a 2 s.c  om
    boolean definitionExist = false;
    XMLStreamReader xsr = null;
    try {
        if (savedFile.length() != 0) {

            XMLInputFactory xif = XMLInputFactory.newFactory();
            StreamSource xml = new StreamSource(savedFile);
            xsr = xif.createXMLStreamReader(xml);
            xsr.nextTag();
            if (definitionId == null) {
                while (xsr.hasNext() && !definitionExist) {
                    if (xsr.getEventType() == XMLStreamConstants.START_ELEMENT
                            && xsr.getLocalName().equals("definitions")
                            && xsr.getAttributeValue(null, "id") == null) {
                        definitionExist = true;
                    } else {
                        xsr.next();
                    }
                }
            } else {
                while (xsr.hasNext() && !definitionExist) {
                    if (xsr.getEventType() == XMLStreamConstants.START_ELEMENT
                            && xsr.getLocalName().equals("definitions")
                            && definitionId.equals(xsr.getAttributeValue(null, "id"))) {
                        definitionExist = true;
                    } else {
                        xsr.next();
                    }
                }
            }

        }
        JAXBContext jobContext;
        Unmarshaller jobUnmarshaller;
        //            if (jobContext == null) {
        jobContext = JAXBContext.newInstance(new Class<?>[] { ShapeDesign.class, Definitions.class });
        //            }
        //            if (jobUnmarshaller == null) {
        jobUnmarshaller = jobContext.createUnmarshaller();
        jobUnmarshaller.setEventHandler(new ValidateJAXB());
        //            }
        if (definitionExist) {
            definition_Load = jobUnmarshaller.unmarshal(xsr, Definitions.class).getValue();//new StreamSource(savedFile)
        }
        if (xsr != null) {
            xsr.close();
        }

    } catch (XMLStreamException ex) {
        Exceptions.printStackTrace(ex);
    } catch (JAXBException ex) {
        //            io.getOut().println("Exception: " + ex.toString());
        ex.printStackTrace();
        System.out.println("Document XML Not Exist");
    }
    return definition_Load;
}

From source file:org.netbeans.jbatch.modeler.spec.core.Definitions.java

public static void unload(ModelerFile file, List<String> definitionIdList) {
    File savedFile = file.getFile();
    if (definitionIdList.isEmpty()) {
        return;/*from   w w w .j a va  2 s .com*/
    }
    try {
        File cloneSavedFile = File.createTempFile("TMP", "job");
        FileUtils.copyFile(savedFile, cloneSavedFile);

        BufferedReader br = new BufferedReader(new FileReader(savedFile));
        String line = null;
        while ((line = br.readLine()) != null) {
            System.out.println("pre savedFile : " + line);
        }

        XMLOutputFactory xof = XMLOutputFactory.newFactory();
        XMLStreamWriter xsw = xof.createXMLStreamWriter(new FileWriter(savedFile));
        xsw.setDefaultNamespace("http://jbatchsuite.java.net");

        xsw.writeStartDocument();
        xsw.writeStartElement("jbatchnb", "root", "http://jbatchsuite.java.net");
        xsw.writeNamespace("jbatch", "http://xmlns.jcp.org/xml/ns/javaee");
        xsw.writeNamespace("jbatchnb", "http://jbatchsuite.java.net");
        xsw.writeNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
        xsw.writeNamespace("java", "http://jcp.org/en/jsr/detail?id=270");
        xsw.writeNamespace("nbm", "http://nbmodeler.java.net");

        if (cloneSavedFile.length() != 0) {
            try {
                XMLInputFactory xif = XMLInputFactory.newFactory();
                StreamSource xml = new StreamSource(cloneSavedFile);
                XMLStreamReader xsr = xif.createXMLStreamReader(xml);
                xsr.nextTag();
                while (xsr.getEventType() == XMLStreamConstants.START_ELEMENT) {
                    //                        Def   Y    N
                    //                        Tag   N(D) Y(D)
                    //                        ________________
                    //                              T    T
                    //                        ----------------
                    //
                    //                        Def   Y    N
                    //                        Tag   Y(S) N(S)
                    //                        ________________
                    //                              S    S
                    //                        ----------------
                    //
                    //                        Def   Y    N
                    //                        Tag   Y(D) N(S)
                    //                        ________________
                    //                              T    S
                    //                        ----------------
                    //
                    //                       (D) => Different
                    //                       (S) => Same
                    //                        Y => Id Exist
                    //                        N => Def Id is null
                    //                        T => Transform
                    //                        S => Skip

                    if (xsr.getLocalName().equals("definitions")) {
                        //                            if (definitionId == null) {
                        //                                if (xsr.getAttributeValue(null, "id") != null) {
                        //                                    transformXMLStream(xsr, xsw);
                        //                                }
                        //                            } else {
                        if (xsr.getAttributeValue(null, "id") == null) {
                            System.out.println("transformXMLStream " + null);
                            transformXMLStream(xsr, xsw);
                        } else {
                            if (!definitionIdList.contains(xsr.getAttributeValue(null, "id"))) {
                                System.out.println("transformXMLStream " + xsr.getAttributeValue(null, "id"));
                                transformXMLStream(xsr, xsw);
                            } else {
                                System.out.println("skipXMLStream " + xsr.getAttributeValue(null, "id"));
                                skipXMLStream(xsr);
                            }
                        }
                        //                            }
                    }
                    System.out.println(
                            "pre xsr.getEventType() : " + xsr.getEventType() + "  " + xsr.getLocalName());
                    xsr.nextTag();
                    System.out.println(
                            "post xsr.getEventType() : " + xsr.getEventType() + "  " + xsr.getLocalName());
                }
            } catch (XMLStreamException ex) {
                Exceptions.printStackTrace(ex);
            }
        }
        xsw.writeEndDocument();
        xsw.close();

        br = new BufferedReader(new FileReader(savedFile));
        line = null;
        while ((line = br.readLine()) != null) {
            System.out.println("post savedFile : " + line);
        }

    } catch (IOException ex) {
        Exceptions.printStackTrace(ex);
    } catch (XMLStreamException ex) {
        Exceptions.printStackTrace(ex);
    }
}

From source file:org.netbeans.jbatch.modeler.specification.model.job.util.JobUtil.java

public void saveModelerFile(ModelerFile modelerFile) {

    Definitions definitions = (Definitions) modelerFile.getDefinitionElement();

    try {/*  www .j av  a 2  s.  c  o m*/
        updateBatchDiagram(modelerFile);
        List<String> closeDefinitionIdList = closeDiagram(modelerFile, definitions.getGarbageDefinitions());
        List<String> definitionIdList = new ArrayList<String>(closeDefinitionIdList);
        //            definitionIdList.addAll(definitions.getGarbageDefinitions());
        definitionIdList.add(definitions.getId());
        File savedFile = modelerFile.getFile();

        BufferedReader br = new BufferedReader(new FileReader(savedFile));
        String line = null;
        while ((line = br.readLine()) != null) {
            System.out.println("savedFile : " + line);
        }

        File cloneSavedFile = File.createTempFile("TMP", "job");
        FileUtils.copyFile(savedFile, cloneSavedFile);
        //            br = new BufferedReader(new FileReader(cloneSavedFile));
        //            line = null;
        //            while ((line = br.readLine()) != null) {
        //                System.out.println("line2 : " + line);
        //            }

        XMLOutputFactory xof = XMLOutputFactory.newFactory();
        XMLStreamWriter xsw = xof.createXMLStreamWriter(new FileWriter(savedFile));
        xsw.setDefaultNamespace("http://jbatchsuite.java.net");

        xsw.writeStartDocument();
        xsw.writeStartElement("jbatchnb", "root", "http://jbatchsuite.java.net");
        xsw.writeNamespace("jbatch", "http://xmlns.jcp.org/xml/ns/javaee");
        xsw.writeNamespace("jbatchnb", "http://jbatchsuite.java.net");
        xsw.writeNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
        xsw.writeNamespace("java", "http://jcp.org/en/jsr/detail?id=270");
        xsw.writeNamespace("nbm", "http://nbmodeler.java.net");

        //            br = new BufferedReader(new FileReader(savedFile));
        //            line = null;
        //            while ((line = br.readLine()) != null) {
        //                System.out.println("line3 : " + line);
        //            }
        if (cloneSavedFile.length() != 0) {
            try {
                XMLInputFactory xif = XMLInputFactory.newFactory();
                StreamSource xml = new StreamSource(cloneSavedFile);
                XMLStreamReader xsr = xif.createXMLStreamReader(xml);
                xsr.nextTag();
                while (xsr.getEventType() == XMLStreamConstants.START_ELEMENT) {
                    //                        Def   Y    N
                    //                        Tag   N(D) Y(D)
                    //                        ________________
                    //                              T    T
                    //                        ----------------
                    //
                    //                        Def   Y    N
                    //                        Tag   Y(S) N(S)
                    //                        ________________
                    //                              S    S
                    //                        ----------------
                    //
                    //                        Def   Y    N
                    //                        Tag   Y(D) N(S)
                    //                        ________________
                    //                              T    S
                    //                        ----------------
                    //
                    //                       (D) => Different
                    //                       (S) => Same
                    //                        Y => Id Exist
                    //                        N => Id is null
                    //                        T => Transform
                    //                        S => Skip

                    if (xsr.getLocalName().equals("definitions")) {
                        //                            if (definitions.getId() == null) {
                        //                                if (xsr.getAttributeValue(null, "id") != null) {
                        //                                    transformXMLStream(xsr, xsw);
                        //                                } else {
                        //                                    skipXMLStream(xsr);
                        //                                }
                        //                            } else {
                        if (xsr.getAttributeValue(null, "id") == null) {
                            if (definitions.getId() == null) {
                                skipXMLStream(xsr);
                            } else {
                                transformXMLStream(xsr, xsw);
                            }
                        } else {
                            if (!definitionIdList.contains(xsr.getAttributeValue(null, "id"))) {
                                transformXMLStream(xsr, xsw);
                            } else {
                                skipXMLStream(xsr);
                            }
                        }
                        //                            }
                    }
                    xsr.nextTag();
                }
            } catch (XMLStreamException ex) {
                Exceptions.printStackTrace(ex);
            }
        }

        JAXBElement<Definitions> je = new JAXBElement<Definitions>(
                new QName("http://jbatchsuite.java.net", "definitions", "jbatchnb"), Definitions.class,
                definitions);
        if (jobContext == null) {
            jobContext = JAXBContext.newInstance(new Class<?>[] { ShapeDesign.class, Definitions.class });
        }
        if (jobMarshaller == null) {
            jobMarshaller = jobContext.createMarshaller();
        }

        // output pretty printed
        jobMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        jobMarshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
        //          jobMarshaller.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, "http://www.omg.org/spec/Batch/20100524/MODEL http://www.omg.org/spec/Batch/2.0/20100501/Batch20.xsd");
        jobMarshaller.setEventHandler(new ValidateJAXB());
        jobMarshaller.marshal(je, System.out);
        jobMarshaller.marshal(je, xsw);

        //            xsw.writeEndElement();
        xsw.writeEndDocument();
        xsw.close();

        //            StringWriter sw = new StringWriter();
        //            jobMarshaller.marshal(file.getDefinitionElement(), sw);
        //            FileUtils.writeStringToFile(savedFile, sw.toString().replaceFirst("xmlns:ns[A-Za-z\\d]{0,3}=\"http://www.omg.org/spec/Batch/20100524/MODEL\"",
        //                    "xmlns=\"http://www.omg.org/spec/Batch/20100524/MODEL\""));
    } catch (JAXBException ex) {
        Exceptions.printStackTrace(ex);
    } catch (IOException ex) {
        Exceptions.printStackTrace(ex);
    } catch (XMLStreamException ex) {
        Exceptions.printStackTrace(ex);
    }

}

From source file:org.opendaylight.controller.config.persist.storage.file.xml.model.Config.java

public static Config fromXml(File from) {
    if (isEmpty(from)) {
        return new Config();
    }//  ww  w .j av  a2  s .  c o m

    try {
        JAXBContext jaxbContext = JAXBContext.newInstance(Config.class);
        Unmarshaller um = jaxbContext.createUnmarshaller();
        XMLInputFactory xif = XMLInputFactory.newFactory();
        xif.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false);
        xif.setProperty(XMLInputFactory.SUPPORT_DTD, false);
        XMLStreamReader xsr = xif.createXMLStreamReader(new StreamSource(from));
        return ((Config) um.unmarshal(xsr));
    } catch (JAXBException | XMLStreamException e) {
        throw new PersistException("Unable to restore configuration", e);
    }
}

From source file:org.silverpeas.core.admin.component.PersonalComponentRegistry.java

private static PersonalComponent loadComponent(File descriptor) {
    try {/*from w w  w  .  ja  va2  s.  c  om*/
        JAXBContext context = JAXBContext.newInstance("org.silverpeas.core.admin.component.model");
        Unmarshaller unmarshaller = context.createUnmarshaller();
        try (InputStream in = new FileInputStream(descriptor)) {
            XMLInputFactory factory = XMLInputFactory.newFactory();
            return (unmarshaller.unmarshal(factory.createXMLStreamReader(in), PersonalComponent.class))
                    .getValue();
        }
    } catch (IOException | JAXBException | XMLStreamException e) {
        throw new SilverpeasRuntimeException(e.getMessage(), e);
    }
}