Tuesday, 13 August 2019

RestWebService using Java Spring Boot

WebService sample for Sending Token / Some String data to the server



public class FcmToken {

private String content;



public String getContent() {
return content;
}

public void setContent(String content) {
this.content = content;
}

}



public class FcmTokenReply {

private String content;

String registrationStatus;
int registrationStatusNumber;
public String getContent() {
return content;
}

public void setContent(String content) {
this.content = content;
}

public String getRegistrationStatus() {
return registrationStatus;
}

public void setRegistrationStatus(String registrationStatus) {
this.registrationStatus = registrationStatus;
}
public int getRegistrationNumber() {
return registrationStatusNumber;
}

public void setRegistrationStatusNumber(int registrationStatusNumber) {
this.registrationStatusNumber = registrationStatusNumber;
}

}



@RestController
public class FcmRegisterController {
@RequestMapping(method = RequestMethod.POST, value = "/register/token")
@ResponseBody
FcmTokenReply registerStudent(@RequestBody FcmToken fcmregdtoken) {
FcmTokenReply tokenreply = new FcmTokenReply();
//This operation we did so that we can get/fetch this using the get request
FCMGetToken.getInstance().add(fcmregdtoken);

         //We are setting the below value just to reply a message back to the caller

tokenreply.setRegistrationStatusNumber(200);
tokenreply.setRegistrationStatus("Successful");
tokenreply.setContent(fcmregdtoken.getContent());
return tokenreply;
}
}

We test this using POST Man by calling the following URL

http://localhost:8080/register/token and passing the following in the body selecting the content type as application xml/JSON


            "content":"dSSFOk:8OQmsO9W8cTxB3i6ymsjB9I5ngDzmstGsZv0lw6RbGf0tIMcD79nlEQG2hoWgxBqU5r-xK3_zTj7V38UF"
}

we get the response as successful


We will write another URL which will get the token which is registered using the POST URL



public class FCMGetToken {

private static FCMGetToken token = null;

private List<FcmToken> tokenRecords;
private String lastToken;

  private FCMGetToken(){
  tokenRecords = new ArrayList<FcmToken>();
    }
public static FCMGetToken getInstance() {
        if(token == null) {
        token = new FCMGetToken();
              return token;
            }
            else {
                return token;
            }
    }
public void add(FcmToken token) {
tokenRecords.add(token);
lastToken = token.getContent();
    }
public List<FcmToken> getTokenRecords() {
    return tokenRecords;
    }
public String getLastToken() {
    return lastToken;
    }
}



@RestController
public class FCMGetTokenController {


@RequestMapping(method = RequestMethod.GET, value = "/register/alltoken")
/* @ResponseBody
  public List<FcmToken> getAllStudents() {
  return FCMGetToken.getInstance().getTokenRecords();
  }*/
@ResponseBody
  public String getlastToken() {
  return FCMGetToken.getInstance().getLastToken();
  }
}

We can test this using the post man by the following URL

http://localhost:8080/register/alltoken


We Write one more webservice like /sendNotification to send the push notification to client app



