📄 xmlutils.java
字号:
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(); } /** * Concat all the text and cdata node children of this elem and return * the resulting text. * (by Matt Duftler) * * @param parentEl the element whose cdata/text node values are to * be combined. * @return the concatanated 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 { protected static Log log = LogFactory.getLog(ParserErrorHandler.class.getName()); /** * Returns a string describing parse exception details */ private String getParseExceptionInfo(SAXParseException spe) { String systemId = spe.getSystemId(); if (systemId == null) { systemId = "null"; } String info = "URI=" + systemId + " Line=" + spe.getLineNumber() + ": " + spe.getMessage(); return info; } // The following methods are standard SAX ErrorHandler methods. // See SAX documentation for more info. public void warning(SAXParseException spe) throws SAXException { if (log.isDebugEnabled()) log.debug( Messages.getMessage("warning00", getParseExceptionInfo(spe))); } 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 * @see #getInputSourceFromURI(String uri, String username, String password) */ public static InputSource getInputSourceFromURI(String uri) { return new InputSource(uri); } /** * Utility to get the bytes uri * * @param source the resource to get */ public static InputSource sourceToInputSource(Source source) { if (source instanceof SAXSource) { return ((SAXSource) source).getInputSource(); } else if (source instanceof DOMSource) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); Node node = ((DOMSource)source).getNode(); if (node instanceof Document) { node = ((Document)node).getDocumentElement(); } Element domElement = (Element)node; ElementToStream(domElement, baos); InputSource isource = new InputSource(source.getSystemId()); isource.setByteStream(new ByteArrayInputStream(baos.toByteArray())); return isource; } else if (source instanceof StreamSource) { StreamSource ss = (StreamSource) source; InputSource isource = new InputSource(ss.getSystemId()); isource.setByteStream(ss.getInputStream()); isource.setCharacterStream(ss.getReader()); isource.setPublicId(ss.getPublicId()); return isource; } else { return getInputSourceFromURI(source.getSystemId()); } } /** * Utility to get the bytes at a protected uri * * This will retrieve 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. * * If no username is provided, we create an InputSource from the uri * and let 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(httpAuthCharEncoding))); } uconn.connect(); return new InputSource(uconn.getInputStream()); } public static final String base64encode(byte[] bytes) { return new String(Base64.encode(bytes)); } public static InputSource getEmptyInputSource() { return new InputSource(bais); } /** * Find a Node with a given QName * * @param node parent node * @param name QName of the child we need to find * @return 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; } /** * Trim all new lines from text nodes. * * @param node */ public static void normalize(Node node) { if (node.getNodeType() == Node.TEXT_NODE) { String data = ((Text) node).getData(); if (data.length() > 0) { char ch = data.charAt(data.length()-1); if(ch == '\n' || ch == '\r' || ch == ' ') { String data2 = trim(data); ((Text) node).setData(data2); } } } for (Node currentChild = node.getFirstChild(); currentChild != null; currentChild = currentChild.getNextSibling()) { normalize(currentChild); } } public static String trim(String str) { if (str.length() == 0) { return str; } if (str.length() == 1) { if ("\r".equals(str) || "\n".equals(str)) { return ""; } else { return str; } } int lastIdx = str.length() - 1; char last = str.charAt(lastIdx); while(lastIdx > 0) { if(last != '\n' && last != '\r' && last != ' ') break; lastIdx--; last = str.charAt(lastIdx); } if(lastIdx == 0) return ""; return str.substring(0, lastIdx); } /** * Converts a List with org.w3c.dom.Element objects to an Array * with org.w3c.dom.Element objects. * @param list List containing org.w3c.dom.Element objects * @return Element[] Array with org.w3c.dom.Element objects */ public static Element[] asElementArray(List list) { Element[] elements = new Element[list.size()]; int i = 0; Iterator detailIter = list.iterator(); while (detailIter.hasNext()) { elements[i++] = (Element) detailIter.next(); } return elements; } public static String getEncoding(Message message, MessageContext msgContext) { return getEncoding(message, msgContext, XMLEncoderFactory.getDefaultEncoder()); } public static String getEncoding(Message message, MessageContext msgContext, XMLEncoder defaultEncoder) { String encoding = null; try { if(message != null) { encoding = (String) message.getProperty(SOAPMessage.CHARACTER_SET_ENCODING); } } catch (SOAPException e) { } if(msgContext == null) { msgContext = MessageContext.getCurrentContext(); } if(msgContext != null && encoding == null){ encoding = (String) msgContext.getProperty(SOAPMessage.CHARACTER_SET_ENCODING); } if (msgContext != null && encoding == null && msgContext.getAxisEngine() != null) { encoding = (String) msgContext.getAxisEngine().getOption(AxisEngine.PROP_XML_ENCODING); } if (encoding == null && defaultEncoder != null) { encoding = defaultEncoder.getEncoding(); } return encoding; }}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -