Search in sources :

Example 1 with RuntimeExceptionHelper

use of com.cdeledu.common.exception.RuntimeExceptionHelper in project wechat by dllwh.

the class XmlUtils method readXML.

/**
 * @方法名称: readXML
 * @方法描述: 从文件获得DOM对象
 *
 * @param xmlFile
 *            XML文件对象
 * @return DOM对象
 * @throws DocumentException
 */
public static Document readXML(File xmlFile) throws DocumentException {
    if (xmlFile == null) {
        throw new NullPointerException("Xml file is null !");
    }
    if (xmlFile.exists() == false) {
        throw new RuntimeExceptionHelper("File [" + xmlFile.getAbsolutePath() + "] not a exist!");
    }
    if (xmlFile.isFile() == false) {
        throw new RuntimeExceptionHelper("[" + xmlFile.getAbsolutePath() + "] not a file!");
    }
    try {
        xmlFile = xmlFile.getCanonicalFile();
        final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        final DocumentBuilder builder = dbf.newDocumentBuilder();
        return builder.parse(xmlFile);
    } catch (Exception e) {
        throw new RuntimeExceptionHelper("Parse xml file [" + xmlFile.getAbsolutePath() + "] error!", e);
    }
}
Also used : DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) DocumentBuilder(javax.xml.parsers.DocumentBuilder) RuntimeExceptionHelper(com.cdeledu.common.exception.RuntimeExceptionHelper) DocumentException(org.dom4j.DocumentException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) SAXException(org.xml.sax.SAXException)

Example 2 with RuntimeExceptionHelper

use of com.cdeledu.common.exception.RuntimeExceptionHelper in project wechat by dllwh.

the class XmlUtils method parseDoc.

/*--------------------------私有方法 end-------------------------------*/
/*--------------------------公有方法 start-------------------------------*/
/**
 * @方法:将String类型的XML转换为XML文档
 * @创建人:独泪了无痕
 * @param xmlStr
 *            XML字符串
 * @return XML文档
 * @throws DocumentException
 */
public static Document parseDoc(String xmlStr) {
    if (StringUtils.isBlank(xmlStr)) {
        throw new RuntimeExceptionHelper("Xml content string is empty !");
    }
    xmlStr = cleanInvalid(xmlStr);
    final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    try {
        final DocumentBuilder builder = dbf.newDocumentBuilder();
        return builder.parse(new InputSource(StringUtilHelper.getReader(xmlStr)));
    } catch (Exception e) {
        throw new RuntimeExceptionHelper("Parse xml file [" + xmlStr + "] error!", e);
    }
}
Also used : InputSource(org.xml.sax.InputSource) DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) DocumentBuilder(javax.xml.parsers.DocumentBuilder) RuntimeExceptionHelper(com.cdeledu.common.exception.RuntimeExceptionHelper) DocumentException(org.dom4j.DocumentException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) SAXException(org.xml.sax.SAXException)

Example 3 with RuntimeExceptionHelper

use of com.cdeledu.common.exception.RuntimeExceptionHelper in project wechat by dllwh.

the class HttpURLConnHelper method initConn.

/**
 * @方法描述: 初始化连接相关信息的Post、Get访问请求参数设置
 * @创建者: 皇族灬战狼
 * @创建时间: 2016年10月12日 上午7:53:09
 * @param url
 *            请求地址
 * @param RequestMethod
 *            请求方法
 * @param isUseProxy
 *            是否代理
 * @return
 */
