Author

Ahsen Saeed

Browsing

We as a programmer sometimes have a strange sense of humor. Being a programmer it isn’t easy. We code all day, debug all night, and go through thousands of code lines trying to clear up all the possible error. Sometimes, it takes a fellow programmer to understand the hardship of another programmer and sometimes the funny jokes of programming do the rest.

1. Todo Write Document

The most painful thing for a programmer is two things: The first one is to write document to others and the second one is why there is no document left by others!!

We dont need to write documentation

2. Engineers Vs Computer Scientists (Source Quora)

Ten computer scientists and ten engineers are on-line to buy train tickets to travel to the tech conference in the nearby city.

Each of the computer scientists walk up to the window to purchase their train ticket, and watch as the engineers combine their money to purchase only one ticket.

“Stupid engineers,” they say amongst themselves, boarding the train.

Soon after departing, the ticket taker enters the train car. All ten of the engineers pile into the restroom with their single ticket.

The ticket taker collects each of the computer scientists’ tickets and proceeds to the rest room. Seeing that it’s occupied, the ticket taker knocks on the door and asks for the occupant’s ticket. The engineers slip their ticket from under the door and the ticket taker moves on.

The computer scientists look at each other in astonishment that the engineers’ plan actually worked.

After the conference, the ten computer scientists and ten engineers line up again to buy their return tickets.

Again, the engineers only buy one ticket, but this time they watch on as the computer scientists buy zero tickets.

“Stupid computer scientists,” they say amongst themselves, boarding the train.

And again, the ticket taker enters the train car and all ten engineers pile into the restroom with their single ticket.

“Ticket please”, a computer scientist says, knocking on the restroom door. Sure enough, the engineers slide their ticket from under the door as the computer scientists pile into the adjacent restroom…

3. Java Primitives Got No Class

An attractive String walks into Java cafe and sees an int, boolean, and double sitting together.

The int walks up to her and say, ” I see you’ve got some tequila. Does that mean you wanna give me a shot?” The String quickly declines.

The same thing happens to boolean and double. Later the bartender asks, “Were those primitives bothering you?” and the String says, “Yes! they’ve got no–class.”

Java primitives meme

4. Found A Bug

The front-engineer of the company has been single for a long time and went to the dating site. After a while, a friend asked him did you find it? The engineer said, No! but found a bug on their page.

Website with bug meme

5. Programming vs How it Actually is

6. Programmer’s Chat

Two programmers who were works in the same company chatted with each other. A complained: “It is to hard to knock code every day. I want to change the line”. B said, “Knock back the car”.

7. Website Built With Joomla

8. Java Loses The Scope

A couple of years ago when I decided to learn programming, a friend of mine recommended to learn Java it has a scope, and now Java has lost its own scope.

Java is beneficial meme

9. Jesus Saves The Code

Jesus and Satan have an argument who is the better programmer. This goes on for a few hours until they came to an agreement to hold a contest with God as a Judge. They furiously, lines of code streaming up the screen for several hours straight.

Seconds before the end of the competition, a bolt of lightning strikes, taking out the electricity.  Moments later, the power is restored, and God announces that the contest is over.  He asks Satan to show his work.  Visibly upset, Satan cries and says, “I have nothing.  I lost it all when the power went out.”

“Very well,” says God, “let us see if Jesus has made any better.”

Jesus presses a key, and the screen comes to life and shows a beutiful screen with sparrows flying at the corner of the screen.

Satan is astonished.  He stutters, “B-b-but how?!  I lost everything, yet Jesus’ program is intact!  How did he do it?”

God chuckles, “Everybody knows… Jesus saves.”

Ctrl S jesus meme

10. Machine Learning Is Love

Thanks for the reading. If you like this post please share it with the community.

Know of any other great jokes on coding? Share them in the comments section below.

Thank you for being here and keep reading…

Here’re some more Articles you might be interested:

Some Keeps to avoid bugs while Programming

Here Are The Ten Best Programming Languages to learn

10 Simple Rules For Best Programming Practices

Google Maps are a great way to show data. It might seem natural that the more geographical point Markers we add the better story it tells. But that’s not always the ideal case because once we’ve hundreds, even more, points the performance of Android application quickly begins to decrease. Let’s see an overloaded marker picture of Google Maps.

Google Maps With So Many MarkersWe all have probably seen a map picture like this. There are so many markers on Google Maps, you can’t even see the map. The colors of markers tell some different kind of story, but there’s so much to overlap with other icons that you might well just be missing other data.

One way of getting rid of this problem to grouped (cluster) the marker’s on a Google Map and show only a specific amount of them. To see how marker clustering looks alike see the below picture.

Google Map Marker Clustering

The number on a cluster indicates how many markers it contains. Once we zoom onto cluster location we’ll able see the markers.

So, this tutorial shows you how to use marker clustering to display a large number of markers on Google Map in an Android application. Enough of this intro on marker clustering let’s dive into Android Studio and start building our application.

Note: I assume that you have successfully set-up Google Maps API in your Android app. If not, then visit Google Maps API get started section.

Getting Started

Before start coding our application we need to add the marker clustering util library (provided by Google) in the app-level build.gradle file.

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
 
    ........
    ........
   
    // MapV2 clustring marker dependency
    implementation 'com.google.maps.android:android-maps-utils:0.5'

    // Google play services location dependency
    implementation 'com.google.android.gms:play-services-location:16.0.0'
}

Sync the project and everything should be fine without any kind of gradle error.

Experiment with marker Clustering

Now that everything is done let’s see how the marker clustering done on Google Maps. The simplest way to show the cluster, first, we need to implement ClusterItem on our model class. Let’s create a simple User class that implements ClusterItem.

public class User implements ClusterItem {

    private final String username;
    private final LatLng latLng;

    public User(String username, LatLng latLng) {
        this.username = username;
        this.latLng = latLng;
    }

    @Override
    public LatLng getPosition() {  // 1
        return latLng;
    }

    @Override
    public String getTitle() {  // 2
        return username;
    }

    @Override
    public String getSnippet() {
        return "";
    }
}

Here’s what going on inside the above code.

  1. The ClusterItem returns the position of the marker, which later Google Maps use’s and show the marker. Must always return same LatLng position.
  2. Title of the marker which will be visible when you click on a single marker.

Next, we need to add the ClusterManager inside our MapActivity.

public class MapActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        SupportMapFragment supportMapFragment = (SupportMapFragment)      getSupportFragmentManager().findFragmentById(R.id.map_fragment);  // 1
        supportMapFragment.getMapAsync(new OnMapReadyCallback() {  // 2
            @Override
            public void onMapReady(GoogleMap googleMap) {
                setUpClusterManager(googleMap);
            }
        });
    }

    private void setUpClusterManager(GoogleMap googleMap){
        ClusterManager<User> clusterManager = new ClusterManager(this, googleMap);  // 3
        googleMap.setOnCameraIdleListener(clusterManager);
        List<User> items = getItems();
        clusterManager.addItems(items);  // 4
        clusterManager.cluster();  // 5
    } 

    private List<User> getItems() {
       ......  // returns the collection of users.
    }
}

Taking each commented section in turn.

  1. Obtain the SupportMapFragment from xml.
  2. Registering a callback to get notified when we’re ready to use Google Maps.
  3. Creates a new ClusterManager which later handles the clustering for our markers. Note the type of argument<User> which declares the ClusterManager to be of User type.
  4. Feed the items to our newly created ClusterManager.
  5. Call the cluster method, you may want to call this method after feeding items to ClusterManager.

Here’s the demo of our application with marker clustering and you can get the finished code for Default Marker Clustering from here.

Custom marker inside the Marker Clustering

Since weren’t satisfied with the default solution, we need to make some customization to our default setup. Now let’s say I need to change the red default marker icon which shows inside the Cluster Marker with my own custom marker. For that, we need to create a new ClusterRenderer with to extend the DefaultClusterRenderer class.

Here, let’s create a new ClusterManager class to show our custom marker instead of default ones.

public class MarkerClusterRenderer extends DefaultClusterRenderer<User> {   // 1

    private static final int MARKER_DIMENSION = 48;  // 2

    private final IconGenerator iconGenerator;
    private final ImageView markerImageView;

    public MarkerClusterRenderer(Context context, GoogleMap map, ClusterManager<User> clusterManager) {
        super(context, map, clusterManager);
        iconGenerator = new IconGenerator(context);  // 3
        markerImageView = new ImageView(context);
        markerImageView.setLayoutParams(new ViewGroup.LayoutParams(MARKER_DIMENSION, MARKER_DIMENSION));
        iconGenerator.setContentView(markerImageView);  // 4
    }

    @Override
    protected void onBeforeClusterItemRendered(User item, MarkerOptions markerOptions) { // 5
        markerImageView.setImageResource(R.drawable.location_vector_icon);  // 6
        Bitmap icon = iconGenerator.makeIcon();  // 7
        markerOptions.icon(BitmapDescriptorFactory.fromBitmap(icon));  // 8
        markerOptions.title(item.getTitle());
    }
} 

Here’s what’s going on inside the MarkerClusterRenderer class.

  1. Extending the default renderer in order to customize the marker’s inside the cluster.
  2. Setting the constant value for the single marker size.
  3. IconGenerator a utility class to generate the Bitmap icon marker.
  4. Adding the child view for IconGenerator class and in our case the ImageView which simply shows the marker.
  5. Called before every ClusterItem added to the Google Maps.
  6. Sets the drawable resource as the content of this marker ImageView.
  7. Generates the Bitmap of the previously custom view setting.
  8. Sets the icon for the marker.

Now we just need to set the instance of MarkerClusterRenderer class to our ClusterManager inside the MapActivity.

private void setUpClusterManager(GoogleMap googleMap) {
        ClusterManager<User> clusterManager = new ClusterManager<>(this, googleMap);
        clusterManager.setRenderer(new MarkerClusterRenderer(this, googleMap, clusterManager));
        ......
        ......
}

After adding the MarkerClusterRenderer class instance here’s the demo of our application with custom markers inside the Marker Clustering. You can get the complete code of Custom Marker Clustering from this link.

I hope this article will help you do custom Marker Clustering on Google Maps with Android application. Anything, I miss in this article please let me know via the comments section.

Thank you for being here and keep reading…

Every modern operating system has the support for multi-threading–so does the application built to run on that operating system. No, doubt multi-threading programming increase the performance and concurrency in our application. For certain applications, it is easier to code different procedures calls and conversation in a different thread than to manage them from the same thread.

Mostly in a client-server application, you definitely want the create the server application in a multi-threaded environment where thousands of clients connected to one server. Well if you think that we’re going to build a client-server application than you’re right. Wait! don’t just close the tab because this time I have got a real-world problem.

Multithreading Meme

Application Overview

First, a little intro to my application so that we’re all on the same page. The application is about to build a smart meter (GPRS Meter) data collector. The application simply opens up a ServerSocket and after that, it accepts clients (Smart Meter) waiting for the connection. There are thousands of smart meters trying to connect to that application. So, when the smart meter connects with the application via socket, the application creates its own separate thread for communication.

Promgramming thread meme

Get Started

The application that we’re going to build will be in Java programming language. So, the first step was simple, I try to open up the ServerSocket holding the Pepsi can in my hand.

public class DeviceListenerRunnable implements Runnable {

    private final int portNumber;  // 1
    private final ServerSocket serverSocket;  
    private final IConnectionEventArgs connectionEventArgs; // 2

    public DeviceListenerRunnable(int portNumber, IConnectionEventArgs connectionEventArgs) {
        this.portNumber = portNumber;
        serverSocket = new ServerSocket(portNumber);  // 3
        this.connectionEventArgs = connectionEventArgs; 
    }

    @Override
    public void run() {
        Socket socket;
        while (!Thread.currentThread().isInterrupted()) {
            try {
                socket = serverSocket.accept();   // 4
                connectionEventArgs.onDeviceConnected(socket, socket.getRemoteSocketAddress().toString());  // 5
                if (!socket.isClosed())
                    new ReceiverThread(socket, connectionEventArgs).start();  // 6
            } catch (Exception ignored) {
            }
        }
    }
}

Here’s what’s going on inside the code:

  1. Port number for ServerSocket.
  2. An interface which notifies the caller that the new smart meter has connected. We’ll see the implementation of IConnectionEventArgs in a couple of minutes.
  3. Creates the ServerSocket with the specified port number.
  4. Waiting for a new client (Smart Meter) to become online.
  5. Sending the Socket and info of connected smart meter back to the caller class.
  6. Creating a new separate thread for the connected smart meter.

Examining the ReceiverThread class

The ReceiverThread class basically processing all the incoming data from the connected smart meter and send data back to caller class via IConnectionEventArgs interface. Every smart meter connected to an application has its own instance of this class. So, if there are a thousand devices connected to the server than it means every device has it’s own instance of ReceiverThread class because every device communicates in a separate thread. Let’s see the implementation of this class.

public class ReceiverThread extends Thread {
    
    private final Closeable closeable;
    private final IConnectionEventArgs connectionEventArgs;  

    public ReceiverThread(@Nonnull Closeable closeable, IConnectionEventArgs connectionEventArgs) {
        this.closeable = closeable;
        this.connectionEventArgs = connectionEventArgs;
    }

    @Override
    public void run() {
        if (closeable instanceof Socket) {
            Socket socket = (Socket) closeable;
            while (!isInterrupted() && !socket.isClosed()) { // 1
                String info = socket.getRemoteSocketAddress().toString();
                try {
                    byte[] data = handleTcp(socket);  // 2
                    connectionEventArgs.onDataReceived(info, socket, data)  // 3
                } catch (IOException e) {
                    connectionEventArgs.onDeviceDisconnected(info, e);  // 4
                    try {
                        interrupt();   // 5
                        socket.close();   // 6
                    } catch (IOException ignored) {
                    }
                    break;
                }
            }
        }
    }

    private byte[] handleTcp(Socket socket) throws IOException {
        // Logic for reading the input stream 
    }
}

Let’s take a brief look at different steps:

  1. Nothing out of ordinary happens simply start a while loop until the current thread is not interrupted or socket is closed.
  2. Handling the incoming TCP data from a smart meter. (If someone want to see the logic behind handleTcp data method just ask in the comment section)
  3. Sending the incoming data back to caller class. (We’ll see the caller class in a couple of minutes)
  4. If IOException occurs, notify the caller class that the smart meter has been disconnected.
  5. Needs to call the interrupt method on the current thread.
  6. Close socket for the smart meter.

Before going any further I think you guys need to see the legendary IConnectionEventArgs interface implementation.

interface IConnectionEventArgs {

     void onDeviceConnected(Socket socket, String info);

     void onDeviceDisconnected(String info, IOException e);

     void onDataReceived(String info, Closeable c, byte[] data); 
}

Implementation of caller class

We got the basics down now we just need to implement the IConnectionEventArgs interface and start the thread for ServerSocket class. So, the DeviceListenerRunnable class listens to new incoming connections from smart meters.

public class ParentMediaHelper implements IConnectionEventArgs {

    private final Thread listenerThread;
    private final DeviceCollection deviceCollection = DeviceCollection.instance();

    public ParentMediaHelper(int portNumber) {
        DeviceListenerRunnable meterListenerRunnable = new DeviceListenerRunnable(portNumber, this); 
        listenerThread = new Thread(meterListenerRunnable);
    }

    public void startListener() { 
        listenerThread.start();  
    }

    @Override
    public void onDeviceConnected(Socket socket, String info) {
        // handle new smart meter connection 
    }

    @Override
    public void onDeviceDisconnected(String info, IOException e) {
        deviceCollection.remove(info) 
    }

    @Override
    public void onDataReceived(String info, Closeable c, byte[] data) {
         if(containsSerialNumber(data)){ 
              String serialNumber = extractSerialNumber(data)
              deviceCollection.insert(Device(info, c, serialNumber))
         }
         // handle other things
    }
}

I know, many of you think that there are thousands of smart meter connected to the server. How can I determine that the data came from which smart meter? Actually when the first time smart meter sends the data (current or voltage) after a successful socket connection. It also sends its serial number (unique identifier) and with that serial number, I create a new Device model and insert the model in my DeviceCollection class. The DeviceCollection simply a singleton class performs the CRUD functionality.

Similarly when the onDeviceDisconnected calls we remove the device from our collection.

Running the Application Server

Nice! all the hard work is done. Now I just need the main function which simply calls the startListener method inside the ParentMediaHelper class.

public class ddssd {

    private static final int PORT_NUMBER = 14001; // Always use port above 1024

    public static void main(String[] args) {
        ParentMediaHelper mediaHelper = new ParentMediaHelper(PORT_NUMBER);
        mediaHelper.startListener();
    }
}

After running the above program, my application starts accepting connection from the smart meter.

Note: If you’re running application on Linux based OS you need to open the specified port.

Alright, guys, this was my story of creating a Java-based server application. If you like this article please share it with the community.

Thank you for being here and keep reading…

Late last year, my company (Intelligent Metering System) starts a new project on smart meters. I won’t go in the detail of smart meters because some of you might not be heard of how it works internally. So, the project is about to build an MDC (Meter Data Collector). The purpose of MDC is to fetch data from multiple smart meters periodically and stores the data inside the mysql database.

Recently, we have completed our project successfully and installed in one of our client’s system. But before installation, we have met this problem where we need to give mysql database access to our client. So, we don’t want to give the whole database access instead to give access only some specific tables of a database. Because the client only needs to know about smart meters data, not about the whole application data.

In this blog post, I’ll focus on how to grant some specific tables remote access when working with mysql database on Linux or Unix-like operating system. Before you begin, you must consider the following prerequisites:

  • Install mysql server on the database server.
  • Start the mysql service via sudo systemctl start mysql.service.
  • Open mysql and create a database instance which table access you want to grant.
  • Allow the remote access to the mysql database server by editing the .cnf. You can see this link for enabling the remote connection in the mysql database server.

Below is the example of my complete mysql database. You can create your own database or use your existing database.

MySQL database table

Create a new mysql user for remote database access

Now in order to grant some specific database tables access, we need to create a new user (with no grant options) from which our client can access only the exposed tables. First, let’s create a new mysql user with the following query at mysql> prompt.

create MySQL new user

Please note the % sign in the above command refers to any host. It means our testUser client can connect to mysql database server via any Ip address.

After the creation of testUser let’s see all mysql user’s hosts and username with the following query.

MySQL username hosts query

Grant some specific mysql database tables access to testUser

Before granting remote database tables access lets see the current grants for testUser with the below query.

MySQL user grants

You see currently there are no database table grants for the testUser.

If you guys have seen the above mdc_collector  database then you know there are a total of ten tables and we only need to give remote access to some specific tables. Now let’s say we want to give access to testUser only billing_data, monthly_billing_data, and load_profile_data tables instead of the complete database. To exposed database tables enter the following commands at mysql> prompt.

After giving remote access to mysql database tables let’s see the selected grants for testUser with the following query.

You see the testUser only has remote access to three tables instead of the complete mdc_collector database. And finally, you may also need to run flush privileges on mysql> prompt.

flush privileges;

Verify remote database table access on a client system

Note: I already told you that in the prerequisites section that the remote connection of mysql DB only works if you’ve enabled the incoming connections in the mysql server machine. You can see this link for reference.

Now if you guys go to your personal machine or any client machine and try to connect the mysql server via any mysql client like the workbench you’ll see the mdc_collector database with only three tables in it. The following shows the connection with workbench.

Workbench MySQL linux database connection

The connection has been successfully made with the mysql database server. Now test the database tables.

MySQL Workbench database access

You can also test the remote database access to mysql server via cmd. If and only if you’ve installed the mysql package inside the client machine.

The above picture is my client machine where I successfully login into mysql server database via remote access.

  • -u testUser: The testUser is our mysql user which we have created inside the server machine.
  • -h 192.168.1.192: Ip-address or hostname where the mysql database server is hosted.
  • -p: Asks for the testUser password.

Now let’s verify that our client user has only three tables remote access instead of complete mysql database.

verify remote database table access

Alright, guys, this was all from this blog. Anything I miss, feel free to let me know using the comments section.

Thank you for being here and keep reading…

Almost in every Android Application, we ask users to add profile picture when signing up and after that, we simply upload the avatar to our backend. But, before uploading that avatar, sometimes, we need to crop the selected image.

So, today I would like to talk about how we can select an image from Gallery or take Picture from the camera and crop that avatar. The application that we’re going to build in this article will work on all versions of Android from Honeycomb (API 11) to Pie (API 28).

For cropping the image we’re going to use UCrop libraryUCrop library aims to provide an ultimate and flexible image cropping experience. You can read more about UCrop library in this article.

Before start coding, I want to show you guys the demo of our application.

Get Started

In Android Studio go to Create Android Project, press next twice and select Empty Activity, then finish. After the Android Studio gradle builds successfully you’re ready to do the code. You can see MainActivity like below.

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}

Include Dependencies

We’re gonna need to add the UCrop dependency in our app-level build.gradle file. Add the below dependency in the build.gradle file.

implementation 'com.github.yalantis:ucrop:2.2.2'

Now add the maven dependency in a top-level build.gradle file.

repositories {
       google()
       jcenter()
       maven { url "https://jitpack.io" }
   }

Once you’ve done these dependencies build your android project and add the following permissions in the Android Manifest file.

<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

You may be curious why the hack I add the Storage permission in order to pick an image from Gallery or take a picture from Camera. Actually, when we select the image from the gallery or take pictures from the camera we need to store an image inside the device memory because of the UCrop library take the Uri instance in order to crop the image. And it would be good because we need to store the cropped image somewhere inside the memory and after that show the image inside the application.

Actually, there’s another thing which we need to discuss before start making our application. As I said at the start of this article, that our application will work on all existing Android devices. So, we need to handle the FileUriExposedException and for that, we need to implement FileProvider in our application. You can read more about FileUriExposedException in this link.

In order to implement FileProvider in your application. First, you need to add a FileProvider <provider/> tag in a AndroidManifest.xml file under the <application/> tag.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    ...
    <application
        ...
        <provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="${applicationId}.provider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/provider_paths"/>
        </provider>
    </application>
</manifest>

The ${applicationId} automatically gets the package name of your Android application and concat the .provider with it.

The @xml/provider_paths we need to add it separately in the resource directory. First, you need to create an xml named directory inside the res folder and then create a file named provider_paths inside the previously created directory. Now paste the following code inside the provider_paths file.

<?xml version="1.0" encoding="utf-8"?>
<paths>
    <external-path name="external_files" path="."/>
</paths>

Done! FileProvider is now declared and be ready to use.

1. Open Camera And Take Picture

First of all, we need to query for all the activities in the device which will handle the  CAPTURE_REQUEST intent. Now let’s open the camera when the user clicks on openCamera dialog action.

Note: I’m not gonna ask for camera or storage permission in this article but you can get the complete code of the above demo application from the Github.

private void openCamera() {
      Intent pictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
      File file = getImageFile(); // 1
      Uri uri;
      if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) // 2
           uri = FileProvider.getUriForFile(activity, BuildConfig.APPLICATION_ID.concat(".provider"), file);
      else
           uri = Uri.fromFile(file); // 3
      pictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri); // 4
      startActivityForResult(pictureIntent, CAMERA_ACTION_PICK_REQUEST_CODE); 
}

Here what’s going on in the openCamera method.

  1. Creating an image File with the getImageFile method. This method simply creates a new File in the external storage directory. We’ll see the implementation of the method in a couple of minutes.
  2.  If the SDK version of the device is API level 23+ then we simply create the Uri with the help of FileProvider in order to prevent the FileUriExposedException. The BuildConfig.APPLICATION_ID simply give us the package name of our application and concat the .provider with it as we did it in the AndroidManifest.xml file.
  3. Simply creates the Uri fromFile utility method if the SDK version is less than 24 API level.
  4. Sets the path of where you want to store the selected image so, that we can read the image in the onActivityResult method from the uri path. We’ll see how to do that.

Now let’s create the getImageFile method inside the Activity class.

String currentPhotoPath = ""; 
private File getImageFile() {
     String imageFileName = "JPEG_" + System.currentTimeMillis() + "_";
     File storageDir = new File(
         Environment.getExternalStoragePublicDirectory(
             Environment.DIRECTORY_DCIM
         ), "Camera"
     );
     File file = File.createTempFile(
         imageFileName, ".jpg", storageDir  
     );
     currentPhotoPath = "file:" + file.getAbsolutePath();
     return file;
 }

This method simply creates a random File name with .jpg extension inside the external storage directory. Also, we’re storing the file path inside the currentPhotoPath variable so that we can read the image from specified photo path.

After taking the picture from Camera our image will be stored inside the data extra’s which we pass when creating the Intent for Camera. Now let’s retrieve our image in onActivityResult method and crop it.

Crop the Taken Picture

First, you need to override the onActivityResult method inside your Activity class and add the following code.

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    if(requestCode == CAMERA_ACTION_PICK_REQUEST_CODE && resultCode == RESULT_OK) {
          Uri uri = Uri.parse(currentPhotoPath);
          openCropActivity(uri, uri);
    }
}

If you observe the code carefully you may have noticed that we’re not using the data.getData() method. It always gives us null because we’re providing a file uri, so load with the currentPhotoPath and call the openCropActivity method.

Note: Our newly taken image will be replaced from the cropped image because I pass the same Uri’s as the sourceUri and destinationUri. You can change this logic by passing a different Uri for a destination.

Add the below openCropActivity method inside your Activity class.

private void openCropActivity(Uri sourceUri, Uri destinationUri) {
        UCrop.of(sourceUri, destinationUri)
        .withMaxResultSize(maxWidth, maxHeight)
        .withAspectRatio(5f, 5f)
        .start(context);
}

The UCrop configuration is created using the builder pattern. The UCrop.of method takes the first parameter as the sourceUri where the image file actually stored and the second parameter as the destinationUri where you want to store the cropped image.

After calling the openCropActivity method the UCrop simply opens up the image cropping activity with the startActivityForResult method and send the cropped image result in the onActivityResult method. Add the updated code inside the onActivityResult method.

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    if(requestCode == CAMERA_ACTION_PICK_REQUEST_CODE && resultCode == RESULT_OK) {
          Uri uri = Uri.parse(currentPhotoPath);
          openCropActivity(uri, uri);
    } else if (requestCode == UCrop.REQUEST_CROP && resultCode == RESULT_OK) {
          Uri uri = UCrop.getOutput(data);
          showImage(uri);
    }
}

In the updated code we simply get our cropped image Uri and call the showImage method.

Next, add the following method inside your Activity class.

private void showImage(Uri imageUri) {
    File file = FileUtils.getFile(context, imageUri);
    InputStream inputStream = new FileInputStream(file);
    Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
    imageView.setImageBitmap(bitmap);
}

Here we’ve completed our first part of an article where we take the picture from a camera and show the cropped image inside the ImageView.

2. Select Image From Gallery

In order to allow the user to select an image, we need to create an Intent which opens up the Documents app and only shows the images. Now let’s open the Documents app when the user clicks on selectImage dialog action.

Let’s create a new method to open the images.

private void openImagesDocument() {
    Intent pictureIntent = new Intent(Intent.ACTION_GET_CONTENT);
    pictureIntent.setType("image/*");  // 1 
    pictureIntent.addCategory(Intent.CATEGORY_OPENABLE);  // 2
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
         String[] mimeTypes = new String[]{"image/jpeg", "image/png"};  // 3
         pictureIntent.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes);
    }
    startActivityForResult(Intent.createChooser(pictureIntent,"Select Picture"), PICK_IMAGE_GALLERY_REQUEST_CODE);  // 4
}

The following shows the explanation of the above code.

  1. By setting the type we specify we only need images no videos or anything else.
  2. The CATEGORY_OPENABLE used to indicate that Intent only wants URI’s that can be opened. You can read more category openable here in this link.
  3. The mimeTypes specify that we are only interested in jpeg or png type images.
  4. The chooser only shows if there are multiple options available else we simply open up the Documents app.

Crop The Selected Picture

Once you’ve selected the image the onActivityResult method will get hit and we only need to update that method. Add the update method code inside the onActivityResult method.

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    if(requestCode == CAMERA_ACTION_PICK_REQUEST_CODE && resultCode == RESULT_OK) {
          Uri uri = Uri.parse(currentPhotoPath);
          openCropActivity(uri, uri);
    } else if (requestCode == UCrop.REQUEST_CROP && resultCode == RESULT_OK) {
          Uri uri = UCrop.getOutput(data);
          showImage(uri);
    } else if (requestCode == PICK_IMAGE_GALLERY_REQUEST_CODE && resultCode == RESULT_OK && data != null) {
          Uri sourceUri = data.getData(); // 1 
          File file = getImageFile(); // 2
          Uri destinationUri = Uri.fromFile(file);  // 3
          openCropActivity(sourceUri, destinationUri);  // 4 
    }
}

The below number points tell you what’s happening inside the updated onActivityResult method.

  1. Get the selected image Uri from data.
  2. Create the image File where you want to store the cropped image result.
  3. Simply creates the destinationUri fromFile utility method.
  4. Calls the openCropActivity method. Here we’re passing different Uri’s because our sourceUri is different where our selected image is stored and destinationUri where we want to save our cropped image result.

Now if you run the application you’ll see that all the application functionality will work perfectly. I hope this article will help you to crop the profile picture image. If you’ve any queries regarding this post please do comment below.

You can get the complete source code of above app from GitHub.

Thank you for being here and keep reading…

I caught myself saying this the other day and it made me think about how do I deal with bugs in my program.

Bad code gave me cancer

Let’s be honest: if you’re like most of the developers, your code probably has tons of bugs caused by many reasons. So, in this article, we’re going to discuss some practices to avoid bugs while developing software or program…

1. Keep reviewing your own code

Before the code is tested you’ve to look at it a few times. Sometimes you can see some hidden code bug. Every professional software developer knows that a code review should be part of a serious development process. The way to review is self-examination (self-checking your own code), mutual checking, experienced programmers or team leaders to check your code. Also, you can upload your code to GitHub to reviewed by the community.

2. Keep looking at the Logs

This is the part of software development that not all developers take seriously. It is best to take a little time and see the Logs. Useful Logs can provide the developer with tremendous help when trying to understand what the code actually does. Logs like the error, info, and warnings ensure you a good amount of info in your code, you should be easily able to trace what has happened by looking at the Logs.

Programming log review

3. Keep codebase separate that contains problems

Code is the enemy; the more you have the slower you go. And as the code grows the number of Bugs grow even faster. Therefore you have to split the code up, so the Bugs in one part of the code doesn’t affect the other areas. You need to depend on versions artifacts from other modules instead of depending on the source of other modules and provides the Isolation.

Versions artifacts dependencyAdvantages of Version Artifacts

  • Isolation
  • Decoupling
  • Faster Builds

Disadvantages of Version Artifacts

  • Dependency hell
  • No continuous Integration
  • Hard to make global changes

For more info, see Agility Require Safety presentation.

4. Keep writing unit Test

The importance of Unit Test cannot be overemphasized. It’s an excellent way to test your own code. The Unit Test gives developers the peace of mind to change code without worrying about the functionality. It must be written in a serious and responsible manner and try to cover the main business problem. The mistake that is often made in writing the Unit Test is that because of urgency to change Bug and forgetting to change the Unit Test at the same time.

If there are too many Bugs in development stages, it will affect the progress of the task. This is what managers don’t want to see.

Unit Test Image

5. Keep looking at compiler Warnings

