下面列出了怎么用javax.xml.parsers.ParserConfigurationException的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Create a <code>SAXParser</code> based on the underlying
* <code>Xerces</code> version.
* @param properties parser specific properties/features
* @return an XML Schema/DTD enabled <code>SAXParser</code>
*/
public static SAXParser newSAXParser(Properties properties)
throws ParserConfigurationException,
SAXException,
SAXNotSupportedException {
SAXParserFactory factory =
(SAXParserFactory)properties.get("SAXParserFactory");
if (versionNumber == null){
versionNumber = getXercesVersion();
version = new Float( versionNumber ).floatValue();
}
// Note: 2.2 is completely broken (with XML Schema).
if (version > 2.1) {
configureXerces(factory);
return factory.newSAXParser();
} else {
SAXParser parser = factory.newSAXParser();
configureOldXerces(parser,properties);
return parser;
}
}
private DocumentBuilder getDocumentBuilder() {
DocumentBuilder builder = null;
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(false);
factory.setIgnoringComments(false);
factory.setIgnoringElementContentWhitespace(false);
factory.setCoalescing(false);
factory.setExpandEntityReferences(false);
factory.setValidating(false);
try {
builder = factory.newDocumentBuilder();
} catch (ParserConfigurationException ex) {
Exceptions.printStackTrace(ex);
}
return builder;
}
protected org.kuali.rice.core.impl.config.property.Config unmarshal(Unmarshaller unmarshaller, InputStream in)
throws SAXException, ParserConfigurationException, IOException,
IllegalStateException, JAXBException {
SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setNamespaceAware(true);
XMLFilter filter = new ConfigNamespaceURIFilter();
filter.setParent(spf.newSAXParser().getXMLReader());
UnmarshallerHandler handler = unmarshaller.getUnmarshallerHandler();
filter.setContentHandler(handler);
filter.parse(new InputSource(in));
return (org.kuali.rice.core.impl.config.property.Config) handler.getResult();
}
/**
* Create an XML string representation of the ProcessConnectionRequest object.
* @throws ParserConfigurationException if exception occurs in XML parser
* @throws TransformerException if exception occurs in XML parser
* @param configurationRequest the request object to convert to XML
* @return XML as String
*/
public synchronized String toXML(final ConfigurationRequest configurationRequest) throws ParserConfigurationException, TransformerException {
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = builderFactory.newDocumentBuilder();
Document dom = builder.newDocument();
Element rootElt = dom.createElement(CONFIGURATION_XML_ROOT);
rootElt.setAttribute(CONFIGURATION_ID_ATTRIBUTE, Integer.toString(configurationRequest.getConfigId()));
dom.appendChild(rootElt);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
StringWriter writer = new StringWriter();
Result result = new StreamResult(writer);
Source source = new DOMSource(dom);
transformer.transform(source, result);
return writer.getBuffer().toString();
}
public void testAsXmlOutput() throws ResourceException, ReportProcessingException, IOException, SAXException,
ParserConfigurationException {
final URL url = getClass().getResource( "Prd-3431.prpt" );
assertNotNull( url );
final ResourceManager resourceManager = new ResourceManager();
resourceManager.registerDefaults();
final Resource directly = resourceManager.createDirectly( url, MasterReport.class );
final MasterReport report = (MasterReport) directly.getResource();
final MemoryByteArrayOutputStream mbos = new MemoryByteArrayOutputStream();
XmlTableReportUtil.createFlowXML( report, new NoCloseOutputStream( mbos ) );
final ByteArrayInputStream bin = new ByteArrayInputStream( mbos.getRaw(), 0, mbos.getLength() );
final DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
final Document document = documentBuilder.parse( bin );
final NodeList table = document.getDocumentElement().getElementsByTagName( "table" );
assertSheetName( (Element) table.item( 0 ), "Summary" );
assertSheetName( (Element) table.item( 1 ), "AuthorPublisher A" );
assertSheetName( (Element) table.item( 2 ), "AuthorPublisher B" );
assertSheetName( (Element) table.item( 3 ), "AuthorPublisher C" );
}
public static Optional<InflatableData> from(byte[] bs) {
InflatableData data;
try {
NSDictionary parse = (NSDictionary) PropertyListParser.parse(bs);
byte[] escrowedKeys = ((NSData) parse.get("escrowedKeys")).bytes();
UUID deviceUuid = UUID.fromString(((NSString) parse.get("deviceUuid")).getContent());
String deviceHardWareId = ((NSString) parse.get("deviceHardWareId")).getContent();
data = new InflatableData(escrowedKeys, deviceUuid, deviceHardWareId);
} catch (ClassCastException | IllegalArgumentException | IOException | NullPointerException
| PropertyListFormatException | ParseException | ParserConfigurationException | SAXException ex) {
logger.warn("-- from() - exception: ", ex);
data = null;
}
return Optional.ofNullable(data);
}
/**
* Returns the node set from input which was specified as the parameter of
* {@link XMLSignatureInput} constructor
* @param circumvent
*
* @return the node set
* @throws SAXException
* @throws IOException
* @throws ParserConfigurationException
* @throws CanonicalizationException
*/
public Set<Node> getNodeSet(boolean circumvent) throws ParserConfigurationException,
IOException, SAXException, CanonicalizationException {
if (inputNodeSet != null) {
return inputNodeSet;
}
if (inputOctetStreamProxy == null && subNode != null) {
if (circumvent) {
XMLUtils.circumventBug2650(XMLUtils.getOwnerDocument(subNode));
}
inputNodeSet = new LinkedHashSet<Node>();
XMLUtils.getSet(subNode, inputNodeSet, excludeNode, excludeComments);
return inputNodeSet;
} else if (isOctetStream()) {
convertToNodes();
Set<Node> result = new LinkedHashSet<Node>();
XMLUtils.getSet(subNode, result, null, false);
return result;
}
throw new RuntimeException("getNodeSet() called but no input data present");
}
/**
* Creates and returns a new instance of MapSettings with default values
* loaded from the given input stream.
*
* @param is
* the input stream that contains an XML representation of the
* map settings
* @return a MapSettings with the values from XML
*/
public static MapSettings getInstance(final InputStream is) {
MapSettings ms = null;
try {
JAXBContext jc = JAXBContext.newInstance(MapSettings.class);
Unmarshaller um = jc.createUnmarshaller();
ms = (MapSettings) um.unmarshal(MegaMekXmlUtil.createSafeXmlSource(is));
} catch (JAXBException | SAXException | ParserConfigurationException ex) {
System.err.println("Error loading XML for map settings: " + ex.getMessage()); //$NON-NLS-1$
ex.printStackTrace();
}
return ms;
}
public static Element createElementInTempDocument(
String name,
String prefix,
String namespaceURI)
{
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
try
{
Document doc = dbf.newDocumentBuilder().newDocument();
return createElement(doc, name, prefix, namespaceURI);
} catch (ParserConfigurationException ex)
{
return null;
}
}
/**
* Parse the input source and return a Document.
* @param source The {@code InputSource} of the document
* @return a DOM Document
* @throws XPathExpressionException if there is an error parsing the source.
*/
Document getDocument(InputSource source)
throws XPathExpressionException {
requireNonNull(source, "Source");
try {
// we'd really like to cache those DocumentBuilders, but we can't because:
// 1. thread safety. parsers are not thread-safe, so at least
// we need one instance per a thread.
// 2. parsers are non-reentrant, so now we are looking at having a
// pool of parsers.
// 3. then the class loading issue. The look-up procedure of
// DocumentBuilderFactory.newInstance() depends on context class loader
// and system properties, which may change during the execution of JVM.
//
// so we really have to create a fresh DocumentBuilder every time we need one
// - KK
DocumentBuilderFactory dbf = JdkXmlUtils.getDOMFactory(overrideDefaultParser);
return dbf.newDocumentBuilder().parse(source);
} catch (ParserConfigurationException | SAXException | IOException e) {
throw new XPathExpressionException (e);
}
}
public static String[] readTitleAuthor() {
String result[] = new String[2];
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setValidating(false);
DocumentBuilder db;
Document doc;
try {
File fXmlFile = new File(org.buildmlearn.toolkit.flashcardtemplate.Constants.XMLFileName);
db = dbf.newDocumentBuilder();
doc = db.parse(fXmlFile);
doc.normalize();
result[0] = doc.getElementsByTagName("title").item(0).getChildNodes()
.item(0).getNodeValue();
result[1] = doc.getElementsByTagName("name").item(0).getChildNodes()
.item(0).getNodeValue();
} catch (ParserConfigurationException | SAXException | IOException e) {
e.printStackTrace();
}
return result;
}
@Before
public void before() {
context = new JUnit4Mockery() {{
setImposteriser(ClassImposteriser.INSTANCE);
}};
authorParser = context.mock(AuthorParser.class);
contentParser = context.mock(ContentParser.class);
dataParser = context.mock(DataParser.class);
fieldParser = context.mock(FieldParser.class);
summaryParser = context.mock(SummaryParser.class);
titleParser = context.mock(TitleParser.class);
updatedParser = context.mock(UpdatedParser.class);
entryParser = new EntryParserImpl(authorParser, contentParser, dataParser,
fieldParser, summaryParser, titleParser,
updatedParser);
try {
document = DocumentBuilderFactory.newInstance()
.newDocumentBuilder().newDocument();
} catch (ParserConfigurationException e) {
fail("Failure to create test document");
}
}
public JUnitResultData parseXmlFile(File xmlFile){
this.xmlFile = xmlFile;
//get the factory
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
JUnitResultData returnResultsForFile = null;
try {
//Using factory get an instance of document builder
DocumentBuilder db = dbf.newDocumentBuilder();
//parse using builder to get DOM representation of the XML file
dom = db.parse(xmlFile);
returnResultsForFile = parseDocument();
returnResultsForFile.setJunitResultfile(xmlFile);
}catch(ParserConfigurationException pce) {
pce.printStackTrace();
}catch(SAXException se) {
se.printStackTrace();
}catch(IOException ioe) {
ioe.printStackTrace();
}
return returnResultsForFile;
}
private void removeByXpathExpression(String pomFilePath, String expression) throws SAXException, IOException, ParserConfigurationException, XPathExpressionException, TransformerException {
File xmlFile = new File(pomFilePath);
Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(xmlFile);
XPath xpath = XPathFactory.newInstance().newXPath();
NodeList nl = (NodeList) xpath.compile(expression).
evaluate(doc, XPathConstants.NODESET);
if (nl != null && nl.getLength() > 0) {
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
node.getParentNode().removeChild(node);
}
Transformer transformer = TransformerFactory.newInstance().newTransformer();
// need to convert to file and then to path to override a problem with spaces
Result output = new StreamResult(new File(pomFilePath).getPath());
Source input = new DOMSource(doc);
transformer.transform(input, output);
}
}
/**
* Creates a new instance of a {@link javax.xml.parsers.DocumentBuilder}
* using the currently configured parameters.
*/
public DocumentBuilder newDocumentBuilder()
throws ParserConfigurationException
{
/** Check that if a Schema has been specified that neither of the schema properties have been set. */
if (grammar != null && attributes != null) {
if (attributes.containsKey(JAXPConstants.JAXP_SCHEMA_LANGUAGE)) {
throw new ParserConfigurationException(
SAXMessageFormatter.formatMessage(null,
"schema-already-specified", new Object[] {JAXPConstants.JAXP_SCHEMA_LANGUAGE}));
}
else if (attributes.containsKey(JAXPConstants.JAXP_SCHEMA_SOURCE)) {
throw new ParserConfigurationException(
SAXMessageFormatter.formatMessage(null,
"schema-already-specified", new Object[] {JAXPConstants.JAXP_SCHEMA_SOURCE}));
}
}
try {
return new DocumentBuilderImpl(this, attributes, features, fSecureProcess);
} catch (SAXException se) {
// Handles both SAXNotSupportedException, SAXNotRecognizedException
throw new ParserConfigurationException(se.getMessage());
}
}
protected void circumventBugIfNeeded(XMLSignatureInput input)
throws CanonicalizationException, ParserConfigurationException,
IOException, SAXException {
if (!input.isNeedsToBeExpanded() || inclusiveNSSet.isEmpty() || inclusiveNSSet.isEmpty()) {
return;
}
Document doc = null;
if (input.getSubNode() != null) {
doc = XMLUtils.getOwnerDocument(input.getSubNode());
} else {
doc = XMLUtils.getOwnerDocument(input.getNodeSet());
}
XMLUtils.circumventBug2650(doc);
}
@Test
public void testPointNegativeLangLat() throws KeyManagementException, NoSuchAlgorithmException, IOException, ParserConfigurationException, SAXException, XpathException,
TransformerException
{
System.out.println("Running testPointNegativeLangLat");
String queryOptionName = "geoConstraintOpt.xml";
DatabaseClient client = getDatabaseClient("rest-admin", "x", getConnType());
// write docs
for (int i = 1; i <= 7; i++)
{
writeDocumentUsingInputStreamHandle(client, "geo-constraint" + i + ".xml", "/geo-constraint/", "XML");
}
setQueryOption(client, queryOptionName);
QueryManager queryMgr = client.newQueryManager();
queryMgr.setView(QueryView.ALL);
// create query def
StringQueryDefinition querydef = queryMgr.newStringDefinition(queryOptionName);
querydef.setCriteria("geo-elem:\"-12,-5\"");
// create handle
DOMHandle resultsHandle = new DOMHandle();
queryMgr.search(querydef, resultsHandle);
// get the result
Document resultDoc = resultsHandle.get();
System.out.println("testPointNegativeLangLat Result : " + convertXMLDocumentToString(resultDoc));
assertXpathEvaluatesTo("1", "string(//*[local-name()='result'][last()]//@*[local-name()='index'])", resultDoc);
assertXpathEvaluatesTo("geo-elem:\"-12,-5\"", "string(//*[local-name()='qtext'])", resultDoc);
// release client
client.release();
}
private Supplier<Element> dummyElementFactory() {
Document result;
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
try {
result = documentBuilderFactory.newDocumentBuilder().newDocument();
} catch (ParserConfigurationException e) {
throw new AssertionError(e);
}
Document doc = result;
return () -> doc.createElement("val");
}
public void parse(URL url) throws IOException, ParserConfigurationException, SAXException {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser;
SSDPDeviceDescriptionParser parser = new SSDPDeviceDescriptionParser(this);
URLConnection urlConnection = url.openConnection();
applicationURL = urlConnection.getHeaderField("Application-URL");
if (applicationURL != null && !applicationURL.substring(applicationURL.length() - 1).equals("/")) {
applicationURL = applicationURL.concat("/");
}
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
Scanner s = null;
try {
s = new Scanner(in).useDelimiter("\\A");
locationXML = s.hasNext() ? s.next() : "";
saxParser = factory.newSAXParser();
saxParser.parse(new ByteArrayInputStream(locationXML.getBytes()), parser);
} finally {
in.close();
if (s != null)
s.close();
}
headers = urlConnection.getHeaderFields();
}
/**
*
* @param file File to save Document to (ie AndroidManifest.xml)
* @param doc Document being saved
* @throws IOException
* @throws SAXException
* @throws ParserConfigurationException
* @throws TransformerException
*/
public static void saveDocument(File file, Document doc)
throws IOException, SAXException, ParserConfigurationException, TransformerException {
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(file);
transformer.transform(source, result);
}
@Test
public void recordGranularityLifecycleTest() throws IOException, ParserConfigurationException, SAXException {
String baseName = "testFileName";
String name = baseName + ".evtx";
TestRunner testRunner = TestRunners.newTestRunner(ParseEvtx.class);
testRunner.setProperty(ParseEvtx.GRANULARITY, ParseEvtx.RECORD);
Map<String, String> attributes = new HashMap<>();
attributes.put(CoreAttributes.FILENAME.key(), name);
testRunner.enqueue(this.getClass().getClassLoader().getResourceAsStream("application-logs.evtx"), attributes);
testRunner.run();
List<MockFlowFile> originalFlowFiles = testRunner.getFlowFilesForRelationship(ParseEvtx.REL_ORIGINAL);
assertEquals(1, originalFlowFiles.size());
MockFlowFile originalFlowFile = originalFlowFiles.get(0);
originalFlowFile.assertAttributeEquals(CoreAttributes.FILENAME.key(), name);
originalFlowFile.assertContentEquals(this.getClass().getClassLoader().getResourceAsStream("application-logs.evtx"));
// We expect the same bad chunks no matter the granularity
List<MockFlowFile> badChunkFlowFiles = testRunner.getFlowFilesForRelationship(ParseEvtx.REL_BAD_CHUNK);
assertEquals(2, badChunkFlowFiles.size());
badChunkFlowFiles.get(0).assertAttributeEquals(CoreAttributes.FILENAME.key(), parseEvtx.getName(baseName, 1, null, ParseEvtx.EVTX_EXTENSION));
badChunkFlowFiles.get(1).assertAttributeEquals(CoreAttributes.FILENAME.key(), parseEvtx.getName(baseName, 2, null, ParseEvtx.EVTX_EXTENSION));
List<MockFlowFile> failureFlowFiles = testRunner.getFlowFilesForRelationship(ParseEvtx.REL_FAILURE);
assertEquals(0, failureFlowFiles.size());
// Whole file fails if there is a failure parsing
List<MockFlowFile> successFlowFiles = testRunner.getFlowFilesForRelationship(ParseEvtx.REL_SUCCESS);
assertEquals(EXPECTED_SUCCESSFUL_EVENT_COUNT, successFlowFiles.size());
// We expect the same number of records to come out no matter the granularity
assertEquals(EXPECTED_SUCCESSFUL_EVENT_COUNT, validateFlowFiles(successFlowFiles));
}
/**
* A (recursive) helper function for parsing the macros used by the XML files describing Galaxy's tools
*
* @param macrosNd
* an XML node that specifies a set of macros
* @param dir
* the directory in which the currently processed macros are located
* @return processed macros accessible by their name
*/
private Map<String, String> processMacros(Node macrosNd, String dir) {
Map<String, String> macrosByName = new HashMap<>();
try {
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Element macrosEl = (Element) macrosNd;
// (1) if additional macro files are to be imported, open the files and recursively invoke this method
NodeList importNds = macrosEl.getElementsByTagName("import");
for (int j = 0; j < importNds.getLength(); j++) {
Element importEl = (Element) importNds.item(j);
String importFileName = importEl.getChildNodes().item(0).getNodeValue().trim();
File file = new File(dir, importFileName);
Document doc = builder.parse(file);
macrosByName.putAll(processMacros(doc.getDocumentElement(), dir));
}
// (2) parse all macros in this set
NodeList macroNds = macrosEl.getElementsByTagName("macro");
for (int j = 0; j < macroNds.getLength(); j++) {
Element macroEl = (Element) macroNds.item(j);
String name = macroEl.getAttribute("name");
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
StreamResult result = new StreamResult(new StringWriter());
DOMSource source = new DOMSource(macroEl);
transformer.transform(source, result);
String macro = result.getWriter().toString();
macro = macro.substring(macro.indexOf('\n') + 1, macro.lastIndexOf('\n'));
macrosByName.put(name, macro);
}
} catch (SAXException | IOException | TransformerException | ParserConfigurationException e) {
e.printStackTrace(System.out);
System.exit(-1);
}
return macrosByName;
}
private Document createDummyDocument() throws ParserConfigurationException {
Document document = Util.createEmptyDocument();
Element linearLayout = document.createElement("LinearLayout");
linearLayout.setAttribute("xmlns:android",
"http://schemas.android.com/apk/res/android");
linearLayout.setAttribute("android:orientation", "vertical");
document.appendChild(linearLayout);
Element textViewWithIdAndText = document.createElement("TextView");
textViewWithIdAndText.setAttribute("android:text", "text");
textViewWithIdAndText.setAttribute("android:id", "@+id/id1");
linearLayout.appendChild(textViewWithIdAndText);
Element textViewWithIdAndHint = document.createElement("TextView");
textViewWithIdAndHint.setAttribute("android:hint", "hint");
textViewWithIdAndHint.setAttribute("android:id", "@+id/id2");
linearLayout.appendChild(textViewWithIdAndHint);
Element textViewWithoutIdAndText = document.createElement("TextView");
textViewWithoutIdAndText.setAttribute("android:text", "text");
linearLayout.appendChild(textViewWithoutIdAndText);
Element textViewWithIdButWithoutTextAndHint = document.createElement("TextView");
textViewWithIdButWithoutTextAndHint.setAttribute("android:id", "@+id/id3");
linearLayout.appendChild(textViewWithIdButWithoutTextAndHint);
return document;
}
private Document copy(Document doc) {
try {
return StaxUtils.copy(doc);
} catch (XMLStreamException | ParserConfigurationException e) {
// ignore
}
return doc;
}
/**
* Returns a new XML document.
*
* @return A document.
*/
public static Document newDocument() {
try {
final DocumentBuilder builder = DocumentBuilderFactory
.newInstance().newDocumentBuilder();
return builder.newDocument();
} catch (ParserConfigurationException e) {
throw new RuntimeException(e);
}
}
private DocumentBuilderFactory newDocFactory() {
final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
try {
factory.setFeature(javax.xml.XMLConstants.FEATURE_SECURE_PROCESSING, true);
factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
} catch (final ParserConfigurationException e) {
throw new IllegalStateException(e);
}
return factory;
}
/**
* Creates a new DOM document.
*/
public static Document createDom() {
synchronized (DOMUtil.class) {
if (db == null) {
try {
DocumentBuilderFactory dbf = XmlUtil.newDocumentBuilderFactory();
dbf.setNamespaceAware(true);
db = dbf.newDocumentBuilder();
} catch (ParserConfigurationException e) {
throw new FactoryConfigurationError(e);
}
}
return db.newDocument();
}
}
@Override
public Document createDocument ()
{
try
{
return this.documentBuilderFactory.newDocumentBuilder ().newDocument ();
}
catch ( final ParserConfigurationException e )
{
throw new RuntimeException ( e );
}
}
/**
* Reads the VoiceXML document from the given <code>InputStream</code>.
*
* @param input
* <code>InputStream</code> for the VoiceXML document.
* @return Retrieved VoiceXML document.
* @exception BadFetchError
* Error reading from the input stream.
*
* @since 0.3
*/
private VoiceXmlDocument readDocument(final InputStream input)
throws BadFetchError {
final InputSource inputSource = new InputSource(input);
try {
return new VoiceXmlDocument(inputSource);
} catch (javax.xml.parsers.ParserConfigurationException pce) {
throw new BadFetchError(pce);
} catch (org.xml.sax.SAXException saxe) {
throw new BadFetchError(saxe);
} catch (java.io.IOException ioe) {
throw new BadFetchError(ioe);
}
}
public JsSimpleDomParser() {
try {
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
documentBuilderFactory.setNamespaceAware(true);
documentBuilderFactory.setCoalescing(true);
documentBuilder = documentBuilderFactory.newDocumentBuilder();
} catch (ParserConfigurationException e) {
throw new RuntimeException(e);
}
}