private HttpURLConnection initConn(String url, String ReqMethod, boolean isUseProxy) throws Exception {
    if (StringUtils.isBlank(url)) {
        throw new RuntimeExceptionHelper("请求的URL不能为空");
    }
    HttpURLConnection httpConn = null;
    // 打开HttpURLConnection
    URL realUrl = new URL(url);
    if (isUseProxy) {
        Map<String, Object> ipMap = IpUtilHelper.getProxyIp();
        // http访问要使用的代理服务器的地址
        String proxyIp = String.valueOf(ipMap.get("proxyIp"));
        // http访问要使用的代理服务器的端口
        String proxyPort = String.valueOf(ipMap.get("proxyPort"));
        // http访问要使用的代理服务器的用户名
        String userName = String.valueOf(ipMap.get("userName"));
        // http访问要使用的代理服务器的密码
        String password = String.valueOf(ipMap.get("proxyPort"));
        Proxy newProxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyIp, Integer.parseInt(proxyPort)));
        if (StringUtils.isNoneBlank(userName) && StringUtils.isNoneBlank(password)) {
            Authenticator.setDefault(new BasicAuthenticator(userName, password));
        }
        urlConn = realUrl.openConnection(newProxy);
    } else {
        urlConn = realUrl.openConnection();
    }
    /**
     * 设置http头通用的请求属性
     */
    urlConn.setRequestProperty(HttpHeaders.ACCEPT, "*/*");
    urlConn.setRequestProperty(HttpHeaders.CONNECTION, "Keep-Alive");
    // 请求表示提交内容类型或返回返回内容的MIME类型
    urlConn.setRequestProperty(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded");
    // 设置 HttpURLConnection的字符编码,从而避免出现乱码
    urlConn.setRequestProperty(HttpHeaders.ACCEPT_CHARSET, URLCHARSET);
    // 浏览页面的访问者在用什么操作系统(包括版本号)、浏览器(包括版本号)等
    urlConn.setRequestProperty(HttpHeaders.USER_AGENT, UserAgentType.PC_Firefox.getValue());
    boolean useHttps = url.startsWith("https");
    if (useHttps) {
        HttpsURLConnection httpsConn = (HttpsURLConnection) realUrl.openConnection();
        // 创建SSLContext对象,并使用我们指定的信任管理器初始化
        TrustManager[] tm = { new MyX509TrustManager() };
        SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
        sslContext.init(null, tm, new java.security.SecureRandom());
        // 从上述SSLContext对象中得到SSLSocketFactory对象
        SSLSocketFactory ssf = sslContext.getSocketFactory();
        httpsConn.setSSLSocketFactory(ssf);
        httpConn = (HttpsURLConnection) httpsConn;
    } else {
        httpConn = (HttpURLConnection) urlConn;
    }
    boolean caches = true;
    /**
     * 发送POST请求必须设置如下所示
     */
    if ("POST".equalsIgnoreCase(ReqMethod)) {
        /**
         * 1.设置是否向httpUrlConnection输出,默认情况下是false<BR/>
         * 2.是否打开输出流 true|false,表示向服务器写数据
         */
        httpConn.setDoOutput(true);
        /**
         * 1.设置是否从httpUrlConnection读入,默认情况下是true<br/>
         * 2.是否打开输入流true|false,表示从服务器获取数据
         */
        httpConn.setDoInput(true);
        /**
         * 1.是否缓存true|false<BR/>
         * 2.Post 请求不能使用缓存
         */
        caches = false;
    }
    // 是否缓存true|false
    httpConn.setUseCaches(caches);
    // 设置连接超时时间,单位毫秒
    httpConn.setConnectTimeout(10 * 1000);
    // 设置读取数据超时时间,单位毫秒
    httpConn.setReadTimeout(60 * 1000);
    // 设置 HttpURLConnection的请求方式-->POST|GET,默认是GET
    if (POST_HTTP.equalsIgnoreCase(ReqMethod)) {
        httpConn.setRequestMethod(POST_HTTP);
    } else if (GET_HTTP.equalsIgnoreCase(ReqMethod)) {
        httpConn.setRequestMethod(GET_HTTP);
    }
    /**
     * 参数配置必须要在connect之前完成
     */
    return httpConn;
}
Also used : RuntimeExceptionHelper(com.cdeledu.common.exception.RuntimeExceptionHelper) InetSocketAddress(java.net.InetSocketAddress) SSLContext(javax.net.ssl.SSLContext) URL(java.net.URL) TrustManager(javax.net.ssl.TrustManager) MyX509TrustManager(com.cdeledu.common.network.MyX509TrustManager) Proxy(java.net.Proxy) HttpURLConnection(java.net.HttpURLConnection) BasicAuthenticator(com.cdeledu.common.httpEntity.BasicAuthenticator) SSLSocketFactory(javax.net.ssl.SSLSocketFactory) HttpsURLConnection(javax.net.ssl.HttpsURLConnection) MyX509TrustManager(com.cdeledu.common.network.MyX509TrustManager)

