javax.xml.stream.XMLInputFactory Java Examples
The following examples show how to use
javax.xml.stream.XMLInputFactory.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Jaxb2CollectionHttpMessageConverterTests.java From spring-analysis-note with MIT License | 6 votes |
@Test @SuppressWarnings("unchecked") public void readXmlRootElementExternalEntityEnabled() throws Exception { Resource external = new ClassPathResource("external.txt", getClass()); String content = "<!DOCTYPE root [" + " <!ELEMENT external ANY >\n" + " <!ENTITY ext SYSTEM \"" + external.getURI() + "\" >]>" + " <list><rootElement><type s=\"1\"/><external>&ext;</external></rootElement></list>"; MockHttpInputMessage inputMessage = new MockHttpInputMessage(content.getBytes("UTF-8")); Jaxb2CollectionHttpMessageConverter<?> c = new Jaxb2CollectionHttpMessageConverter<Collection<Object>>() { @Override protected XMLInputFactory createXmlInputFactory() { XMLInputFactory inputFactory = XMLInputFactory.newInstance(); inputFactory.setProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES, true); return inputFactory; } }; Collection<RootElement> result = c.read(rootElementListType, null, inputMessage); assertEquals(1, result.size()); assertEquals("Foo Bar", result.iterator().next().external); }
Example #2
Source File: TsoGeneratorSpeedAutomatonTest.java From powsybl-core with Mozilla Public License 2.0 | 6 votes |
@Test public void testXml() throws IOException, XMLStreamException { String xml = "<?xml version=\"1.0\" ?><index name=\"tso-generator-speed-automaton\"><onUnderSpeedDisconnectedGenerators><gen>a</gen><gen>b</gen></onUnderSpeedDisconnectedGenerators><onOverSpeedDisconnectedGenerators><gen>c</gen></onOverSpeedDisconnectedGenerators></index>"; XMLInputFactory xmlif = XMLInputFactory.newInstance(); TsoGeneratorSpeedAutomaton index; try (Reader reader = new StringReader(xml)) { XMLStreamReader xmlReader = xmlif.createXMLStreamReader(reader); try { index = TsoGeneratorSpeedAutomaton.fromXml("c1", xmlReader); } finally { xmlReader.close(); } } assertTrue(index.getOnUnderSpeedDiconnectedGenerators().equals(Arrays.asList("a", "b"))); assertTrue(index.getOnOverSpeedDiconnectedGenerators().equals(Arrays.asList("c"))); assertEquals(xml, index.toXml()); }
Example #3
Source File: PersistentResourceXMLParserTestCase.java From wildfly-core with GNU Lesser General Public License v2.1 | 6 votes |
@Test public void testChildlessResource() throws Exception { MyParser parser = new ChildlessParser(); String xml = "<subsystem xmlns=\"" + MyParser.NAMESPACE + "\">" + " <cluster attr1=\"alice\"/>" + "</subsystem>"; StringReader strReader = new StringReader(xml); XMLMapper mapper = XMLMapper.Factory.create(); mapper.registerRootElement(new QName(MyParser.NAMESPACE, "subsystem"), parser); XMLStreamReader reader = XMLInputFactory.newInstance().createXMLStreamReader(new StreamSource(strReader)); List<ModelNode> operations = new ArrayList<>(); mapper.parseDocument(operations, reader); ModelNode subsystem = opsToModel(operations); StringWriter stringWriter = new StringWriter(); XMLExtendedStreamWriter xmlStreamWriter = createXMLStreamWriter(XMLOutputFactory.newInstance() .createXMLStreamWriter(stringWriter)); SubsystemMarshallingContext context = new SubsystemMarshallingContext(subsystem, xmlStreamWriter); mapper.deparseDocument(parser, context, xmlStreamWriter); String out = stringWriter.toString(); Assert.assertEquals(normalizeXML(xml), normalizeXML(out)); }
Example #4
Source File: Bug6388460.java From openjdk-jdk9 with GNU General Public License v2.0 | 6 votes |
@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()); } }
Example #5
Source File: RDBMSDataSourceReader.java From micro-integrator with Apache License 2.0 | 6 votes |
public static RDBMSConfiguration loadConfig(String xmlConfiguration) throws DataSourceException { try { xmlConfiguration = CarbonUtils.replaceSystemVariablesInXml(xmlConfiguration); JAXBContext ctx = JAXBContext.newInstance(RDBMSConfiguration.class); XMLInputFactory inputFactory = XMLInputFactory.newInstance(); inputFactory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false); inputFactory.setProperty(XMLInputFactory.SUPPORT_DTD, false); XMLStreamReader xmlReader = inputFactory.createXMLStreamReader(new StringReader(xmlConfiguration)); return (RDBMSConfiguration) ctx.createUnmarshaller().unmarshal(xmlReader); } catch (Exception e) { throw new DataSourceException("Error in loading RDBMS configuration: " + e.getMessage(), e); } }
Example #6
Source File: Configuration.java From Flink-CEPplus with Apache License 2.0 | 6 votes |
private XMLStreamReader parse(InputStream is, String systemIdStr, boolean restricted) throws IOException, XMLStreamException { if (!quietmode) { LOG.debug("parsing input stream " + is); } if (is == null) { return null; } SystemId systemId = SystemId.construct(systemIdStr); ReaderConfig readerConfig = XML_INPUT_FACTORY.createPrivateConfig(); if (restricted) { readerConfig.setProperty(XMLInputFactory.SUPPORT_DTD, false); } return XML_INPUT_FACTORY.createSR(readerConfig, systemId, StreamBootstrapper.getInstance(null, systemId, is), false, true); }
Example #7
Source File: XmlProcessBase.java From Mycat2 with GNU General Public License v3.0 | 6 votes |
/** * 默认转换将指定的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; }
Example #8
Source File: XmlFiles.java From packagedrone with Eclipse Public License 1.0 | 6 votes |
/** * Test if this file is an XML file * * @param path * the path to check * @return <code>true</code> if this is an XML file * @throws IOException * if the probing fails */ public static boolean isXml ( final Path path ) throws IOException { final XmlToolsFactory xml = Activator.getXmlToolsFactory (); final XMLInputFactory xin = xml.newXMLInputFactory (); try ( InputStream stream = new BufferedInputStream ( Files.newInputStream ( path ) ) ) { try { final XMLStreamReader reader = xin.createXMLStreamReader ( stream ); reader.next (); return true; } catch ( final XMLStreamException e ) { return false; } } }
Example #9
Source File: AtomServiceDocumentConsumerTest.java From olingo-odata2 with Apache License 2.0 | 6 votes |
private XMLStreamReader createStreamReader(final String fileName) throws IOException, EntityProviderException { XMLInputFactory factory = XMLInputFactory.newInstance(); factory.setProperty(XMLInputFactory.IS_VALIDATING, false); factory.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, true); InputStream in = ClassLoader.class.getResourceAsStream(fileName); if (in == null) { throw new IOException("Requested file '" + fileName + "' was not found."); } XMLStreamReader streamReader; try { streamReader = factory.createXMLStreamReader(in); } catch (XMLStreamException e) { throw new EntityProviderException(EntityProviderException.COMMON.addContent("Invalid Service Document")); } return streamReader; }
Example #10
Source File: XmlPolicyModelUnmarshaller.java From openjdk-jdk9 with GNU General Public License v2.0 | 6 votes |
/** * 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)); } }
Example #11
Source File: TestPayloadNameRequestWrapper.java From javamelody with Apache License 2.0 | 6 votes |
private boolean scanForChildTag(String tagName, String xml) throws XMLStreamException { final XMLInputFactory factory = XMLInputFactory.newInstance(); final XMLStreamReader reader = factory .createXMLStreamReader(new ByteArrayInputStream(xml.getBytes())); //advance to first tag (reader starts at "begin document") reader.next(); final boolean found = PayloadNameRequestWrapper.scanForChildTag(reader, tagName); if (found) { assertEquals("Found wrong tag", tagName, reader.getLocalName()); } reader.close(); return found; }
Example #12
Source File: XmlRecordSource.java From nifi with Apache License 2.0 | 6 votes |
public XmlRecordSource(final InputStream in, final boolean ignoreWrapper) throws IOException { try { final XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance(); // Avoid XXE Vulnerabilities xmlInputFactory.setProperty(XMLInputFactory.SUPPORT_DTD, false); xmlInputFactory.setProperty("javax.xml.stream.isSupportingExternalEntities", false); xmlEventReader = xmlInputFactory.createXMLEventReader(in); if (ignoreWrapper) { readStartElement(); } } catch (XMLStreamException e) { throw new IOException("Could not parse XML", e); } }
Example #13
Source File: XmlFilterReader.java From knox with Apache License 2.0 | 6 votes |
protected XmlFilterReader( Reader reader, UrlRewriteFilterContentDescriptor config ) throws IOException, XMLStreamException { this.reader = reader; this.config = config; writer = new StringWriter(); buffer = writer.getBuffer(); offset = 0; document = null; stack = new Stack<>(); isEmptyElement = false; factory = XMLInputFactory.newFactory(); //KNOX-620 factory.setProperty( XMLConstants.ACCESS_EXTERNAL_DTD, Boolean.FALSE ); //KNOX-620 factory.setProperty( XMLConstants.ACCESS_EXTERNAL_SCHEMA, Boolean.FALSE ); /* This disables DTDs entirely for that factory */ factory.setProperty(XMLInputFactory.SUPPORT_DTD, Boolean.FALSE); /* disable external entities */ factory.setProperty("javax.xml.stream.isSupportingExternalEntities", Boolean.FALSE); factory.setProperty( "javax.xml.stream.isReplacingEntityReferences", Boolean.FALSE ); factory.setProperty("http://java.sun.com/xml/stream/" + "properties/report-cdata-event", Boolean.TRUE); parser = factory.createXMLEventReader( reader ); }
Example #14
Source File: TestCharacterLimits.java From woodstox with Apache License 2.0 | 6 votes |
public void testLongCDATA() throws Exception { try { Reader reader = createLongReader("<![CDATA[", "]]>", true); XMLInputFactory factory = getNewInputFactory(); factory.setProperty(WstxInputProperties.P_MAX_TEXT_LENGTH, Integer.valueOf(50000)); XMLStreamReader xmlreader = factory.createXMLStreamReader(reader); while (xmlreader.next() != XMLStreamReader.START_ELEMENT) { } assertEquals(XMLStreamReader.CDATA, xmlreader.next()); while (xmlreader.next() != XMLStreamReader.START_ELEMENT) { } fail("Should have failed"); } catch (XMLStreamException ex) { _verifyTextLimitException(ex); } }
Example #15
Source File: DefaultAttributeTest.java From openjdk-jdk9 with GNU General Public License v2.0 | 6 votes |
@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()); } }
Example #16
Source File: XMLStreamReaderFactory.java From TencentKona-8 with GNU General Public License v2.0 | 5 votes |
public Zephyr(XMLInputFactory xif, Class clazz) throws NoSuchMethodException { zephyrClass = clazz; setInputSourceMethod = clazz.getMethod("setInputSource", InputSource.class); resetMethod = clazz.getMethod("reset"); try { // Turn OFF internal factory caching in Zephyr. // Santiago told me that this makes it thread-safe. xif.setProperty("reuse-instance", false); } catch (IllegalArgumentException e) { // falls through } this.xif = xif; }
Example #17
Source File: XStreamUnmarshallerTests.java From spring-analysis-note with MIT License | 5 votes |
@Test public void unmarshalStaxSourceXmlStreamReader() throws Exception { XMLInputFactory inputFactory = XMLInputFactory.newInstance(); XMLStreamReader streamReader = inputFactory.createXMLStreamReader(new StringReader(INPUT_STRING)); Source source = StaxUtils.createStaxSource(streamReader); Object flights = unmarshaller.unmarshal(source); testFlight(flights); }
Example #18
Source File: StreamingWorkbookReader.java From data-prep with Apache License 2.0 | 5 votes |
void loadSheets(XSSFReader reader, ReadOnlySharedStringsTable sst, StylesTable stylesTable, int rowCacheSize) throws IOException, InvalidFormatException, XMLStreamException { lookupSheetNames(reader.getWorkbookData()); Iterator<InputStream> iter = reader.getSheetsData(); int i = 0; while (iter.hasNext()) { XMLEventReader parser = XMLInputFactory.newInstance().createXMLEventReader(iter.next()); sheets.add(new StreamingSheet(sheetNames.get(i++), new StreamingSheetReader(sst, stylesTable, parser, rowCacheSize))); } }
Example #19
Source File: DefaultProcessValidatorTest.java From flowable-engine with Apache License 2.0 | 5 votes |
@Test public void testWarningError() throws UnsupportedEncodingException, XMLStreamException { String flowWithoutConditionNoDefaultFlow = "<?xml version='1.0' encoding='UTF-8'?>" + "<definitions id='definitions' xmlns='http://www.omg.org/spec/BPMN/20100524/MODEL' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:activiti='http://activiti.org/bpmn' targetNamespace='Examples'>" + " <process id='exclusiveGwDefaultSequenceFlow'> " + " <startEvent id='theStart' /> " + " <sequenceFlow id='flow1' sourceRef='theStart' targetRef='exclusiveGw' /> " + " <exclusiveGateway id='exclusiveGw' name='Exclusive Gateway' /> " + // no default = "flow3" !! " <sequenceFlow id='flow2' sourceRef='exclusiveGw' targetRef='theTask1'> " + " <conditionExpression xsi:type='tFormalExpression'>${input == 1}</conditionExpression> " + " </sequenceFlow> " + " <sequenceFlow id='flow3' sourceRef='exclusiveGw' targetRef='theTask2'/> " + // one would be OK " <sequenceFlow id='flow4' sourceRef='exclusiveGw' targetRef='theTask2'/> " + // but two unconditional not! " <userTask id='theTask1' name='Input is one' /> " + " <userTask id='theTask2' name='Default input' /> " + " </process>" + "</definitions>"; XMLInputFactory xif = XMLInputFactory.newInstance(); InputStreamReader in = new InputStreamReader(new ByteArrayInputStream(flowWithoutConditionNoDefaultFlow.getBytes()), "UTF-8"); XMLStreamReader xtr = xif.createXMLStreamReader(in); BpmnModel bpmnModel = new BpmnXMLConverter().convertToBpmnModel(xtr); Assert.assertNotNull(bpmnModel); List<ValidationError> allErrors = processValidator.validate(bpmnModel); Assert.assertEquals(1, allErrors.size()); Assert.assertTrue(allErrors.get(0).isWarning()); }
Example #20
Source File: ActProcessService.java From Shop-for-JavaWeb with MIT License | 5 votes |
/** * 将部署的流程转换为模型 * @param procDefId * @throws UnsupportedEncodingException * @throws XMLStreamException */ @Transactional(readOnly = false) public org.activiti.engine.repository.Model convertToModel(String procDefId) throws UnsupportedEncodingException, XMLStreamException { ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().processDefinitionId(procDefId).singleResult(); InputStream bpmnStream = repositoryService.getResourceAsStream(processDefinition.getDeploymentId(), processDefinition.getResourceName()); XMLInputFactory xif = XMLInputFactory.newInstance(); InputStreamReader in = new InputStreamReader(bpmnStream, "UTF-8"); XMLStreamReader xtr = xif.createXMLStreamReader(in); BpmnModel bpmnModel = new BpmnXMLConverter().convertToBpmnModel(xtr); BpmnJsonConverter converter = new BpmnJsonConverter(); ObjectNode modelNode = converter.convertToJson(bpmnModel); org.activiti.engine.repository.Model modelData = repositoryService.newModel(); modelData.setKey(processDefinition.getKey()); modelData.setName(processDefinition.getResourceName()); modelData.setCategory(processDefinition.getCategory());//.getDeploymentId()); modelData.setDeploymentId(processDefinition.getDeploymentId()); modelData.setVersion(Integer.parseInt(String.valueOf(repositoryService.createModelQuery().modelKey(modelData.getKey()).count()+1))); ObjectNode modelObjectNode = new ObjectMapper().createObjectNode(); modelObjectNode.put(ModelDataJsonConstants.MODEL_NAME, processDefinition.getName()); modelObjectNode.put(ModelDataJsonConstants.MODEL_REVISION, modelData.getVersion()); modelObjectNode.put(ModelDataJsonConstants.MODEL_DESCRIPTION, processDefinition.getDescription()); modelData.setMetaInfo(modelObjectNode.toString()); repositoryService.saveModel(modelData); repositoryService.addModelEditorSource(modelData.getId(), modelNode.toString().getBytes("utf-8")); return modelData; }
Example #21
Source File: JCA15TestCase.java From ironjacamar with Eclipse Public License 1.0 | 5 votes |
/** * Equal * @throws Exception In case of an error */ @Test public void testEqual() throws Exception { RaParser parser = new RaParser(); InputStream is1 = JCA15TestCase.class.getClassLoader(). getResourceAsStream("../../resources/test/spec/ra-1.5.xml"); assertNotNull(is1); XMLStreamReader xsr1 = XMLInputFactory.newInstance().createXMLStreamReader(is1); Connector c1 = parser.parse(xsr1); assertNotNull(c1); is1.close(); InputStream is2 = JCA15TestCase.class.getClassLoader(). getResourceAsStream("../../resources/test/spec/ra-1.5.xml"); assertNotNull(is2); XMLStreamReader xsr2 = XMLInputFactory.newInstance().createXMLStreamReader(is2); Connector c2 = parser.parse(xsr2); assertNotNull(c2); is2.close(); assertEquals(c1, c2); }
Example #22
Source File: StAXManager.java From jdk8u60 with GNU General Public License v2.0 | 5 votes |
public void setProperty(String name, Object value){ checkProperty(name); if (name.equals(XMLInputFactory.IS_VALIDATING) && Boolean.TRUE.equals(value)){ throw new IllegalArgumentException(CommonResourceBundle.getInstance().getString("message.validationNotSupported") + CommonResourceBundle.getInstance().getString("support_validation")); } else if (name.equals(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES) && Boolean.TRUE.equals(value)) { throw new IllegalArgumentException(CommonResourceBundle.getInstance().getString("message.externalEntities") + CommonResourceBundle.getInstance().getString("resolve_external_entities_")); } features.put(name,value); }
Example #23
Source File: StAXManager.java From openjdk-jdk9 with GNU General Public License v2.0 | 5 votes |
private void initConfigurableReaderProperties(){ //spec v1.0 default values features.put(XMLInputFactory.IS_NAMESPACE_AWARE, Boolean.TRUE); features.put(XMLInputFactory.IS_VALIDATING, Boolean.FALSE); features.put(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES, Boolean.TRUE); features.put(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, Boolean.TRUE); features.put(XMLInputFactory.IS_COALESCING, Boolean.FALSE); features.put(XMLInputFactory.SUPPORT_DTD, Boolean.FALSE); features.put(XMLInputFactory.REPORTER, null); features.put(XMLInputFactory.RESOLVER, null); features.put(XMLInputFactory.ALLOCATOR, null); features.put(STAX_NOTATIONS,null ); }
Example #24
Source File: MassageStoreAdminClient.java From product-ei with Apache License 2.0 | 5 votes |
public void addMessageStore(DataHandler dh) throws IOException, LocalEntryAdminException, XMLStreamException, Exception { messageStoreAdminServiceStub = this.setMessageStoreStubStub(); XMLStreamReader parser = XMLInputFactory.newInstance().createXMLStreamReader(dh.getInputStream()); StAXOMBuilder builder = new StAXOMBuilder(parser); OMElement localEntryElem = builder.getDocumentElement(); messageStoreAdminServiceStub.addMessageStore(localEntryElem.toString()); }
Example #25
Source File: PubchemParserTest.java From act with GNU General Public License v3.0 | 5 votes |
@Test public void testParserProcessesTheCorrectChemicals() throws Exception { File testFile = new File(this.getClass().getResource("CompoundTest.xml.gz").getFile()); String expectedInchi1 = "InChI=1S/C18H27FN2/c1-2-14-11-17(20-16-5-3-4-6-16)13-21(12-14)18-9-7-15(19)8-10-18/h7-10,14,16-17,20H,2-6,11-13H2,1H3"; String expectedSmiles1 = "CCC1CC(CN(C1)C2=CC=C(C=C2)F)NC3CCCC3"; String expectedCanonicalName1 = "N-cyclopentyl-5-ethyl-1-(4-fluorophenyl)piperidin-3-amine"; Long expectedPubchemId1 = 84000001L; Chemical testChemical1 = new Chemical(1L, expectedPubchemId1, expectedCanonicalName1, expectedSmiles1); testChemical1.setInchi(expectedInchi1); String expectedInchi2 = "InChI=1S/C16H23FN2/c17-13-5-3-9-16(11-13)19-10-4-8-15(12-19)18-14-6-1-2-7-14/h3,5,9,11,14-15,18H,1-2,4,6-8,10,12H2"; String expectedSmiles2 = "C1CCC(C1)NC2CCCN(C2)C3=CC(=CC=C3)F"; String expectedCanonicalName2 = "N-cyclopentyl-1-(3-fluorophenyl)piperidin-3-amine"; Long expectedPubchemId2 = 84000002L; Chemical testChemical2 = new Chemical(2L, expectedPubchemId2, expectedCanonicalName2, expectedSmiles2); testChemical2.setInchi(expectedInchi2); List<Chemical> expectedChemicals = new ArrayList<>(); expectedChemicals.add(testChemical1); expectedChemicals.add(testChemical2); XMLInputFactory factory = XMLInputFactory.newInstance(); XMLEventReader eventReader = factory.createXMLEventReader(new GZIPInputStream(new FileInputStream(testFile))); int counter = 0; Chemical actualChemical; while ((actualChemical = pubchemParser.extractNextChemicalFromXMLStream(eventReader)) != null) { Chemical expectedChemical = expectedChemicals.get(counter); assertEquals("Inchis parsed from the xml file should be the same as expected", expectedChemical.getInChI(), actualChemical.getInChI()); assertEquals("Canonical name parsed from the xml file should be the same as expected", expectedChemical.getCanon(), actualChemical.getCanon()); assertEquals("Smiles parsed from the xml file should be the same as expected", expectedChemical.getSmiles(), actualChemical.getSmiles()); assertEquals("Pubchem id parsed from the xml file should be the same as expected", expectedChemical.getPubchemID(), actualChemical.getPubchemID()); counter++; } assertEquals("Two chemicals should be parsed from the xml file", 2, counter); }
Example #26
Source File: EndpointTemplateAdminServiceClient.java From product-ei with Apache License 2.0 | 5 votes |
public void addEndpointTemplate(DataHandler dh) throws IOException, XMLStreamException { XMLStreamReader parser = XMLInputFactory.newInstance().createXMLStreamReader(dh.getInputStream()); //create the builder StAXOMBuilder builder = new StAXOMBuilder(parser); OMElement endpointTemplate = builder.getDocumentElement(); endpointTemplateAdminStub.addEndpointTemplate(endpointTemplate.toString()); }
Example #27
Source File: XMLDocumentFragmentScannerImpl.java From openjdk-8-source with GNU General Public License v2.0 | 5 votes |
public void reset(PropertyManager propertyManager){ super.reset(propertyManager); // other settings // fDocumentSystemId = null; fNamespaces = ((Boolean)propertyManager.getProperty(XMLInputFactory.IS_NAMESPACE_AWARE)).booleanValue(); fNotifyBuiltInRefs = false ; //fElementStack2.clear(); //fReplaceEntityReferences = true; //fSupportExternalEntities = true; Boolean bo = (Boolean)propertyManager.getProperty(XMLInputFactoryImpl.IS_REPLACING_ENTITY_REFERENCES); fReplaceEntityReferences = bo.booleanValue(); bo = (Boolean)propertyManager.getProperty(XMLInputFactoryImpl.IS_SUPPORTING_EXTERNAL_ENTITIES); fSupportExternalEntities = bo.booleanValue(); Boolean cdata = (Boolean)propertyManager.getProperty(Constants.ZEPHYR_PROPERTY_PREFIX + Constants.STAX_REPORT_CDATA_EVENT) ; if(cdata != null) fReportCdataEvent = cdata.booleanValue() ; Boolean coalesce = (Boolean)propertyManager.getProperty(XMLInputFactory.IS_COALESCING) ; if(coalesce != null) fIsCoalesce = coalesce.booleanValue(); fReportCdataEvent = fIsCoalesce ? false : (fReportCdataEvent && true) ; //if fIsCoalesce is set to true, set the value of fReplaceEntityReferences to true, //if fIsCoalesce is set to false, take the value of fReplaceEntityReferences as set by application fReplaceEntityReferences = fIsCoalesce ? true : fReplaceEntityReferences; // setup Driver //we dont need to do this -- nb. //setScannerState(SCANNER_STATE_CONTENT); //setDriver(fContentDriver); //fEntityManager.test(); // JAXP 1.5 features and properties XMLSecurityPropertyManager spm = (XMLSecurityPropertyManager) propertyManager.getProperty(XML_SECURITY_PROPERTY_MANAGER); fAccessExternalDTD = spm.getValue(XMLSecurityPropertyManager.Property.ACCESS_EXTERNAL_DTD); fSecurityManager = (XMLSecurityManager)propertyManager.getProperty(Constants.SECURITY_MANAGER); resetCommon(); }
Example #28
Source File: XmlUtil.java From openjdk-jdk8u with GNU General Public License v2.0 | 5 votes |
public static XMLInputFactory newXMLInputFactory(boolean secureXmlProcessingEnabled) { XMLInputFactory factory = XMLInputFactory.newInstance(); if (isXMLSecurityDisabled(secureXmlProcessingEnabled)) { // TODO-Miran: are those apppropriate defaults? factory.setProperty(XMLInputFactory.SUPPORT_DTD, false); factory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false); } return factory; }
Example #29
Source File: PropertyManager.java From hottub with GNU General Public License v2.0 | 5 votes |
/** * Important point: * 1. We are not exposing Xerces namespace property. Application should configure namespace through * Stax specific property. * */ private void initConfigurableReaderProperties(){ //spec default values supportedProps.put(XMLInputFactory.IS_NAMESPACE_AWARE, Boolean.TRUE); supportedProps.put(XMLInputFactory.IS_VALIDATING, Boolean.FALSE); supportedProps.put(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES, Boolean.TRUE); supportedProps.put(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, Boolean.TRUE); supportedProps.put(XMLInputFactory.IS_COALESCING, Boolean.FALSE); supportedProps.put(XMLInputFactory.SUPPORT_DTD, Boolean.TRUE); supportedProps.put(XMLInputFactory.REPORTER, null); supportedProps.put(XMLInputFactory.RESOLVER, null); supportedProps.put(XMLInputFactory.ALLOCATOR, null); supportedProps.put(STAX_NOTATIONS,null ); //zephyr (implementation) specific properties which can be set by the application. //interning is always done supportedProps.put(Constants.SAX_FEATURE_PREFIX + Constants.STRING_INTERNING_FEATURE , new Boolean(true)); //recognizing java encoding names by default supportedProps.put(Constants.XERCES_FEATURE_PREFIX + Constants.ALLOW_JAVA_ENCODINGS_FEATURE, new Boolean(true)) ; //in stax mode, namespace declarations are not added as attributes supportedProps.put(Constants.ADD_NAMESPACE_DECL_AS_ATTRIBUTE , Boolean.FALSE) ; supportedProps.put(Constants.READER_IN_DEFINED_STATE, new Boolean(true)); supportedProps.put(Constants.REUSE_INSTANCE, new Boolean(true)); supportedProps.put(Constants.ZEPHYR_PROPERTY_PREFIX + Constants.STAX_REPORT_CDATA_EVENT , new Boolean(false)); supportedProps.put(Constants.ZEPHYR_PROPERTY_PREFIX + Constants.IGNORE_EXTERNAL_DTD, Boolean.FALSE); supportedProps.put(Constants.XERCES_FEATURE_PREFIX + Constants.WARN_ON_DUPLICATE_ATTDEF_FEATURE, new Boolean(false)); supportedProps.put(Constants.XERCES_FEATURE_PREFIX + Constants.WARN_ON_DUPLICATE_ENTITYDEF_FEATURE, new Boolean(false)); supportedProps.put(Constants.XERCES_FEATURE_PREFIX + Constants.WARN_ON_UNDECLARED_ELEMDEF_FEATURE, new Boolean(false)); fSecurityManager = new XMLSecurityManager(true); supportedProps.put(SECURITY_MANAGER, fSecurityManager); fSecurityPropertyMgr = new XMLSecurityPropertyManager(); supportedProps.put(XML_SECURITY_PROPERTY_MANAGER, fSecurityPropertyMgr); }
Example #30
Source File: TopologyMarshaller.java From knox with Apache License 2.0 | 5 votes |
@Override public Topology readFrom(Class<Topology> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException, WebApplicationException { Topology topology = null; try { if (isReadable(type, genericType, annotations, mediaType)) { Map<String, Object> properties = Collections.emptyMap(); JAXBContext context = JAXBContext.newInstance(new Class[]{Topology.class}, properties); Unmarshaller u = context.createUnmarshaller(); u.setProperty(UnmarshallerProperties.MEDIA_TYPE, mediaType.getType() + "/" + mediaType.getSubtype()); if (mediaType.isCompatible(MediaType.APPLICATION_XML_TYPE)) { // Safeguard against entity injection (KNOX-1308) XMLInputFactory xif = XMLInputFactory.newFactory(); xif.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false); xif.setProperty(XMLInputFactory.SUPPORT_DTD, false); xif.setProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES, false); XMLStreamReader xsr = xif.createXMLStreamReader(new StreamSource(entityStream)); topology = (Topology) u.unmarshal(xsr); } else { topology = (Topology) u.unmarshal(entityStream); } } } catch (XMLStreamException | JAXBException e) { throw new IOException(e); } return topology; }