Blog

  • How to create mock server response and connect to Android Retrofit

    How to create mock server response and connect to Android Retrofit

    Here I want to talk about mock responses for your Retrofit.

    Sometimes we should continue mobile development even backend not ready. We can be never blocked on it if will use mock responses. Sure we need specify JSON response before starting. But we need only JSON format of the backend response to start.

    Let’s see.

    First we need create implementation of Interceptor and this class will contains all logic for server responses.

    Feel free parse requests and create your own if/else cases

    Here is sample FakeInterceptor.java

    package com.hrupin.fakeinterceptorsample.retrofit;
    
    import android.content.Context;
    import android.util.Log;
    
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.net.URI;
    import java.util.ArrayList;
    import java.util.List;
    
    import okhttp3.Interceptor;
    import okhttp3.MediaType;
    import okhttp3.Protocol;
    import okhttp3.Request;
    import okhttp3.Response;
    import okhttp3.ResponseBody;
    import okio.Buffer;
    
    /**
     *
     */
    public class FakeInterceptor implements Interceptor {
        private static final String TAG = FakeInterceptor.class.getSimpleName();
        private static final String FILE_EXTENSION = ".json";
        private Context mContext;
    
        private String mContentType = "application/json";
    
        public FakeInterceptor(Context context) {
            mContext = context;
        }
    
        /**
         * Set content type for header
         *
         * @param contentType Content type
         * @return FakeInterceptor
         */
        public FakeInterceptor setContentType(String contentType) {
            mContentType = contentType;
            return this;
        }
    
        @Override
        public Response intercept(Chain chain) throws IOException {
            List<String> listSuggestionFileName = new ArrayList<>();
            String method = chain.request().method().toLowerCase();
    
            Response response = null;
            // Get Request URI.
            final URI uri = chain.request().url().uri();
            Log.d(TAG, "--> Request url: [" + method.toUpperCase() + "]" + uri.toString());
    
            String defaultFileName = getFileName(chain);
    
            if (defaultFileName != null) {
                String fileName = getFilePath(uri, defaultFileName);
                Log.d(TAG, "Read data from file: " + fileName);
                try {
                    InputStream is = mContext.getAssets().open(fileName);
                    BufferedReader r = new BufferedReader(new InputStreamReader(is));
                    StringBuilder responseStringBuilder = new StringBuilder();
                    String line;
                    while ((line = r.readLine()) != null) {
                        responseStringBuilder.append(line).append('\n');
                    }
                    Log.d(TAG, "Response: " + responseStringBuilder.toString());
                    Response.Builder builder = new Response.Builder();
                    builder.request(chain.request());
                    builder.protocol(Protocol.HTTP_1_0);
                    builder.addHeader("content-type", mContentType);
    
                    builder.body(ResponseBody.create(MediaType.parse(mContentType), responseStringBuilder.toString().getBytes()));
                    builder.code(200);
                    builder.message(responseStringBuilder.toString());
    
                    response = builder.build();
                } catch (IOException e) {
                    Log.e(TAG, e.getMessage(), e);
                }
            } else {
                for (String file : listSuggestionFileName) {
                    Log.e(TAG, "File not exist: " + getFilePath(uri, file));
                }
                response = chain.proceed(chain.request());
            }
    
            Log.d(TAG, "<-- END [" + method.toUpperCase() + "]" + uri.toString());
            return response;
        }
    
        private String getFileName(Chain chain) {
    
            String method = chain.request().method();
            if (method.equals("POST")) {
                String fileName = null;
                String lastSegment = chain.request().url().pathSegments().get(chain.request().url().pathSegments().size() - 1);
    
                if (lastSegment.equals("login")) {
                    fileName = "login";
                } else {
                    fileName = lastSegment;
                }
    
                return fileName + FILE_EXTENSION;
            }
            return "none" + FILE_EXTENSION;
        }
    
        private String getFilePath(URI uri, String fileName) {
            String path;
            if (uri.getPath().lastIndexOf('/') != uri.getPath().length() - 1) {
                path = uri.getPath().substring(0, uri.getPath().lastIndexOf('/') + 1);
            } else {
                path = uri.getPath();
            }
            return uri.getHost() + path + fileName;
        }
    }
    

    The key method is public Response intercept(Chain chain). You can play inside this method and prepare responses for your client side.

    I’ve created sample login form with mock server requests

    OkHttp log

    D/OkHttp: --> POST http://mockapi/login http/1.1
    D/OkHttp: Content-Type: application/json
    D/OkHttp: Content-Length: 47
    D/OkHttp: Accept: application/json
    D/OkHttp: {"email":"test@test.com","password":"password"}
    D/OkHttp: --> END POST (47-byte body)
    D/OkHttp: <-- 200 {
    D/OkHttp:   "id":"uceruc65tfvifbvuyfd67t",
    D/OkHttp:   "name":"John"
    D/OkHttp: }
    D/OkHttp:  http://mockapi/login (1ms)
    D/OkHttp: content-type: application/json
    D/OkHttp: {
    D/OkHttp:   "id":"uceruc65tfvifbvuyfd67t",
    D/OkHttp:   "name":"John"
    D/OkHttp: }
    D/OkHttp: <-- END HTTP (53-byte body)

     

    Download it from github

    Feel free download source code of the sample application from my github

    Nice codding

  • How to configure PHP with Nginx webserver on Mac OS X

    How to configure PHP with Nginx webserver on Mac OS X

    Before starting installation PHP-FPM and configurations you should have Nginx installed and configured. If you don’t have it ready please follow my previous post about installing and configuring Nginx on Mac OS X. Here is the link https://www.hrupin.com/2017/11/how-to-install-nginx-webserver-on-mac-os-x

    So, here we have installed and configured NGinx. Let’s install and configure PHP-FPM. Here is step by step instructions

    • Install php71 using Homebrew
      brew tap homebrew/dupes
      brew tap homebrew/php
      brew search php
      brew install php71 --without-apache --with-fpm
    • Setup automatic launch php after mac start
      mkdir -p ~/Library/LaunchAgents
      cp /usr/local/opt/php71/homebrew.mxcl.php71.plist ~/Library/LaunchAgents/
      launchctl load -w ~/Library/LaunchAgents/homebrew.mxcl.php71.plist
    • Edit /usr/local/etc/php/7.1/php.ini and replace
      ;cgi.fix_pathinfo=1

      with next string

      cgi.fix_pathinfo=0
    • Edit /usr/local/etc/php/7.1/php-fpm.d/www.conf file and put there your username and group. You need find next lines and edit them like next. Please replace YOUR_USERNAME with your username and YOUR_GROUP with name of your group
      user = YOUR_USERNAME
      group = YOUR_GROUP
    • Next we need edit default virtualhost and add make it look like this
      server {
          listen   80; ## listen for ipv4; this line is default and implied
          listen   [::]:80 default_server ipv6only=on; ## listen for ipv6
      
          server_name  localhost;
          
          root       /var/www/localhost;
      
          index index.php index.html index.htm;
       
          access_log  /usr/local/etc/nginx/logs/default.access.log;
          error_log  /usr/local/etc/nginx/logs/default.error.log;
       
          location ~ \.php$ {
              try_files      $uri = 404;
              fastcgi_pass   127.0.0.1:9000;
              fastcgi_index  index.php;
              fastcgi_param  SCRIPT_FILENAME $document_root$fastcgi_script_name;
              include        fastcgi_params;
          }
      
          error_page  404     /404.html;
          error_page  403     /403.html;
      }
    • Install mcrypt
      sudo brew install php71-mcrypt
    • Prepare test web content. Create file  /var/www/localhost/info.php with next content
      <?php
          phpinfo();
      ?>
    • Save all files and restart PHP
      sudo brew services stop php71
      sudo brew services start php71
    • Restart Nginx
      sudo nginx -s stop
      sudo nginx
    • Check how Nginx works
      curl -IL http://localhost/info.php
    • Output should be like this
      HTTP/1.1 200 OK
      Server: nginx/1.12.1
      Date: Sat, 11 Nov 2017 22:01:37 GMT
      Content-Type: text/html; charset=UTF-8
      Connection: keep-alive
      X-Powered-By: PHP/7.1.11
    • Also you can run http://localhost/info.php in your browser and you should see phpinfo table like this

    Now Nginx able to work with PHP

  • How to install Nginx webserver on Mac OS X

    How to install Nginx webserver on Mac OS X

    Before start you should ensure that you have Command Line Tools installed in your mac. It is part of XCode. You should have it installed and updated.

    • Install Command Line Tools if not exist
      xcode-select --install
    • Install Nginx using Homebrew
      brew tap homebrew nginx 
      brew install nginx
      
    • Test Installation
      ## Start Nginx
      sudo nginx
      
      ## Check if Nginx is running on 8080 port
      curl -IL http://127.0.0.1:8080
    • Output should look like this
      HTTP/1.1 200 OK
      Server: nginx/1.12.1
      Date: Sat, 11 Nov 2017 21:11:39 GMT
      Content-Type: text/html
      Content-Length: 138
      Last-Modified: Sat, 11 Nov 2017 19:49:46 GMT
      Connection: keep-alive
      ETag: "5a07545a-8a"
      Accept-Ranges: bytes
    • Also you can open http://127.0.0.1:8080 in your browser. You should get the next page 

    Nginx installed successful.

    I prefer to make configurations for virtual hosts right after webserver installation. You can do the same using following instructions

    • Prepare dirs before making configuration
      mkdir -p /usr/local/etc/nginx/logs
      mkdir -p /usr/local/etc/nginx/sites-available
      mkdir -p /usr/local/etc/nginx/sites-enabled
      sudo mkdir -p /var/www
      sudo chown :staff /var/www
      sudo chmod 775 /var/www
    • Prepare default content for webpages. Create /var/www/localhost/index.html file with following content
      <!DOCTYPE html>
      <html>
      	<head>
      		<title>Localhost</title>
      	</head>
      	<body>
      		<h1>It Works!</h1>
      		<p>Welcome to Nginx</p>
      	</body>
      </html>
    • Edit Nginx config file /usr/local/etc/nginx/nginx.conf and make it look like this
      worker_processes  1;
       
      error_log  /usr/local/etc/nginx/logs/error.log debug;
       
      events {
          worker_connections  1024;
      }
       
      http {
          include             mime.types;
          default_type        application/octet-stream;
       
          log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                            '$status $body_bytes_sent "$http_referer" '
                            '"$http_user_agent" "$http_x_forwarded_for"';
       
          access_log  /usr/local/etc/nginx/logs/access.log  main;
       
          sendfile            on;
       
          keepalive_timeout   65;
       
          index index.html index.php;
       
          include /usr/local/etc/nginx/sites-enabled/*; 
      }
    • Create /usr/local/etc/nginx/sites-available/default file with following content
      server {
          listen       80;
          server_name  localhost;
          root       /var/www/localhost/;
       
          access_log /usr/local/etc/nginx/logs/default.access.log;
          error_log /usr/local/etc/nginx/logs/default.error.log;
      
          error_page  404     /404.html;
          error_page  403     /403.html;
      }
    • Make symbolic link to sites-avalable/default into sites-enabled
      sudo ln -s /usr/local/etc/nginx/sites-available/default /usr/local/etc/nginx/sites-enabled/default
    • Save files and restart Nginx
      sudo nginx -s stop
      sudo nginx
    • Check how Nginx works
      curl -IL http://localhost
    • Output should look like this
      HTTP/1.1 200 OK
      Server: nginx/1.12.1
      Date: Sat, 11 Nov 2017 21:29:44 GMT
      Content-Type: text/html
      Content-Length: 138
      Last-Modified: Sat, 11 Nov 2017 19:49:46 GMT
      Connection: keep-alive
      ETag: "5a07545a-8a"
      Accept-Ranges: bytes
    • Also you can open your browser with http://localhost. You should see neext

    Nginx installed. Next  post will be about Nginx and PHP configurations

  • Mac OS X hotkeys you must know

    Mac OS X hotkeys you must know

    Operations which will be described can be done normally using mouse or trackpad. But if you want to make your working process really fast and productive then you in the right place.

    I’ll tell you about the most common shortcuts which you probably already know.

    Hope this page will help people who don’t know them to bring their work experience into new level.

    Command + CCopy the selected item to the Clipboard
    Command + VPaste the contents of the Clipboard into the current document or app
    Command + XCut the selected item and copy it to the Clipboard.
    Command + ZUndo the previous command.
    Command + ASelect All items.
    Command–Space barSpotlight: Show or hide the Spotlight search field.
    Command-TabSwitch apps: Switch to the next most recently used app among your open apps.
    Shift-Command-3Screenshot: Take a screenshot of the entire screen.
    Shift-Command-4Screenshot: Take a screenshot of the selected region.
    Option-Command-EscForce Quit: Choose an app to force quit.
  • Detect sim card availability in the Android dual sim device

    Detect sim card availability in the Android dual sim device

    Below you can find code which help you find if SIM card available in the device.
    There two solutions. One for Android API less than 22 and for Android API greater than or equal to 22.

    Problem that dualsim support added in API-22. And we should deal with devices which support dual sim and has API less than 22.

    So solution for API less than 22.

    public boolean isSimAvailable(Context context){
        TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        if (telephonyManager.getSimSerialNumber() != null){
            return true;
        }
        return false;
    }

    You can ask why I’m not checking for phone number. I do this because the phone number is not 100% available. Sim card serial number always available.

    Second solution for API greater than or equal to 22

    public boolean isSimAvailable(Context context){
        SubscriptionManager sManager = (SubscriptionManager) context.getSystemService(Context.TELEPHONY_SUBSCRIPTION_SERVICE);
        SubscriptionInfo infoSim1 = sManager.getActiveSubscriptionInfoForSimSlotIndex(0);
        SubscriptionInfo infoSim2 = sManager.getActiveSubscriptionInfoForSimSlotIndex(1);
        if(infoSim1 != null || infoSim2 != null) {
             return true;
        }
        return false;
    }

    And here is universal solution:

    public boolean isSimAvailable(Context context){
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
            SubscriptionManager sManager = (SubscriptionManager) context.getSystemService(Context.TELEPHONY_SUBSCRIPTION_SERVICE);
            SubscriptionInfo infoSim1 = sManager.getActiveSubscriptionInfoForSimSlotIndex(0);
            SubscriptionInfo infoSim2 = sManager.getActiveSubscriptionInfoForSimSlotIndex(1);
            if(infoSim1 != null || infoSim2 != null) {
                 return true;
            }
        }else{
            TelephonyManager telephonyManager = (TelephonyManager) App.getInstance().getSystemService(Context.TELEPHONY_SERVICE);
            if (telephonyManager.getSimSerialNumber() != null){
                return true;
            }
        }
        return false;
    }

    Let me know your solution in comments.

  • Letsencrypt automatic certificate renew

    Letsencrypt automatic certificate renew

    To make automatic renew you Letsencrypt certificates you need create crontab job.

    Here is simple instructions

    1. Create /root/certrenew.sh file with content:

    #!/bin/bash
    PATH=/usr/sbin:/usr/bin:/sbin:/bin
    sudo service nginx stop
    /home/igor/letsencrypt/letsencrypt-auto renew
    service nginx start
    exit 0

    2. Make it executable `chmod +x /root/certrenew.sh`
    3. `sudo crontab -e`
    4. Add crontab job. Job for running every day at 3:15AM will be next:

    15 3 * * * /root/certrenew.sh >> /var/log/le-renew.log

    /var/log/le-renew.log – log file

    Let me know better approach in comments.

  • How to automatically restart MySQL service

    How to automatically restart MySQL service

    Here is instruction how to launch MySQL server after close unexpectedly.

    1. Create /root/mysqlfix.sh file with next content:

    #!/bin/bash
    PATH=/usr/sbin:/usr/bin:/sbin:/bin
    if [[ ! "$(/usr/sbin/service mysql status)" =~ "active (running)" ]]
    then
        echo $(date -u) "MySQL service on the server has been stopped. It has now been restarted."
        sudo service mysql start
    fi

    2. Make it executable `chmod +x /root/mysqlfix.sh`
    3. `sudo crontab -e`
    4. Add crontab job. For 3 min period job will be next:

    */3 * * * * /root/mysqlfix.sh >> /var/log/mysqlfix.log 2>&1

    /var/log/mysqlfix.log – log file

    Let me know better approach in comments.

  • How to automatically restart Nginx

    How to automatically restart Nginx

    Here is instruction how to launch Nginx server after close unexpectedly.

    1. Create /root/nginxfix.sh file with next content:

    #!/bin/bash
    PATH=/usr/sbin:/usr/bin:/sbin:/bin
    if [[ ! "$(/etc/init.d/nginx status)" =~ "active (running)" ]]
    then
        echo $(date -u) "NGINX server has been stopped. It has now been restarted."
        service nginx start
    fi

    2. Make it executable chmod +x /root/nginxfix.sh
    3. sudo crontab -e
    4. Add crontab job. For 3 min period job will be next:

    */3 * * * * /root/nginxfix.sh >> /var/log/nginxfix.log 2>&1

    /var/log/nginxfix.log – log file

    Let me know better approach in comments.

  • How to fix Attempting to renew cert from /etc/letsencrypt/renewal/example.com.conf produced an unexpected error: Problem binding to port 443: Could not bind to IPv4 or IPv6.. Skipping.

    How to fix Attempting to renew cert from /etc/letsencrypt/renewal/example.com.conf produced an unexpected error: Problem binding to port 443: Could not bind to IPv4 or IPv6.. Skipping.

    Issue:

    Attempting to renew cert from /etc/letsencrypt/renewal/example.com.conf produced an unexpected error: Problem binding to port 443: Could not bind to IPv4 or IPv6.. Skipping.

    How to fix:

    Just stop webserver before renew letsencrypt.

    sudo service nginx stop
    cd letsencrypt
    sudo ./letsencrypt-auto renew
    sudo service nginx start
  • How to get size of the app data in Android

    How to get size of the app data in Android

    Here is few lines how to get size of directory in Android.
    To get size of directory you need sum sizes of all files in this directory and subdirectories.

    So, we need recursion.

    long sizeOfCacheDir = getCacheDirSize(getCacheDir());
    textViewSize.setText("Cache dir size = " + sizeOfCacheDir + " bytes");

    Where :

    private long getCacheDirSize(File file) {
        long size = 0;
        for (File f : file.listFiles()) {
            if (f.listFiles() == null) {
                size = size + f.length();
            } else {
                size = size + getCacheDirSize(f);
            }
        }
        return size;
    }

    Short sample project here on my github:

    Download it from github