diff --git a/yxt-supervise-monitor-biz/pom.xml b/yxt-supervise-monitor-biz/pom.xml index a2f7715..fa221be 100644 --- a/yxt-supervise-monitor-biz/pom.xml +++ b/yxt-supervise-monitor-biz/pom.xml @@ -70,6 +70,14 @@ javacv-platform 1.3.3 + + + + net.sf.json-lib + json-lib + 2.4 + jdk15 + diff --git a/yxt-supervise-monitor-biz/src/main/java/com/yxt/supervise/monitor/biz/call/CallRest.java b/yxt-supervise-monitor-biz/src/main/java/com/yxt/supervise/monitor/biz/call/CallRest.java new file mode 100644 index 0000000..a1606f4 --- /dev/null +++ b/yxt-supervise-monitor-biz/src/main/java/com/yxt/supervise/monitor/biz/call/CallRest.java @@ -0,0 +1,181 @@ +package com.yxt.supervise.monitor.biz.call; + +import cn.hutool.core.bean.BeanUtil; +import cn.hutool.http.HttpUtil; +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import com.yxt.common.core.query.PagerQuery; +import com.yxt.common.core.result.ResultBean; +import com.yxt.common.core.vo.PagerVo; +import com.yxt.supervise.monitor.api.demobaseentity.DemoBaseentity; +import com.yxt.supervise.monitor.api.demobaseentity.DemoBaseentityDto; +import com.yxt.supervise.monitor.api.demobaseentity.DemoBaseentityQuery; +import com.yxt.supervise.monitor.api.demobaseentity.DemoBaseentityVo; +import com.yxt.supervise.monitor.biz.demobaseentity.DemoBaseentityService; +import com.yxt.supervise.monitor.biz.util.HttpUtils; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import org.apache.http.client.methods.HttpGet; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import java.io.IOException; +import java.security.KeyManagementException; +import java.security.KeyStoreException; +import java.security.NoSuchAlgorithmException; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@Api(tags = "基础实体类") +@RestController("com.yxt.supervise.monitor.biz.call.CallRest") +@RequestMapping("/call") +public class CallRest { + + @Autowired + private DemoBaseentityService demoBaseentityService; + + @ApiOperation("根据条件分页查询数据的列表") + @PostMapping("/listPage") + public ResultBean> listPage(@RequestBody PagerQuery pq) { + ResultBean rb = ResultBean.fireFail(); + PagerVo pv = demoBaseentityService.listPageVo(pq); + return rb.success().setData(pv); + } + + @ApiOperation("获取token") + @GetMapping("/getCallToken") + public String getCallToken() throws Exception { + String url = "https://api2.hik-cloud.com/oauth/token"; + Map param = new HashMap<>(); + param.put("client_id", "e8e655dfcb154be6962f270fe375edc1"); // 客户端ID String + param.put("client_secret", "3ca20239398c4b86b27c6a080d8345e1"); //访问密钥 String + param.put("grant_type", "client_credentials"); //认证模式 String 目前仅支持client_credentials + String result = HttpUtils.sendPostMap(url, param,""); + return result; + } + + @ApiOperation("获取子系统列表") + @GetMapping("/getCallSonList") + public String getCallSonList() throws NoSuchAlgorithmException, KeyStoreException, IOException, KeyManagementException { + // deviceSerial 设备序列号 String + String url = "https://api2.hik-cloud.com/api/v1/device/isapi/alarmHost/subSystems?deviceSerial=Q16362484"; + String result = HttpUtils.sendGet(url, "35ad3e80-1de4-4477-827e-0473320cf644"); + return result; + } + + @ApiOperation("子系统布防") + @GetMapping("/getCallArm") + public String getCallArm() { + ResultBean rb = ResultBean.fireFail(); + String url = "https://api2.hik-cloud.com/api/v1/device/isapi/alarmHost/subSystem/arm"; + Map param = new HashMap<>(); + param.put("deviceSerial", "Q16362484"); //设备序列号 string + param.put("sysId", 2); //子系统id int + param.put("armType", "stay"); //布防类型,stay:在家布防;away:外出布防 string + String paramJson = JSONObject.toJSONString(param); + String result = HttpUtils.sendPostJson(url, paramJson, "35ad3e80-1de4-4477-827e-0473320cf644"); + return result; + } + + @ApiOperation("子系统撤防") + @GetMapping("/getCallDisArm") + public String getCallDisArm(){ + ResultBean rb = ResultBean.fireFail(); + String url = "https://api2.hik-cloud.com/api/v1/device/isapi/alarmHost/subSystem/disarm"; + Map param = new HashMap<>(); + param.put("deviceSerial", "Q16362484"); // 设备序列号 string + param.put("sysId", 1); // 子系统id int + String paramJson = JSONObject.toJSONString(param); + String result = HttpUtils.sendPostJson(url, paramJson, "35ad3e80-1de4-4477-827e-0473320cf644"); + return result; + } + + @ApiOperation("创建消息消费者") + @GetMapping("/createCallConsumer") + public String createConsumer() { + /** + * 1.该接口用于创建消费者ID,最多同时存在五个消费者ID。 + * + * 2.消费者如果5分钟未调用拉取消息接口将被删除。 + */ + ResultBean rb = ResultBean.fireFail(); + String url = "https://api2.hik-cloud.com/api/v1/mq/consumer/group1"; + Map param = new HashMap<>(); + String result = HttpUtils.sendPostMap(url, param, "35ad3e80-1de4-4477-827e-0473320cf644"); + return result; + } + + @ApiOperation("获取消息列表") + @GetMapping("/getCallMessageList") + public String getMessageList(String consumerId) { + /** + * 1.该接口用于创建消费者ID,最多同时存在五个消费者ID。 + * + * 2.消费者如果5分钟未调用拉取消息接口将被删除。 + */ + ResultBean rb = ResultBean.fireFail(); + String url = "https://api2.hik-cloud.com/api/v1/mq/consumer/messages"; + Map param = new HashMap<>(); + param.put("consumerId", consumerId); // 消费者id string +// param.put("consumerId", "220bb942f63746d5a885703659bf08cd"); // 消费者id string + String result = HttpUtils.sendPostMap(url, param, "35ad3e80-1de4-4477-827e-0473320cf644"); + return result; + } + + @ApiOperation("提交消息偏移量") + @GetMapping("/doCallMessageOffsets") + public String doMessageOffsets(String consumerId){ + /** + * 1.该接口用于创建消费者ID,最多同时存在五个消费者ID。 + * + * 2.消费者如果5分钟未调用拉取消息接口将被删除。 + */ + ResultBean rb = ResultBean.fireFail(); + String url = "https://api2.hik-cloud.com/api/v1/mq/consumer/offsets"; + Map param = new HashMap<>(); + param.put("consumerId", consumerId); // 消费者id string +// param.put("consumerId", "220bb942f63746d5a885703659bf08cd"); // 消费者id string + String result = HttpUtils.sendPostMap(url, param, "35ad3e80-1de4-4477-827e-0473320cf644"); + return result; + } + + + @ApiOperation("获取所有防区状态") + @GetMapping("/getCallZoneStatusList") + public String getCallZoneStatusList(String consumerId) throws NoSuchAlgorithmException, KeyStoreException, IOException, KeyManagementException { + String url = "https://api2.hik-cloud.com/api/v1/device/isapi/alarmHost/zoneStatus/list?deviceSerial=Q16362484"; + String result = HttpUtils.sendGet(url, "35ad3e80-1de4-4477-827e-0473320cf644"); + return result; + } + + @ApiOperation("新增") + @PostMapping("/insert") + public ResultBean save(@RequestBody DemoBaseentityDto dto) { + return demoBaseentityService.saveInsert(dto); + } + + @ApiOperation("修改") + @PostMapping("/update") + public ResultBean update(@RequestBody DemoBaseentityDto dto) { + return demoBaseentityService.saveUpdate(dto); + } + + @ApiOperation("根据sid查询") + @GetMapping("/fetchVoBySid/{sid}") + public ResultBean fetchVoBySid(@PathVariable String sid) { + ResultBean rb = ResultBean.fireFail(); + DemoBaseentity entity = demoBaseentityService.fetchBySid(sid); + DemoBaseentityVo vo = new DemoBaseentityVo(); + BeanUtil.copyProperties(entity, vo); + return rb.success().setData(vo); + } + + @ApiOperation("删除") + @DeleteMapping("/deleteBySid/{sid}") + public ResultBean deleteBySid(@PathVariable String sid) { + ResultBean rb = ResultBean.fireFail(); + int i = demoBaseentityService.deleteBySid(sid); + return rb.success().setMsg("删除成功"); + } +} diff --git a/yxt-supervise-monitor-biz/src/main/java/com/yxt/supervise/monitor/biz/util/HttpUtils.java b/yxt-supervise-monitor-biz/src/main/java/com/yxt/supervise/monitor/biz/util/HttpUtils.java new file mode 100644 index 0000000..92841f8 --- /dev/null +++ b/yxt-supervise-monitor-biz/src/main/java/com/yxt/supervise/monitor/biz/util/HttpUtils.java @@ -0,0 +1,464 @@ +package com.yxt.supervise.monitor.biz.util; + +import net.sf.json.JSONObject; +import org.apache.http.*; +import org.apache.http.client.ClientProtocolException; +import org.apache.http.client.CookieStore; +import org.apache.http.client.HttpClient; +import org.apache.http.client.config.RequestConfig; +import org.apache.http.client.entity.UrlEncodedFormEntity; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.conn.ClientConnectionManager; +import org.apache.http.conn.scheme.Scheme; +import org.apache.http.conn.scheme.SchemeRegistry; +import org.apache.http.conn.ssl.SSLConnectionSocketFactory; +import org.apache.http.conn.ssl.SSLSocketFactory; +import org.apache.http.cookie.Cookie; +import org.apache.http.entity.ContentType; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.BasicCookieStore; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.DefaultHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.message.BasicNameValuePair; +import org.apache.http.ssl.SSLContextBuilder; +import org.apache.http.ssl.TrustStrategy; +import org.apache.http.util.EntityUtils; + +import javax.net.ssl.SSLContext; +import javax.net.ssl.TrustManager; +import javax.net.ssl.X509TrustManager; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.HttpURLConnection; +import java.net.URL; +import java.security.KeyManagementException; +import java.security.KeyStoreException; +import java.security.NoSuchAlgorithmException; +import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +/** + * Created by Administrator on 2019/4/11. + */ +public class HttpUtils { + + private static CloseableHttpClient httpClient; + + /** + * 创建没有证书的SSL链接工厂类 + * + * @return + * @throws NoSuchAlgorithmException + * @throws KeyStoreException + * @throws KeyManagementException + */ + public static SSLConnectionSocketFactory getSSLConnectionSocketFactory() throws NoSuchAlgorithmException, + KeyStoreException, KeyManagementException { + SSLContextBuilder context = new SSLContextBuilder().useProtocol("TLSv1.2"); + + context.loadTrustMaterial(null, new TrustStrategy() { + + public boolean isTrusted(X509Certificate[] arg0, String arg1) + throws CertificateException { + // TODO Auto-generated method stub + return false; + } + // @Override + // public boolean isTrusted(X509Certificate[] arg0, String arg1) + // throws CertificateException { + // return true; + // } + }); + return new SSLConnectionSocketFactory(context.build()); + } + + /** + * 发送HttpPost请求,参数为map + * @param url + * @param params + * @return + */ + public static String sendPostJson(String url, String params,String token) { + CloseableHttpClient httpclient = HttpClients.createDefault(); + String EntityStr = null; + try { + HttpPost httppost = new HttpPost(url); +// for (Map.Entry entry : maps.entrySet()) {//设置header +// httppost.setHeader(entry.getKey(),entry.getValue().toString()); +// +// } + httppost.setEntity(new StringEntity(params, ContentType.create("application/json", "UTF-8"))); +// StringEntity stringEntity = new StringEntity(params, "UTF-8"); +// stringEntity.setContentType("application/json"); +// httppost.setEntity(stringEntity); + +// httppost.setHeader("Content-Type", "application/json"); + httppost.setHeader("Authorization", "Bearer " + token); + + CloseableHttpResponse response = httpclient.execute(httppost); + try { + HttpEntity resEntity = response.getEntity(); + if (resEntity != null) { + EntityStr = EntityUtils.toString(response.getEntity()); + // System.out.println("返回信息--" + EntityStr); + + } else { + + } + EntityUtils.consume(resEntity); + } finally { + response.close(); + } + } catch (ClientProtocolException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } finally { + try { + httpclient.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + return EntityStr; + } + + /** + * post方式访问 + * + * @param url 路径 + * @param map 参数 + * @return + */ + public static String sendPostMap(String url, Map map, String token) { + + String charset = "UTF-8"; + HttpClient httpClient = null; + HttpPost httpPost = null; + String result = null; + + try { + httpClient = new SSLClient(); + httpPost = new HttpPost(url); + //设置参数 + + List list = new ArrayList(); + Iterator iterator = map.entrySet().iterator(); + while (iterator.hasNext()) { + Map.Entry elem = (Map.Entry) iterator.next(); + list.add(new BasicNameValuePair(elem.getKey(), elem.getValue())); + } + if (list.size() > 0) { + UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, charset); + httpPost.setEntity(entity); + } + if (token != "") { + httpPost.setHeader("Authorization", "Bearer " + token); + } + HttpResponse response = httpClient.execute(httpPost); + if (response != null) { + HttpEntity resEntity = response.getEntity(); + if (resEntity != null) { + result = EntityUtils.toString(resEntity, charset); + } + } + } catch (Exception ex) { + ex.printStackTrace(); + } + return result; + } + + /** + * 链接GET请求 + * + * @param url + * @return + * @throws KeyManagementException + * @throws NoSuchAlgorithmException + * @throws KeyStoreException + * @throws ClientProtocolException + * @throws IOException + */ + public static String sendGet(String url, String token) throws KeyManagementException, + NoSuchAlgorithmException, KeyStoreException, ClientProtocolException, IOException { + String[] strArray = new String[5]; + // 获取cookies信息 + CookieStore store = new BasicCookieStore(); + CloseableHttpClient client = HttpClients.custom().setDefaultCookieStore(store).build(); + HttpGet httpGet = null; + CloseableHttpResponse resp = null; + String jsonString = ""; + try { + httpGet = new HttpGet(url); + httpGet.setHeader("Authorization", "Bearer " + token); + resp = client.execute(httpGet); + //读取cookie信息 + List cookielist = store.getCookies(); + for (Cookie c : cookielist) { + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + String cookie_name = c.getName(); + String cookie_value = c.getValue(); + String cookie_expiry_date = sdf.format(c.getExpiryDate()); + } + + HttpEntity entity = resp.getEntity(); + jsonString = EntityUtils.toString(entity, "UTF-8"); + +// String headCookie = ""; +// Header[] hs = resp.getHeaders("Set-Cookie"); +// if (hs.length > 0) { +// headCookie = hs[0].toString(); +// } +// strArray[0] = headCookie; +// strArray[1] = jsonString; +// return strArray; + return jsonString; + } catch (Exception ex) { + return null; + } finally { + if (resp != null) { + try { + resp.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + if (httpGet != null) { + httpGet.releaseConnection(); + } + } + } + + /** + * 链接Post请求 (带类型的参数) + * + * @param url + * @param parameter + * @param cookies + * @return + * @throws Exception + */ + public static String PostFomData(String url, Map parameter, String cookies) throws Exception { + URL urls = new URL(url); + HttpURLConnection connection = null; + OutputStream outputStream = null; + String rs = null; + try { + connection = (HttpURLConnection) urls.openConnection(); + connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=----footfoodapplicationrequestnetwork"); + connection.setDoOutput(true); + connection.setDoInput(true); + connection.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.8"); + connection.setRequestProperty("Accept", "*/*"); + connection.setRequestProperty("Range", "bytes=" + ""); + connection.setRequestProperty("Cookie", cookies); + connection.setConnectTimeout(8000); + connection.setReadTimeout(20000); + connection.setRequestMethod("POST"); + + StringBuffer buffer = new StringBuffer(); + int len = 0; + if (parameter != null) + len = parameter.size(); + + for (Map.Entry vo : parameter.entrySet()) { + // vo.getKey(); + // vo.getValue(); + buffer.append("------footfoodapplicationrequestnetwork\r\n"); + buffer.append("Content-Disposition: form-data; name=\""); + buffer.append(vo.getKey()); + buffer.append("\"\r\n\r\n"); + buffer.append(vo.getValue()); + buffer.append("\r\n"); + } + if (parameter != null) + buffer.append("------footfoodapplicationrequestnetwork--\r\n"); + outputStream = connection.getOutputStream(); + outputStream.write(buffer.toString().getBytes()); + try { + connection.connect(); + if (connection.getResponseCode() == 200) { + InputStream is = connection.getInputStream(); + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + int i; + while ((i = is.read()) != -1) { + baos.write(i); + } + rs = baos.toString(); + JSONObject obj = JSONObject.fromObject(rs); + if (obj.getBoolean("success")) { + return "ok"; + } else { + String result_temp = UicodeBackslashU.unicodeToCn(obj.getString("error_desc")); + return result_temp; + } + // rs = getWebSource(connection.getInputStream()); + } + } catch (Exception e) { + rs = null; + } + return rs; + } finally { + try { + outputStream.close(); + } catch (Exception e) { + } + outputStream = null; + if (connection != null) + connection.disconnect(); + connection = null; + } + } + // ------------------------------------------------------------------------------------------------------- + + /** + * 链接POST请求 + * + * @param url + * @param jsonParm + * @return + * @throws KeyManagementException + * @throws NoSuchAlgorithmException + * @throws KeyStoreException + * @throws ClientProtocolException + * @throws IOException + */ + public static String connectPostJsonUrl(String url, String jsonParm, String token) throws KeyManagementException, + NoSuchAlgorithmException, KeyStoreException, ClientProtocolException, IOException { + SSLConnectionSocketFactory sslsf = getSSLConnectionSocketFactory(); + CloseableHttpClient client = HttpClients.custom().setSSLSocketFactory(sslsf).build(); + RequestConfig config = RequestConfig.custom().setSocketTimeout(10000).setConnectTimeout(5000).build(); + HttpPost httpPost = null; + CloseableHttpResponse resp = null; + try { + httpPost = new HttpPost(url); + httpPost.setConfig(config); + StringEntity params = new StringEntity(jsonParm, "UTF-8"); + params.setContentType("application/json"); + httpPost.setEntity(params); + + if (token != "") { + httpPost.setHeader("Authorization", "Bearer " + token); + } + resp = client.execute(httpPost); + + // 获取返回 + HttpEntity entity = resp.getEntity(); + String jsonString = EntityUtils.toString(entity, "UTF-8"); + jsonString = UicodeBackslashU.unicodeToCn(jsonString); + + // 获取头部 + Header[] hs = resp.getHeaders("Set-Cookie"); + String headCookie = hs[0].toString(); + + if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { + return jsonString; + } + } catch (IOException e) { + if (e instanceof org.apache.http.conn.ConnectTimeoutException) { + throw new org.apache.http.conn.ConnectTimeoutException("connect timed out"); + } + if (e instanceof java.net.SocketTimeoutException) { + throw new java.net.SocketTimeoutException("Read timed out"); + } +// System.out.println(e); + throw new IOException("IOException"); + } finally { + if (resp != null) { + try { + resp.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + if (httpPost != null) { + httpPost.releaseConnection(); + } + try { + client.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + return null; + } + + /** + * @param url + * @param jsonObj + * @return + */ + public static String postUrlEncoded2(String url, JSONObject jsonObj, String cookies) { + try { + HttpClient httpClient = new DefaultHttpClient();//申明一个网络访问客户端 + HttpPost post = new HttpPost(url);//post方式 + // 1. 头部 + post.setHeader("DataEncoding", "UTF-8"); + post.setHeader("Cookie", cookies); + + // 2. 内容 + StringEntity entity = new StringEntity(jsonObj.toString(), "utf-8"); + entity.setContentEncoding("UTF-8"); + entity.setContentType("application/x-www-form-urlencoded"); + post.setEntity(entity);//带上参数 + + // 3. 执行 + HttpResponse httpResponse = httpClient.execute(post);//响应结果 + String result = UicodeBackslashU.unicodeToCn(EntityUtils.toString(httpResponse.getEntity(), "UTF-8")); //向服务器请求之后返回的数据结果 + + // 4. 处理返回 + if (httpResponse.getStatusLine().getStatusCode() == 200) {//如果是200 表示成功 + JSONObject obj = JSONObject.fromObject(result); + if (obj.getBoolean("success")) { + return "ok"; + } else { + String result_temp = UicodeBackslashU.unicodeToCn(obj.getString("error_desc")); + return result_temp; + } + } + + // 5. 返回 + return result; + } catch (Exception e) { + // Log.i("post_exception", e.toString()); + return "提交数据到爱牵挂服务器异常!"; + } + + } + +} + +class SSLClient extends DefaultHttpClient { + //用于进行Https请求的HttpClient + public SSLClient() throws Exception { + super(); + SSLContext ctx = SSLContext.getInstance("TLS"); + X509TrustManager tm = new X509TrustManager() { + + public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { + } + + public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { + } + + public X509Certificate[] getAcceptedIssuers() { + return null; + } + }; + ctx.init(null, new TrustManager[]{tm}, null); + SSLSocketFactory ssf = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); + ClientConnectionManager ccm = this.getConnectionManager(); + SchemeRegistry sr = ccm.getSchemeRegistry(); + sr.register(new Scheme("https", 443, ssf)); + } +} diff --git a/yxt-supervise-monitor-biz/src/main/java/com/yxt/supervise/monitor/biz/util/UicodeBackslashU.java b/yxt-supervise-monitor-biz/src/main/java/com/yxt/supervise/monitor/biz/util/UicodeBackslashU.java new file mode 100644 index 0000000..338ea5e --- /dev/null +++ b/yxt-supervise-monitor-biz/src/main/java/com/yxt/supervise/monitor/biz/util/UicodeBackslashU.java @@ -0,0 +1,78 @@ +package com.yxt.supervise.monitor.biz.util; + +import java.util.regex.Pattern; + +public final class UicodeBackslashU { + // 单个字符的正则表达式 + private static final String singlePattern = "[0-9|a-f|A-F]"; + // 4个字符的正则表达式 + private static final String pattern = singlePattern + singlePattern + + singlePattern + singlePattern; + + + /** + * 把 \\u 开头的单字转成汉字,如 \\u6B65 -> 步 + * + * @param str + * @return + */ + private static String ustartToCn(final String str) { + StringBuilder sb = new StringBuilder().append("0x") + .append(str.substring(2, 6)); + Integer codeInteger = Integer.decode(sb.toString()); + int code = codeInteger.intValue(); + char c = (char) code; + return String.valueOf(c); + } + + /** + * 字符串是否以Unicode字符开头。约定Unicode字符以 \\u开头。 + * + * @param str 字符串 + * @return true表示以Unicode字符开头. + */ + private static boolean isStartWithUnicode(final String str) { + if (null == str || str.length() == 0) { + return false; + } + if (!str.startsWith("\\u")) { + return false; + } + // \u6B65 + if (str.length() < 6) { + return false; + } + String content = str.substring(2, 6); + + boolean isMatch = Pattern.matches(pattern, content); + return isMatch; + } + + /** + * 字符串中,所有以 \\u 开头的UNICODE字符串,全部替换成汉字 + * + * @param str + * @return + */ + public static String unicodeToCn(final String str) { + // 用于构建新的字符串 + StringBuilder sb = new StringBuilder(); + // 从左向右扫描字符串。tmpStr是还没有被扫描的剩余字符串。 + // 下面有两个判断分支: + // 1. 如果剩余字符串是Unicode字符开头,就把Unicode转换成汉字,加到StringBuilder中。然后跳过这个Unicode字符。 + // 2.反之, 如果剩余字符串不是Unicode字符开头,把普通字符加入StringBuilder,向右跳过1. + int length = str.length(); + for (int i = 0; i < length; ) { + String tmpStr = str.substring(i); + if (isStartWithUnicode(tmpStr)) { // 分支1 + sb.append(ustartToCn(tmpStr)); + i += 6; + } else { // 分支2 + sb.append(str.substring(i, i + 1)); + i++; + } + } + return sb.toString(); + } + +}