Are there new compiler warnings..? That’s the question I ask myself every time before pushing the code on Git. Compiler warnings are very helpful to identify the Bugs in your code. Yes! I know they are too many of them but once every tenth of compiler warnings or so, the compiler actually has a point. We do sometimes write code that compiles successfully but does something odd that we didn’t intend.

Compiler warnings meme

6. Keep a focus on Development

In the era of social media, we’re always disturbed by various information like Instagram, Facebook, Tinder, Whatsapp etc. If we’re constantly interrupted by various things, wait for us to return the original when things are found. So, make sure you’ve no assumptions about your module the existing dependent module and the other modules to be dependent. Try and achieve an interface level agreement among all stakeholders.

7. Keep it simple & Stupid (KISS)

Avoid fancy coding and avoid fancy language features. The more complicated the code, the more likely there’s a bug. Avoid long lines. Instead of writing this:

val launchMissileStatus = missile.getLaunchMissileObject(
            prepareConfiguration().getConfig().confidId,
            getSecureSSHKey(getAdmin().adminId),
            getConnectivityManager()
        ).launchcMissile()
if (launchMissileStatus)
  println("Missile successfully launched")

write

val config = prepareConfiguration().getConfig()
val configId = config.configId
val adminId = getAdmin().adminId
val sshKey = getSecureSSHKey(adminId)
val connManager = getConnectivityManager()
val launchMissileObject = missile.getLaunchMissileObject(configId,sshKey,connManager)
val launchMissileStatus = launchMissileObject.launchMissile()

if (launchMissileStatus)
     println("Missile successfully launched")

It would be way easier to debug and find bugs.

8. Keep using existing Libraries

I’m sure all of you read this line “Don’t reinvent the wheel“. If there are well-tested libraries that do the same function that you’re planning to do then you should use the specific library. You don’t get paid to do what’s already done. I think the following quote is good for this:

The good programmers write code; great programmers steal code.

Alright, this concludes some practices to avoid bugs while programming. If you like what you read please share the knowledge with the community.

What’s next

Ten Simple Rules For Best Programming Practices

Thank you for being here and keep reading…

This story is the third part of our Android Cab Booking App tutorial If you didn’t read the previous ones you can start here.

Previously In Android Cab Booking App

In the previous article, we discussed how to read the online-drivers from Firebase Realtime Database, create the data structure for Drivers and animate multiples markers on Google Maps.

Also, I update the apps on GitHub. You can follow me by looking at the code. Java application link and Kotlin application link.

9. Show progress animation inside PinView

If you guys see the demo in the first article, you’ll understand that as soon as the Google Maps camera movement start. The ProgressBar inside the PinView start animating until the nearest Driver found and after that, we’ll calculate the distance with DistanceMatrixAPI between the nearest Driver location and the PinView location. Later the distance calculation we hide the ProgressBar and show the distance duration inside the PinView.

So, in order to animate the ProgressBar, we need to implement OnCameraMoveStartedListener on MainActivity. The OnCameraMoveStartedListener has its callback function which defines what action needs to be done when the camera starts its movement. In this callback, we need to start the ProgressBar animation.

Let’s start the ninth part of Cab Booking Application by implementing the OnCameraMoveStartedListener on MainActivity.

class MainActivity : AppCompatActivity(), GoogleMap.OnCameraIdleListener, GoogleMap.OnCameraMoveStartedListener {
      private var googleMap : GoogleMap? = null
      override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            .......
            .......
            val supportMapFragment = supportFragmentManager.findFragmentById(R.id.map) as SupportMapFragment supportMapFragment.getMapAsync { googleMap ->
                    googleMap.setOnCameraIdleListener(this)
                    googleMap.setOnCameraMoveStartedListener(this)  // implements the OnCameraStartedListener                        
                    this.googleMap = googleMap 
            }
     }

The OnCameraMoveStartedListener has one abstract method and we need to implement it as well. Below is the onCameraMoveStarted overridden method.

override fun onCameraMoveStarted(p: Int) {
     pinTimeTextView.visibility = GONE
     pinProgressLoader.visibility = VISIBLE
}

In the onCameraMoveStarted method, we show the ProgressBar and hide the previously shown TextView. Now if you run the application, you’ll see that when the app opens the ProgressBar start animating inside the PinView.Google Maps PinView Animation

10. Get the nearest driver and calculate the Distance

In order to get the nearest Driver, we need to know the PinView location exactly where the user stops while dragging it. If you guy’s remembered from the previous article, we exactly face the same problem when we need to Reverse Geocode a location where user drags the Pin. So, for this, we need to update our onCameraIdle method inside the MainActivity.

Update the onCameraIdle method inside the MainActivity class.

override fun onCameraIdle() {
    val position = googleMap.cameraPosition.target
    viewModel.makeReverseGeocodeRequest(position, geoCoderValue.value)
    viewModel.onCameraIdle(latLng);
}

Next, add the below method inside the MainActivityViewModel class.

fun onCameraIdle(latLng: LatLng) {
        launch(coroutineContext + Dispatchers.Default) {
            if (driverRepo.allItems().isNotEmpty()) {
                val driver = driverRepo.getNearestDriver(latLng.latitude, latLng.longitude)
                driver?.let { calculateDistance(latLng, it) }
            }
        }
    }

At first, we launch a coroutine because the getNearestDriver method is a suspended method. After that, we check if the List<Driver> that we’re keeping inside the DriverCollection is not empty. Later we call the getNearestDriver method inside DriverCollection and call the calculateDistance method if the nearest Driver is not null.

You can get the DriverCollection class from GitHub.

Add the below calculateDistance method inside the MainActivityViewModel class.

private fun calculateDistance(latLng: LatLng, driver: Driver) {
    launch(coroutineContext + Dispatchers.IO) {  // 1
        val destination = arrayOf(driver.lat.toString() + "," + driver.lng.toString())
        val origins = arrayOf(latLng.latitude.toString() + "," + latLng.longitude.toString())
        DistanceMatrixApi.getDistanceMatrix(googleMapHelper.geoContextDistanceApi(), origins, destination)  // 2
            .mode(TravelMode.DRIVING)
            .setCallback(object : PendingResult.Callback<DistanceMatrix> {

                override fun onFailure(e: Throwable?) {
                }

                override fun onResult(result: DistanceMatrix?) {
                    if (result != null)
                        _calculateDistance.postValue(result.rows[0].elements[0].duration.humanReadable)  // 3
                }
            })
    }
}

Let’s go through the logic behind the above code:

  1. launch a coroutine in IO dispatcher, because it is a good approach to execute all network requests inside the IO dispatcher.
  2. The DistanceMatrixApi class is from the dependency which we add in the first article. You can read more about how to use the library here on GitHub.
  3. If the DistanceMatrix result is not null then we pass the result to MainActivity via LiveData to show the distance duration inside the PinView.

Note: The distance we’re calculating is from Driver location to PinView location. That’s how the Careem application shows the calculated distance inside PinView.

Next, add the geoContextDistanceApi method inside the GoogleMapHelper class.

class GoogleMapHelper(private val resources : Resources) {

   companion object {
       private val geoApiContextBuilder = GeoApiContext.Builder()
   }

   .......
   .......

   private fun distanceApi(): String {
        return resources.getString(R.string.google_distance_matrix_api_key)  // replace with your own distance matrix api key.
   }

   fun geoContextDistanceApi(): GeoApiContext {
        return geoApiContextBuilder
            .apiKey(distanceApi())
            .build()
   }
}

Now that we’ve added the utility method inside the GoogleMapHelper class. We need to declare _calculateDistance inside MainActivityViewModel class in order to observe from MainActivity.

private val _calculateDistance = MediatorLiveData<String>()

val calculateDistance : LiveData<String> = _calculateDistance

Next, add the following code inside the MainActivity onCreate method to observe calculateDistance instance from MainActivityViewModel class.

// 1
viewModel.calculateDistance
            .observe(this, Observer { distance ->
                   pinTimeTextView.text = distance
                   pinTimeTextView.visibility = VISIBLE
                   pinProgressLoader.visibility = GONE
            })

When the Observer interface invoked we simply set the distance to pinTimeTextView and hide the currently showing pinProgressLoader.

