java类javax.xml.stream.XMLInputFactory的实例源码

IssueTracker70.java 文件源码 项目:openjdk-jdk10 阅读 17 收藏 0 点赞 0 评论 0
private void testGetAttributeValueWithNs(String nameSpace, String attrName, Consumer<String> checker) throws Exception {
    XMLInputFactory xif = XMLInputFactory.newInstance();
    XMLStreamReader xsr = xif.createXMLStreamReader(new FileInputStream(testFile));

    while (xsr.hasNext()) {
        xsr.next();
        if (xsr.isStartElement()) {
            String v;
            v = xsr.getAttributeValue(nameSpace, attrName);
            checker.accept(v);
        }
    }
}
Issue44Test.java 文件源码 项目:openjdk-jdk10 阅读 17 收藏 0 点赞 0 评论 0
@Test
public void testStartElement() {
    try {
        XMLInputFactory xif = XMLInputFactory.newInstance();
        // File file = new File("./tests/XMLStreamReader/sgml.xml");
        // FileInputStream inputStream = new FileInputStream(file);
        XMLStreamReader xsr = xif.createXMLStreamReader(this.getClass().getResourceAsStream("sgml.xml"));

        xsr.getName();
    } catch (IllegalStateException ise) {
        // expected
        System.out.println(ise.getMessage());
    } catch (Exception e) {
        e.printStackTrace();
        Assert.fail("Exception occured: " + e.getMessage());
    }
}
XlsxSheetContentParser.java 文件源码 项目:rapidminer 阅读 21 收藏 0 点赞 0 评论 0
/**
 * Closes the current open {@link XMLStreamReader} and creates a new one which starts the
 * reading process at the first row. It is assumed the the XLSX content and operator
 * configuration remain the same.
 *
 * @param factory
 *            the {@link XMLInputFactory} that should be used to open the
 *            {@link XMLStreamReader}.
 *
 * @throws IOException
 *             if an I/O error has occurred
 * @throws XMLStreamException
 *             if there are errors freeing associated XML reader resources or creating a new XML
 *             reader
 */
void reset(XMLInputFactory xmlFactory) throws IOException, XMLStreamException {

    // close open file and reader object
    close();

    // create new file and stream reader objects
    xlsxZipFile = new ZipFile(xlsxFile);
    ZipEntry workbookZipEntry = xlsxZipFile.getEntry(workbookZipEntryPath);
    if (workbookZipEntry == null) {
        throw new FileNotFoundException(
                "XLSX file is malformed. Reason: Selected workbook is missing in XLSX file. Path: "
                        + workbookZipEntryPath);
    }
    InputStream inputStream = xlsxZipFile.getInputStream(workbookZipEntry);
    reader = xmlFactory.createXMLStreamReader(new InputStreamReader(inputStream, encoding));

    // reset other variables
    currentRowIndex = -1;
    parsedRowIndex = -1;
    currentRowContent = null;
    nextRowWithContent = null;
    hasMoreContent = true;
    Arrays.fill(emptyColumn, true);
}
IssueTracker24.java 文件源码 项目:openjdk-jdk10 阅读 19 收藏 0 点赞 0 评论 0
@Test
public void testInconsistentGetPrefixBehaviorWhenNoPrefix() throws Exception {
    String xml = "<root><child xmlns='foo'/><anotherchild/></root>";

    XMLInputFactory factory = XMLInputFactory.newInstance();
    XMLStreamReader r = factory.createXMLStreamReader(new StringReader(xml));
    r.require(XMLStreamReader.START_DOCUMENT, null, null);
    r.next();
    r.require(XMLStreamReader.START_ELEMENT, null, "root");
    Assert.assertEquals(r.getPrefix(), "", "prefix should be empty string");
    r.next();
    r.require(XMLStreamReader.START_ELEMENT, null, "child");
    r.next();
    r.next();
    r.require(XMLStreamReader.START_ELEMENT, null, "anotherchild");
    Assert.assertEquals(r.getPrefix(), "", "prefix should be empty string");
}
StreamReaderTest.java 文件源码 项目:openjdk-jdk10 阅读 18 收藏 0 点赞 0 评论 0
/**
 * Verifies that after switching to a different XML Version (1.1), the parser
 * is initialized properly (the listener was not registered in this case).
 *
 * @param path the path to XML source
 * @throws Exception
 */
