Monday, July 28, 2014

Install Android studio in Linux

1. Download Android studio https://developer.android.com/sdk/installing/studio.html
2. Unpack and go to {studio}/bin
3. Run ./studio.sh to start Android studio

Thursday, July 24, 2014

Compare date strings in Java

To compare date strings:
package com.blogspot.javainpassion;

import org.joda.time.format.DateTimeFormatter;
import org.joda.time.format.ISODateTimeFormat;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateApp {
    public static void main(String[] args) {
        try {

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date date1 = sdf.parse("2014-07-20");
            Date date2 = sdf.parse("2014-04-25");

            System.out.println(sdf.format(date1));
            System.out.println(sdf.format(date2));

            if (date1.after(date2)) {
                System.out.println("Date1 is after Date2");
            }

            if (date1.before(date2)) {
                System.out.println("Date1 is before Date2");
            }

            if (date1.equals(date2)) {
                System.out.println("Date1 is equal to Date2");
            }

            // Joda-time library
            DateTimeFormatter dtf = ISODateTimeFormat.dateTimeNoMillis();
            Long dateMillis1 = dtf.parseMillis("2014-07-20T00:00:00+02:00");
            Long dateMillis2 = dtf.parseMillis("2014-07-25T00:00:00+02:00");
            if (dateMillis1 < dateMillis2) {
                System.out.println("dateMillis1 is before dateMillis2");
            }

            if (dateMillis1 > dateMillis2) {
                System.out.println("dateMillis1 is after dateMillis2");
            }

            if (dateMillis1 == dateMillis2) {
                System.out.println("dateMillis1 is equal dateMillis2");
            }

        } catch (ParseException ex) {
            ex.printStackTrace();
        }
    }
}

Wednesday, July 23, 2014

Convert Collection to List in Java

Collection to List
List list = new ArrayList(yourCollection);

Sorting java collection

Java uses the Merge sorting algorithm to sort collection. We can sort java collections using the java.util.Collections.sort() method. This method applies for List'collection type:
- List
- LinkedList

Natural Sorting:
List list = new ArrayList();
//add elements to the list
Collections.sort(list);


