caTea 블로그

fcm server side code spring java 본문

spring(java)

fcm server side code spring java

ZaRas 2016. 12. 12. 23:01
반응형

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.io.OutputStream;

import java.net.URL;

import java.security.SecureRandom;

import java.security.cert.X509Certificate;

import java.util.ArrayList;

import java.util.Map;


import javax.net.ssl.HttpsURLConnection;

import javax.net.ssl.SSLContext;

import javax.net.ssl.SSLSocketFactory;

import javax.net.ssl.TrustManager;

import javax.net.ssl.X509TrustManager;


import org.json.simple.JSONArray;

import org.json.simple.JSONObject;

import org.json.simple.parser.JSONParser;


import com.mosition.mes.utility.Utility;


public class FCMManager {


private static FCMManager mFCMManager = null;

private String mUrl = "https://fcm.googleapis.com/fcm/send"; //request URL

private HttpsURLConnection httpConnection = null; // HTTP object

private String mServerKey = null;

//TEST DEVICE

private String mDeviceTargetID = "eZHkRPpWk-U:APA91bEk9sjMkRtZGn_pzo-Y-LqGCVvXNYSK7kibozs3VUqZIvMuZqIvEBL5-rR5DqG3kwAsDqnGPJcC-G0oD11rKVVs-VOow21yQqW-SGK3qN4cjU5CugB_AZs4A3CNqxSG3c8INJPU";

private OutputStream os = null;

private BufferedReader in = null;

private ArrayList<String> mDeviceTokenList = null;

public static FCMManager getInstance(String serverKey, String deviceToken){

if(mFCMManager == null){

mFCMManager = new FCMManager(serverKey, deviceToken);

}

return mFCMManager;

}

public static FCMManager getInstance(String serverKey, ArrayList<String> deviceTokenList){

if(mFCMManager == null){

mFCMManager = new FCMManager(serverKey, deviceTokenList);

}

return mFCMManager;

}

public FCMManager(String serverKey, String deviceToken){

mServerKey = serverKey;

mDeviceTargetID = deviceToken;

}

public FCMManager(String serverKey, ArrayList<String> deviceTokenList){

mServerKey = serverKey;

mDeviceTokenList = deviceTokenList;

}

/**

* no exist url param

* @return Boolean IS SUCCESS

*/

public FcmVO postFCM(String title, String text) throws Exception{

return postFCM(mUrl, title, text, null);

}

/**

* exist payload

* @param title

* @param text

* @param payload

* @return

* @throws Exception

*/

public FcmVO postFCM(String title, String text, Map<String, String> payload) throws Exception{

return postFCM(mUrl, title, text, payload);

}


/**

* exist url param

* @param request url

* @return Boolean IS SUCCESS

* @throws IOException 

*/

@SuppressWarnings("unchecked")

public FcmVO postFCM(String url, String title, String text, Map<String, String> payload) throws Exception{

FcmVO fcmVO = new FcmVO();

if(Utility.isNull(mServerKey) == true || Utility.isNull(mDeviceTargetID) == true || Utility.isNull(title) == true){

fcmVO.setErrorMsg("Empty Serverkey or DeviceToken or title");

return fcmVO;

}

try{

URL conUrl = new URL(mUrl);

httpConnection = (HttpsURLConnection) conUrl.openConnection();

httpConnection.setSSLSocketFactory(createSslSocketFactory());

httpConnection.setRequestMethod("POST");

httpConnection.setRequestProperty("Authorization", "key=" + mServerKey); //server key

httpConnection.setRequestProperty("Content-Type", "application/json");

httpConnection.setDoInput(true);

httpConnection.setDoOutput(true);

JSONObject bodyJson = new JSONObject();

JSONObject postJson = new JSONObject();

JSONObject payloadJson = new JSONObject();

bodyJson.put("title", title);

bodyJson.put("text", text);

postJson.put("notification", bodyJson);

if(mDeviceTokenList != null){

JSONArray rid = new JSONArray();

for(String data : mDeviceTokenList){

rid.add(data);

}

postJson.put("registration_ids", rid);

} else{

postJson.put("to", mDeviceTargetID);

}

//payload setting

if(payload != null){

for(String key : payload.keySet()){

payloadJson.put(key, payload.get(key));

}

postJson.put("data", payloadJson);

}

String postStringData = postJson.toJSONString();

os = httpConnection.getOutputStream();

os.write(postStringData.getBytes("UTF-8"));

// For POST only - END


int responseCode = httpConnection.getResponseCode();

if(responseCode != HttpsURLConnection.HTTP_OK){

fcmVO.setErrorMsg("FAIL FCM STATUS CODE = " + responseCode);

}

BufferedReader in = new BufferedReader(new InputStreamReader(httpConnection.getInputStream()));

String inputLine;

StringBuffer response = new StringBuffer();


while ((inputLine = in.readLine()) != null) {

response.append(inputLine);

}

String resultStr = response.toString();

JSONParser parser = new JSONParser();

JSONObject resultJson = (JSONObject)parser.parse(resultStr);

long isSuccess = (Long)resultJson.get("success");

if(isSuccess > 0){

fcmVO.setSuccess(true);

} else {

fcmVO.setSuccess(false);

}

fcmVO.setResultStr(resultStr);

} catch (Exception e){

e.printStackTrace();

} finally{

if(os != null){

os.flush();

os.close();

}

if(in != null){

in.close();

}

}

return fcmVO;

}


private static SSLSocketFactory createSslSocketFactory() throws Exception {


TrustManager[] byPassTrustManagers = new TrustManager[] { new X509TrustManager() {


public X509Certificate[] getAcceptedIssuers() {


return new X509Certificate[0];


}


public void checkClientTrusted(X509Certificate[] chain,

String authType) {


}


public void checkServerTrusted(X509Certificate[] chain,

String authType) {


}


} };


SSLContext sslContext = SSLContext.getInstance("TLS");


sslContext.init(null, byPassTrustManagers, new SecureRandom());


return sslContext.getSocketFactory();


}


}



===================================


package com.mosition.mes.process.gcm.server;


import java.io.Serializable;


public class FcmVO implements Serializable{


private static final long serialVersionUID = -7204545453020796283L;

private boolean isSuccess; // is Success

private String resultStr = null; // result info

private String errorMsg = null; // error message

public FcmVO() {

isSuccess = false;

resultStr = "";

}

public boolean isSuccess() {

return isSuccess;

}

public void setSuccess(boolean isSuccess) {

this.isSuccess = isSuccess;

}

public String getResultStr() {

return resultStr;

}

public void setResultStr(String resultStr) {

this.resultStr = resultStr;

}

public String getErrorMsg() {

return errorMsg;

}

public void setErrorMsg(String errorMsg) {

this.errorMsg = errorMsg;

}

}



728x90

'spring(java)' 카테고리의 다른 글

바코드 생성  (0) 2016.05.17
html convert pdf (html문서를 pdf 파일로 변환)  (0) 2016.05.11
http 데이터 송수신 클라이언트단  (0) 2016.01.29
java mail sand example  (0) 2015.09.10
java excel paser example  (0) 2015.09.10