21 Nov 2013

Java Reflection

1.How to know the method which is calling this method?


Reflection.getCallerClass(realFramesToSkip) //here realFramesToSkip is how many level you want to go up, for immediate caller you should use 1, if you want a method 1 level up then 2 etc.


2. How to get the parameters of a method in class?


public class Employee{

   private String strFirstName, strLastName;
   
   public void setStrFirstName(String strFirstName){
               this.strFirstName = strFirstName;
   }

    public String getStrFirstName(){
               return strFirstName;
   }
}

public class Demo{
    public static void main(String[] args){
         Class classEmp = Employee.class;
         Method methodSetstrFirstName =                                                           classEmp.getMethod("setStrFirstName");
         Parameter[]  params = method.getParameters();
        for(int m=0; m<params.length;m++)
 {
Parameter param = params[m];
String paramName = param.getName();
String paramType = param.getType().getSimpleName();
            System.out.println("Name:"+paramName+" Type:"+paramType);
         }

}

Output:

Name:setStrFirstName Type:String

Note: getParameters method on class Method is available only from java8, refer the docs here.

28 Oct 2013

How to Optimize your SQL Query?

How to Optimize your SQL Query?

  • Avoid "order by" or "distinct" in Query.
  • Join only on Primary keys or Unique keys of the table, join on all the primary keys or unique keys if the table has multiple primary keys or unique keys.
  • Don't use UDF in the select list or on the where clause because this udf will be executed on each row of the result set which could be costly. 
  • Avoid sub queries in the query, sub queries will hinder the performance as they may miss the indexes the underlying table is having which will make the engine take more time to identify the rows.
  • Try to move where conditions to inner joins if possible, because the where conditions will be applied on the joined set, instead if you add conditions to the joins then the joining subsets will reduce.
  • Use joins instead of  in/ not in clause.
  • TODO:How to join table data?Explain with an example

Disable Foreign key check in mysql

Disable Foreign key check in mysql:

SET foreign_key_checks = 1 

//usually this is added at the beginning of the   dump file for disabling the foreign key checks while restoring the dump.

11 Aug 2013

Apache compression.

Compressing web pages on Apache server

Compress the web pages on Apache server, so the size of the files the client(browser) receives will be reduced (by almost 5 folds).

Follow the configuration to compress the file on apache server.

In the httpd/conf.d/vhosts.conf file in linux add the following lines

# DEFLATE by type - html, text, css, xml
AddOutputFilterByType DEFLATE text/html text/plain text/css text/xml
 

# DEFLATE by type - javascript 
AddOutputFilterByType DEFLATE application/x-javascript application/javascript text/javascript text/x-js text/x-javascript
 

# DEFLATE by extension
AddOutputFilter DEFLATE js css htm html xml

The above lines compresses the file types specified in the #ed lines only(js, css, html, htm, xml and its associated mime types).

This compresses only js, css, html, htm, xml files and its associated mime types. All others will be sent uncompressed.

This compresses for all browsers.

follow this for documentation http://httpd.apache.org/docs/2.2/mod/mod_deflate.html.


2 Aug 2013

Database Order by

DB related:


Order by:


1.The arguments for order by may not have to be in the select list can be in the sub queries of the select list.

2.Order by A,B,C : ordering of B will be done after ordering of A if the order of A is not disturbed, similarly to ordering of C also.

EX:In the below arrangement,

ABC
12000-1004000
-150002006000
15250-3005000

if I say "Order by A desc, B asc , c desc" in the query then the output will be
A               B               C
15200    -300        5000
12000    -100        4000
-15000    200        6000

if you see B column is not ordering in asc because if it orders in ascending then order of A will be disturbed, similarly for C also.

20 Mar 2013

Linux Commands.

Linux Commands can do lot more which are almost never possible in for a programming to do in windows I think!!!.

One thing about linux, never do anythink without really knowing what you are doing.Linux Will allow you to do anything if you are a root user.

These are the commands I recently explored on linux(02-02-2013)

1.fdisk - details about disks on the system.

2.fsck - Check file systems on the system.

3.ntfsundelete - to restore the deleted files.

4.scalpel -   Recover files or data fragments from a disk image.

5.export - to add  environment variable to linux.Ex:to add path /home/user/pathwherejars to your class path.
   export CLASSPATH=$CLASSPATH:"/home/user/pathwherejars"

6.env - to see all the environment variable to linux.

7.To find all the users on linux
    cat /etc/password | cut -d ":" -f1

8.To find userid for a specific username
    id -u "username"

9.To search for a string in the whole directory files.
    grep -R "StringToBeSearched" filepath

