TriplePi

Untitled

Nov 26th, 2018
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 8.49 KB | None | 0 0
  1. package ru.bacca.eaeu.service;
  2.  
  3. import com.fasterxml.jackson.annotation.JsonProperty;
  4. import com.fasterxml.jackson.core.JsonProcessingException;
  5. import com.fasterxml.jackson.databind.ObjectMapper;
  6. import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
  7. import org.slf4j.Logger;
  8. import org.slf4j.LoggerFactory;
  9. import org.springframework.beans.factory.annotation.Value;
  10. import org.springframework.core.io.ClassPathResource;
  11. import org.springframework.stereotype.Service;
  12.  
  13. import java.io.*;
  14. import java.net.HttpURLConnection;
  15. import java.net.URL;
  16. import java.nio.charset.StandardCharsets;
  17. import java.util.Arrays;
  18. import java.util.Map;
  19. import java.util.Scanner;
  20.  
  21. @Service
  22. public class CloudMessagingService {
  23.     private static final Logger log = LoggerFactory.getLogger(CloudMessagingService.class);
  24.  
  25.     private static String PATH_TO_SERVICE_ACCOUNT;
  26.     private static String PROJECT_ID;
  27.  
  28.     @Value("${eaeu.push.path_to_service_account}")
  29.     private void setPathToServiceAccount(String pathToServiceAccount) {
  30.         CloudMessagingService.PATH_TO_SERVICE_ACCOUNT = pathToServiceAccount;
  31.     }
  32.  
  33.     @Value("${eaeu.push.project_id}")
  34.     private void setProjectId(String projectId) {
  35.         CloudMessagingService.PROJECT_ID = projectId;
  36.     }
  37.  
  38.     private static final String BASE_URL = "https://fcm.googleapis.com";
  39.     private static final String MESSAGING_SCOPE = "https://www.googleapis.com/auth/firebase.messaging";
  40.     private static final String[] SCOPES = {MESSAGING_SCOPE};
  41.  
  42.     private static final String MESSAGE_KEY = "message";
  43.  
  44.  
  45.     private static String getAccessToken() throws IOException {
  46.         GoogleCredential googleCredential = GoogleCredential
  47.                 .fromStream(new ClassPathResource(PATH_TO_SERVICE_ACCOUNT).getInputStream())
  48.                 .createScoped(Arrays.asList(SCOPES));
  49.         googleCredential.refreshToken();
  50.         return googleCredential.getAccessToken();
  51.     }
  52.  
  53.     private static URL processUrl(String baseUrl,String projectId) throws IOException{
  54.         return new URL(baseUrl + "/v1/projects/" + projectId + "/messages:send");
  55.     }
  56.  
  57.     private static HttpURLConnection getConnection() throws IOException {
  58.         URL url = processUrl(BASE_URL,PROJECT_ID);
  59.         HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
  60.         httpURLConnection.setRequestProperty("Authorization", "Bearer " + getAccessToken());
  61.         httpURLConnection.setRequestProperty("Content-Type", "application/json; UTF-8");
  62.         return httpURLConnection;
  63.     }
  64.  
  65.     private static Boolean sendMessage(String fcmMessage) throws IOException {
  66.         HttpURLConnection connection = getConnection();
  67.         connection.setDoOutput(true);
  68.         DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
  69.         outputStream.write(fcmMessage.getBytes(StandardCharsets.UTF_8));
  70.         outputStream.flush();
  71.         outputStream.close();
  72.  
  73.         int responseCode = connection.getResponseCode();
  74.         if (responseCode == 200) {
  75.             String response = inputStreamToString(connection.getInputStream());
  76.             log.info("Message sent to Firebase for delivery, response:");
  77.             log.info(response);
  78.             return true;
  79.         } else {
  80.             log.info("Unable to send message to Firebase:");
  81.             String response = inputStreamToString(connection.getErrorStream());
  82.             log.info(response);
  83.             return false;
  84.         }
  85.     }
  86.  
  87.     public Boolean sendPushNotificationOnDevice(String token, String title, String body, Map<String, String> payload) {
  88.         String notificationMessage = buildNotificationMessageForToken(token, title, body, payload);
  89.  
  90.         log.info("FCM request body for message using common notification object:");
  91.         prettyPrint(notificationMessage);
  92.         try {
  93.             return sendMessage(notificationMessage);
  94.         } catch (IOException e) {
  95.             log.error("Exception when sending a message", e);
  96.             return false;
  97.         }
  98.     }
  99.  
  100.     public Boolean sendPushNotificationOnTopic(String topic, String title, String body, Map<String, String> payload) {
  101.         String notificationMessage = buildNotificationMessageForTopic(topic, title, body, payload);
  102.  
  103.         log.info("FCM request body for message using common notification object:");
  104.         prettyPrint(notificationMessage);
  105.         try {
  106.             return sendMessage(notificationMessage);
  107.         } catch (IOException e) {
  108.             log.error("Exception when sending a message", e);
  109.             return false;
  110.         }
  111.     }
  112.  
  113.     private static String buildNotificationMessageForTopic(String topic, String title, String body, Map<String, String> payload) {
  114.         ObjectMapper mapper = new ObjectMapper();
  115.         JFcm jFcm = new JFcm();
  116.         JFcm.JMessage jMessage = new JFcm.JMessage();
  117.         JFcm.JMessage.JNotification jNotification = new JFcm.JMessage.JNotification();
  118.  
  119.         if (payload != null)
  120.             jMessage.setPayload(payload);
  121.  
  122.         jMessage.setTopic(topic);
  123.  
  124.         jNotification.setTitle(title);
  125.         jNotification.setBody(body);
  126.  
  127.         jFcm.setMessage(jMessage);
  128.         jMessage.setNotification(jNotification);
  129.  
  130.         try {
  131.             return mapper.writeValueAsString(jFcm);
  132.         } catch (JsonProcessingException e) {
  133.             log.error("Error while processing json",e);
  134.         }
  135.         return "";
  136.     }
  137.  
  138.     private static String buildNotificationMessageForToken(String token, String title, String body, Map<String, String> payload) {
  139.         ObjectMapper mapper = new ObjectMapper();
  140.         JFcm jFcm = new JFcm();
  141.         JFcm.JMessage jMessage = new JFcm.JMessage();
  142.         JFcm.JMessage.JNotification jNotification = new JFcm.JMessage.JNotification();
  143.  
  144.         jMessage.setPayload(payload);
  145.  
  146.         jMessage.setToken(token);
  147.  
  148.         jNotification.setTitle(title);
  149.         jNotification.setBody(body);
  150.  
  151.         jFcm.setMessage(jMessage);
  152.         jMessage.setNotification(jNotification);
  153.  
  154.         try {
  155.             return mapper.writeValueAsString(jFcm);
  156.         } catch (JsonProcessingException e) {
  157.             log.error("Error while processing json",e);
  158.         }
  159.         return "";
  160.     }
  161.  
  162.     private static class JFcm {
  163.  
  164.         @JsonProperty(MESSAGE_KEY)
  165.         private JMessage message;
  166.  
  167.         public JMessage getMessage() {
  168.             return message;
  169.         }
  170.  
  171.         void setMessage(JMessage message) {
  172.             this.message = message;
  173.         }
  174.  
  175.         private static class JMessage {
  176.  
  177.             @JsonProperty("token")
  178.             private String token;
  179.  
  180.             @JsonProperty("topic")
  181.             private String topic;
  182.  
  183.             @JsonProperty("notification")
  184.             private JNotification notification;
  185.  
  186.             @JsonProperty("data")
  187.             private Map<String, String> payload;
  188.  
  189.             public String getToken() {
  190.                 return token;
  191.             }
  192.  
  193.             void setToken(String token) {
  194.                 this.token = token;
  195.             }
  196.  
  197.             public JNotification getNotification() {
  198.                 return notification;
  199.             }
  200.  
  201.             void setNotification(JNotification notification) {
  202.                 this.notification = notification;
  203.             }
  204.  
  205.             public Map<String, String> getPayload() {
  206.                 return payload;
  207.             }
  208.  
  209.             void setPayload(Map<String, String> payload) {
  210.                 this.payload = payload;
  211.             }
  212.  
  213.             public String getTopic() {
  214.                 return topic;
  215.             }
  216.  
  217.             public void setTopic(String topic) {
  218.                 this.topic = topic;
  219.             }
  220.  
  221.             private static class JNotification {
  222.  
  223.                 @JsonProperty("title")
  224.                 private String title;
  225.  
  226.                 @JsonProperty("body")
  227.                 private String body;
  228.  
  229.                 public String getTitle() {
  230.                     return title;
  231.                 }
  232.  
  233.                 void setTitle(String title) {
  234.                     this.title = title;
  235.                 }
  236.  
  237.                 public String getBody() {
  238.                     return body;
  239.                 }
  240.  
  241.                 void setBody(String body) {
  242.                     this.body = body;
  243.                 }
  244.             }
  245.         }
  246.     }
  247.  
  248.     private static String inputStreamToString(InputStream inputStream) {
  249.         StringBuilder stringBuilder = new StringBuilder();
  250.         Scanner scanner = new Scanner(inputStream);
  251.         while (scanner.hasNext()) {
  252.             stringBuilder.append(scanner.nextLine());
  253.         }
  254.         return stringBuilder.toString();
  255.     }
  256.  
  257.     private static void prettyPrint(String jsonObject) {
  258.         log.info(jsonObject);
  259.     }
  260. }
Add Comment
Please, Sign In to add comment