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.
 
 

Java 8 Features

Why Java 8

python -->10 lines of code In java -->100 lines of code

1)Java 8 code is concised code they did this by enabling functional programming
2)Most powerful concept lamda expressions to enable functional programming
3)Following is normal way of writing code
public class TestDurga {
 public static int square(int n)
 {
  return n*n;
 }

 public static void main(String[] args) {
  System.out.println("4 is "+square(4));
 }
}
Using Java 8 we can do the following
Function<Integer,Integer> f=i->i*i;
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));

 Main Features of Java 8

Lamda Expressions
Functional Interface
Defautl and Static Methods
Predifined Functional Interface
 Producer
 Consumer
 Predicate
 Function
 Supplier
Double Colon Operator(::)
Streams
Data and Tine API
Optional Class
Nashorn Java Script Engine
Lamda Expressions
--------------------------------------------------------------
Lisp first pgming language which uses lamda expressions
Already there in many languages in ruby ,python ,java script-- It came very lately in java
Main objective of lamda expressions
----------------------------------------
1)Bring benefits of functional pgming in java

What is Lamda Expressions
-------------------------
1)Its anonymous function
 *)With out return type
 *)With out name
 *)not having modifier
2)Very Very easy Concept
3)How to Write this lamda Expressions??
  public void m1()
  {
   S.O.P("hello");
  }

  Now convert this in to lamda expressions Only usage of special symbol is required(->)
  ()->{S.O.P("hello");}

  If body has only one line then remove curly braces
  ()->S.O.P("hello");

  Example 2
  --------------
  public void m1(int a ,int b)
  {
   S.O.P(a+b);
  }

  Into Lamda expressions

  (int a,int b)->s.o.p(a+b);

  some times compiler can guess type automatically then no need to specify int,float ,etc
  ( a, b)->s.o.p(a+b);

  Example 3
  ------------
  public int squareIt(int n)
  {

   return n*n;
  }

  This in to Lamda Expressions
  n ->  n*n;

  With out curly braces we need not specify return statement
  With in curly braces if we want to return some value then we should use return statement

  Example 4
  ----------------
  public void m1(String s)
  {

   return s.length();
  }

  s->s.length();

4)How can we call this lamda expression?
------------------------------------------------------
 *)FI(Functional Interface) is the special word used in this case
  Annotation used here @FunctionalInterface
 *)FunctionalInterface Contains the following
  Runnable,Comparable,Comparator,ActionListener,Callable
  All these are interfaces and contain only one method
 *)Interface which contaings Single Abstract Method(SAM) are called as FI.This is required to invoke Lamda Expressions

  public void m1()
  {
   S.O.P("hello");
  }

 *)Functional Interface can take any number of default and static methods but it must have only one abstract method
5)FI with respect to inheritance
 If parent interface is functional interface then child interface is also FI if child does not define its own abstract method
 Note :Normal Interface can contain any number of abstract methods
6)interface Intf
{
public void m1();
}

public class Test
{
p s v m()
{
Intf i = ()->s.o.p("hello");
i.m1(); 

}
}

To provide reference to lamda expression FI is required
Example 2:
----------------
interface Intf
{
public void add(int a ,int b);
}
public class Test
{
p s v m()
{
Intf i = ( a, b)->s.o.p("hello"+a+b);
i.add(4,4); 

}
}

Comparator Example with Lamda and with out Lamda
------------------------------------------------------------------------------
Comparator has only one method

Compare(Object obj1,Object obj2);

Returns -ve if obj1<obj2
Returns +ve if obj1>obj2
Returns 0  if obj1 == obj2

OLD Implementation With Out Lamda

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


// OLD Implementation With Out Lamda
//Collections.sort(testList,new MyComp() );

With Lamda

Comparator< Integer> c = (o1,o2)-> (o1<02)?-1:(o1>o2)?1:0;
//With Lamda
Collections.sort(testList,c );
System.out.println("After sorting "+testList);
testList.stream().forEach(System.out::println);
o/p
prints numbers in line by line
List<Integer> finalEvenNumberList=testList.stream().filter(i->i%2==0).collect(Collectors.toList());
System.out.println(finalEvenNumberList);
o/p
prints only the even numbers


