FCM Server Environment

For creating FCM Servlet base server, you must have knowledge of j2ee. In below example we create a j2ee Servlet with name ServletFCM.java which handle all fcm request.

Add your SERVER_KEY in below example, if you don't have you can get it from Firebase Console.

Servlet ServletFCM.java
package com.theitbulls.bulls;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.servlet.ServletException;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.theitbulls.bulls.utils.Utils;

import net.sf.json.JSONObject;

@WebServlet("/fcm")
public class ServletFCM extends ServletCommon {
	private static final long serialVersionUID = 1970183635002795877L;

	// you can get your SERVER KEY https://console.firebase.google.com/
	public static final String SERVER_KEY = "YOUR SERVER KEY";

	public final static String URL_FCM = "https://fcm.googleapis.com/fcm/send";

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		sendMsg(response, "Not valid method to access.", true);
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			String strType = request.getParameter("type");
			if (Utils.isEmpty(strType)) {
				sendMsg(response, "Type parameter not found.", true);
				return;
			}

			int type = Integer.parseInt(strType);
			String token = request.getParameter("token");
			
			if(Utils.isEmpty(token)) {
				sendMsg(response, "Token not found.", true);
				return;
			}
			// sending FCM Notification only
			if (type == 0) {
				String title = request.getParameter("title");
				String msg = request.getParameter("msg");
				
				String result = pushNotification(token, title, msg);
				sendMsg(response, result, false);
				return;
			}
			// sending FCM Data Notification
			if (type == 1) {
				BufferedReader br = request.getReader();
				StringBuffer strBuff = new StringBuffer();
				String line = null;
				while ((line = br.readLine()) != null) {
					strBuff.append(line);
				}
				JSONObject jsonData = JSONObject.fromObject(strBuff.toString());
				
				String result = pushDataNotification(token, jsonData);
				sendMsg(response, result, false);
				return;
			}
			sendMsg(response, "Type not valid", true);
		} catch (Exception e) {
			sendMsg(response, e.toString(), true);
		}
	}

	public String pushNotification(String token, String title, String msgBody) throws Exception {
		// https://github.com/snj07/FCMNotifJavaAPI

		URL url = new URL(URL_FCM);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();

		conn.setUseCaches(false);
		conn.setDoInput(true);
		conn.setDoOutput(true);

		conn.setRequestMethod("POST");
		conn.setRequestProperty("Authorization", "key=" + SERVER_KEY);
		conn.setRequestProperty("Content-Type", "application/json");

		JSONObject json = new JSONObject();
		// json.put("to", "topics/" + (mnuId == 108 ? "trackBuzz" : "ons"));

		// https://firebase.google.com/docs/cloud-messaging/send-message
		// https://firebase.google.com/docs/cloud-messaging/concept-options#notifications_and_data_messages
		json.put("to", token);
		// json.put("sound", "achat.mp3");

		JSONObject info = new JSONObject();
		info.put("title", title);
		info.put("body", msgBody);
		
		json.put("notification", info);
		json.put("priority", "high");

		OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
		wr.write(json.toString());
		wr.flush();

		return convertIOToStr(conn.getInputStream());
	}

	public String pushDataNotification(String token, JSONObject jsonData) throws Exception {
		URL url = new URL(URL_FCM);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();

		conn.setUseCaches(false);
		conn.setDoInput(true);
		conn.setDoOutput(true);

		conn.setRequestMethod("POST");
		conn.setRequestProperty("Authorization", "key=" + SERVER_KEY);
		conn.setRequestProperty("Content-Type", "application/json");

		JSONObject json = new JSONObject();
		json.put("registration_ids", new String[] { token });

		json.put("data", jsonData);
		json.put("priority", "high");

		OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
		wr.write(json.toString());
		wr.flush();

		return convertIOToStr(conn.getInputStream());
	}

	private static String convertIOToStr(InputStream inputStream) throws IOException {
		final int bufferSize = 1024;
		final char[] buffer = new char[bufferSize];
		final StringBuilder out = new StringBuilder();
		InputStreamReader in = new InputStreamReader(inputStream, "UTF-8");
		for (;;) {
			int rsz = in.read(buffer, 0, buffer.length);
			if (rsz < 0)
				break;
			out.append(buffer, 0, rsz);
		}
		return out.toString();
	}

	private void sendMsg(HttpServletResponse response, String msg, boolean error) throws IOException {
		JSONObject obj = new JSONObject();
		obj.put("success", error ? "error" : "ok");
		if (error) {
			obj.put("error", msg);
		} else {
			obj.put("data", msg);
		}

		sendData(response, obj.toString());
	}

	private void sendData(ServletResponse response, String json) throws IOException {
		response.setContentType("application/json");

		PrintWriter out = response.getWriter();
		out.print(json);
		out.flush();
	}

}