下面列出了怎么用org.xml.sax.InputSource的API类实例代码及写法,或者点击链接到github查看源代码。
private boolean pushReader(ExternalEntity next)
throws IOException, SAXException {
InputEntity r = InputEntity.getInputEntity(dtdHandler, locale);
InputSource s;
try {
s = next.getInputSource(resolver);
} catch (IOException e) {
String msg =
"unable to open the external entity from :" + next.systemId;
if (next.publicId != null)
msg += " (public id:" + next.publicId + ")";
SAXParseException spe = new SAXParseException(msg,
getPublicId(), getSystemId(), getLineNumber(), getColumnNumber(), e);
dtdHandler.fatalError(spe);
throw e;
}
r.init(s, next.name, in, next.isPE);
in = r;
return true;
}
private static XMLInputSource saxToXMLInputSource(InputSource sis) {
String publicId = sis.getPublicId();
String systemId = sis.getSystemId();
Reader charStream = sis.getCharacterStream();
if (charStream != null) {
return new XMLInputSource(publicId, systemId, null, charStream,
null);
}
InputStream byteStream = sis.getByteStream();
if (byteStream != null) {
return new XMLInputSource(publicId, systemId, null, byteStream,
sis.getEncoding());
}
return new XMLInputSource(publicId, systemId, null);
}
public static InputSource loadEffectivePom(
File moduleFile, MavenContext context)
throws IOException, InterruptedException {
MavenExecutor exec = context.build(moduleFile);
exec.evalEffectivePom(context);
if (0 != exec.getExitCode()) {
MavenLogger.LOG.warn(
"Err {} getting effective POM for {}\n\nMaven Console output >\n{}",
exec.getExitCode(), moduleFile.getPath(), exec.getOut());
}
String effPom = exec.getEffPom();
if (Strings.isNullOrEmpty(effPom)) {
MavenLogger.LOG.warn(
"Empty effective POM for {}\n\nMaven Console output >\n",
moduleFile.getPath(), exec.getOut());
}
StringReader reader = new StringReader(effPom);
return new InputSource(reader);
}
@Test
public void noNamespacePrefixes() throws Exception {
Assume.assumeTrue(wwwSpringframeworkOrgIsAccessible());
StringWriter stringWriter = new StringWriter();
AbstractStaxHandler handler = createStaxHandler(new StreamResult(stringWriter));
xmlReader.setContentHandler(handler);
xmlReader.setProperty("http://xml.org/sax/properties/lexical-handler", handler);
xmlReader.setFeature("http://xml.org/sax/features/namespaces", true);
xmlReader.setFeature("http://xml.org/sax/features/namespace-prefixes", false);
xmlReader.parse(new InputSource(new StringReader(COMPLEX_XML)));
assertThat(stringWriter.toString(), isSimilarTo(COMPLEX_XML).withNodeFilter(nodeFilter));
}
public Framework(final String name, final File bsFile) {
super(name, null);
try {
final File pathf = bsFile.getCanonicalFile().getParentFile().getParentFile().getParentFile();
path = pathf.getParentFile().getParentFile().getCanonicalPath();
} catch (IOException x) {
throw new RuntimeException(x);
}
binaries = findBinaries(path, name);
pkg = ClassGenerator.JOBJC_PACKAGE + "." + name.toLowerCase();
try {
rootNode = (Node)XPATH.evaluate("signatures", new InputSource(bsFile.getAbsolutePath()), XPathConstants.NODE);
} catch (final XPathExpressionException e) { throw new RuntimeException(e); }
protocols = new ArrayList<Protocol>();
categories = new ArrayList<Category>();
}
@Override
public InputSource resolveEntity (
String name,
String publicId,
String baseURI,
String systemId)
throws SAXException, IOException {
try {
if (shouldLoadAsResource(systemId)) {
log.debug("Loading entity '" + systemId + "' as resource");
return resourceToInputSource(publicId, systemId);
}
else {
return super.resolveEntity(publicId, systemId);
}
}
catch (Exception e) {
// not in spec but too bad
throw new PluginException("Error resolving entity: " + systemId + ": " + e, e);
}
}
@Test(dataProvider = "illegalCharactersData")
public void test(int character) throws Exception {
// Construct the XML document as a String
int[] cps = new int[]{character};
String txt = new String(cps, 0, cps.length);
String inxml = "<topElement attTest=\'" + txt + "\'/>";
String exceptionText = "NO EXCEPTION OBSERVED";
String hexString = "0x" + Integer.toHexString(character);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
dbf.setValidating(false);
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource isrc = new InputSource(new StringReader(inxml));
try {
db.parse(isrc);
} catch (SAXException e) {
exceptionText = e.toString();
}
System.out.println("Got Exception:" + exceptionText);
assertTrue(exceptionText.contains("attribute \"attTest\""));
assertTrue(exceptionText.contains("element is \"topElement\""));
assertTrue(exceptionText.contains("Unicode: " + hexString));
}
@Test
public void setFromXML() throws Exception {
String[] expected = new String[] { "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>",
"<SRE name=\"Hello\" mainClass=\"io.sarl.Boot\" libraryPath=\"" + this.path.toPortableString()
+ "\" standalone=\"true\">",
"<libraryLocation packageRootPath=\"\" sourcePath=\"\" systemLibraryPath=\"" + this.path.toPortableString()
+ "\"/>",
"<libraryLocation packageRootPath=\"\" sourcePath=\"\" systemLibraryPath=\"x.jar\"/>",
"<libraryLocation packageRootPath=\"\" sourcePath=\"\" systemLibraryPath=\"y.jar\"/>",
"<libraryLocation packageRootPath=\"\" sourcePath=\"\" systemLibraryPath=\"z.jar\"/>", "</SRE>", };
StringBuilder b = new StringBuilder();
for (String s : expected) {
b.append(s);
// b.append("\n");
}
try (ByteArrayInputStream bais = new ByteArrayInputStream(b.toString().getBytes())) {
DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
parser.setErrorHandler(new DefaultHandler());
Element root = parser.parse(new InputSource(bais)).getDocumentElement();
this.sre.setFromXML(root);
assertTrue(this.sre.isStandalone());
assertEquals(this.path, this.sre.getJarFile());
assertEquals("Hello", this.sre.getName());
assertEquals("io.sarl.Boot", this.sre.getMainClass());
}
}
/**
* Create and populate the entity as specified by its type and XML
* definition.
*
* @param entityTypeCode The Entity Type code.
* @param xml The XML of the associated entity.
* @return The populated entity.
* @throws ApsSystemException If errors detected while retrieving the
* entity.
*/
protected IApsEntity createEntityFromXml(String entityTypeCode, String xml) throws ApsSystemException {
try {
IApsEntity entityPrototype = this.getEntityPrototype(entityTypeCode);
SAXParserFactory parseFactory = SAXParserFactory.newInstance();
SAXParser parser = parseFactory.newSAXParser();
InputSource is = new InputSource(new StringReader(xml));
EntityHandler handler = this.getEntityHandler();
handler.initHandler(entityPrototype, this.getXmlAttributeRootElementName(), this.getCategoryManager());
parser.parse(is, handler);
return entityPrototype;
} catch (ParserConfigurationException | SAXException | IOException t) {
logger.error("Error detected while creating the entity. typecode: {} - xml: {}", entityTypeCode, xml, t);
throw new ApsSystemException("Error detected while creating the entity", t);
}
}
@Test(dataProvider = "illegalCharactersData")
public void test(int character) throws Exception {
// Construct the XML document as a String
int[] cps = new int[]{character};
String txt = new String(cps, 0, cps.length);
String inxml = "<topElement attTest=\'" + txt + "\'/>";
String exceptionText = "NO EXCEPTION OBSERVED";
String hexString = "0x" + Integer.toHexString(character);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
dbf.setValidating(false);
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource isrc = new InputSource(new StringReader(inxml));
try {
db.parse(isrc);
} catch (SAXException e) {
exceptionText = e.toString();
}
System.out.println("Got Exception:" + exceptionText);
assertTrue(exceptionText.contains("attribute \"attTest\""));
assertTrue(exceptionText.contains("element is \"topElement\""));
assertTrue(exceptionText.contains("Unicode: " + hexString));
}
public static <T> Object unmarshal(final Class<T> type, final InputStream in) throws ParserConfigurationException, SAXException, JAXBException {
final InputSource inputSource = new InputSource(in);
final SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setNamespaceAware(true);
factory.setValidating(false);
final JAXBContext ctx = JAXBContextFactory.newInstance(type);
final Unmarshaller unmarshaller = ctx.createUnmarshaller();
unmarshaller.setEventHandler(new ValidationEventHandler() {
public boolean handleEvent(final ValidationEvent validationEvent) {
System.out.println(validationEvent);
return false;
}
});
return unmarshaller.unmarshal(inputSource);
}
@Test
public void testGetChildElementsByTagNameNS() throws Exception
{
String xml = "<root><a xmlns='urn:test'/><b/><n:a xmlns:n='urn:test'/><c/></root>";
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(new StringReader(xml)));
Collection<Element> elements = DOMHelper.getChildElementsByTagNameNS(doc.getDocumentElement(), "urn:test", "a");
Assert.assertNotNull(elements);
Assert.assertEquals(2, elements.size());
for (Element element : elements)
{
Assert.assertEquals("a", element.getLocalName());
}
}
public static Map<String, Object> extractCustomAttributes(final String xml) {
final SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setNamespaceAware(true);
spf.setValidating(false);
try {
final SAXParser saxParser = spf.newSAXParser();
final XMLReader xmlReader = saxParser.getXMLReader();
final CustomAttributeHandler handler = new CustomAttributeHandler();
xmlReader.setContentHandler(handler);
xmlReader.parse(new InputSource(new StringReader(xml)));
return handler.getAttributes();
} catch (final Exception e) {
log.error(e.getMessage(), e);
return Collections.emptyMap();
}
}
/**
* Loads the document and updates build-time (latency) statistics
*/
public void loadDocument(String uri) {
try {
final long stamp = System.currentTimeMillis();
_dom = (DOMEnhancedForDTM)_dtmManager.getDTM(
new SAXSource(_reader, new InputSource(uri)),
false, null, true, false);
_dom.setDocumentURI(uri);
// The build time can be used for statistics for a better
// priority algorithm (currently round robin).
final long thisTime = System.currentTimeMillis() - stamp;
if (_buildTime > 0)
_buildTime = (_buildTime + thisTime) >>> 1;
else
_buildTime = thisTime;
}
catch (Exception e) {
_dom = null;
}
}
@Test
public void testTasksXML() throws JSONException, Exception {
WebResource r = resource();
Map<JobId, Job> jobsMap = appContext.getAllJobs();
for (JobId id : jobsMap.keySet()) {
String jobId = MRApps.toString(id);
ClientResponse response = r.path("ws").path("v1").path("history")
.path("mapreduce").path("jobs").path(jobId).path("tasks")
.accept(MediaType.APPLICATION_XML).get(ClientResponse.class);
assertEquals(MediaType.APPLICATION_XML_TYPE, response.getType());
String xml = response.getEntity(String.class);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xml));
Document dom = db.parse(is);
NodeList tasks = dom.getElementsByTagName("tasks");
assertEquals("incorrect number of elements", 1, tasks.getLength());
NodeList task = dom.getElementsByTagName("task");
verifyHsTaskXML(task, jobsMap.get(id));
}
}
public boolean eval() throws BuildException {
if (nullOrEmpty(fileName)) {
throw new BuildException("No file set");
}
File file = new File(fileName);
if (!file.exists() || file.isDirectory()) {
throw new BuildException(
"The specified file does not exist or is a directory");
}
if (nullOrEmpty(path)) {
throw new BuildException("No XPath expression set");
}
XPath xpath = XPathFactory.newInstance().newXPath();
InputSource inputSource = new InputSource(fileName);
Boolean result = Boolean.FALSE;
try {
result = (Boolean) xpath.evaluate(path, inputSource,
XPathConstants.BOOLEAN);
} catch (XPathExpressionException e) {
throw new BuildException("XPath expression fails", e);
}
return result.booleanValue();
}
public void testXSchema() throws Exception{
File xsdFile = new File(test_Constants.TEST_RESOURCE_DIR + "Book.xsd");
assertTrue("xsdFile " + xsdFile.getAbsolutePath() + " exists",
xsdFile.exists());
InputStream xmlFile = test_Validator.class.getResourceAsStream("/BookXsdGenerated.xml");
assertNotNull("xmlFile exists", xmlFile);
try {
validator = new Validator(new InputSource(xmlFile));
validator.useXMLSchema(true);
assertTrue("Schema " + validator.toString(), validator.isValid());
} finally {
xmlFile.close();
}
}
private ID getPrescriberIdFromKmehr(InputStream is) throws XPathExpressionException {
XPath xPath = XPathFactory.newInstance().newXPath();
NamespaceContext nsCtx = new MapNamespaceContext("http://www.ehealth.fgov.be/standards/kmehr/schema/v1");
xPath.setNamespaceContext(nsCtx);
InputSource inputSource = new InputSource(is);
Document doc = (Document) xPath.evaluate("/", inputSource, XPathConstants.NODE);
String idValue = xPath.evaluate("/ns1:kmehrmessage/ns1:header/ns1:sender/ns1:hcparty/ns1:id[@S='ID-HCPARTY' and @SV='1.0']/text()", doc);
String type = xPath.evaluate("/ns1:kmehrmessage/ns1:header/ns1:sender/ns1:hcparty/ns1:cd[@S='CD-HCPARTY' and @SV='1.0']/text()", doc);
ID id = new ID();
id.setIdType("NIHII");
id.setValue(idValue);
id.setType(type);
return id;
}
/**
* @param xml
* @return a list of Entrys from the given xml string.
* @throws IOException
* @throws SAXException
*/
public static List<SonosEntry> getEntriesFromString(String xml) throws SAXException {
XMLReader reader = XMLReaderFactory.createXMLReader();
EntryHandler handler = new EntryHandler();
reader.setContentHandler(handler);
try {
reader.parse(new InputSource(new StringReader(xml)));
} catch (IOException e) {
logger.error("Could not parse Entries from String {}", xml);
}
return handler.getArtists();
}
public InputSource getInputSource(EntityResolver r)
throws IOException, SAXException {
InputSource retval;
retval = r.resolveEntity(publicId, systemId);
// SAX sez if null is returned, use the URI directly
if (retval == null)
retval = Resolver.createInputSource(new URL(systemId), false);
return retval;
}
@Override
public int compareTo(XSD x) {
if (x == null) return 1;
if (namespace != null && x.namespace != null) {
int c = namespace.compareTo(x.namespace);
if (c != 0) return c;
}
if (wsdlSchema != null || url == null || (url.toString().compareTo(x.url.toString()) != 0)) {
// Compare XSD content to prevent copies of the same XSD showing up
// more than once in the WSDL. For example the
// CommonMessageHeader.xsd used by the EsbSoapValidator will
// normally also be imported by the XSD for the business response
// message (for the Result part).
try {
InputSource control = new InputSource(getInputStream());
InputSource test = new InputSource(x.getInputStream());
Diff diff = new Diff(control, test);
if (diff.similar()) {
return 0;
} else if (wsdlSchema != null || url == null) {
return Misc.streamToString(getInputStream(), "\n", false).compareTo(Misc.streamToString(x.getInputStream(), "\n", false));
}
} catch (Exception e) {
LOG.warn("Exception during XSD compare", e);
}
}
return url.toString().compareTo(x.url.toString());
}
@Test
public void test() {
try {
Transformer transformer = TransformerFactory.newInstance().newTransformer();
copyDTDtoWorkDir();
File outf = new File(USER_DIR + "Bug4693341.out");
StreamResult result = new StreamResult(new FileOutputStream(outf));
String in = getClass().getResource("Bug4693341.xml").getPath();
File file = new File(in);
StreamSource source = new StreamSource(new FileInputStream(file), ("file://" + in));
transformer.transform(source, result);
//URL inputsource = new URL("file", "", golden);
URL output = new URL("file", "", outf.getPath());
// error happens when trying to parse output
String systemId = output.toExternalForm();
System.out.println("systemId: " + systemId);
InputSource is = new InputSource(systemId);
SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
parser.parse(is, new DefaultHandler());
} catch (Exception ex) {
Assert.fail(ex.getMessage());
}
}
/**
* Extract file name from input source.
*
* @param inputSource the input source
* @return the string
*/
public static String extractFileNameFromInputSource(InputSource inputSource) {
if (inputSource.getByteStream() != null) {
return extractFileNameFromInputStream(inputSource.getByteStream());
}
if (inputSource.getCharacterStream() != null) {
return extractFileNameFromReader(inputSource.getCharacterStream());
}
return null;
}
public Node generateAssignFromNodeInstanceResponseToStringVarAsNode(final String stringVarName,
final String nodeInstanceResponseVarName) throws IOException,
SAXException {
final String templateString =
generateAssignFromNodeInstanceResonseToStringVar(stringVarName, nodeInstanceResponseVarName);
final InputSource is = new InputSource();
is.setCharacterStream(new StringReader(templateString));
final Document doc = this.docBuilder.parse(is);
return doc.getFirstChild();
}
/**
* convert an array of {@link InputSource InputSource} into an
* array of {@link Source Source}
*
* @param schemas array of {@link InputSource InputSource}
* @return array of {@link Source Source}
*/
private static Source[] getSchemaSource(InputSource[] schemas, EntityResolver entityResolver) throws SAXException {
SAXSource[] sources = new SAXSource[schemas.length];
for (int i = 0; i < schemas.length; i++) {
sources[i] = new SAXSource(schemas[i]);
// sources[i].getXMLReader().setEntityResolver(entityResolver);
}
return sources;
}
public JRXmlDataSource(
JasperReportsContext jasperReportsContext,
InputStream in,
String selectExpression,
boolean isNamespaceAware
) throws JRException
{
this(jasperReportsContext, JRXmlUtils.parse(new InputSource(in), isNamespaceAware), selectExpression);
this.inputStream = in;
this.closeInputStream = false;
}
public static void main(String[] args) throws SAXException, IOException {
XMLReader reader = XMLReaderFactory.createXMLReader();
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(Payloads.NO_FEEDBACK_SINGLE_LINE
.getBytes());
//todo 修复方式
reader.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
reader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
reader.setFeature("http://xml.org/sax/features/external-general-entities", false);
reader.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
reader.parse(new InputSource(byteArrayInputStream));
}
public void parse(InputSource is, HandlerBase hb)
throws SAXException, IOException {
if (is == null) {
throw new IllegalArgumentException();
}
if (hb != null) {
xmlReader.setDocumentHandler(hb);
xmlReader.setEntityResolver(hb);
xmlReader.setErrorHandler(hb);
xmlReader.setDTDHandler(hb);
xmlReader.setContentHandler(null);
}
xmlReader.parse(is);
}
public static SourceBean fromXMLStream(InputSource stream, boolean trimCharacters, boolean upperCase)
throws SourceBeanException {
if (stream == null) {
TracerSingleton.log(
Constants.NOME_MODULO,
TracerSingleton.WARNING,
"SourceBean::fromXMLStream: stream nullo");
return null;
} // if (stream == null)
SourceBean sourceBean = null;
XMLReader parser = new SAXParser();
try {
SourceBeanContentHandler contentHandler =
new SourceBeanContentHandler(trimCharacters, upperCase);
parser.setContentHandler(contentHandler);
parser.parse(stream);
sourceBean = contentHandler.getSourceBean();
} // try
catch (Exception ex) {
TracerSingleton.log(
Constants.NOME_MODULO,
TracerSingleton.CRITICAL,
"SourceBean::fromXMLString: impossibile elaborare lo stream XML",
ex);
throw new SourceBeanException("Impossibile elaborare lo stream XML");
} // catch (Exception ex) try
return sourceBean;
}
public static ArrayList<LogEvent> parse(Reader reader, boolean cleanup) throws Exception {
// Create the XML input factory
SAXParserFactory factory = SAXParserFactory.newInstance();
// Create the XML LogEvent reader
SAXParser p = factory.newSAXParser();
if (cleanup) {
// some versions of the log have slightly malformed XML, so clean it
// up before passing it to SAX
reader = new LogCleanupReader(reader);
}
LogParser log = new LogParser();
try {
p.parse(new InputSource(reader), log);
} catch (Throwable th) {
th.printStackTrace();
// Carry on with what we've got...
}
// Associate compilations with their NMethods
for (NMethod nm : log.nmethods.values()) {
Compilation c = log.compiles.get(nm.getId());
nm.setCompilation(c);
// Native wrappers for methods don't have a compilation
if (c != null) {
c.setNMethod(nm);
}
}
// Initially we want the LogEvent log sorted by timestamp
Collections.sort(log.events, sortByStart);
return log.events;
}