@RestController
public class SendNotificationController {

public final static String AUTH_KEY_FCM = "key=FCM Console we can get this under cloud msging tab";
public final static String API_URL_FCM = "https://fcm.googleapis.com/fcm/send";


@RequestMapping(method = RequestMethod.POST, value = "/sendNotification")
@ResponseBody
private String sendPOST() throws IOException {
String lastToken = FCMGetToken.getInstance().getLastToken();
System.out.println("Inside post "+lastToken);
URL obj = new URL(API_URL_FCM);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
// con.setRequestProperty("User-Agent", USER_AGENT);

// For POST only - START
con.setDoOutput(true);

con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
con.setRequestProperty("Content-Type", "application/json");

con.setRequestProperty("Authorization", AUTH_KEY_FCM);

String postJsonData = "{\r\n" +
"  \"notification\": \r\n" +
"  {\r\n" +
"    \"title\": \"Hello Client This is From Server\",\r\n" +
"    \"text\": \"Your Text\",\r\n" +
"    \"sound\": \"default\",\r\n" +
"    \"badge\": \"1\",\r\n" +
"    \r\n" +
"    \"color\": \"#990000\",\r\n" +
"      \r\n" +
"    \r\n" +
"  },\r\n" +
"  \"priority\" : \"high\",\r\n" +
"  \"registration_ids\" : \r\n" +
[\r\n" + "\""+
lastToken+ "\""+ "\r\n" +
"    ]\r\n" +
"}";



OutputStream os = con.getOutputStream();
os.write(postJsonData.getBytes());
os.flush();
os.close();
// For POST only - END
con.connect();
int responseCode = con.getResponseCode();
System.out.println("POST Response Code :: " + responseCode);

if (responseCode == HttpURLConnection.HTTP_OK) { // success
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();

while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();

// print result
System.out.println(response.toString());
} else {
System.out.println("POST request not worked");
}
return "Success";
}

Monday, 12 August 2019

FCM Client App and the Server Sample which sends token to FCM which will PUSH to the Client


Following Dependencies in Gradle



implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.google.firebase:firebase-analytics:16.3.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
implementation 'com.android.support:design:28.0.0'
implementation 'com.google.firebase:firebase-messaging:17.6.0'
implementation 'com.google.firebase:firebase-core:16.0.9'

Following service class

public class MyFirebaseInstanceIdService extends FirebaseMessagingService {





    @Override    
       public void onNewToken(String token) {
        super.onNewToken(token);
        Log.e("Refreshed token:",token);


        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
        preferences.edit().putString("fcmToken",token).apply();
    }


    @Override    
       public void onMessageReceived(RemoteMessage remoteMessage) {
        super.onMessageReceived(remoteMessage);

       //if the message contains data payload        
       //It is a map of custom keyvalues        //we can read it easily        
        if(remoteMessage.getData().size() > 0){
            //handle the data message here    }

        //getting the title and the body        
        String title = remoteMessage.getNotification().getTitle();
        String body = remoteMessage.getNotification().getBody();

        //then here we can use the title and body to build a notification    
    }
}

Manifest Add the following



<service    android:name=".service.MyFirebaseInstanceIdService"android:stopWithTask="false">
    <intent-filter>
        <action android:name="com.google.firebase.MESSAGING_EVENT" />
    </intent-filter>
</service>

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
<uses-permission android:name="android.permission.INTERNET" />


Run the App you should be able to see token in logcat


We can then send this token to the webservice using HttpURLConnection to the server


public class SendPostRequest extends AsyncTask<String, Void, String> {

    protected void onPreExecute(){}

    protected String doInBackground(String... arg0) {


        try{

            SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
             
            //For Emulator testing we can use this IP if we are running our server in 8080
            URL url = new URL("http://10.0.2.2:8080/register/token");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
         //   conn.setReadTimeout(15000 /* milliseconds */);           // conn.setConnectTimeout(15000 /* milliseconds */);            
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty( "charset", "utf-8");
            conn.setRequestMethod("POST");
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setUseCaches (false);
            JSONObject postDataParams = new JSONObject();
            postDataParams.put("content" ,  sp.getString("fcmToken"," "));            
            Log.e("params",postDataParams.toString());
            OutputStream os = conn.getOutputStream();
            BufferedWriter writer = new BufferedWriter(
            new OutputStreamWriter(os, "UTF-8"));
            writer.write(postDataParams.toString());


            writer.flush();
            writer.close();
            os.close();
            conn.connect();

            int responseCode=conn.getResponseCode();

            if (responseCode == HttpsURLConnection.HTTP_OK) {

                BufferedReader in=new BufferedReader(
                        new InputStreamReader(
                                conn.getInputStream()));
                StringBuffer sb = new StringBuffer("");
                String line="";

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

                    sb.append(line);
                    break;
                }

                in.close();
                return sb.toString();

            }
            else {
                return new String("false : "+responseCode);
            }
        }
        catch(Exception e){
            return new String("Exception: " + e.getMessage());
        }

    }

    @Override    
     protected void onPostExecute(String result) {

        Toast.makeText(getApplicationContext(), result,
                Toast.LENGTH_LONG).show();
    }
    }


    

Call this in onCreate() or on Button Click



App Server has now the token it will send this to FCM which will PUSH Notification to the Client App




public class ServerDemo {

 //This is the server key which we will get from Firebase console our App and the FCM Tab we should select
 public final static String AUTH_KEY_FCM = "key=AAMMM";
 public final static String API_URL_FCM = "https://fcm.googleapis.com/fcm/send"; 
      //This is the token which client App receives from FCM
 public static String CLIENT_TOKEN = null;

 public static void main(String[] args) throws IOException {

  FileOutputStream fileOutputStream = null;
  BufferedReader bufferedReader = null;

  try { 
 //Here we are fetching the token which we received from FCM
   URL url = new URL("http://localhost:8080/register/alltoken");

   bufferedReader = new BufferedReader(new InputStreamReader(url.openStream()));
   fileOutputStream = new FileOutputStream("C:\\Softwares\\Test.txt");
   String input;

   while ((input = bufferedReader.readLine()) != null) {
    CLIENT_TOKEN = input;
    System.out.println(input);
    fileOutputStream.write(input.getBytes());
   }

   bufferedReader.close();
   fileOutputStream.close();
   // System.out.println(results.get(0));

  } catch (MalformedURLException me) {
   me.printStackTrace();
  } catch (IOException ie) {
   ie.printStackTrace();
  }

  sendPOST();
 }

 private static void sendPOST() throws IOException {
  System.out.println("Inside post "+CLIENT_TOKEN);
  URL obj = new URL(API_URL_FCM);
  HttpURLConnection con = (HttpURLConnection) obj.openConnection();
  con.setRequestMethod("POST");
  // con.setRequestProperty("User-Agent", USER_AGENT);

  // For POST only - START
  con.setDoOutput(true);

  con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
  con.setRequestProperty("Content-Type", "application/json");

  con.setRequestProperty("Authorization", AUTH_KEY_FCM);

  String postJsonData = "{\r\n" + 
    "  \"notification\": \r\n" + 
    "  {\r\n" + 
    "    \"title\": \"Hello Client This is From Server\",\r\n" + 
    "    \"text\": \"Your Text\",\r\n" + 
    "    \"sound\": \"default\",\r\n" + 
    "    \"badge\": \"1\",\r\n" + 
    "    \r\n" + 
    "    \"color\": \"#990000\",\r\n" + 
    "      \r\n" + 
    "    \r\n" + 
    "  },\r\n" + 
    "  \"priority\" : \"high\",\r\n" + 
    "  \"registration_ids\" : \r\n" + 
    "   [\r\n" + "\""+ 
          CLIENT_TOKEN+ "\""+ "\r\n" + 
    "    ]\r\n" + 
    "}";

  

  OutputStream os = con.getOutputStream();
  os.write(postJsonData.getBytes());
  os.flush();
  os.close();
  // For POST only - END
  con.connect();
  int responseCode = con.getResponseCode();
  System.out.println("POST Response Code :: " + responseCode);

  if (responseCode == HttpURLConnection.HTTP_OK) { // success
   BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
   String inputLine;
   StringBuffer response = new StringBuffer();

   while ((inputLine = in.readLine()) != null) {
    response.append(inputLine);
   }
   in.close();

   // print result
   System.out.println(response.toString());
  } else {
   System.out.println("POST request not worked");
  }
 }
}




Pass a HashMap from Angular Client to Spring boot API

This example is for the case where fileData is very huge and in json format   let map = new Map<string, string>()      map.set(this.ge...