s1.compareTp(s2)--->Always applicable for alphabetical order

Refer my post Comparator example using java8 for example



Anonymous class and Lamda Expressions
--------------------------------------------------
Anonymous class are more powerful than Lamda Expression

Exmaple
---------
interface A
{


m1();
m2();


}

//Following is anonymous inner class

A a = new A()
{

public void m1()
{
}
public void m2()
{
}



};

Here in the above interface we cannot go for FI and lamda expressions since we have two abstract methods here.
Where ever Lamda expressions are there anonymous class can come

Anonymous Class can extend normal class, abstract class
Anonymous Class can implement an interface which contain any number of abstract methods


Lamda Expression can implement interface which contain single Abstract method



Default methods
--------------------------------
Untill 1.7 every method inside interface is public and abstract
From 1.8 we can take default and static methods also inside interface
From 1.9 private methods also allowed
Varialbles inside interface are always public static final

Default method also known as defender , virtual extension methods

This to avoid condition like in future if we add new method in interface then all the classes implementing interface will be effected.
Then in this scenario we declare method as default

Default method can be overrided in the implemented class.
While overriding we should use public void , we cannot use default inside the class


we cannot keep the object class metods as default methods in interface

Java does not support multiple inheritance (diamond problem , ambiguity problem)


Note:
Interface static method by default not available to implemented class.
Interface static methods should be called only by using Interface name
Main Method inside interface possible from 1.8 onwards
If all methods needs to be static then best approach is to declare all methods inside the interface and implement it in a class

Predifined Functional Interface : Predicate
---------------------------------------------------------------------------------------------------------------------
Predicate
Function
Consumer
Supplier


predicate(I)

public abstarct boolean test(T t)

interface predicate<T>
{
 public boolean test(T t);

}

Function
functional
Interface Function<T,R>
{

public R apply(t t)
}



Consumer method has accept

1)Function chaining is also possible

f1.andthen(f2).apply(i);   --> f1 followed by f2(f1 first and then f2 is applied)
f1.compose(f2).apply(i);   --> f2 is applied first then f1 is applied


Note
Predicate reurns boolean always
Function can return any type function(T,R)
Consumeer only consumes and will not return any thing consumer<T>

For consumer also chaning is possible


Supplier
-------------------------
It never takes any input
interface supplier<R>
{

public R get();

}


Supplier for Random OTP
--------------------------
Check java class


Note
--------
predicate -->test()
Function--> apply()
Consumer --> accept()
supplier--->get()

Normal predicate takes only one argument and performs conditional check

Two input arguments then what to use because predicate Function Consumer take only one

Requirement
------------
Sum of two is even or not
then go for two argument functional interface
Bipredicate


BiFunction
-----------------------------------
Check my workspace for this example
three args----1 input 2 input third is return type
interface BiFunction<t,u,r>
{

public R apply(t,u)

}



BiConsmer

--------------------------------
Refer my workspace



Additional Functional Interface
------------------------------------------------

Predicate<Integer> p=i->i%2==0 ; this has performance issues(autoxoxing and unboxing going on)
to overcome we go for primitive version of functional interface.Since the before is applicable well for objects


IntPredicate p =i->i%2==0;
for(int x1:x )
{
if(p.test(x1))
System.out.println(x1);
}

Here in the above example no performance issues , here no autoboxing is happening




Primitive predicate types

int predicate
double predicate
long predicate

Primitive version of function types


Function<Integer,Integer> fTest=i1->i1*i1;
System.out.println(fTest.apply(8));
this has performance issues(autoxoxing and unboxing going on)
to overcome we go for primitive version of functional interface.


Primitive types of Consumer
------------------------------------
IntConsumer
DoubleConsumer
LongConsumer

Primitive Supplier
---------------------------
BooleanSupplier
getasBoolean();
IntSupplier
getasInt();





Method and Constructor reference(Alternative for Lamda expressions)
--------------------------------------------------------------------
Code reusability
:: use this operator(For method reference / constructor reference)
Can we use instance methods???
Yes we can take both instance and static methods
No worry about return type and arguments must be same
Different return types are allowed but only restriction argument types must be watched(TestDurgaMesgRef Refer this)