So, here we’ve completed the tenth part of the Frisbee application. Now when you run the application you’ll see the nearest Driver duration inside the PinView and also the duration updates when the Google Maps camera movement stops. Build and run to view the application progress. Here is mine:

Google Map Custom PinView With Text

Bravo! this concludes that our Frisbee application is complete. Hopefully, the next article will be on Driver application and it’ll be the last article on Android cab booking app tutorial. Stay tuned!

Thank you for being here and keep reading…

Previous Part

Disclaimer: The information provided in this article is my own personal opinion and research. You may share your opinion in the comment section at the end of this article.

I still remember that day back in 2013 when I decided to learn programming and that was one of the best decision I took in my life. But before start learning, I asked myself.

What Programming language should I learn first?

As we advance to 2019, it’s a good time to reflect on our top learning priorities for 2019. Before start talking about Programming Languages let me clarify:

  • I’m not arguing that any language is objectively better than any other.
  • I agree that developers should eventually learn more than one language.

Let’s dive right in with the first Programming Language:

1. Python

Python has been a growing programming language and it shows no signs of disappearing. You’ll find it in web applications, desktop apps, network servers, machine learning, media tools and more.

You might find Python useful for back-end services and API’s, if you’re in security or Site Reliability Engineering. Python-based web development framework like DjangoPyramid and Turbo Gear have found more and more popularity.

In the end, it’s a good choice for beginner developers to learn Python, as it’s high-level and easy to read and comprehend language. Python stats according to PYPL site.

2018 Programming Languages Stats2. JavaScript

JavaScript is the most popular language according to Stack OverFlow. More than half of all developers use JavaScript. It’s vital to front-end development and increasingly relevant to back-end development. And it’s rapidly expanding into areas like game development and the (IOT) Internet of things. JavaScript stats according to Stack OverFlow survey for 2018.

Stack OverFlow lanfuages stats for 2018

JavaScript allows you to build interactive websites, and it’s truly an essential web tool technology alongside HTML and CSS, and because most browsers in some way implement JavaScript. It’s crucial for getting into web-development and learning this language but it’s generally easier to pick and do something tangible with, in part because of all accessible UI.

JavaScript Gif

3. Rust

If you haven’t heard Rust before, it’s a new system-level programming language that is changing the way we think about programming. Rust came in first place in the 2018 Stack OverFlow Developer survey for developer most loved and wanted language.

Stack OverFlow 2018 loved programming languages

Rust language originally developed by Mozilla Foundation and it operates as a low-level language, suited for performance critical code. Rust is created with the purpose of avoiding the dangling pointers, buffer overflows or any other kind of memory errors.

For a beginner, Rust might be a bit of a struggle to pick up as it insists on various rules to achieve memory safety. However, experienced developers love it, and it’s quite possible that in the next few years Rust will be in very high demand.

rust programming language fire

4. Go

Go is a minimal language like Python. Since it is developed by Google, who are also Python lovers, they came up a language which is simple to write like Python but more efficient like C++Go provides better features to write concurrent programs. In the era when multi-core apps are being written, Go addresses the need quite well and also there’s built-in support of concurrency in it.

Go programming languages

Combining the best aspects of functional and object-oriented programming, as well as featuring a valuable set of inbuilt development tools. Some good and famous projects are using it, for instance, kubernetes and Ethereum Cryptozoic Project are based on Go.

5. Swift

If you want to get into IOS mobile development, you should definitely consider Swift as a high-paid career path. Swift is a relatively new programming language released in 2014. It’s Apple’s new language options for programming native IOS and Mac-OS applications. Native apps have been found to outperform hybrid apps, and Sprite-Kit makes it even easier to build 2D games.  It is considered an improvement in terms of usability and performance compared to Objective-C.

Swift Programming Language

Swift is a statically typed language means that XCode checks your error for you, so your errors are easier to track down, and further, it operates faster. By the way, XCode is the editor for the Swift language.

6. Kotlin

Kotlin is the second most loved and wanted a programming language in 2018 Stack OverFlow survey. Kotlin language is originally developed by JetBrains. It is fully inter-operable with Java and comes with no limitations. It can be used almost everywhere Java is used today: for server-side development, Android Apps, and much more.

Android developer has also been using Kotlin language from some time and loved the most. In 2017 Google announced that, Kotlin is now the official language for Android development. Kotlin works great with all existing Java libraries and frameworks and runs with same level of performance as with Java.

Kotlin language and Android

7. C++

C++ is a highly efficient and flexible language, first created back in 1985. It has remained in high demand due to high performance, reliability, and variety of contexts you can use it in. Microsoft Windows and Google Chrome are the two of the most well-known projects created with C++, and indeed most of Amazon’s website are written in C++.

C++ still going strong

A career with C++ involves developing desktop applications, especially performance-intensive tasks. You’ll find C++ in a wide range of applications– from GUI application to 3D graphics for a game to real-time mathematical solutions.

8. TypeScript

TypeScript is a programming language designed for large-scale JavaScript application development. In 2018 TypeScript capture the imagination of wider developer community. This language is not just for a front-end developer, it is now used to power back-ends, create hybrid mobile applications, architect cloud solutions, design neural networks and even control robots.

typescript_everywhere

It’s no surprise that TypeScript is now fundamental to core JavaScript frameworks – even Google decided to use it in Angular.

9. Java

Java is arguably the most popular programming language you’ve ever heard. It is a language created by mighty James Gosling from Sun MicroSystems in 1991. There’s a great saying ”write once run everywhere” capture one of the keys that make Java so valuable. It’s powerful JVM (Java Virtual Machine) which makes it cross-platform compatible.

Learn Java

There are so many Gurus and Pandits saying that the Java will be forgotten after the Kotlin language introduced. Java has died and resurrected more times than we can count and it is still right here. According to the latest 2018 Stack OverFlow survey Java is still on number fifth in Programming & Markup Languages section.

10. F#

F# is originally developed by F# Software Foundation. There was a time nothing much happening in Web regarding of F# but according to the latest survey, F# ranks in highest salary comparative to other programming languages. F# is most often used as a crossed-platform Common Language Infrastructure (CLI) language, but it can also generate JavaScript and GPU code. The following shows the F# salary comparison:

Stack OverFlow salary survey 2018

That concludes the list of top ten programming languages you should consider learning in 2019. If you like what you read, share your knowledge with the community.

Thank you for being here and keep reading…

Here’re some more Articles you might be interested:

— 10 Funny Jokes Of 2019 Only True Programmers Will Get

— 10 Simple Rules For Best Programming Practices

— Some Keeps to avoid bugs while Programming

In this article, I walk you through the development of a very basic Java JAX_RS web-services with Jwt (Json web token) authentication. For web-services, we’re going to use Jersey which is an open source framework for RESTful Web Services in Java. Before jump into coding and start authenticating the user I want to tell you a brief workflow of our application.

Application Workflow

  • In order to use the web-services, the user sends a request to get a token by passing his/her credentials.
  • Our web-service validates the credentials, and return an encrypted privateKey aka token, which will only be valid for the next thirty minutes.
  • With every request, the user needs to send the privateKey in the request header, and if the key is invalid or expires then we send back the WebApplicationException, else we simply return the result.

We’ll implement a custom ContainerRequestFilter, which is in the simple words, a gateway of our application. Every request made by the client first came to our custom filter and we validate the privateKey before allowing the request to go to any service.

Like I said at the start of this article, we’ll create a privateKey aka token with Jwt (Json web token). In order to create a web-based token, we’ll use the Java Jwt library made by mighty lhazlewood.

There’s a great article on Json Web Token go and check it out => 5 Easy Septs to understand Json Web Token (Jwts)

Application Workflow Diagram

As mention above, in the Application Workflow section our server or web-services will generate a privateKey or Jwt token for the user. With the Jwt token, the user then safely communicate with the application. Below is the workflow diagram.

Jwt workflow diagram

This is indeed a simplistic introduction to our application.  Next, below is the demo of our application for visualization.

In case I miss something, you can follow me by looking in the code which I pushed on GitHub.