@Test(dataProvider = "getPaths")
public void testSwitchXMLVersions(String path) throws Exception {
    XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance();
    xmlInputFactory.setProperty("javax.xml.stream.isCoalescing", true);
    XMLStreamReader xmlStreamReader = xmlInputFactory.createXMLStreamReader(
            this.getClass().getResourceAsStream(path));

    while (xmlStreamReader.hasNext()) {
        int event = xmlStreamReader.next();
        if (event == XMLStreamConstants.START_ELEMENT) {
            if (xmlStreamReader.getLocalName().equals("body")) {
                String elementText = xmlStreamReader.getElementText();
                Assert.assertTrue(!elementText.contains("</body>"),
                        "Fail: elementText contains </body>");
            }
        }
    }
}
Jsr173MR1Req5Test.java 文件源码 项目:openjdk-jdk10 阅读 17 收藏 0 点赞 0 评论 0
@Test
public void testAttributeCountNoNS() {
    XMLInputFactory ifac = XMLInputFactory.newInstance();

    try {
        // Turn off NS awareness to count xmlns as attributes
        ifac.setProperty("javax.xml.stream.isNamespaceAware", Boolean.FALSE);

        XMLStreamReader re = ifac.createXMLStreamReader(getClass().getResource(INPUT_FILE1).toExternalForm(),
                this.getClass().getResourceAsStream(INPUT_FILE1));
        while (re.hasNext()) {
            int event = re.next();
            if (event == XMLStreamConstants.START_ELEMENT) {
                // System.out.println("#attrs = " + re.getAttributeCount());
                Assert.assertTrue(re.getAttributeCount() == 3);
            }
        }
        re.close();
    } catch (Exception e) {
        e.printStackTrace();
        Assert.fail("Exception occured: " + e.getMessage());
    }
}
BaseStAXUT.java 文件源码 项目:openjdk-jdk10 阅读 21 收藏 0 点赞 0 评论 0
/**
 * @return True if setting succeeded, and property supposedly was
 *         succesfully set to the value specified; false if there was a
 *         problem.
 */