Example 4 with RuntimeExceptionHelper

use of com.cdeledu.common.exception.RuntimeExceptionHelper in project wechat by dllwh.

the class XmlUtils method toStr.

/**
 * 将XML文档转换为String<br>
 * 此方法会修改Document中的字符集
 *
 * @param doc
 *            XML文档
 * @param charset
 *            自定义XML的字符集
 * @return XML字符串
 */
public static String toStr(Document doc, String charset) {
    try {
        StringWriter writer = StringUtilHelper.getWriter();
        final Transformer xformer = TransformerFactory.newInstance().newTransformer();
        xformer.setOutputProperty(OutputKeys.ENCODING, charset);
        xformer.setOutputProperty(OutputKeys.INDENT, "yes");
        xformer.transform(new DOMSource(doc), new StreamResult(writer));
        return writer.toString();
    } catch (Exception e) {
        throw new RuntimeExceptionHelper("Trans xml document to string error!", e);
    }
}
Also used : DOMSource(javax.xml.transform.dom.DOMSource) Transformer(javax.xml.transform.Transformer) StringWriter(java.io.StringWriter) StreamResult(javax.xml.transform.stream.StreamResult) RuntimeExceptionHelper(com.cdeledu.common.exception.RuntimeExceptionHelper) DocumentException(org.dom4j.DocumentException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) SAXException(org.xml.sax.SAXException)

Example 5 with RuntimeExceptionHelper

use of com.cdeledu.common.exception.RuntimeExceptionHelper in project wechat by dllwh.

the class NetworkUtil method localIpv4s.

/**
 * @方法:获得本机的IP地址列表
 * @创建人:独泪了无痕
 * @return
 */
public static final Set<String> localIpv4s() {
    Enumeration<NetworkInterface> networkInterfaces = null;
    try {
        networkInterfaces = NetworkInterface.getNetworkInterfaces();
    } catch (SocketException e) {
        throw new RuntimeExceptionHelper(e.getMessage(), e);
    }
    if (networkInterfaces == null) {
        throw new RuntimeExceptionHelper("Get network interface error!");
    }
    final HashSet<String> ipSet = new HashSet<String>();
    while (networkInterfaces.hasMoreElements()) {
        final NetworkInterface networkInterface = networkInterfaces.nextElement();
        final Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses();
        while (inetAddresses.hasMoreElements()) {
            final InetAddress inetAddress = inetAddresses.nextElement();
            if (inetAddress != null && inetAddress instanceof Inet4Address) {
                ipSet.add(inetAddress.getHostAddress());
            }
        }
    }
    return ipSet;
}
Also used : SocketException(java.net.SocketException) Inet4Address(java.net.Inet4Address) RuntimeExceptionHelper(com.cdeledu.common.exception.RuntimeExceptionHelper) NetworkInterface(java.net.NetworkInterface) InetAddress(java.net.InetAddress) HashSet(java.util.HashSet)

Aggregations

RuntimeExceptionHelper (com.cdeledu.common.exception.RuntimeExceptionHelper)5 ParserConfigurationException (javax.xml.parsers.ParserConfigurationException)3 DocumentException (org.dom4j.DocumentException)3 SAXException (org.xml.sax.SAXException)3 DocumentBuilder (javax.xml.parsers.DocumentBuilder)2 DocumentBuilderFactory (javax.xml.parsers.DocumentBuilderFactory)2 BasicAuthenticator (com.cdeledu.common.httpEntity.BasicAuthenticator)1 MyX509TrustManager (com.cdeledu.common.network.MyX509TrustManager)1 StringWriter (java.io.StringWriter)1 HttpURLConnection (java.net.HttpURLConnection)1 Inet4Address (java.net.Inet4Address)1 InetAddress (java.net.InetAddress)1 InetSocketAddress (java.net.InetSocketAddress)1 NetworkInterface (java.net.NetworkInterface)1 Proxy (java.net.Proxy)1 SocketException (java.net.SocketException)1 URL (java.net.URL)1 HashSet (java.util.HashSet)1 HttpsURLConnection (javax.net.ssl.HttpsURLConnection)1 SSLContext (javax.net.ssl.SSLContext)1