Get Started

To begin, create a new Maven web project using an IDE and open the pom.xml file. Here we need to add dependencies for Jersey and Jwt.

<dependencies>
        ...........
        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-core</artifactId>
            <version>1.19.4</version>
        </dependency>
        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-grizzly2</artifactId>
            <version>1.19.4</version>
        </dependency>
        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-json</artifactId>
            <version>1.19.4</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.jersey.ext</groupId>
            <artifactId>jersey-entity-filtering</artifactId>
            <version>2.14</version>
        </dependency>
        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt-api</artifactId>
            <version>0.10.5</version>
        </dependency>
        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt-impl</artifactId>
            <version>0.10.5</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt-jackson</artifactId>
            <version>0.10.5</version>
            <scope>runtime</scope>
        </dependency>
        .........
    </dependencies>

Once you’ve added the above dependencies compile the Maven project and you’re good to go.

In order to start building our application first let’s see our EndPoint class. Below is our HomeApiService, which is an EndPoint of our application.

@Path("/")
public class HomeApiService {

    @POST
    @Path(value = "authorization_service")
    @JwtCustomToken
    @Produces(MediaType.APPLICATION_JSON)
    public Response authorizationService(@QueryParam("username") String userName, @QueryParam("password") String password) {
        if (userName.isEmpty())
            return getResponse(new BaseResponse(BaseResponse.FAILURE, "username field cannot be empty!"));
        if (password.isEmpty())
            return getResponse(new BaseResponse(BaseResponse.FAILURE, "password field cannot be empty!"));
        String privateKey = JwTokenHelper.getInstance().generatePrivateKey(userName, password);
        return getResponse(new AuthorizationResponse(BaseResponse.SUCCESS, "You're authenticated successfully. Private key will be valid for 30 mins", privateKey));
    }
    
    @GET
    @Path("allDevices")
    @Produces(MediaType.APPLICATION_JSON)
    public Response getAllDevices() {
         return getResponse(new DeviceCollection(Arrays.asList(new Device("Electric Kettle", 1, true), new Device("Computer", 1, true), new Device("Motorcycle", 3, false), new Device("Sandwich Maker", 4, true))));
    }

As you can see the basic JAX-RX Endpoint has two methods both returning a Response object. Now if you guy’s have seen the demo, then you probably see that in order to get allDevices we first need to authenticate our user and pass the privateKey inside the header of the request. Below is the explanation of the above two methods:

  • authorizationService: The user needs to get authenticated, invoking an HTTP POST and passing a username and password . Once authenticated, we simply call our jwTokenHelper class to create a token based on the username and password also set some other claims like thirty minutes expiration. You’ll see that how to create Jwt token in a couple of minutes.
  • getAllDevices: Simply returns a List of devices.

Filter checking for json web Token (Jwt)

So, we’ve added the EndPoint to our application but where did we check that the user adds the privateKey inside the header of the request. For this, we need to implement  ConatinerRequestFilter and after that the filter allows us to check the headers for every request. Like I said at the above of this article, the filter is like a gateway to our application. Every request sent by the client first came to our custom filter and after that, it goes to the EndPoint address. Below is JsTokenFilterNeeded class.

@Provider   
@JwtCustomToken   // 1
@Priority(Priorities.AUTHENTICATION)  // 2
public class JsTokenFilterNeeded implements ContainerRequestFilter {
   
   private static final String AUTHORIZATION_SERVICE_PATH = "authorization_service";  
   private static final String PRIVATE_KEY = "privateKey";   
   private JwTokenHelper jwTokenHelper = JwTokenHelper.getInstance();

   @Override
    public ContainerRequest filter(ContainerRequest request) {  // 3
        String path = request.getPath();                     
        if(path.equals(AUTHORIZATION_SERVICE_PATH))        // |       4
             return request;
        String privateKeyHeaderValue = request.getHeaderValue(PRIVATE_KEY);  // 5
        if (privateKeyHeaderValue == null || privateKeyHeaderValue.isEmpty())
            throw new WebApplicationException(getUnAuthorizeResponse(PRIVATE_KEY + " is missing in header"))   // 6
        try {
             provider.jwTokenHelper.claimKey(privateKeyHeaderValue);   // 7
        } catch(Exception e) {
            if (e instanceof ExpiredJwtException) {
                throw new WebApplicationException(getUnAuthorizeResponse(PRIVATE_KEY + " is expired"));
            } else if (e instanceof MalformedJwtException) {
                throw new WebApplicationException(getUnAuthorizeResponse(PRIVATE_KEY + " is not correct"));
            }
        }
        return request;
    }

    private Response getUnAuthorizeResponse(String message) {
       return Response.ok(BaseResponse.FAILURE, message
       ).status(Response.Status.UNAUTHORIZED)
        .type(MediaType.APPLICATION_JSON)
        .build()
    }
}

Let’s go through the logic behind the implementation.

  1. The JwtCustomToken is just a JAX-RS name binding (think of it’s as a CDI interceptor binding), so it’s just an annotation that binds to a filter. We’ll see that how to create JwtCustomToken annotation in a couple of minutes.
  2. Priority for user authentication. You can read more about other priorities in this link.
  3. The filter method is invoked at runtime whenever a new request came.
  4. If the path of the current request is authorization_service then we simply return the ContainerRequest immediately because at here our client trying to create a new privateKey. Also in here, we don’t need to check that user added the Jwt token inside the header request or not.
  5. Gets the HTTP Authorization header from the request (the privateKey).
  6. If privateKey is not added inside the header of the request then we simply throw WebApplicationException with a message (privateKey is missing in header).
  7. It validates the token (privateKey) using the Jwt library. If the token is valid then, in the end, we simply return the ContainerRequest and if it is not valid or token expires WebApplicationException thrown with a specific message.

The following shows the code snippet for JwtCustomToken annotation class.

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
@NameBinding
public @interface JsonTokenNeeded {
}

Issue a json web token (Jwt) or privateKey

Now we have a filter that checks that the privateKey is passed inside the HTTP header. But how is this token issued? Here comes our JwTokenHelper class which create JJwt token based on user’s username and password also claims the token.

public class JwTokenHelper {

   private static JwTokenHelper jwTokenHelper = null;
   private static final long EXPIRATION_LIMIT = 30;
   private Key key = Keys.secretKeyFor(SignatureAlgorithm.HS256);

   private JwTokenHelper() {
   }

   public static JwTokenHelper getInstance() {
      if(jwTokenHelper == null)
           jwTokenHelper = new JwTokenHelper();
      return jwTokenHelper;
   }

   //  1
   public String generatePrivateKey(String username, String password) {
       return Jwts
                .builder()
                .setSubject(username)
                .setSubject(password)
                .setExpiration(getExpirationDate())
                .signWith(key)
                .compact();
   }
   
   // 2
   public void claimKey(String privateKey) throws ExpiredJwtException, MalformedJwtException  {
      Jwts
                .parser()
                .setSigningKey(key)
                .parseClaimsJws(privateKey);
   }

   // 3
   private Date getExpirationDate() {
       long currentTimeInMillis = System.currentTimeMillis();
       long expMilliSeconds = TimeUnit.MINUTES.toMillis(EXPIRATION_LIMIT);
       return new Date(currentTimeInMillis + expMilliSeconds);
   }

}

Below is the explanation of the above code.