protected static boolean setNamespaceAware(XMLInputFactory f, boolean state) throws XMLStreamException {
    try {
        f.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, state ? Boolean.TRUE : Boolean.FALSE);

        /*
         * 07-Sep-2005, TSa: Let's not assert, but instead let's see if it
         * sticks. Some implementations might choose to silently ignore
         * setting, at least for 'false'?
         */
        return (isNamespaceAware(f) == state);
    } catch (IllegalArgumentException e) {
        /*
         * Let's assume, then, that the property (or specific value for it)
         * is NOT supported...
         */
        return false;
    }
}
UnderOverVoltageSecurityIndexTest.java 文件源码 项目:powsybl-core 阅读 17 收藏 0 点赞 0 评论 0
@Test
public void testXml() throws IOException, XMLStreamException {
    String xml = "<?xml version=\"1.0\" ?><index name=\"underovervoltage\"><vx>0.5</vx></index>";
    XMLInputFactory xmlif = XMLInputFactory.newInstance();
    UnderOverVoltageSecurityIndex index;
    try (Reader reader = new StringReader(xml)) {
        XMLStreamReader xmlReader = xmlif.createXMLStreamReader(reader);
        try {
            index = UnderOverVoltageSecurityIndex.fromXml("c1", xmlReader);
        } finally {
            xmlReader.close();
        }
    }
    assertTrue(index.getIndexValue() == 0.5d);
    assertEquals(xml, index.toXml());
}
SmallSignalSecurityIndexTest.java 文件源码 项目:powsybl-core 阅读 16 收藏 0 点赞 0 评论 0
@Test
public void testXml() throws IOException, XMLStreamException {
    String xml = "<?xml version=\"1.0\" ?><index name=\"smallsignal\"><matrix name=\"gmi\"><m><r>0.5</r></m></matrix><matrix name=\"ami\"><m><r>1.0 2.0</r></m></matrix><matrix name=\"smi\"><m><r>3.0 4.0</r><r>5.0 6.0</r></m></matrix></index>";
    XMLInputFactory xmlif = XMLInputFactory.newInstance();
    SmallSignalSecurityIndex index;
    try (Reader reader = new StringReader(xml)) {
        XMLStreamReader xmlReader = xmlif.createXMLStreamReader(reader);
        try {
            index = SmallSignalSecurityIndex.fromXml("c1", xmlReader);
        } finally {
            xmlReader.close();
        }
    }
    assertTrue(index.getGmi() == 0.5d);
    assertTrue(Arrays.equals(index.getAmi(), new double[] {1, 2}));
    assertTrue(Arrays.deepEquals(index.getSmi(), new double[][] {new double[] {3, 4}, new double[] {5, 6}}));
    assertEquals(xml, index.toXml());
}
TsoUndervoltageSecurityIndexTest.java 文件源码 项目:powsybl-core 阅读 25 收藏 0 点赞 0 评论 0
@Test
public void testXml() throws IOException, XMLStreamException {
    String xml = "<?xml version=\"1.0\" ?><index name=\"tso-undervoltage\"><computation-succeed>true</computation-succeed><undervoltage-count>1</undervoltage-count></index>";
    XMLInputFactory xmlif = XMLInputFactory.newInstance();
    TsoUndervoltageSecurityIndex index;
    try (Reader reader = new StringReader(xml)) {
        XMLStreamReader xmlReader = xmlif.createXMLStreamReader(reader);
        try {
            index = TsoUndervoltageSecurityIndex.fromXml("c1", xmlReader);
        } finally {
            xmlReader.close();
        }
    }
    assertTrue(index.getUndervoltageCount() == 1);
    assertEquals(xml, index.toXml());
}
TsoSynchroLossSecurityIndexTest.java 文件源码 项目:powsybl-core 阅读 17 收藏 0 点赞 0 评论 0
@Test
public void testXml() throws IOException, XMLStreamException {
    String xml = "<?xml version=\"1.0\" ?><index name=\"tso-synchro-loss\"><synchro-loss-count>1</synchro-loss-count></index>";
    XMLInputFactory xmlif = XMLInputFactory.newInstance();
    TsoSynchroLossSecurityIndex index;
    try (Reader reader = new StringReader(xml)) {
        XMLStreamReader xmlReader = xmlif.createXMLStreamReader(reader);
        try {
            index = TsoSynchroLossSecurityIndex.fromXml("c1", xmlReader);
        } finally {
            xmlReader.close();
        }
    }
    assertTrue(index.getSynchroLossCount() == 1);
    assertEquals(xml, index.toXml());
}
OverloadSecurityIndexTest.java 文件源码 项目:powsybl-core 阅读 17 收藏 0 点赞 0 评论 0
@Test
public void testXml() throws IOException, XMLStreamException {
    String xml = "<?xml version=\"1.0\" ?><index name=\"overload\"><fx>0.5</fx></index>";
    XMLInputFactory xmlif = XMLInputFactory.newInstance();
    OverloadSecurityIndex index;
    try (Reader reader = new StringReader(xml)) {
        XMLStreamReader xmlReader = xmlif.createXMLStreamReader(reader);
        try {
            index = OverloadSecurityIndex.fromXml("c1", xmlReader);
        } finally {
            xmlReader.close();
        }
    }
    assertTrue(index.getIndexValue() == 0.5d);
    assertEquals(xml, index.toXml());
}
NamespaceTest.java 文件源码 项目:openjdk-jdk10 阅读 20 收藏 0 点赞 0 评论 0
@Test
public void testChildElementNamespace() {
    try {
        XMLInputFactory xif = XMLInputFactory.newInstance();
        xif.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, Boolean.TRUE);
        InputStream is = new java.io.ByteArrayInputStream(getXML().getBytes());
        XMLStreamReader sr = xif.createXMLStreamReader(is);
        while (sr.hasNext()) {
            int eventType = sr.next();
            if (eventType == XMLStreamConstants.START_ELEMENT) {
                if (sr.getLocalName().equals(childElement)) {
                    QName qname = sr.getName();
                    Assert.assertTrue(qname.getPrefix().equals(prefix) && qname.getNamespaceURI().equals(namespaceURI)
                            && qname.getLocalPart().equals(childElement));
                }
            }
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}
XmlProcessBase.java 文件源码 项目:mycat-src-1.6.1-RELEASE 阅读 19 收藏 0 点赞 0 评论 0
/**
 * 默认转换将指定的xml转化为
* 方法描述
* @param inputStream
* @param fileName
* @return
* @throws JAXBException
* @throws XMLStreamException
* @创建日期 2016年9月16日
*/
public Object baseParseXmlToBean(String fileName) throws JAXBException, XMLStreamException {
    // 搜索当前转化的文件
    InputStream inputStream = XmlProcessBase.class.getResourceAsStream(fileName);

    // 如果能够搜索到文件
    if (inputStream != null) {
        // 进行文件反序列化信息
        XMLInputFactory xif = XMLInputFactory.newFactory();
        xif.setProperty(XMLInputFactory.SUPPORT_DTD, false);
        XMLStreamReader xmlRead = xif.createXMLStreamReader(new StreamSource(inputStream));

        return unmarshaller.unmarshal(xmlRead);
    }

    return null;
}
DefaultAttributeTest.java 文件源码 项目:openjdk-jdk10 阅读 21 收藏 0 点赞 0 评论 0
@Test
public void testStreamReader() {
    XMLInputFactory ifac = XMLInputFactory.newInstance();
    XMLOutputFactory ofac = XMLOutputFactory.newInstance();

    try {
        ifac.setProperty(ifac.IS_REPLACING_ENTITY_REFERENCES, new Boolean(false));

        XMLStreamReader re = ifac.createXMLStreamReader(this.getClass().getResource(INPUT_FILE).toExternalForm(),
                this.getClass().getResourceAsStream(INPUT_FILE));

        while (re.hasNext()) {
            int event = re.next();
            if (event == XMLStreamConstants.START_ELEMENT && re.getLocalName().equals("bookurn")) {
                Assert.assertTrue(re.getAttributeCount() == 0, "No attributes are expected for <bookurn> ");
                Assert.assertTrue(re.getNamespaceCount() == 2, "Two namespaces are expected for <bookurn> ");
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        Assert.fail("Exception occured: " + e.getMessage());
    }
}
StreamReaderTest.java 文件源码 项目:openjdk-jdk10 阅读 19 收藏 0 点赞 0 评论 0
/**
 * CR 6631264 / sjsxp Issue 45:
 * https://sjsxp.dev.java.net/issues/show_bug.cgi?id=45
 * XMLStreamReader.hasName() should return false for ENTITY_REFERENCE
 */
@Test
public void testHasNameOnEntityEvent() throws Exception {
    XMLInputFactory xif = XMLInputFactory.newInstance();
    xif.setProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES, false);
    XMLStreamReader r = xif.createXMLStreamReader(
            this.getClass().getResourceAsStream("ExternalDTD.xml"));
    while (r.next() != XMLStreamConstants.ENTITY_REFERENCE) {
        System.out.println("event type: " + r.getEventType());
        continue;
    }
    if (r.hasName()) {
        System.out.println("hasName returned true on ENTITY_REFERENCE event.");
    }
    Assert.assertFalse(r.hasName()); // fails
}
StAXSourceTest.java 文件源码 项目:openjdk-jdk10 阅读 28 收藏 0 点赞 0 评论 0
@Test
public final void testStAXSource2() throws XMLStreamException {
    XMLInputFactory ifactory = XMLInputFactory.newInstance();
    ifactory.setProperty("javax.xml.stream.supportDTD", Boolean.TRUE);

    StAXSource ss = new StAXSource(ifactory.createXMLStreamReader(getClass().getResource("5368141.xml").toString(),
            getClass().getResourceAsStream("5368141.xml")));
    DOMResult dr = new DOMResult();

    TransformerFactory tfactory = TransformerFactory.newInstance();
    try {
        Transformer transformer = tfactory.newTransformer();
        transformer.transform(ss, dr);
    } catch (Exception e) {
        Assert.fail(e.getMessage());
    }
}
SchemaHelper.java 文件源码 项目:Proyecto-DASI 阅读 29 收藏 0 点赞 0 评论 0
/** Attempt to construct the specified object from this XML string
 * @param xml the XML string to parse
 * @param xsdFile the name of the XSD schema that defines the object
 * @param objclass the class of the object requested
 * @return if successful, an instance of class objclass that captures the data in the XML string
 */
static public Object deserialiseObject(String xml, String xsdFile, Class<?> objclass) throws JAXBException, SAXException, XMLStreamException
{
    Object obj = null;
    JAXBContext jaxbContext = getJAXBContext(objclass);
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    final String schemaResourceFilename = new String(xsdFile);
    URL schemaURL = MalmoMod.class.getClassLoader().getResource(schemaResourceFilename);
    Schema schema = schemaFactory.newSchema(schemaURL);
    Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
    jaxbUnmarshaller.setSchema(schema);

    StringReader stringReader = new StringReader(xml);

    XMLInputFactory xif = XMLInputFactory.newFactory();
    xif.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false);
    xif.setProperty(XMLInputFactory.SUPPORT_DTD, false);
    XMLStreamReader XMLreader = xif.createXMLStreamReader(stringReader);

    obj = jaxbUnmarshaller.unmarshal(XMLreader);
    return obj;
}
FeatureConfigSnapshotHolder.java 文件源码 项目:hashsdn-controller 阅读 18 收藏 0 点赞 0 评论 0
public FeatureConfigSnapshotHolder(final ConfigFileInfo fileInfo,
                                   final Feature feature) throws JAXBException, XMLStreamException {
    Preconditions.checkNotNull(fileInfo);
    Preconditions.checkNotNull(fileInfo.getFinalname());
    Preconditions.checkNotNull(feature);
    this.fileInfo = fileInfo;
    this.featureChain.add(feature);
    // TODO extract utility method for umarshalling config snapshots
    JAXBContext jaxbContext = JAXBContext.newInstance(ConfigSnapshot.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(new File(fileInfo.getFinalname())));
    unmarshalled = (ConfigSnapshot) um.unmarshal(xsr);
}
StAXEventReader.java 文件源码 项目:OpenJSharp 阅读 20 收藏 0 点赞 0 评论 0
public StAXEventReader(XMLStreamReader reader) throws  XMLStreamException {
    _streamReader = reader ;
    _eventAllocator = (XMLEventAllocator)reader.getProperty(XMLInputFactory.ALLOCATOR);
    if(_eventAllocator == null){
        _eventAllocator = new StAXEventAllocatorBase();
    }
    //initialize
    if (_streamReader.hasNext())
    {
        _streamReader.next();
        _currentEvent =_eventAllocator.allocate(_streamReader);
        events[0] = _currentEvent;
        hasEvent = true;
    } else {
        throw new XMLStreamException(CommonResourceBundle.getInstance().getString("message.noElement"));
    }
}
XMLStreamReaderImpl.java 文件源码 项目:OpenJSharp 阅读 22 收藏 0 点赞 0 评论 0
/**
 * Resets this instance so that this instance is ready for reuse.
 */
public void reset(){
    fReuse = true;
    fEventType = 0 ;
    //reset entity manager
    fEntityManager.reset(fPropertyManager);
    //reset the scanner
    fScanner.reset(fPropertyManager);
    //REVISIT:this is too ugly -- we are getting XMLEntityManager and XMLEntityReader from
    //property manager, it should be only XMLEntityManager
    fDTDDecl = null;
    fEntityScanner = (XMLEntityScanner)fEntityManager.getEntityScanner()  ;
    //default value for this property is true. However, this should be false when using XMLEventReader... Ugh..
    //because XMLEventReader should not have defined state.
    fReaderInDefinedState = ((Boolean)fPropertyManager.getProperty(READER_IN_DEFINED_STATE)).booleanValue();
    fBindNamespaces = ((Boolean)fPropertyManager.getProperty(XMLInputFactory.IS_NAMESPACE_AWARE)).booleanValue();
    versionStr = null;
}
ProcessingInstructionTest.java 文件源码 项目:openjdk-jdk10 阅读 20 收藏 0 点赞 0 评论 0
@Test
public void testPITargetAndData() {
    try {
        XMLInputFactory xif = XMLInputFactory.newInstance();
        String PITarget = "soffice";
        String PIData = "WebservicesArchitecture";
        String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<?" + PITarget + " " + PIData + "?>" + "<foo></foo>";
        // System.out.println("XML = " + xml) ;
        InputStream is = new java.io.ByteArrayInputStream(xml.getBytes());
        XMLStreamReader sr = xif.createXMLStreamReader(is);
        while (sr.hasNext()) {
            int eventType = sr.next();
            if (eventType == XMLStreamConstants.PROCESSING_INSTRUCTION) {
                String target = sr.getPITarget();
                String data = sr.getPIData();
                Assert.assertTrue(target.equals(PITarget) && data.equals(PIData));
            }
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}
SchemaInfo.java 文件源码 项目:elastic-db-tools-for-java 阅读 20 收藏 0 点赞 0 评论 0
/**
 * Initializes a new instance of the <see cref="SchemaInfo"/> class.
 */
public SchemaInfo(ResultSet reader,
        int offset) {
    try (StringReader sr = new StringReader(reader.getSQLXML(offset).getString())) {
        JAXBContext jc = JAXBContext.newInstance(SchemaInfo.class);

        XMLInputFactory xif = XMLInputFactory.newFactory();
        xif.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false);
        xif.setProperty(XMLInputFactory.SUPPORT_DTD, false);
        XMLStreamReader xsr = xif.createXMLStreamReader(sr);

        SchemaInfo schemaInfo = (SchemaInfo) jc.createUnmarshaller().unmarshal(xsr);

        this.referenceTables = new ReferenceTableSet(schemaInfo.getReferenceTables());
        this.shardedTables = new ShardedTableSet(schemaInfo.getShardedTables());
    }
    catch (SQLException | JAXBException | XMLStreamException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
SDDocumentSource.java 文件源码 项目:openjdk-jdk10 阅读 20 收藏 0 点赞 0 评论 0
/**
 * Creates a {@link SDDocumentSource} from {@link XMLStreamBuffer}.
 * @param systemId
 * @param xsb
 * @return
 */
public static SDDocumentSource create(final URL systemId, final XMLStreamBuffer xsb) {
    return new SDDocumentSource() {
        @Override
        public XMLStreamReader read(XMLInputFactory xif) throws XMLStreamException {
            return xsb.readAsXMLStreamReader();
        }

        @Override
        public XMLStreamReader read() throws XMLStreamException {
            return xsb.readAsXMLStreamReader();
        }

        @Override
        public URL getSystemId() {
            return systemId;
        }
    };
}
Bug6388460.java 文件源码 项目:openjdk-jdk10 阅读 19 收藏 0 点赞 0 评论 0
@Test
public void test() {
    try {

        Source source = new StreamSource(util.BOMInputStream.createStream("UTF-16BE", this.getClass().getResourceAsStream("Hello.wsdl.data")),
                    this.getClass().getResource("Hello.wsdl.data").toExternalForm());
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        TransformerFactory factory = TransformerFactory.newInstance();
        Transformer transformer = factory.newTransformer();
        transformer.transform(source, new StreamResult(baos));
        System.out.println(new String(baos.toByteArray()));
        ByteArrayInputStream bis = new ByteArrayInputStream(baos.toByteArray());
        InputSource inSource = new InputSource(bis);

        XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance();
        xmlInputFactory.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, Boolean.TRUE);
        XMLStreamReader reader = xmlInputFactory.createXMLStreamReader(inSource.getSystemId(), inSource.getByteStream());
        while (reader.hasNext()) {
            reader.next();
        }
    } catch (Exception ex) {
        ex.printStackTrace(System.err);
        Assert.fail("Exception occured: " + ex.getMessage());
    }
}
XmlPolicyModelUnmarshaller.java 文件源码 项目:openjdk-jdk10 阅读 24 收藏 0 点赞 0 评论 0
/**
 * Method checks if the storage type is supported and transforms it to XMLEventReader instance which is then returned.
 * Throws PolicyException if the transformation is not succesfull or if the storage type is not supported.
 *
 * @param storage An XMLEventReader instance.
 * @return The storage cast to an XMLEventReader.
 * @throws PolicyException If the XMLEventReader cast failed.
 */
private XMLEventReader createXMLEventReader(final Object storage)
        throws PolicyException {
    if (storage instanceof XMLEventReader) {
        return (XMLEventReader) storage;
    }
    else if (!(storage instanceof Reader)) {
        throw LOGGER.logSevereException(new PolicyException(LocalizationMessages.WSP_0022_STORAGE_TYPE_NOT_SUPPORTED(storage.getClass().getName())));
    }

    try {
        return XMLInputFactory.newInstance().createXMLEventReader((Reader) storage);
    } catch (XMLStreamException e) {
        throw LOGGER.logSevereException(new PolicyException(LocalizationMessages.WSP_0014_UNABLE_TO_INSTANTIATE_READER_FOR_STORAGE(), e));
    }

}
Bug6472982Test.java 文件源码 项目:openjdk-jdk10 阅读 25 收藏 0 点赞 0 评论 0
@Test
public void testNamespaceContext() {
    try {
        XMLInputFactory xif = XMLInputFactory.newInstance();
        xif.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, Boolean.TRUE);
        InputStream is = new java.io.ByteArrayInputStream(getXML().getBytes());
        XMLStreamReader sr = xif.createXMLStreamReader(is);
        NamespaceContext context = sr.getNamespaceContext();
        Assert.assertTrue(context.getPrefix("") == null);

    } catch (IllegalArgumentException iae) {
        Assert.fail("NamespacePrefix#getPrefix() should not throw an IllegalArgumentException for empty uri. ");
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}
StAXEventReader.java 文件源码 项目:openjdk-jdk10 阅读 24 收藏 0 点赞 0 评论 0
public StAXEventReader(XMLStreamReader reader) throws  XMLStreamException {
    _streamReader = reader ;
    _eventAllocator = (XMLEventAllocator)reader.getProperty(XMLInputFactory.ALLOCATOR);
    if(_eventAllocator == null){
        _eventAllocator = new StAXEventAllocatorBase();
    }
    //initialize
    if (_streamReader.hasNext())
    {
        _streamReader.next();
        _currentEvent =_eventAllocator.allocate(_streamReader);
        events[0] = _currentEvent;
        hasEvent = true;
    } else {
        throw new XMLStreamException(CommonResourceBundle.getInstance().getString("message.noElement"));
    }
}
Config.java 文件源码 项目:hashsdn-controller 阅读 27 收藏 0 点赞 0 评论 0
public static Config fromXml(final File from) {
    if(isEmpty(from)) {
        return new Config();
    }

    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);
    }
}
DefaultFactoryWrapperTest.java 文件源码 项目:openjdk-jdk10 阅读 18 收藏 0 点赞 0 评论 0
@DataProvider(name = "jaxpFactories")
public Object[][] jaxpFactories() throws Exception {
    return new Object[][] {
            { DocumentBuilderFactory.newInstance(), (Produce)factory -> ((DocumentBuilderFactory)factory).newDocumentBuilder() },
            { SAXParserFactory.newInstance(), (Produce)factory -> ((SAXParserFactory)factory).newSAXParser() },
            { SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI), (Produce)factory -> ((SchemaFactory)factory).newSchema() },
            { TransformerFactory.newInstance(), (Produce)factory -> ((TransformerFactory)factory).newTransformer() },
            { XMLEventFactory.newInstance(), (Produce)factory -> ((XMLEventFactory)factory).createStartDocument() },
            { XMLInputFactory.newInstance(), (Produce)factory -> ((XMLInputFactory)factory).createXMLEventReader(new StringReader("")) },
            { XMLOutputFactory.newInstance(), (Produce)factory -> ((XMLOutputFactory)factory).createXMLEventWriter(new StringWriter()) },
            { XPathFactory.newInstance(), (Produce)factory -> ((XPathFactory)factory).newXPath() },
            { DatatypeFactory.newInstance(), (Produce)factory -> ((DatatypeFactory)factory).newXMLGregorianCalendar() }
    };
}


问题


面经


文章

微信
公众号

扫码关注公众号