f82f947c962674daed06830f08b211b43cd1387d.svn-base 12 KB

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