throw user defined exception in java
public class ExceptionTest {

public static void main(String args[]) {
int empId = 10;
try {
String userName = getUserNameById(empId);
System.out.println(userName);
} catch (UserNotFoundException ue) {
// log the exception
}
}

private static String getUserNameById(int empId) throws UserNotFoundException {
User user = userDao.getUserById(empId);
if (user == null) {
// throwing the exception here
throw new UserNotFoundException("User not present in Database");
}
return user.getName();
}
}

Monday, 7 January 2019

Android Location Services Using GPS BackGround Service to Update

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


public class MainActivity extends AppCompatActivity {

    private ArrayList<String> permissionsToRequest;
    private ArrayList<String> permissionsRejected = new ArrayList();
    private ArrayList<String> permissions = new ArrayList();

    private final static int ALL_PERMISSIONS_RESULT = 101;
    LocationTrack gpsTracker;
    List<Address> addresses;
    Geocoder geocoder;

    private TextView displayTv,displayAddress;
    private static final String TAG = MainActivity.class.getSimpleName();
    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        displayTv = (TextView)findViewById(R.id.tvDisplay);
        displayAddress = (TextView)findViewById(R.id.tvAddress);
        try {
            if (ContextCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED ) {
                ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, 101);
            }
        } catch (Exception e){
            e.printStackTrace();
        }
        gpsTracker = new LocationTrack(MainActivity.this);
        if(gpsTracker.canGetLocation()){
            double latitude = gpsTracker.getLatitude();
            double longitude = gpsTracker.getLongitude();
            displayTv.setText(String.valueOf(latitude)+"   "+String.valueOf(longitude));

        }else{
            gpsTracker.showSettingsAlert();
        }



        LocalBroadcastManager.getInstance(this).registerReceiver(
                new BroadcastReceiver() {
                    @Override                    public void onReceive(Context context, Intent intent) {
                        String latitude = intent.getStringExtra(LocationTrack.EXTRA_LATITUDE);
                        String longitude = intent.getStringExtra(LocationTrack.EXTRA_LONGITUDE);

                        if (latitude != null && longitude != null) {
                            displayAddress.setText("Service started" + "\n Latitude : " + latitude + "\n Longitude: " + longitude);

                        }
                    }
                }, new IntentFilter(LocationTrack.ACTION_LOCATION_BROADCAST)
        );
    }








}
 
 
import android.Manifest;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.widget.Toast;

import java.util.List;

import static android.content.ContentValues.TAG;