  1. In here we set few claims for Json Web Token. Add the username and password, set expiration date for privateKey and sign in with SignatureAlgorithm.HS256.
  2. Validating the key with Jwts parser. If the key is not valid then the method throws MalformedJwtException and if it expires then it throws ExpiredJwtException.
  3. This is the method which sets that the privateKey is only valid for the next thirty minutes.

Now that we’ve all part’s, let’s put them together and run our application. In this article, we only see the configuration by extending ResourceConfig instead of a web.xml file.

public class MyResourceConfig extends DefaultResourceConfig {

    
    public MyResourceConfig() {
        super(HomeApiService.class); 
        Map<String, Object> maps = new HashMap<String, Object>();
        maps.put(ResourceConfig.PROPERTY_CONTAINER_RESPONSE_FILTERS, CORSFilter.class);  
        maps.put(ResourceConfig.PROPERTY_CONTAINER_REQUEST_FILTERS, JsTokenFilterNeeded.class);
        setPropertiesAndFeatures(maps);
    }
}

The DefaultResourceConfig class is itself an extension of JAX-RX Application class and also provides some convenience methods like setPropertiesAndFeatures to register our filters. Now in our MyResourceConfig constructor, we define a Map<String,Object> that will hold our resource and response filters and later set maps to ResourceConfig.

Run your rest Service

To run your web application paste the following code snippet inside your main method and afterward run the application like you run a simple java program.

public static void main(String[] args) {
        ResourceConfig resourceConfig = new MyResourceConfig();
        try {
             // change with your application ip and port address. 
            GrizzlyServerFactory.createHttpServer(URI.create("http://000.000.000.000:xxxx"), resourceConfig);   
            System.in.read();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

Closing Up

In this article, I just wanted to show you how easy it is to issue and validate the Json Web Token with JAX-RX. Anything which I miss in this article please let me know via comment.

What’s next

Thank you for being here and keep reading…

There are a few 🏆 treasures that have been added as a part of JDK 11 and help developers to minimize coding efforts. Some of them you definitely know such as responsive Http2/API, you can run the source code directly without compiling. However, have you tried extensions of common classes such as String, Optional, Collections and Files, and if you haven’t already, congratulations, you’ll learn about some of them in this article.

You can download the JDK 11 from this link.

1. Local parameter type inference for Lambda Expressions

JDK 11 allows var keyword to be used when declaring the formal parameters of implicitly typed lambda expressions:

Function<String, String> append = (var string) -> string + " World";
String appendedString = append.apply("Hello");
System.out.println(appendedString);

It’s not just adding the var keyword to the variable that omits the type. The JDK 11 also allow annotations to be added to lambda’s parameters without having to write full variable type name. Let’s take a look at with example:

Function<String, String> append = (@NonNull var string) -> string + " World";
String appendedString = append.apply("Hello");
System.out.println(appendedString);

// Output of above program
Hello World

Now the apply method inside the Function accepts the NonNull value.

2. Usage of String:: repeat method to copy a String

A String method for repeating sequences of characters has been long requested from a user in StackOverflow.

RepeatMethodForJDK11

Now from JDK 11, we have a repeat method that does exactly what we need.

var str = "abc";
var repeated = str.repeat(3);
System.out.println(repeated);

// Output of above program
abcabcabc

3. Create a Path with Path::of method

I really like the Path API, which solves the problem of switching between paths, URIs, URLs, and FILEs. In Java 11 we can use Paths::get and Path::of methods to make them very uniform.

Path googlePath = Path.of(URI.create("www.google.com"))
Path studentFilePath = Path.of("/home/Students/student.txt")

4. Files::readString and Files::writeString for file reading and Writing

If you need to read content from a very large file, we generally use lines method which returns a lazy stream. Similarly, if you want to store content in a file at the same time, I usually write to the files using the write method by passing an Iterable.

But in JDK 11, two methods of readString and writeString have been added to Files class.

String studentFileContent = Files.readString(Path.of("student.txt"))
String modifiedStudentContent = addNewSubject(studentFileContent)
Files.writeString(Path.of("student-mod.txt"),modifiedStudentContent)

5. String::lines to get the number of data Rows

You have a multi-line string and you want to do a separate operation for each line. You can do this with String::lines method.

var multiline = "My\nname is\nahsen saeed";
Stream<String> stream = multiline.lines();
stream.map(String::toUpperCase)
      .forEach(System.out::println);

// Output of above program
MY
NAME IS
AHSEN SAEED

The lines in the Stream are in the order in which they occur in the string. Unlike split, the new lines method is lazy.

Note: The new line in a string in the above example uses \n in Windows. Although, I’m using it in Linux, lines method can still split them. In a different operating system, the lines method will use \r, \n, \r\n as terminators. Even if we mix them in a string.

6. Usage of Optional::isEmpty instead of isPresent

Almost in every application, we need to check that if the value exists or not and for that, we often use the Optional::isPresent method. I know! there is no problem in writing that, but writing does not understand the meaning of well. Now if we need to check that the value is empty inside the Optional::isPresent method then we add the ! operator at the front.

val optional: Optional<String> = Optional.empty()
if(!optional.isPresent)
    // value is empty

This ! is easily forgotten on Optional starting with Java 11, we have a better solution.

val optional: Optional<String> = Optional.empty()
    if (optional.isEmpty) {
        //  value is empty
    }

The isEmpty method is used to return true if the value is not present.

7. Handling regular expressions with Pattern::asMatchPredicate

You have a regular expression and want to do some filtering based on it. What do you do?

Pattern<String> chracterPredicate = Pattern.compile("ah").asPredicate();
Stream.of("coding","ahsan","infinite")
       .filter(chracterPredicate)
       .forEach(System.out::println);

// Output of above program
ahsan

We had the asPredicate method as part of JDK 8, which will create a Predicate if and only if the given Pattern is found in a given string.

In JDK 11 we’ve another method Pattern::asMatchPredicate. So, what is the difference between them:

  • asPredicate: Under the hood, the asPredicate method called  matcher(s).find().
  • asMatchPredicate: It will checks if the entire string conforms to this regular expression. This method behaves like matcher(s).matches().

Now let’s say you have a regular expression that verifies the email.

private static final String EMAIL_PATTERN = "^[a-zA-Z0-9#_~!$&'()*+,;=:.\"<>@\\[\\]\\\\][email protected][a-zA-Z0-9-]+(\\.[a-zA-Z0-9-]+)*$";

var pattern = Pattern.compile(EMAIL_PATTERN).asMatchPredicate();
Stream.of("[email protected]")
      .filter(pattern)
      .forEach(sendEmailToMySecretary);

You see the asMatchPredicate method checks our regular expression internally and return the email if it is matched with the regular expression.

8. Usage of the strip, stripLeading, and stripTrailing

JDK 11 introduces the strip methods, which have some subtle differences from trim, let’s see them one by one:

8.1 strip

The strip() method is used to remove the leading and trailing whitespaces. It is helpful to remove the white space from the beginning and the end of a string.

var s = " Michale ";
String stripResult = s.strip(); 
System.out.println(stripResult)

// Output of above program
"Michale"

8.2 stripLeading

The stripLeading() method is used to remove the white space from the beginning of a string.

var s = " Michale ";
String stripLeadingResult = s.stripLeading();
System.out.println(stripLeadingResult)

// Output o above program
"Michale "

8.3 stripTrailing

The stripTrailing() method is used to remove the white spaces from the end of a string.

var s = " Michale ";
String stripTrailingResult = s.stripTrailing();
System.out.println(stripTrailingResult)

// Output of above program
" Michale"

9. Handle empty I/O operations with null StreamReader

What do you do when you need an InputStream that doesn’t process any data? What about an empty OutputStream, Reader or maybe Writer? In Java 11 you can do the following conversions:

InputStream inputStream = InputStream.nullInputStream();
OutputStream outputStream = OutputStream.nullOutputStream();
Reader reader = Reader.nullReader();
Writer writer = Writer.nullWriter();

10. Convert collections to arrays using Collection::toArray

How did you turn the collection into an array before Java 11?

Studen[] studentArray = studentList.toArray(new Student[0]);

The above toArray method returns an array if the list fits in the specified array. Otherwise, a new array is allocated with the runtime type of the specified array and size of the list.

Now that we have a method which returns an array of specified type T. Why do we need another function? Is there a better way to handle it? In Java 11, you can do this:

Student[] studentArray = studentList.toArray(Student[]::new);

This is a new overloading method used by collection classes to receive IntFunction. The above Collection::toArray method returns an array of the corresponding length based on the length of the input data. It can be expressed in a brief and clear manner as T[]::new.

What’s next

Closing Up

Hope you found this story useful and interesting. Feel free to share your feedback and comments below.

Thank you for being here and keep reading…