xmlutils.java
来自「开源的axis2框架的源码。用于开发WEBSERVER」· Java 代码 · 共 586 行 · 第 1/2 页
JAVA
586 行
*/
public static QName getQNameFromString(String str, Node e) {
if (str == null || e == null) {
return null;
}
int idx = str.indexOf(':');
if (idx > -1) {
String prefix = str.substring(0, idx);
String ns = getNamespace(prefix, e);
if (ns == null) {
return null;
}
return new QName(ns, str.substring(idx + 1));
} else {
return new QName("", str);
}
}
/**
* Returns a string for a particular QName, mapping a new prefix
* if necessary.
*/
public static String getStringForQName(QName qname, Element e) {
String uri = qname.getNamespaceURI();
String prefix = getPrefix(uri, e);
if (prefix == null) {
int i = 1;
prefix = "ns" + i;
while (getNamespace(prefix, e) != null) {
i++;
prefix = "ns" + i;
}
e.setAttributeNS(Constants.NS_URI_XMLNS,
"xmlns:" + prefix, uri);
}
return prefix + ":" + qname.getLocalPart();
}
/**
* Concatinates all the text and cdata node children of this elem and returns
* the resulting text.
* (by Matt Duftler)
*
* @param parentEl the element whose cdata/text node values are to
* be combined.
* @return Returns the concatinated string.
*/
public static String getChildCharacterData(Element parentEl) {
if (parentEl == null) {
return null;
}
Node tempNode = parentEl.getFirstChild();
StringBuffer strBuf = new StringBuffer();
CharacterData charData;
while (tempNode != null) {
switch (tempNode.getNodeType()) {
case Node.TEXT_NODE :
case Node.CDATA_SECTION_NODE:
charData = (CharacterData) tempNode;
strBuf.append(charData.getData());
break;
}
tempNode = tempNode.getNextSibling();
}
return strBuf.toString();
}
public static class ParserErrorHandler implements ErrorHandler {
/**
* Returns a string describing parse exception details
*/
private String getParseExceptionInfo(SAXParseException spe) {
String systemId = spe.getSystemId();
if (systemId == null) {
systemId = "null";
}
return "URI=" + systemId +
" Line=" + spe.getLineNumber() +
": " + spe.getMessage();
}
// The following methods are standard SAX ErrorHandler methods.
// See SAX documentation for more info.
public void warning(SAXParseException spe) throws SAXException {
}
public void error(SAXParseException spe) throws SAXException {
String message = "Error: " + getParseExceptionInfo(spe);
throw new SAXException(message);
}
public void fatalError(SAXParseException spe) throws SAXException {
String message = "Fatal Error: " + getParseExceptionInfo(spe);
throw new SAXException(message);
}
}
/**
* Utility to get the bytes uri.
* Does NOT handle authenticated URLs,
* use getInputSourceFromURI(uri, username, password)
*
* @param uri the resource to get
*/
public static InputSource getInputSourceFromURI(String uri) {
return new InputSource(uri);
}
/**
* Utility to get the bytes at a protected uri
* <p/>
* Retrieves the URL if a username and password are provided.
* The java.net.URL class does not do Basic Authentication, so we have to
* do it manually in this routine.
* <p/>
* If no username is provided, creates an InputSource from the uri
* and lets the InputSource go fetch the contents.
*
* @param uri the resource to get
* @param username basic auth username
* @param password basic auth password
*/
private static InputSource getInputSourceFromURI(String uri,
String username,
String password)
throws IOException, ProtocolException, UnsupportedEncodingException {
URL wsdlurl = null;
try {
wsdlurl = new URL(uri);
} catch (MalformedURLException e) {
// we can't process it, it might be a 'simple' foo.wsdl
// let InputSource deal with it
return new InputSource(uri);
}
// if no authentication, just let InputSource deal with it
if (username == null && wsdlurl.getUserInfo() == null) {
return new InputSource(uri);
}
// if this is not an HTTP{S} url, let InputSource deal with it
if (!wsdlurl.getProtocol().startsWith("http")) {
return new InputSource(uri);
}
URLConnection connection = wsdlurl.openConnection();
// Does this work for https???
if (!(connection instanceof HttpURLConnection)) {
// can't do http with this URL, let InputSource deal with it
return new InputSource(uri);
}
HttpURLConnection uconn = (HttpURLConnection) connection;
String userinfo = wsdlurl.getUserInfo();
uconn.setRequestMethod("GET");
uconn.setAllowUserInteraction(false);
uconn.setDefaultUseCaches(false);
uconn.setDoInput(true);
uconn.setDoOutput(false);
uconn.setInstanceFollowRedirects(true);
uconn.setUseCaches(false);
// username/password info in the URL overrides passed in values
String auth = null;
if (userinfo != null) {
auth = userinfo;
} else if (username != null) {
auth = (password == null) ? username : username + ":" + password;
}
if (auth != null) {
uconn.setRequestProperty("Authorization",
"Basic " +
base64encode(auth.getBytes(charEncoding)));
}
uconn.connect();
return new InputSource(uconn.getInputStream());
}
public static String base64encode(byte[] bytes) {
return Base64.encode(bytes);
}
public static InputSource getEmptyInputSource() {
return new InputSource(bais);
}
/**
* Finds a Node with a given QNameb.
*
* @param node parent node
* @param name QName of the child we need to find
* @return Returns child node.
*/
public static Node findNode(Node node, QName name) {
if (name.getNamespaceURI().equals(node.getNamespaceURI()) &&
name.getLocalPart().equals(node.getLocalName())) {
return node;
}
NodeList children = node.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
Node ret = findNode(children.item(i), name);
if (ret != null) {
return ret;
}
}
return null;
}
/**
* Converts a given DOM Element to an OMElement.
*
* @param element
* @return Returns OMElement.
* @throws Exception
*/
public static OMElement toOM(Element element) throws Exception {
Source source = new DOMSource(element);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Result result = new StreamResult(baos);
Transformer xformer = TransformerFactory.newInstance().newTransformer();
xformer.transform(source, result);
ByteArrayInputStream is = new ByteArrayInputStream(baos.toByteArray());
XMLStreamReader reader = StAXUtils
.createXMLStreamReader(is);
StAXOMBuilder builder = new StAXOMBuilder(reader);
builder.setCache(true);
return builder.getDocumentElement();
}
/**
* Converts a given OMElement to a DOM Element.
*
* @param element
* @return Returns Element.
* @throws Exception
*/
public static Element toDOM(OMElement element) throws Exception {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
element.serialize(baos);
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
return factory.newDocumentBuilder().parse(bais).getDocumentElement();
}
/**
* Converts a given inputstream to an OMNode
*
* @param inputStream
* @return
* @throws javax.xml.stream.XMLStreamException
*
*/
public static OMNode toOM(InputStream inputStream) throws XMLStreamException {
XMLStreamReader xmlReader = StAXUtils
.createXMLStreamReader(inputStream);
OMFactory fac = OMAbstractFactory.getOMFactory();
StAXOMBuilder staxOMBuilder = new StAXOMBuilder(fac, xmlReader);
return staxOMBuilder.getDocumentElement();
}
/**
* Converts a given Reader to an OMNode
*
* @param reader
* @return
* @throws XMLStreamException
*/
public static OMNode toOM(Reader reader) throws XMLStreamException {
XMLStreamReader xmlReader = StAXUtils
.createXMLStreamReader(reader);
OMFactory fac = OMAbstractFactory.getOMFactory();
StAXOMBuilder staxOMBuilder = new StAXOMBuilder(fac, xmlReader);
return staxOMBuilder.getDocumentElement();
}
}
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?