Monday, 27 April 2020

Weighted Round Robin Sample Java Example

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.google.common.math.IntMath;

public class WeightedRRImpl {
public static void main(String[] args) {
WeightedRRImpl wrr = new WeightedRRImpl();
Map<Integer, Integer> instanceMap = new HashMap<Integer, Integer>();
instanceMap.put(0, 20);
instanceMap.put(1, 28);
instanceMap.put(2, 21);
/*instanceMap.put(3, 4);
instanceMap.put(4, 25);
instanceMap.put(5, 0);*/
/*
* instanceMap.put(3, 4); instanceMap.put(4, 25);
*/

/*
* instanceMap.put(0, 9); instanceMap.put(1, 10); instanceMap.put(2, 8);
* instanceMap.put(3, 7); instanceMap.put(4, 6);
*/
// int gcd = 1;
List<Integer> instanceList = new ArrayList<Integer>(instanceMap.values());
int gcd = wrr.getGCD(instanceList);

System.out.println("**** gcd " + gcd);
/*
* for (int i=0;i<instanceList.size()-1;i++) { BigInteger bigInt = new
* BigInteger(instanceList.get(i).toString()); gcd = bigInt.gcd(new
* BigInteger(instanceList.get(i+1).toString())).intValue(); }
*/

Collections.sort(instanceList);
int max = instanceList.get(instanceList.size() - 1);
int previous = -1;
for (int i = 1; i <= 3; i++) {
// System.out.println("previous "+previous);

Map.Entry<Integer, Integer> entry = wrr.scheduleNext(instanceMap, gcd, max, previous);
if (entry != null) {
previous = entry.getKey();
System.out.println("selected instance:" + previous + " weight:" + entry.getValue());
} else {
System.out.println("Entry is null");
}
}

/*
* System.out.println(gcd); System.out.println(wrr.getGCD(instanceList));
*/

}

private Map.Entry<Integer, Integer> scheduleNext(Map<Integer, Integer> instanceMap, int gcd, int max,
int previous) {
int i = previous;
int cw = (previous == -1) ? 0 : instanceMap.get(previous);
while (true) {
i = (i + 1) % instanceMap.size();
if (i == 0) {
cw = cw - gcd;
if (cw <= 0) {
cw = max;
if (cw == 0)
return null;
}
}
if (instanceMap.get(i) >= cw) {
instanceMap.put(i, cw);
System.out.println("cw " + cw);
// System.out.println("i ==== "+i);
for (Map.Entry<Integer, Integer> entry : instanceMap.entrySet()) {
if (entry.getKey() == i) {
return entry;
}
}
}
}

}


private int getGCD(List<Integer> integerList) {

int result = integerList.get(0);
for (int i = 1; i < integerList.size(); i++) {
result = IntMath.gcd(integerList.get(i), result);

if (result == 1) {
return 1;
}
}

return result;

}

}

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");
  }
 }
}




Thursday, 4 July 2019

Split String and Store it in an array

public class RegTest {

public static void main(String[] args) {
String s = "you,are,my";
String[] test = s.split("[^a-zA-Z]+");
for(String strPrint  : test )
{
System.out.println(strPrint);
}
}
}

Sunday, 30 June 2019

Disable few dates in Android using Android Date picker

final Calendar c = Calendar.getInstance();
mYear = c.get(Calendar.YEAR);
mMonth = c.get(Calendar.MONTH);
mDay = c.get(Calendar.DAY_OF_MONTH);


c.add(Calendar.DATE, 3);
DatePickerDialog datePickerDialog = new DatePickerDialog(view.getContext(),
        new DatePickerDialog.OnDateSetListener() {

            @Override            public void onDateSet(DatePicker view, int year,
                                  int monthOfYear, int dayOfMonth) {

                txtDate.setText(dayOfMonth + "-" + (monthOfYear + 1) + "-" + year);

            }
        }, mYear, mMonth, mDay);
datePickerDialog.getDatePicker().setMaxDate(c.getTimeInMillis());

c.add(Calendar.DATE, -6);
datePickerDialog.getDatePicker().setMinDate(c.getTimeInMillis());
datePickerDialog.show();

Tuesday, 9 April 2019

Comparator Example using Java 8

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;

class MyComp implements Comparator<Integer>
{

@Override
public int compare(Integer o1, Integer o2) {
// TODO Auto-generated method stub

return (o1<02)?-1:(o1>o2)?1:0;

//Into Lamda Expression


/*if(o1<o2)
{
return -1;
}
else if(o1>o2)
{
return 1;
}

else
{
return 0;
}*/

}


}
 class TestDurga {

//Older Version
public static int square(int n)
{
return n*n;
}

public static void main(String[] args) {

//Concise Code Java 8
Function<Integer,Integer> f=i->i*i;
Predicate<Integer> p=i->i%2==0;
System.out.println("4 is "+square(4));
System.out.println("5 is "+f.apply(5));
System.out.println("4 is even "+p.test(4));
System.out.println("5 is even "+p.test(5));
ArrayList<Integer> testList = new ArrayList<Integer>();
testList.add(5);
testList.add(15);
testList.add(20);

testList.add(0);
System.out.println(testList);
Comparator< Integer> c = (o1,o2)-> (o1<o2)?-1:(o1>o2)?1:0;
// OLD Implementation With Out Lamda
//Collections.sort(testList,new MyComp() );
//With Lamda
Collections.sort(testList,c );
System.out.println("After sorting "+testList);
testList.stream().forEach(System.out::println);
List<Integer> finalEvenNumberList=testList.stream().filter(i->i%2==0).collect(Collectors.toList());
System.out.println(finalEvenNumberList);
}

}

Tuesday, 5 February 2019

Android Latest Updates

In Google I/O 2018, a new publishing format has been introduced for Android applications called Android App Bundle. It is a new upload format that includes all your app’s compiled code and resources, but defers APK generation and signing to Google Play. Traditionally, Android apps are distributed using a special file called an Android Package(.apk).

Why should we use this new format?

  • Dynamic Delivery : Google Play’s new app serving model, called Dynamic Delivery, uses your app bundle to generate and serve optimized APKs for each user’s device configuration, so they download only the code and resources they need to run your app. For example, you don’t need other languages strings if you have set English as your default language.
  • No need to manually manage multiple APKs : You no longer have to build, sign, and manage multiple APKs to support different devices, and users get smaller, more optimized downloads. For example, now you don’t have to create multiple APKs for devices with different screen resolutions.
  • Dynamic Feature Module : These modules contain features and assets that you can decide not to include when users first download and install your app. Using the Play Core Library, your app can later request to download those modules as dynamic feature APKs. For example, video calling feature and camera filters can be downloaded later on demand.
  • Reduced APK size : Using Split APK mechanism(explained later), Google Play can break up a large app into smaller, discrete packages that are installed on a user’s device as required. On average, apps published with app bundles are 20% smaller in size.
 
 

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...