Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package ru.bacca.eaeu.service;
- import com.fasterxml.jackson.annotation.JsonProperty;
- import com.fasterxml.jackson.core.JsonProcessingException;
- import com.fasterxml.jackson.databind.ObjectMapper;
- import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- import org.springframework.beans.factory.annotation.Value;
- import org.springframework.core.io.ClassPathResource;
- import org.springframework.stereotype.Service;
- import java.io.*;
- import java.net.HttpURLConnection;
- import java.net.URL;
- import java.nio.charset.StandardCharsets;
- import java.util.Arrays;
- import java.util.Map;
- import java.util.Scanner;
- @Service
- public class CloudMessagingService {
- private static final Logger log = LoggerFactory.getLogger(CloudMessagingService.class);
- private static String PATH_TO_SERVICE_ACCOUNT;
- private static String PROJECT_ID;
- @Value("${eaeu.push.path_to_service_account}")
- private void setPathToServiceAccount(String pathToServiceAccount) {
- CloudMessagingService.PATH_TO_SERVICE_ACCOUNT = pathToServiceAccount;
- }
- @Value("${eaeu.push.project_id}")
- private void setProjectId(String projectId) {
- CloudMessagingService.PROJECT_ID = projectId;
- }
- private static final String BASE_URL = "https://fcm.googleapis.com";
- private static final String MESSAGING_SCOPE = "https://www.googleapis.com/auth/firebase.messaging";
- private static final String[] SCOPES = {MESSAGING_SCOPE};
- private static final String MESSAGE_KEY = "message";
- private static String getAccessToken() throws IOException {
- GoogleCredential googleCredential = GoogleCredential
- .fromStream(new ClassPathResource(PATH_TO_SERVICE_ACCOUNT).getInputStream())
- .createScoped(Arrays.asList(SCOPES));
- googleCredential.refreshToken();
- return googleCredential.getAccessToken();
- }
- private static URL processUrl(String baseUrl,String projectId) throws IOException{
- return new URL(baseUrl + "/v1/projects/" + projectId + "/messages:send");
- }
- private static HttpURLConnection getConnection() throws IOException {
- URL url = processUrl(BASE_URL,PROJECT_ID);
- HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
- httpURLConnection.setRequestProperty("Authorization", "Bearer " + getAccessToken());
- httpURLConnection.setRequestProperty("Content-Type", "application/json; UTF-8");
- return httpURLConnection;
- }
- private static Boolean sendMessage(String fcmMessage) throws IOException {
- HttpURLConnection connection = getConnection();
- connection.setDoOutput(true);
- DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
- outputStream.write(fcmMessage.getBytes(StandardCharsets.UTF_8));
- outputStream.flush();
- outputStream.close();
- int responseCode = connection.getResponseCode();
- if (responseCode == 200) {
- String response = inputStreamToString(connection.getInputStream());
- log.info("Message sent to Firebase for delivery, response:");
- log.info(response);
- return true;
- } else {
- log.info("Unable to send message to Firebase:");
- String response = inputStreamToString(connection.getErrorStream());
- log.info(response);
- return false;
- }
- }
- public Boolean sendPushNotificationOnDevice(String token, String title, String body, Map<String, String> payload) {
- String notificationMessage = buildNotificationMessageForToken(token, title, body, payload);
- log.info("FCM request body for message using common notification object:");
- prettyPrint(notificationMessage);
- try {
- return sendMessage(notificationMessage);
- } catch (IOException e) {
- log.error("Exception when sending a message", e);
- return false;
- }
- }
- public Boolean sendPushNotificationOnTopic(String topic, String title, String body, Map<String, String> payload) {
- String notificationMessage = buildNotificationMessageForTopic(topic, title, body, payload);
- log.info("FCM request body for message using common notification object:");
- prettyPrint(notificationMessage);
- try {
- return sendMessage(notificationMessage);
- } catch (IOException e) {
- log.error("Exception when sending a message", e);
- return false;
- }
- }
- private static String buildNotificationMessageForTopic(String topic, String title, String body, Map<String, String> payload) {
- ObjectMapper mapper = new ObjectMapper();
- JFcm jFcm = new JFcm();
- JFcm.JMessage jMessage = new JFcm.JMessage();
- JFcm.JMessage.JNotification jNotification = new JFcm.JMessage.JNotification();
- if (payload != null)
- jMessage.setPayload(payload);
- jMessage.setTopic(topic);
- jNotification.setTitle(title);
- jNotification.setBody(body);
- jFcm.setMessage(jMessage);
- jMessage.setNotification(jNotification);
- try {
- return mapper.writeValueAsString(jFcm);
- } catch (JsonProcessingException e) {
- log.error("Error while processing json",e);
- }
- return "";
- }
- private static String buildNotificationMessageForToken(String token, String title, String body, Map<String, String> payload) {
- ObjectMapper mapper = new ObjectMapper();
- JFcm jFcm = new JFcm();
- JFcm.JMessage jMessage = new JFcm.JMessage();
- JFcm.JMessage.JNotification jNotification = new JFcm.JMessage.JNotification();
- jMessage.setPayload(payload);
- jMessage.setToken(token);
- jNotification.setTitle(title);
- jNotification.setBody(body);
- jFcm.setMessage(jMessage);
- jMessage.setNotification(jNotification);
- try {
- return mapper.writeValueAsString(jFcm);
- } catch (JsonProcessingException e) {
- log.error("Error while processing json",e);
- }
- return "";
- }
- private static class JFcm {
- @JsonProperty(MESSAGE_KEY)
- private JMessage message;
- public JMessage getMessage() {
- return message;
- }
- void setMessage(JMessage message) {
- this.message = message;
- }
- private static class JMessage {
- @JsonProperty("token")
- private String token;
- @JsonProperty("topic")
- private String topic;
- @JsonProperty("notification")
- private JNotification notification;
- @JsonProperty("data")
- private Map<String, String> payload;
- public String getToken() {
- return token;
- }
- void setToken(String token) {
- this.token = token;
- }
- public JNotification getNotification() {
- return notification;
- }
- void setNotification(JNotification notification) {
- this.notification = notification;
- }
- public Map<String, String> getPayload() {
- return payload;
- }
- void setPayload(Map<String, String> payload) {
- this.payload = payload;
- }
- public String getTopic() {
- return topic;
- }
- public void setTopic(String topic) {
- this.topic = topic;
- }
- private static class JNotification {
- @JsonProperty("title")
- private String title;
- @JsonProperty("body")
- private String body;
- public String getTitle() {
- return title;
- }
- void setTitle(String title) {
- this.title = title;
- }
- public String getBody() {
- return body;
- }
- void setBody(String body) {
- this.body = body;
- }
- }
- }
- }
- private static String inputStreamToString(InputStream inputStream) {
- StringBuilder stringBuilder = new StringBuilder();
- Scanner scanner = new Scanner(inputStream);
- while (scanner.hasNext()) {
- stringBuilder.append(scanner.nextLine());
- }
- return stringBuilder.toString();
- }
- private static void prettyPrint(String jsonObject) {
- log.info(jsonObject);
- }
- }
Add Comment
Please, Sign In to add comment