Sorting uses a Comparator
List<CustomObject> list = new ArrayList<CustomObject>();
Comparator<CustomObject> comparator = new Comparator<CustomObject>() {
    public int compare(CustomObject c1, CustomObject c2) {
        return c2.getYourField() - c1.getYourField(); // use your logic    }
};

Collections.sort(list, comparator);

Tuesday, July 15, 2014

The useful memory commands in Linux


  • top
Monitor processes
kiennguyen@kiennguyen-OptiPlex-790:~$ top

top - 13:21:33 up 2 days,  4:23, 14 users,  load average: 0.09, 0.20, 0.20

Tasks: 278 total,   1 running, 277 sleeping,   0 stopped,   0 zombie

%Cpu(s):  1.9 us,  0.7 sy,  0.0 ni, 96.1 id,  1.3 wa,  0.0 hi,  0.0 si,  0.0 st

KiB Mem:   8054712 total,  7755744 used,   298968 free,    31392 buffers

KiB Swap:  4070396 total,   805808 used,  3264588 free,  1204956 cached

 
  PID USER      PR  NI  VIRT  RES  SHR S  %CPU %MEM    TIME+  COMMAND                                                                                                                                        

 2920 kiennguy  20   0  693m  88m  19m S   2.3  1.1  77:41.36 skype                                                                                                                                          

 3344 kiennguy  20   0 1339m 471m  21m S   2.0  6.0  40:55.79 firefox                                                                                                                                        

13202 kiennguy  20   0 3618m 1.0g  18m S   1.3 12.8  16:32.04 java                                                                                                                                           

19523 kiennguy  20   0 1041m 104m  25m S   1.3  1.3   0:26.08 chrome                                                                                                                                         

 3580 kiennguy  20   0  579m  23m 7936 S   0.7  0.3   1:58.67 gnome-terminal                                                                                                                                 

15301 kiennguy  20   0  800m  21m 7908 S   0.7  0.3   1:07.96 chromium-browse                                                                                                                                

16530 kiennguy  20   0 1001m 149m  45m S   0.7  1.9  10:47.10 chrome                                                                                                                                         

17010 kiennguy  20   0 2030m 320m 4936 S   0.7  4.1   2:15.19 java                                                                                                                                           

 1736 root      20   0  106m  952  568 S   0.3  0.0   4:37.82 ruby                                                                                                                                           

 2103 root      20   0 50056 3964  900 S   0.3  0.0   4:23.66 ruby1.8                                                                                                                                        

10324 kiennguy  20   0 3932m 1.1g 3736 S   0.3 14.1  25:23.91 java                                                                                                                                           

20346 kiennguy  20   0 1017m  95m  25m S   0.3  1.2   0:16.64 chrome
  • vmstat
Virtual memory statistics
kiennguyen@kiennguyen-OptiPlex-790:~$ vmstat
procs -----------memory---------- ---swap-- -----io---- -system-- ----cpu----
 r  b   swpd   free   buff  cache   si   so    bi    bo   in   cs us sy id wa
 1  0 847924 240864  20220 1116116    1    2    17    34   46   53  3  1 95  1
  • ulimit
Control the resources and processes available
kiennguyen@kiennguyen-OptiPlex-790:~$ ulimit -a
core file size          (blocks, -c) 0
data seg size           (kbytes, -d) unlimited
scheduling priority             (-e) 0
file size               (blocks, -f) unlimited
pending signals                 (-i) 62776
max locked memory       (kbytes, -l) 64
max memory size         (kbytes, -m) unlimited
open files                      (-n) 1024
pipe size            (512 bytes, -p) 8
POSIX message queues     (bytes, -q) 819200
real-time priority              (-r) 0
stack size              (kbytes, -s) 8192
cpu time               (seconds, -t) unlimited
max user processes              (-u) 62776
virtual memory          (kbytes, -v) unlimited
file locks                      (-x) unlimited
  • ps
Display screen shots of current running process
kiennguyen@kiennguyen-OptiPlex-790:~$ ps aux | grep tomcat
1000     10324  0.8 14.0 4027260 1131316 pts/11 Sl+ Jul14  25:28 /opt/devel/tools/jdk1.6.0_34/bin/java -Djava.util.logging.config.file=/opt/devel/tools/apache-tomcat-6.0.35/conf/logging.properties -Xshare:auto -Xms1024M -Xmx1G -XX:MaxPermSize=512M -Dexo.directory.base=/opt/devel -javaagent:/opt/devel/solr/newrelic/newrelic.jar -Dsolr.solr.home=/opt/devel/solr -Dsolr.data.dir=/opt/devel/solr/data -Dsolr.slave.url=http://localhost:8080/solr -Dsolr.master.url=http://localhost:8080/solr -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=1024 -Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager -Djava.endorsed.dirs=/opt/devel/tools/apache-tomcat-6.0.35/endorsed -classpath /opt/devel/tools/apache-tomcat-6.0.35/bin/bootstrap.jar -Dcatalina.base=/opt/devel/tools/apache-tomcat-6.0.35 -Dcatalina.home=/opt/devel/tools/apache-tomcat-6.0.35 -Djava.io.tmpdir=/opt/devel/tools/apache-tomcat-6.0.35/temp org.apache.catalina.startup.Bootstrap start
1000     21485  0.0  0.0  10924   924 pts/25   S+   13:32   0:00 grep tomcat
  • kill
Kill process
kiennguyen@kiennguyen-OptiPlex-790:~$ kill -9 19523
  • iftop
Monitor the network bandwidth

Enable HTTPS in Play Framework

Play framework supported to serve HTTPS. We need to have a certificate

1. Create a self-signed SSL Certificate

Generate a private key:
openssl genrsa -des3 -out server.key 1024
Generating RSA private key, 1024 bit long modulus
.....................++++++
.................................++++++
unable to write 'random state'
e is 65537 (0x10001)
Enter pass phrase for server.key:
Verifying - Enter pass phrase for server.key:

Generate a CSR
openssl req -new -key server.key -out server.csr
Enter pass phrase for server.key:
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [AU]:VN
State or Province Name (full name) [Some-State]:HaNoi
Locality Name (eg, city) []:HaNoi
Organization Name (eg, company) [Internet Widgits Pty Ltd]:Niteco Ltd
Organizational Unit Name (eg, section) []:Software technology
Common Name (e.g. server FQDN or YOUR name) []:niteco.se
Email Address []:nguyenanhkien2a at gmail dot com

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:123456
An optional company name []:

Remove passphase from key
cp server.key server.key.org
openssl rsa -in server.key.org -out server.key

Enter pass phrase for server.key.org:
writing RSA key

Generate a certificate
openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt

Signature ok
subject=/C=VN/ST=HaNoi/L=HaNoi/O=Niteco Ltd/OU=Software technology/CN=niteco.se/emailAddress=nguyenanhkien2a at gmail dot com
Getting Private key

2. Add the certificate in your configuration

Add the configuration below into file {APP}/conf/application.conf
https.port=9443
certificate.key.file=conf/server.key
certificate.file=conf/server.crt
certificate.password=Asdfg@123456
trustmanager.algorithm=JKS

Note: We must locate the server.crt and server.key in the application conf folder. Play framework cannot read from outsite folder

3. Restart your play application

Basic git commands

  • git init
To create a new Git repository
git init
git init <directory>
  • git clone
Clone the repository in local machine
git clone <repo>
git clone <repo> <directory>
  • git config
Define author name, email for commits
git config user.name <name>
git config --global user.name <name>
git config --global user.email <email>

Example
git config user.name kien.nguyen
git config --global user.name kien.nguyen
git config --global user.email nguyenanhkien2a@gmail.com
  • git diff
View a change in details (line by line)
git diff <file>
git diff --cache
git diff --base <file>
git diff <source_branch> <target_branch>
  • git status
List files in staged, unstaged, untracked.
git status
  • git reset
Clear all local changes
git reset
git reset <file>
git reset --hard
git reset <commit>
git reset --hard <commit>
  • git add
Add a change to staging area, staging area will be used into commit
git add <file>
git add <directory>
git add .
git add *
  • git commit
Commit your changes in staging area to HEAD in local working repository
git commit -m "your message"

Commit all your changes in staging/unstaging to HEAD in local working reposiroty
git commit -a -m "your message"

Edit the last commit
git commit --amend
  • git log
View committed snapshots
git log
git log -n <number>
git log --oneline
git log --stat
git log <file>
git log -p
git log --author="<pattern>"
git log --grep="<pattern>"
  • git fetch
Fetch latest changes from remote repository
git fetch
git fetch origin
  • git pull
Fetch and update commits from remote repository into local working repository
git pull
  • git push
Push local working branch to remote repository
git push
git push origin <remote_branch>

Example:
git push origin master
  • git branch
List all branches in your local repository
git branch
  • git checkout
    Checkout a branch to working tree
    git checkout <branch>