/** * Created by namratha.asher on 12/21/2018. */
public class LocationTrack extends Service implements LocationListener {
    private final Context mContext;
    // flag for GPS status    boolean isGPSEnabled = false;
    // flag for network status    boolean isNetworkEnabled = false;
    // flag for GPS status    boolean canGetLocation = false;
    Location location; // location    double latitude; // latitude    double longitude; // longitude    // The minimum distance to change Updates in meters    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters    // The minimum time between updates in milliseconds    private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute    // Declaring a Location Manager    protected LocationManager locationManager;
    public static final String ACTION_LOCATION_BROADCAST = LocationTrack.class.getName() + "LocationBroadcast";
    public static final String EXTRA_LATITUDE = "extra_latitude";
    public static final String EXTRA_LONGITUDE = "extra_longitude";
    public LocationTrack(Context context) {
        this.mContext = context;
        getLocation();
    }
    public Location getLocation() {
        try {
            locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
            // getting GPS status            isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
          //  isGPSEnabled = false;            // getting network status           /* isNetworkEnabled = locationManager                    .isProviderEnabled(LocationManager.NETWORK_PROVIDER);*/            isNetworkEnabled = false;
            if (!isGPSEnabled && !isNetworkEnabled) {
                // no network provider is enabled            } else {
                this.canGetLocation = true;
                // First get location from Network Provider                if (isNetworkEnabled) {
                    //check the network permission                    if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                        ActivityCompat.requestPermissions((MainActivity) mContext, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 101);
                    }
                    locationManager.requestLocationUpdates(
                            LocationManager.NETWORK_PROVIDER,
                            0,
                            0, this);
                    Log.d("Network", "Network");
                    if (locationManager != null) {
                       /* location = locationManager                                .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);*/                        List<String> providers = locationManager.getProviders(true);
                        Location bestLocation = null;

                        for (String provider : providers) {
                            Location l = locationManager.getLastKnownLocation(provider);
                            if (l == null) {
                                continue;
                            }
                            if (bestLocation == null || l.getAccuracy() < bestLocation.getAccuracy()) {
                                // Found best last known location: %s", l);                                bestLocation = l;
                            }
                        }

                        if (bestLocation != null) {
                            latitude = bestLocation.getLatitude();
                            longitude = bestLocation.getLongitude();
                        }
                    }
                }
                // if GPS Enabled get lat/long using GPS Services                if (isGPSEnabled) {
                    if (location == null) {
                        //check the network permission                        if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                            ActivityCompat.requestPermissions((MainActivity) mContext, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 101);
                        }
                        locationManager.requestLocationUpdates(
                                LocationManager.GPS_PROVIDER,
                                MIN_TIME_BW_UPDATES,
                                MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                        Log.d("GPS Enabled", "GPS Enabled");
                        if (locationManager != null) {
                            location = locationManager                                    .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                            if (location != null) {
                                latitude = location.getLatitude();
                                longitude = location.getLongitude();
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return location;
    }
    /**     * Stop using GPS listener     * Calling this function will stop using GPS in your app     * */    public void stopUsingGPS(){
        if(locationManager != null){
            locationManager.removeUpdates(LocationTrack.this);
        }
    }
    /**     * Function to get latitude     * */    public double getLatitude(){
        if(location != null){
            latitude = location.getLatitude();
        }
        // return latitude        return latitude;
    }
    /**     * Function to get longitude     * */    public double getLongitude(){
        if(location != null){
            longitude = location.getLongitude();
        }
        // return longitude        return longitude;
    }
    /**     * Function to check GPS/wifi enabled     * @return boolean     * */    public boolean canGetLocation() {
        return this.canGetLocation;
    }
    /**     * Function to show settings alert dialog     * On pressing Settings button will lauch Settings Options     * */    public void showSettingsAlert(){
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
        // Setting Dialog Title        alertDialog.setTitle("GPS is settings");
        // Setting Dialog Message        alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
        // On pressing Settings button        alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog,int which) {
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                mContext.startActivity(intent);
            }
        });
        // on pressing cancel button        alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });
        alertDialog.show();
    }
    @Override    public void onLocationChanged(Location location) {
        Log.v("TEST****", "IN ON LOCATION CHANGE, lat=" + latitude + ", lon=" + longitude);
//        Toast.makeText(this,"Loc",Toast.LENGTH_LONG).show();        if (location != null) {
            Log.d(TAG, "== location != null");

            //Send result to activities            sendMessageToUI(String.valueOf(location.getLatitude()), String.valueOf(location.getLongitude()));
        }
    }

    private void sendMessageToUI(String lat, String lng) {

        Log.d(TAG, "Sending info...");

        Intent intent = new Intent(ACTION_LOCATION_BROADCAST);
        intent.putExtra(EXTRA_LATITUDE, lat);
        intent.putExtra(EXTRA_LONGITUDE, lng);
        LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
    }
    @Override    public void onProviderDisabled(String provider) {
    }
    @Override    public void onProviderEnabled(String provider) {
    }
    @Override    public void onStatusChanged(String provider, int status, Bundle extras) {
    }
    @Override    public IBinder onBind(Intent arg0) {
        return null;
    }
}
 
Layout
 
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:id="@+id/activity_main"    android:layout_width="match_parent"    tools:context=".MainActivity"    android:layout_height="match_parent">

    <Button        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:id="@+id/btn"        android:layout_centerInParent="true"        android:text="GET LOCATION" />

    <TextView        android:id="@+id/tvDisplay"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_below="@+id/btn"        android:layout_centerHorizontal="true"        android:layout_marginTop="39dp"        android:text="TextView" />

    <TextView        android:id="@+id/tvAddress"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignParentTop="true"        android:layout_alignStart="@+id/btn"        android:layout_marginStart="15dp"        android:layout_marginTop="75dp"        android:text="TextView" />
</RelativeLayout>

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