Implementation Of Firebase Cloud Messaging in Spring Server To Push Notification
Posted By : Himanshu Kumar | 29-Apr-2018
Introduction:-
Firebase is a backend stage for building Web, Android, and IOS applications. It offers continuous database, distinctive APIs, different confirmation writes and facilitating stage. This is a basic instructional exercise, which covers the fundamentals of the Firebase stage and discloses how to manage its different parts and sub-segments.
Firebase can control your application's backend, including information stockpiling, client confirmation, static facilitating, and that's only the tip of the iceberg. Spotlight on making remarkable client encounters. We will deal with the rest. Assemble cross-stage local portable and web applications with our Android, iOS, and JavaScript SDKs. You can likewise associate Firebase to your current backend utilizing our server-side libraries or our REST API.
Advantages of firebase:-
It is basic and easy to use. No requirement for entangled setup.
The information is ongoing, which implies that each change will consequently refresh associated customers.
Firebase offers basic control dashboard.
There are various valuable administrations to pick.
The main features of firebase:-
Ongoing Database − Firebase underpins JSON information and all clients associated with it get live updates after each change.
Verification − We can utilize unknown, secret key or diverse social confirmations.
Facilitating − The applications can be conveyed over secured association with Firebase servers.
Now we can see here how to implement firebase with restful API.
Step 1:- Go to Settings of your Firebase Project in Firebase Console to get Server Key.
Step 2: - Setup a spring boot starter project using your ide like Spring tool suite or eclipse.
Add Dependencies to pom.xml file:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20160810</version>
</dependency>
Step 3:- Now, Create an interceptor Service to push notification from API to the mobile device : -
package com.firebase.service;
import java.io.IOException;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.http.client.support.HttpRequestWrapper;
public class HeaderRequestInterceptor implements ClientHttpRequestInterceptor {
private final String headerName;
private final String headerValue;
public HeaderRequestInterceptor(String headerName, String headerValue) {
this.headerName = headerName;
this.headerValue = headerValue;
}
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
throws IOException {
HttpRequest wrapper = new HttpRequestWrapper(request);
wrapper.getHeaders().set(headerName, headerValue);
return execution.execute(wrapper, body);
}
}
Step 4:- create a service to send a notification from API to the mobile device which accepts server secret key.
package com.firebase.service;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.stereotype.Service;
@Service
public class AndroidPushNotificationsService {
private static final String FIREBASE_API_URL = "https://fcm.googleapis.com/fcm/send";
private static final String FIREBASE_SERVER_KEY = "AAAAUOixqdU:APA91bG2_wYVIlQczRvbySoNMRIyAzGBijCAVLINvNJNisBKFQaGwbsWMLFJDN-TgvnqEiER7z0rp1fyX1wIo1GNnDm84n6EtpDspxMvZHM0ChT3LITVRHjRax7RwIyt_hK8uN-lNxu-";
public static String sendPushNotification(String deviceToken, String Message, String Message1) throws IOException {
String result = "";
URL url = new URL(FIREBASE_API_URL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setUseCaches(false);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Authorization", "key=" + FIREBASE_SERVER_KEY);
conn.setRequestProperty("Content-Type", "application/json");
JSONObject json = new JSONObject();
try {
json.put("to", deviceToken.trim());
JSONObject data = new JSONObject();
data.put("Key-1", Message);
data.put("Key-2", Message1);
json.put("data", data);
JSONObject info = new JSONObject();
info.put("title", "EZBitex Exchange"); // Notification title
info.put("body", "EZBitex Exchange"); // Notification
info.put("message", "hello user"); // body
json.put("notification", info);
} catch (JSONException e1) {
e1.printStackTrace();
}
try {
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(json.toString());
wr.flush();
BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
result = "succcess";
} catch (Exception e) {
e.printStackTrace();
result = "failure";
}
System.out.println("GCM Notification is sent successfully");
return result;
}
}
Step 5: - Finally create a controller i.e API so that heat comes on server API and we can see the response on the mobile device.
package com.firebase.controller;
import java.io.IOException;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class WebController {
private final String TOPIC = "Ezbitex Exchange";
@Autowired
com.firebase.service.AndroidPushNotificationsService androidPushNotificationsService;
@RequestMapping(value = "/send", method = RequestMethod.GET, produces = "application/json")
public ResponseEntity<String> send() throws JSONException {
JSONObject body = new JSONObject();
body.put("to", "/topics/" + TOPIC);
body.put("priority", "high");
JSONObject notification = new JSONObject();
notification.put("title", "Ezbitex");
notification.put("body", "Welcome to Ezbitex Exchange!");
JSONObject data = new JSONObject();
data.put("Key-1", "JSA Data 1");
data.put("Key-2", "JSA Data 2");
body.put("notification", notification);
body.put("data", data);
/**
* { "notification": { "title": "JSA Notification", "body": "Happy Message!" },
* "data": { "Key-1": "JSA Data 1", "Key-2": "JSA Data 2" }, "to":
* "/topics/JavaSampleApproach", "priority": "high" }
*/
HttpEntity<String> request = new HttpEntity<>(body.toString());
String deviceToken = "ecvVeSTNZkE:APA91bGZmJD5drrxoVWl_6ZyYN32Hjy27K22X2mADN3gYrks6xW9aMmjNFuSOiJ9ViEgySz2imwyMjme4Lclcs5-TgQiMjR2Y_SNzyIhNhwe8nvkuJlNHJQqsGfASvX6nv4mrfY8csix";
try {
String pushNotification = androidPushNotificationsService.sendPushNotification(deviceToken, "Hello dude",
"welcome to Ezbitex exchange");
return new ResponseEntity<>(pushNotification, HttpStatus.OK);
} catch (IOException e) {
}
return new ResponseEntity<>("Push Notification ERROR!", HttpStatus.BAD_REQUEST);
}
}
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Himanshu Kumar
Himanshu Kumar is a seasoned Backend Developer with extensive experience in the industry. He has a deep understanding and hands-on expertise in a range of technologies, including Core Java, Spring-Boot, Hibernate, Apache Kafka messaging queue, and blockchain development with Ethereum, Tron, and smart contract development. He is also well-versed in relational databases like MySQL and PostgreSQL. His proficiency in API implementation, web services, development testing, and deployment has contributed to the successful delivery of various client projects, such as Wethio Exchange, Hedgex Exchange, Envoychain payment gateway based on Stellar assets, and more. With a creative mind and excellent analytical skills, Himanshu enjoys staying up to date with the latest technologies and exploring new ideas to bring value to his work.