61d0911820c721fbd4f0d63c7e92e8342b67abe9.svn-base 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  1. package com.iamberry.app.api.util;
  2. import static com.iamberry.app.config.ImberryConfig.SMS_PASSWORD;
  3. import static com.iamberry.app.config.ImberryConfig.SMS_TEXT;
  4. import static com.iamberry.app.config.ImberryConfig.SMS_URL;
  5. import static com.iamberry.app.config.ImberryConfig.SMS_USERNAME;
  6. import java.io.BufferedReader;
  7. import java.io.IOException;
  8. import java.io.InputStream;
  9. import java.io.InputStreamReader;
  10. import java.text.MessageFormat;
  11. import java.text.ParseException;
  12. import java.text.SimpleDateFormat;
  13. import java.util.ArrayList;
  14. import java.util.Calendar;
  15. import java.util.Date;
  16. import java.util.HashMap;
  17. import java.util.List;
  18. import java.util.Map;
  19. import java.util.Random;
  20. import javax.servlet.http.HttpServletRequest;
  21. import org.apache.http.HttpEntity;
  22. import org.apache.http.NameValuePair;
  23. import org.apache.http.client.entity.UrlEncodedFormEntity;
  24. import org.apache.http.client.methods.CloseableHttpResponse;
  25. import org.apache.http.client.methods.HttpPost;
  26. import org.apache.http.entity.ContentType;
  27. import org.apache.http.entity.mime.MultipartEntityBuilder;
  28. import org.apache.http.entity.mime.content.StringBody;
  29. import org.apache.http.impl.client.CloseableHttpClient;
  30. import org.apache.http.impl.client.HttpClients;
  31. import org.apache.http.message.BasicNameValuePair;
  32. import org.apache.http.util.EntityUtils;
  33. import com.iamberry.app.config.Constants;
  34. import com.iamberry.app.core.dto.RecordDTO;
  35. import com.iamberry.app.tool.dto.AddressDTO;
  36. import com.iamberry.app.tool.util.HttpUtility;
  37. import com.iamberry.app.tool.util.JsonParseUtil;
  38. import com.iamberry.app.tool.util.Result;
  39. import com.thoughtworks.xstream.XStream;
  40. import com.thoughtworks.xstream.io.xml.StaxDriver;
  41. public class Utility {
  42. public static String DATA_STORE = "";
  43. private static final String AB = "123456789abcdefghijklmnpqrstuvwxyz";
  44. private static Random rnd = new Random();
  45. public static String getDateByDay() {
  46. Calendar cal = Calendar.getInstance();
  47. StringBuffer buffer = new StringBuffer();
  48. buffer.append(cal.get(Calendar.YEAR));
  49. buffer.append(cal.get(Calendar.MONTH) + 1);
  50. buffer.append(cal.get(Calendar.DAY_OF_MONTH));
  51. return buffer.toString();
  52. }
  53. public static boolean contains(String[] array, String item) {
  54. try {
  55. for (int i = 0; i < array.length; i++) {
  56. if (array[i].equals(item)) {
  57. return true;
  58. }
  59. }
  60. } catch (Exception ex) {
  61. }
  62. return false;
  63. }
  64. public static String normalizePath(String path) {
  65. return path.replace("\\\\", "\\").replace("\\", "/").replace("//", "/").replace("..", ".");
  66. }
  67. public static String getRandomString(int len) {
  68. StringBuilder sb = new StringBuilder(len);
  69. for (int i = 0; i < len; i++)
  70. sb.append(AB.charAt(rnd.nextInt(AB.length())));
  71. return sb.toString();
  72. }
  73. public static int CalculateAge(Long date) {
  74. Date birthDate = new Date(0);
  75. if (date != null)
  76. birthDate = new Date(date);
  77. SimpleDateFormat format = new SimpleDateFormat("yyyy");
  78. int birthYear = Integer.parseInt(format.format(birthDate));
  79. int currentYear = Integer.parseInt(format.format(new Date(System.currentTimeMillis())));
  80. int age = currentYear - birthYear;
  81. return age;
  82. }
  83. public static List<RecordDTO> convertMap(List<Map<String, Object>> list, String dateType) {
  84. List<RecordDTO> maps = new ArrayList<RecordDTO>();
  85. try {
  86. SimpleDateFormat sdf = null;
  87. for (Map<String, Object> map : list) {
  88. switch (dateType) {
  89. case "days":
  90. sdf = new SimpleDateFormat("yyyyMMddHH");
  91. break;
  92. case "weeks":
  93. sdf = new SimpleDateFormat("yyyyMMdd");
  94. break;
  95. case "years":
  96. sdf = new SimpleDateFormat("yyyyMM");
  97. break;
  98. }
  99. Date key = sdf.parse(map.get(dateType).toString());
  100. Double value = Double.parseDouble(map.get("volume").toString());
  101. maps.add(new RecordDTO(key.getTime(), value));
  102. }
  103. } catch (Exception e) {
  104. }
  105. return maps;
  106. }
  107. public static Map<String, List<RecordDTO>> synAppMachineRecord(Map<String, List<RecordDTO>> oldMap) {
  108. Map<String, List<RecordDTO>> synMap = oldMap;
  109. int appSize = synMap.get("app").size();
  110. int machineSize = synMap.get("machine").size();
  111. int signer = 0;
  112. long appDate = 0l, machineDate = 0l;
  113. RecordDTO appRecord, machineRecord;
  114. for (int i = 0; i < appSize && i < machineSize; i++) {
  115. appRecord = synMap.get("app").get(i);
  116. machineRecord = synMap.get("machine").get(signer);
  117. appDate = appRecord.getRecordDate();
  118. machineDate = machineRecord.getRecordDate();
  119. if (appDate == machineDate) {
  120. signer++;
  121. } else if (appDate < machineDate) {
  122. synMap.get("machine").add(i, new RecordDTO(appDate, 0));
  123. machineSize++;
  124. signer++;
  125. } else {
  126. synMap.get("app").add(signer, new RecordDTO(machineDate, 0));
  127. appSize++;
  128. signer++;
  129. }
  130. }
  131. while (signer < machineSize) {
  132. synMap.get("app").add(new RecordDTO(synMap.get("machine").get(signer).getRecordDate(), 0));
  133. signer++;
  134. }
  135. while (signer < appSize) {
  136. synMap.get("machine").add(new RecordDTO(synMap.get("app").get(signer).getRecordDate(), 0));
  137. signer++;
  138. }
  139. return synMap;
  140. }
  141. public static Map<String, List<RecordDTO>> fillAppMachineRecordWithZero(Map<String, List<RecordDTO>> synedMap, String dataType,
  142. String chosenDate) {
  143. Map<String, List<RecordDTO>> fillMap = synedMap;
  144. Calendar calendar = Calendar.getInstance();
  145. List<Integer> existTimePoint = new ArrayList<Integer>();
  146. long timePoint = 0l;
  147. switch (dataType) {
  148. case "days":
  149. if (fillMap.get("app").isEmpty()) {
  150. calendar.setTime(Utility.formatStringToDate("yyyy-MM-dd HH:mm:ss", chosenDate));
  151. }
  152. fillMap.get("app").forEach(record -> {
  153. calendar.setTime(new Date(record.getRecordDate()));
  154. existTimePoint.add(calendar.get(Calendar.HOUR_OF_DAY));
  155. });
  156. for (int i = 0; i < 24; i++) {
  157. if (!existTimePoint.remove(new Integer(i))) {
  158. calendar.set(Calendar.HOUR_OF_DAY, i);
  159. timePoint = calendar.getTimeInMillis();
  160. fillMap.get("app").add(i, new RecordDTO(timePoint, 0));
  161. fillMap.get("machine").add(i, new RecordDTO(timePoint, 0));
  162. }
  163. }
  164. break;
  165. case "weeks":
  166. if (fillMap.get("app").isEmpty()) {
  167. calendar.setTime(Utility.formatStringToDate("yyyy-MM-dd HH:mm:ss", chosenDate));
  168. }
  169. fillMap.get("app").forEach(record -> {
  170. calendar.setTime(new Date(record.getRecordDate()));
  171. existTimePoint.add(calendar.get(Calendar.DAY_OF_WEEK));
  172. });
  173. if (existTimePoint.contains(new Integer(1))) {
  174. calendar.add(Calendar.DATE, -7);
  175. }
  176. for (int i = 2; i <= 7; i++) {
  177. if (!existTimePoint.remove(new Integer(i))) {
  178. calendar.set(Calendar.DAY_OF_WEEK, i);
  179. timePoint = calendar.getTimeInMillis();
  180. fillMap.get("app").add(i - 2, new RecordDTO(timePoint, 0));
  181. fillMap.get("machine").add(i - 2, new RecordDTO(timePoint, 0));
  182. }
  183. }
  184. if (!existTimePoint.contains(new Integer(1))) {
  185. calendar.add(Calendar.DATE, 7);
  186. calendar.set(Calendar.DAY_OF_WEEK, 1);
  187. timePoint = calendar.getTimeInMillis();
  188. fillMap.get("app").add(new RecordDTO(timePoint, 0));
  189. fillMap.get("machine").add(new RecordDTO(timePoint, 0));
  190. }
  191. break;
  192. case "years":
  193. if (fillMap.get("app").isEmpty()) {
  194. calendar.setTime(Utility.formatStringToDate("yyyy-MM-dd HH:mm:ss", chosenDate));
  195. }
  196. fillMap.get("app").forEach(record -> {
  197. calendar.setTime(new Date(record.getRecordDate()));
  198. existTimePoint.add(calendar.get(Calendar.MONTH));
  199. });
  200. for (int i = 0; i <= 11; i++) {
  201. if (!existTimePoint.remove(new Integer(i))) {
  202. calendar.set(Calendar.MONTH, i);
  203. timePoint = calendar.getTimeInMillis();
  204. fillMap.get("app").add(i, new RecordDTO(timePoint, 0));
  205. fillMap.get("machine").add(i, new RecordDTO(timePoint, 0));
  206. }
  207. }
  208. break;
  209. }
  210. return fillMap;
  211. }
  212. public static String getRandomCode(int len) {
  213. StringBuilder sb = new StringBuilder(len);
  214. for (int i = 0; i < len; i++)
  215. sb.append("0123456789".charAt(rnd.nextInt("0123456789".length())));
  216. return sb.toString();
  217. }
  218. public static String getIp(HttpServletRequest request) {
  219. String ip = request.getHeader("x-forwarded-for");
  220. if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
  221. ip = request.getHeader("Proxy-Client-IP");
  222. }
  223. if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
  224. ip = request.getHeader("WL-Proxy-Client-IP");
  225. }
  226. if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
  227. ip = request.getRemoteAddr();
  228. }
  229. // 获取ip地址, 若多级代理,第一个IP为客户端真实IP,多个IP按照','分割
  230. if (ip != null && ip.indexOf(",") != -1) {
  231. ip = ip.split(",")[0];
  232. }
  233. return ip;
  234. }
  235. public static String CDN_WRITE_BASE_64_URL = "http://cms.iamberry.com/open-cdn/ssl/data/write/base64";
  236. public static String uploadBase64File(String base64Data, String path) {
  237. try {
  238. if (base64Data != null) {
  239. StringBody pic = new StringBody(base64Data, ContentType.DEFAULT_TEXT);
  240. StringBody type = new StringBody("jpg", ContentType.TEXT_PLAIN);
  241. HttpEntity entity = MultipartEntityBuilder.create().addPart("type", type).addPart("base64data", pic)
  242. .build();
  243. String result = HttpUtility.httpsPost(CDN_WRITE_BASE_64_URL, entity);
  244. // JSONObject json = new JSONObject(result);
  245. // int requestSatus = json.getJSONObject("header").getInt("status");
  246. // if (1000 == requestSatus) {
  247. // path = json.getJSONObject("data").get("url").toString();
  248. // }
  249. return path;
  250. }
  251. } catch (Exception e) {
  252. return null;
  253. }
  254. return "";
  255. }
  256. public static String readFile(InputStream in) {
  257. BufferedReader reader = null;
  258. String result = "";
  259. try {
  260. InputStreamReader inputStreamReader = new InputStreamReader(in, "UTF-8");
  261. reader = new BufferedReader(inputStreamReader);
  262. String tempString = null;
  263. while ((tempString = reader.readLine()) != null) {
  264. result += tempString;
  265. }
  266. reader.close();
  267. } catch (IOException e) {
  268. e.printStackTrace();
  269. } finally {
  270. if (reader != null) {
  271. try {
  272. reader.close();
  273. } catch (IOException e) {
  274. e.printStackTrace();
  275. }
  276. }
  277. }
  278. return result;
  279. }
  280. public static String sendCodeAsSMS(String phoneNum, Map<String, Integer> status) throws Exception {
  281. String code = getRandomCode(4);
  282. CloseableHttpClient client = HttpClients.createDefault();
  283. Map<String, String> params = new HashMap<String, String>();
  284. CloseableHttpResponse response = null;
  285. params.put("username", SMS_USERNAME);
  286. params.put("password", SMS_PASSWORD);
  287. params.put("mobile", phoneNum);
  288. params.put("content", MessageFormat.format(SMS_TEXT, code));
  289. HttpPost method = new HttpPost(SMS_URL);
  290. if (params != null) {
  291. List<NameValuePair> paramList = new ArrayList<NameValuePair>();
  292. for (Map.Entry<String, String> param : params.entrySet()) {
  293. NameValuePair pair = new BasicNameValuePair(param.getKey(), param.getValue());
  294. paramList.add(pair);
  295. }
  296. method.setEntity(new UrlEncodedFormEntity(paramList, "UTF-8"));
  297. }
  298. response = client.execute(method);
  299. HttpEntity entity = response.getEntity();
  300. if (entity != null) {
  301. String result = EntityUtils.toString(entity);
  302. XStream xs = new XStream(new StaxDriver());
  303. xs.alias("result", Result.class);
  304. Result object = (Result)xs.fromXML(result);
  305. response.close();
  306. status.put(Constants.SMS_RETURNCODE, object.getResultcode());
  307. if (0 == object.getResultcode()) {
  308. return code;
  309. }
  310. }
  311. return null;
  312. }
  313. public static AddressDTO getDefaultAddress(String jsonList) {
  314. List<AddressDTO> addressDTOs = JsonParseUtil.parseAddressList(jsonList);
  315. for (AddressDTO addressDTO : addressDTOs) {
  316. if (addressDTO.getDefaultAddress() == 1) {
  317. return addressDTO;
  318. }
  319. }
  320. return null;
  321. }
  322. public static String getOrderSn(Long id) {
  323. if (id == null)
  324. throw new NullPointerException("id can not be null");
  325. SimpleDateFormat format = new SimpleDateFormat("yyMMdd");
  326. String date = format.format(new Date());
  327. String sn = String.format("%0" + 5 + "d", id);
  328. return "LTR" + date + sn;
  329. }
  330. public static String formatDateToString(String format, Date date) {
  331. SimpleDateFormat sdf = new SimpleDateFormat(format);
  332. return sdf.format(date);
  333. }
  334. public static Date formatStringToDate(String format, String dateStr) {
  335. SimpleDateFormat sdf = new SimpleDateFormat(format);
  336. Date date = null;
  337. try {
  338. date = sdf.parse(dateStr);
  339. } catch (ParseException e) {
  340. e.printStackTrace();
  341. date = new Date();
  342. }
  343. return date;
  344. }
  345. }