PushUtils.java 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  1. package com.lemon.lifecenter.scheduler.common;
  2. import java.io.FileNotFoundException;
  3. import java.io.IOException;
  4. import java.text.DateFormat;
  5. import java.text.ParseException;
  6. import java.text.SimpleDateFormat;
  7. import java.util.Calendar;
  8. import java.util.Date;
  9. import java.util.HashMap;
  10. import org.slf4j.Logger;
  11. import org.slf4j.LoggerFactory;
  12. import org.springframework.core.io.ClassPathResource;
  13. import org.springframework.stereotype.Component;
  14. import com.google.auth.oauth2.GoogleCredentials;
  15. import com.google.firebase.FirebaseApp;
  16. import com.google.firebase.FirebaseOptions;
  17. import com.google.firebase.messaging.AndroidConfig;
  18. import com.google.firebase.messaging.AndroidNotification;
  19. import com.google.firebase.messaging.ApnsConfig;
  20. import com.google.firebase.messaging.Aps;
  21. import com.google.firebase.messaging.ApsAlert;
  22. import com.google.firebase.messaging.AndroidNotification.Priority;
  23. import com.google.firebase.messaging.FirebaseMessaging;
  24. import com.google.firebase.messaging.FirebaseMessagingException;
  25. import com.google.firebase.messaging.Message;
  26. @Component
  27. public class PushUtils {
  28. private final Logger logger = LoggerFactory.getLogger(this.getClass());
  29. public HashMap<String, String> sendFcm(String deviceKey, String title, String content) {
  30. HashMap<String, String> result = new HashMap<String, String>();
  31. try {
  32. ClassPathResource cpr = new ClassPathResource("firebase/mcare-ctc-firebase-adminsdk-sn0dw-e165549145.json");
  33. FirebaseOptions options = new FirebaseOptions.Builder()
  34. .setCredentials(GoogleCredentials.fromStream(cpr.getInputStream()))
  35. .setDatabaseUrl("https://mcare-ctc.firebaseio.com/")
  36. .build();
  37. if (FirebaseApp.getApps().isEmpty()) {
  38. FirebaseApp.initializeApp(options);
  39. }
  40. String registrationToken = deviceKey;
  41. AndroidNotification notification = AndroidNotification.builder().setTitle(title).setBody(content).setPriority(Priority.MAX).build();
  42. AndroidConfig androidConfig = AndroidConfig.builder().setPriority(AndroidConfig.Priority.HIGH).setNotification(notification).setTtl(7200).build();
  43. ApsAlert apsAlert = ApsAlert.builder().setTitle(title).setBody(content).build();
  44. Aps aps = Aps.builder().setSound("default").setAlert(apsAlert).build();
  45. ApnsConfig apnsConfig = ApnsConfig.builder().setAps(aps).build();
  46. Message message = Message.builder()
  47. .setAndroidConfig(androidConfig)
  48. .setApnsConfig(apnsConfig)
  49. .setToken(registrationToken).build();
  50. String response = FirebaseMessaging.getInstance().send(message);
  51. result.put("success", "success");
  52. return result;
  53. } catch (FileNotFoundException e) {
  54. // logger.error("fileNotFound -- > " + e);
  55. result.put("FileNotFound", "FileNotFound");
  56. } catch (IOException e) {
  57. logger.error("IOException -- > " + e);
  58. result.put("IOException", "IOException");
  59. } catch (FirebaseMessagingException e) {
  60. // logger.error("FirebaseMessagingException -- > " + e);
  61. // logger.error("FirebaseMessagingException -- > " + e.getErrorCode());
  62. // logger.error("FirebaseMessagingException -- > " + e.getMessage());
  63. // result = errorMsg(e.getErrorCode().toString().trim());
  64. result.put(e.getErrorCode().toString().trim(), e.getMessage());
  65. }
  66. return result;
  67. }
  68. // private String errorMsg(String e) {
  69. // String msg = "";
  70. // if (fcmErrorCode().get(e) != null) {
  71. // msg = fcmErrorCode().get(e);
  72. // } else {
  73. // msg = fcmErrorCode().get("FATAL");
  74. // }
  75. //
  76. // return msg;
  77. // }
  78. //
  79. // private HashMap<String, String> fcmErrorCode() {
  80. // HashMap<String, String> code = new HashMap<String, String>();
  81. // code.put("UNSPECIFIED_ERROR", "이 오류에 대한 추가 정보가 없습니다.");
  82. // code.put("INVALID_ARGUMENT", "(HTTP 오류 코드 = 400) 요청 매개 변수가 유효하지 않습니다. google.rpc.BadRequest 유형의 확장자가 리턴되어 유효하지 않은 필드를 지정합니다.");
  83. // code.put("UNREGISTERED", " (HTTP 오류 코드 = 404) FCM에서 앱 인스턴스가 등록 해제되었습니다. 이것은 일반적으로 사용 된 토큰이 더 이상 유효하지 않으며 새로운 토큰을 사용해야 함을 의미합니다.");
  84. // code.put("SENDER_ID_MISMATCH", "(HTTP 오류 코드 = 403) 인증 된 발신자 ID가 등록 토큰의 발신자 ID와 다릅니다.");
  85. // code.put("QUOTA_EXCEEDED", "(HTTP 오류 코드 = 429) 메시지 대상에 대한 전송 제한이 초과되었습니다. 초과 한 할당량을 지정하기 위해 google.rpc.QuotaFailure 유형의 확장이 반환됩니다..");
  86. // code.put("UNAVAILABLE", " (HTTP 오류 코드 = 503) 서버가 과부하되었습니다.");
  87. // code.put("INTERNAL", "(HTTP 오류 코드 = 500) 알 수없는 내부 오류가 발생했습니다.");
  88. // code.put("THIRD_PARTY_AUTH_ERROR", "(HTTP 오류 코드 = 401) APN 인증서 또는 웹 푸시 인증 키가 잘못되었거나 없습니다.");
  89. // code.put("FATAL", "알수없는 오류");
  90. // code.put("FileNotFound", "FileNotFound");
  91. // code.put("IOException", "IOException");
  92. // return code;
  93. // }
  94. public String getNowYm() {
  95. DateFormat dateFormat = new SimpleDateFormat("yyyyMM");
  96. Date date = new Date();
  97. return dateFormat.format(date);
  98. }
  99. public String getNextYm() {
  100. DateFormat dateFormat = new SimpleDateFormat("yyyyMM");
  101. Calendar cal = Calendar.getInstance();
  102. cal.add (cal.MONTH, + 1); //다음달
  103. return dateFormat.format(cal.getTime());
  104. }
  105. public String getNow() {
  106. DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  107. Date date = new Date();
  108. return dateFormat.format(date);
  109. }
  110. public boolean compareDateTime(String dateTime) {
  111. boolean result = false;
  112. try {
  113. DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  114. Date date = new Date();
  115. Date nowTime = dateFormat.parse(dateFormat.format(date));
  116. Date sendTime = dateFormat.parse(dateTime);
  117. result = nowTime.after(sendTime) || nowTime.equals(sendTime);
  118. } catch (ParseException e) {
  119. // TODO Auto-generated catch block
  120. e.printStackTrace();
  121. result = false;
  122. }
  123. return result;
  124. }
  125. public boolean compareTime(String time) {
  126. boolean result = false;
  127. try {
  128. DateFormat dateFormat = new SimpleDateFormat("HH:mm");
  129. Date date = new Date();
  130. Date nowTime = dateFormat.parse(dateFormat.format(date));
  131. Date sendTime = dateFormat.parse(time);
  132. result = nowTime.equals(sendTime);
  133. } catch (ParseException e) {
  134. // TODO Auto-generated catch block
  135. e.printStackTrace();
  136. result = false;
  137. }
  138. return result;
  139. }
  140. // public void apnsSend() {
  141. // ClassPathResource cpr = new ClassPathResource("apns/dev/certify.p12");
  142. // logger.error("name -- > " + cpr.getFilename());
  143. // logger.error("path -- > " + cpr.getPath());
  144. // try {
  145. // logger.error("file -- > " + cpr.getFile().getAbsolutePath());
  146. //
  147. // ApnsService service =
  148. // APNS.newService()
  149. // .withCert(cpr.getFile().getAbsolutePath(), "jksong092") // 指定p12文件及密钥
  150. // .withSandboxDestination() // 使用苹果推送测试服务器
  151. // //.withProductionDestination() // 使用苹果推送生产服务器
  152. // .build();
  153. //
  154. // String payload = APNS.newPayload()
  155. //// .alertTitle("推送标题") // 标题
  156. // .alertBody("푸시발송 테스트") // 内容
  157. // .customField("sourceCode", "01") // 自定义字段
  158. // .customField("url", "https://www.qq.com") // 自定义字段
  159. // .sound("default") // 提示声音
  160. // //.sound("msgsound.caf") // 提示声音(自定义)
  161. // .badge(1) // 应用角标
  162. // .build();
  163. //
  164. // String token = "1EDAE24F474C7CB5497AD92BB92C506033218BF37E7C808C8CD3B28154D41B07";
  165. //
  166. // service.push(token, payload);
  167. //
  168. // } catch (IOException e) {
  169. // // TODO Auto-generated catch block
  170. // e.printStackTrace();
  171. // }
  172. //
  173. // }
  174. }