    -n - print the line number of the match
    -i - ignore case

10.To know the shell for linux

    ps -p $$ // last column gives me my shell

11.To Know machine architecture if it is 32 bit or 64

   #getconf LONG_BIT

12.To check the user (root) owned files.
 
   # find . -user root

13.Find -size +1000M
 
   # find -size +1000M
 
14.Check for words from English dictionary look command

   # look floor

15.web page over HTTP for the directory structure tree and can be accessed at port 8000 (http:ipaddress:8000)

   python -m SimpleHTTPServer

16. java -cp /data/Mine/Scripts/jars/mysql-connector-java-5.1.18-bin.jar:.

  Note the :. in the end of the cp path, to include the current directory.

17. netstat - command to know the network connections, ports, routing tables... on linux system.use "man netstat" on you linux system to know more.

18. Set date in linux system using the following command

     date -s "29 JUN 2014 23:55:00"

19.  sudo update-java-alternatives -s java-1.7.0-openjdk-amd64

     Update the java in your system with any version available in your system.

20. To find the OS distribution

     cat /etc/*release
221.

18 Mar 2013

Threading in Java

Well before going to threading in java, let us see what is a Thread.

Thread:Thread is a small process which will have same features as process but switching threads is simple and easy to the processor than switching processes,because process will have big tables associated with them for maintaining there states and lot more info needs to be save while switching and taking back the process but threads want to maintain such tables.

How do we create threads in Java?

Threads can be created in two ways in Java

1.Implement a Runnable Interface.
2.Extend Thread Class .

Implementing Runnable Interface appears to be more useful because as we know we can extend only one class in Java so if we extend Thread Class then we cannot extend any other Class so.

Knowing both exists is a good thing so let us learn both.

Example of creating a Thread through implementing Runnable interface.

      class Student implements Runnable
     {
         @Override
          public void run()
         {


             for( int i = 0 ; i < 10 ; i++ )
             {
                   System.out.println("Implementing Runnable interface");     
             }            
          }   
    
}


Runnable is a interface with only one method run() so we need to define that method in the implementing class (here Student).

Creating a Thread from the Threaded class(here Student).

      Student objStudent = new Student();//create an object of Class Student

      Thread threadStudent = new Thread(objStudent);//Pass object to Thread                                                                                          //constructor to make it a thread

How to start a Thread:

     threadStudent.start();

This will spawn a thread which will start executing method run() of Student class
asynchronously(term used to specify that the process wont happen in sequence but will happen parallely), that is now the statements in run() method will be executed parallely to statements following threadStudent.start().

Grouping threads


    We can Group threads while creating them, which will help us identify the threads by there groups.

     Create a thread group to which threads are added.

          ThreadGroup objStudGrp = new ThreadGroup("UGGroup");

     Create a thread with objStudGrp as thread group.

          Thread threadStudent = new Thread(objStudGrp,objStudent);

     
    We can find the count of Threads running in the current JVM  doing the following:

         Thread.activeCount();

    The above statement gives all the Threads running in the current JVM, but to differentiate  threads we created we can use the Thread Groups to find the count,

      objStudGrp.activeCount();

    We can make a thread wait, Say For Example:We created a two threads,

     Thread thread1 = new Thread(objStudGrp,new Student());

     Thread thread2 = new Thread(objStudGrp,new Student());
    
    start both the threads,

     thread1.start();
     thread2.start();

    Above statements starts the threads thread1 and thread2 i.e threads will execute what is there in run() method of class Student.If you want to make thread1 to wait for 10 seconds then you can do it using the following statement

   thread1.wait(10000); //thread1 waits for 10000 milliseconds i.e 10 seconds.

   If you want thread2 to wait till thread1 finishes then 

   thread1.start();//start both the threads
   thread2.start();

  
   synchronized( thread2 )
   {
         thread2.wait(); //make thread thread2 wait
   }

   // check if the thread thread1 is alive(still running)
   while( thread1.isAlive() )//returns true if the thread is started and not yet died.
   {
         Thread.sleep(1000);//let the current thread sleep for 1000 milliseconds before
                                       //checking again
   }

   
   //when the above  looping comes out then it implies thread1 is not alive anymore.
   //notify the thread2 to restart the execute
 
   thread2.notify();