Monday, 20 January 2014

Linux Command



Linux Commands






Find Command 

## To search for files in /target_directory and all its sub-directories, that have been modified in the last 60 minutes:

    $ find /target_directory -type f -mmin -60

## To search for files in /target_directory and all its sub-directories, that have been modified in the last 2 days:

    $ find /target_directory -type f -mtime -2

## To search for files in /target_directory and all its sub-directories no more than 3 levels deep, that have been modified in the last 2 days:

    $ find /target_directory -type f -mtime -2 -depth -3

## You can also specify the range of update time. To search for files in /target_directory and all its sub-directories, that have been modified in the last 7 days, but not in the last 3 days:

    $ find /target_directory -type f -mtime -7 ! -mtime -3

## To search for files in /target_directory (and all its sub-directories) that have been modified in the last 60 minutes, and print out their file attributes:

    $ find /target_directory -type f -mmin -60 -exec ls -al {} \;
    $ find /target_directory -type f -mmin -60 | xargs ls -l



## Find all files in current directory and subdirectory, greater than some size using find command in Unix:

find . -size +1000c -exec ls -l {} \;

Always use a c after the number, and specify the size in bytes, otherwise you will get confuse because find -size list files based on size of disk block. To find files using a range of file sizes, a minus or plus sign can be specified before the number. The minus sign means "less than," and the plus sign means "greater than." Suppose if you want to find all the files within a range you can use find command as below.

## It return files which size is greater than 50M

find . -size +50000000c -exec ls -lh {} \;

## It return files which extension are .java and end with other character

find . -type f -name "*.java*" -print


Change Shell by Cmd 
   
##First, find out available shell list:

    $ less /etc/shells
   
##Now change your shell name to /bin/tcsh:

    $ chsh -s /bin/tcsh
   
##When promte for password, type your own password. If you just type chsh command, it will prompt for shell name interactively:

    $ chsh

Owner Ship Cmd on File System 

    $chmod u+x <filename>
    $chmod uog+xwr <filename>
           u : User           
           g : Group   
           o : Other
           ---------
           r : Read  : 4
           w : Write : 2
           x : Execute : 1
    $chmod 660 <Filename> // owner group other

    $chmod 751 tech

    $chmod u=rwx, g=rx, o=x tech
   
    <chown> change ownership of file system.


##As the owner, jim can use the chmod command to permit or deny other users access to program.c.

    $chown jim program.c


##To change the owner and group of all files in the directory /tmp/src to owner john and group build:

    $chown -R john:build /tmp/src 

   
Linux Version Info

## see your current Linux kernel version:

    $ uname -r
    $ uname -mrs

## To print all information, enter:

    $ uname -a

## see Linux version info:

    $ cat /proc/version

## Here is another output from my Debian based serve

    $ lsb_release -a
   
 Process Command line Info

## Display a tree of processes

    $ pstree

## Dynamic real-time view of a running system

    $ top

## Display all running process:

    $ ps aux | less

## Print a process tree using ps

    $ ps -ejH
    $ ps axjf

## Get info about threads

    $  ps -eLf

## Get security info

    $ ps -eo euser,ruser,suser,fuser,f,comm,label
    $ ps axZ
    $ ps -eM

## Save Process Snapshot to a file

    $ top -b -n1 > /tmp/process.log
    <<you can email result to yourself>>

    $ top -b -n1 | mail -s 'Process snapshot' you@example.com


Sunday, 5 January 2014

how-to-remove-duplicates-from-array-java-without-collection-API


In this program, we have not used any collection class to remove duplicates, In this example, we are removing duplicates elements from array and copying them into newly result array.


1:  import java.util.Arrays;  
2:  /**  
3:   * @author Ajaykumar.gupta  
4:   *  
5:   */  
6:  public class RemoveDublicateElements {  
7:      /**  
8:       * Suppose let have a arrays of integer elements.  
9:       */  
10:      private static int[] array = { 1, 2, 3, 4, 2, 4, 5, 6, 7, 1, 3, 5, 9, 8, 7,  
11:              6, 7, 8, 9, 0, 8, 6, 5, 0, 5, 4, 3, 2, 5, 6, 0, 1, 2, 3, 4, 5, 6 };  
12:      public static void main(String args[]){  
13:          int[] values = removeDublicate(array);  
14:          for(int i=0; i < values.length ;i++ ){  
15:              System.out.print(values[i]+" ");  
16:          }  
17:      }  
18:      private static int[] removeDublicate(int[] array){  
19:          /**  
20:           * Sort Array elements first.  
21:           */  
22:          Arrays.sort(array);  
23:          // Allocated a new array with same size.  
24:          int []result= new int[array.length];  
25:          // Assigned a first element into a previous variable.  
26:          int previous = result[0];  
27:          // Assigned a smallest elements into Array zero position.  
28:          result[0] = previous;  
29:          int num = 1;  
30:          for(int i=1; i <array.length;i++){  
31:              int ch = array[i];  
32:              // Logic is applied for removed duplicate elements and assigned to result array  
33:              if(previous != ch){  
34:                  result[num++] = ch;  
35:              }  
36:              previous = ch;  
37:          }  
38:          // Removed Blank space(Zero) and copy exect size of array and return it to caller.  
39:          return Arrays.copyOf(result, num);  
40:      }  
41:  }  

Output : 0 1 2 3 4 5 6 7 8 9

Monday, 21 October 2013

String.concat vs +Operator in String Java Class

Introduction

Concatenation of Strings is very easy in Java - all you need is a '+'. It can't get any easier than that, right? Unfortunately there are a few pitfalls. One thing you should remember from your first Java lessons is a small albeit important detail: String objects are immutable. Once constructed they cannot be changed anymore.
Whenever you "change" the value of a String you create a new object and make that variable reference this new object. Appending a String to another existing one is the same kind of deal: a new String containing the stuff from both is created and the old one is dropped.
You might wonder why Strings are immutable in first place. There are two very compelling reasons for it:
  1. Immutable basic types makes things easier. If you pass a String to a function you can be sure that its value won't change.
  2. Security. With mutable Strings one could bypass security checks by changing the value right after the check. (Same thing as the first point, really.)

The performance impact of String.concat()

Each time you append something via '+' (String.concat()) a new String is created, the old stuff is copied, the new stuff is appended, and the oldString is thrown away. The bigger the String gets the longer it takes - there is more to copy and more garbage is produced.
Creating a String with a length of 65536 (character by character) already takes about 22 seconds on an AMD64 X2 4200+. The following diagram illustrates the exponentially growing amount of required time:
String.concat() - exponential growth
Figure 1: StringBuilder vs StringBuffer vs String.concat
StringBuilder and StringBuffer are also shown, but at this scale they are right onto the x-axis. As you can see String.concat() is slow. Amazingly slow in fact. It's so bad that the guys over at FindBugs added a detector for String.concat inside loops to their static code analysis tool.

When to use '+'

Using the '+' operator for concatenation isn't bad per se though. It's very readable and it doesn't necessarily affect performance. Let's take a look at the kind of situations where you should use '+'.
a) Multi-line Strings:
String text=
    "line 1\n"+
    "line 2\n"+
    "line 3";
Since Java doesn't feature a proper multi-line String construct like other languages, this kind of pattern is often used. If you really have to you can embed massive blocks of text this way and there are no downsides at all. The compiler creates a single String out of this mess and no concatenation happens at runtime.
b) Short messages and the like:
System.out.println("x:"+x+" y:"+y);
The compiler transforms this to:
System.out.println((new StringBuilder()).append("x:").append(x).append(" y:").append(y).toString());
Looks pretty silly, doesn't it? Well, it's great that you don't have to write that kind of code yourself. ;)
If you're interested in byte code generation: Accordingly to Arno Unkrig (the amazing dude behind Janino) the optimal strategy is to useString.concat() for 2 or 3 operands, and StringBuilder for 4 or more operands (if available - otherwise StringBuffer). Sun's compiler always usesStringBuilder/StringBuffer though. Well, the difference is pretty negligible.

When to use StringBuilder and StringBuffer

This one is easy to remember: use 'em whenever you assembe a String in a loop. If it's a short piece of example code, a test program, or something completely unimportant you won't necessarily need that though. Just keep in mind that '+' isn't always a good idea.

StringBuilder and StringBuffer compared

StringBuilder is rather new - it was introduced with 1.5. Unlike StringBuffer it isn't synchronized, which makes it a tad faster:
StringBuilder compared with StringBuffer
Figure 2: StringBuilder vs StringBuffer
As you can see the graphs are sort of straight with a few bumps here and there caused by re-allocation. Also StringBuilder is indeed quite a bit faster. Use that one if you can.

Initial capacity

Both - StringBuilder and StringBuffer - allow you to specify the initial capacity in the constructor. Of course this was also a thing I had to experiment with. Creating a 0.5mb String 50 times with different initial capacities:
different initial capacities compared
Figure 3: StringBuilder and StringBuffer with different initial capacities
The step size was 8 and the default capacity is 16. So, the default is the third dot. 16 chars is pretty small and as you can see it's a very sensible default value.
If you take a closer look you can also see that there is some kind of rhythm: the best initial capacities (local optimum) are always a power of two. And the worst results are always just before the next power of two. The perfect results are of course achieved if the required size is used from the very beginning (shown as dashed lines in the diagram) and no resizing happens at all.

Some insight

That "PoT beat" is of course specific to Sun's implementations of StringBuilder and StringBuffer. Other implementations may show a slightly different behavior. However, if these particular implementations are taken as target one can derive two golden rules from these results:
  1. If you set the capacity use a power of two value.
  2. Do not use the String/CharSequence constructors ever. They set the capacity to the length of the given String/CharSequence + 16, which can be virtually anything.

Benchmarking method

In order to get meaningful results I took care of a few things:
  • VM warmup
  • separate runs for each test
  • each sample is the median of 5 runs
  • inner loops were inside of each bench unit

Some of discussion example below :
What does the compiler do here?
String s = "This "
s += "is anoher "
s += "concatenated "
s += "string"
Theoretically a compiler could optimize in such way below :
In practice you'll get either this:
String s = "This ";
s = (new StringBuilder()).append(s).append("is another ").toString();
s = (new StringBuilder()).append(s).append("concatenated ").toString();
s = (new StringBuilder()).append(s).append("string").toString();

Second,Example :
String s = "This ";
s = (new StringBuilder()).append(s).append("is another ").toString();
s = (new StringBuilder()).append(s).append("concatenated ").toString();
s = (new StringBuilder()).append(s).append("string").toString();
or that:
String s = "This ";
s = s.concat("is another ");
s = s.concat("concatenated ");
s = s.concat("string ");
How many String object will be created in below chunk of code : 
String s1 = "Hello"+"world";
String s2 = s1+"Java";
if you look at the compiled code, you can easily guess:
String s1 = "Helloworld";
String s2 = (new StringBuilder(String.valueOf(s1))).append("Java").toString();
Do some step way to determined number of String object are created.
The answer is 3.
You can view the deassembled result by:
javap -verbose YourClass
The Constant pool includes:
...
const #17 = Asciz       Helloworld;
...
const #30 = Asciz       Java;
...
It means two strings ("Helloworld" and "Java") are compile-time constant expression which will be interned into constant pool automatically.
The code:
Code:
 Stack=3, Locals=3, Args_size=1
 0:   ldc     #16; //String Helloworld
 2:   astore_1
 3:   new     #18; //class java/lang/StringBuilder
 6:   dup
 7:   aload_1
 8:   invokestatic    #20; //Method java/lang/String.valueOf:(Ljava/lang/Object;)Ljava/lang/String;
 11:  invokespecial   #26; //Method java/lang/StringBuilder."<init>":(Ljava/lang/String;)V
 14:  ldc     #29; //String Java
 16:  invokevirtual   #31; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
 19:  invokevirtual   #35; //Method java/lang/StringBuilder.toString:()Ljava/lang/String;
 22:  astore_2
 23:  return
It indicates that s2 is created by StringBuilder.append() and toString().
To make this more interesting, javac can optimize the code in constant folding. You can guess the count of strings created by the following code:
final String s1 = "Hello" + "world";
String s2 = s1 + "Java";
"final" means s1 is constant which can help javac to build the value of s2 and intern s2. So the count of string created here is 2.
Reference link:

Tuesday, 27 August 2013

Shallow Copy vs Deep Copy

Shallow Copy 


Shallow copy is a bit-wise copy of an object. So a new object is created that has an exact copy of the values in the original object.If any of the fields of the object are references to other object then only the reference addresses are copied.

One important Point to be Noted from the Person Class:

Person class doesn't implements Clonable interfaces so is it the reason why cloned and original object point to same Persone Object.

Points To be Noted :
  1. Changes to the cloned Person object is getting reflected in the original object as well.
  2. Changes to the direct attribute(field i.e. a) of cloned object is not updated in original object.


class Employee {

 private String name;
 private int id;
 public Employee() {}
 public Employee(int id, String name) {
  this.id = id;
  this.name = name;
 }

 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public int getId() {
  return id;
 }
 public void setId(int id) {
  this.id = id;
 }
 @Override
 public String toString() {
  StringBuilder builder = new StringBuilder();
  builder.append("Employee [name=");
  builder.append(name);
  builder.append(", id=");
  builder.append(id);
  builder.append("]");
  return builder.toString();
 }
 public Object clone() throws CloneNotSupportedException{
  System.out.println(" Clone method of Employee Class doesn't get called ever.");
  return super.clone();
  
 }
}
Now run CloneTest class again and notice the output.Output is still the same. In fact Person class clone() method is not called at all; and hence you will not notice print statement put in its clone method.






package com.clone.example; 

public class ShallowCopyTest {
 
 public static void main(String args[]) throws CloneNotSupportedException{
  
  Employee employee = new Employee(1,"Ajay Kumar");
  Department department = new Department(1001,employee);
  System.out.println(" Department Details"+department);
  System.out.println(" Employee   Details"+department.getEmployee());

  // Shallow Cloning of Employee Object.
  
  Department department_clone_1 = (Department)department.clone();
  System.out.println(" Clone Department Details"+department_clone_1);
  
  // After cloning of Department object , Get Employee Object and made changes in properties.
  Employee employee_clone_1 = department_clone_1.getEmployee();
  employee_clone_1.setName(" Ram Kumar ");
  
  /*
   * Shallow Copy : Employee Clone Objects are point to same reference
   * of Original Employee Object so any changes get reflected to Original
   * Object of Employee. 
   *  
   */
  
  System.out.println("  Real Object  : "+ department);
  System.out.println("  Clone Object : "+ department_clone_1);
 
 }
}  

class Employee {

 private String name;

 private int id;

 public Employee() {}

 public Employee(int id, String name) {
  this.id = id;
  this.name = name;
 }

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 public int getId() {
  return id;
 }

 public void setId(int id) {
  this.id = id;
 }

 @Override
 public String toString() {
  StringBuilder builder = new StringBuilder();
  builder.append("Employee [name=");
  builder.append(name);
  builder.append(", id=");
  builder.append(id);
  builder.append("]");
  return builder.toString();
 }

 

}

class Department implements Cloneable {

 private int department;

 private Employee employee;

 public Department() {}

 public Department(int department, Employee employee) {
  this.department = department;
  this.employee = employee;
 }

 public int getDepartment() {
  return department;
 }

 public void setDepartment(int department) {
  this.department = department;
 }

 public Employee getEmployee() {
  return employee;
 }

 public void setEmployee(Employee employee) {
  this.employee = employee;
 }

 public Object clone() throws CloneNotSupportedException {
  return super.clone();

 }

 @Override
 public String toString() {
  StringBuilder builder = new StringBuilder();
  builder.append("Department [department=");
  builder.append(department);
  builder.append(", employee=");
  builder.append(employee);
  builder.append("]");
  return builder.toString();
 }

}

 
Output is : 

Department DetailsDepartment [department=1001, employee=Employee [name=Ajay Kumar, id=1]]
Employee   DetailsEmployee [name=Ajay Kumar, id=1]

Clone Department DetailsDepartment [department=1001, employee=Employee [name=Ajay Kumar, id=1]]
Real Object  : Department [department=1001, employee=Employee [name= Ram Kumar , id=1]]

Clone Object : Department [department=1001, employee=Employee [name= Ram Kumar , id=1]]


Deep Copy

A Deep Copy, copies all fields, and makes copies of dynamically allocated memory pointed to by fields. So a deep copy occurs when an object is copied along with the objects to which it refers.
So in our case deep copy will have a separate Person copy so that changes in Clone1 doesn't get reflected in Original object.

So now it's easy to understand what is a Deep Copy :



We just need to make sure that clone method creates a new copy of Person object. That's it !
package com.clone.example;

class Employee implements Cloneable {

 private String name;

 private int id;

 public Employee() {

 }

 public Employee(int id, String name) {
  this.id = id;
  this.name = name;
 }

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 public int getId() {
  return id;
 }

 public void setId(int id) {
  this.id = id;
 }

 @Override
 public String toString() {
  StringBuilder builder = new StringBuilder();
  builder.append("Employee [name=");
  builder.append(name);
  builder.append(", id=");
  builder.append(id);
  builder.append("]");
  return builder.toString();
 }

 public Object clone() throws CloneNotSupportedException {
  return super.clone();

 }

}

class Department implements Cloneable {

 private int department;

 private Employee employee;

 public Department() {

 }

 public Department(int department, Employee employee) {

  this.department = department;
  this.employee = employee;

 }

 public int getDepartment() {

  return department;

 }

 public void setDepartment(int department) {
  this.department = department;
 }

 public Employee getEmployee() {
  return employee;
 }

 public void setEmployee(Employee employee) {
  this.employee = employee;
 }

 public Object clone() throws CloneNotSupportedException {
  Department d = (Department) super.clone();
  d.employee = (Employee) employee.clone();
  return d;

 }

 @Override
 public String toString() {
  StringBuilder builder = new StringBuilder();
  builder.append("Department [department=");
  builder.append(department);
  builder.append(", employee=");
  builder.append(employee);
  builder.append("]");
  return builder.toString();
 }
}

public class DeepCopyTest {

 public static void main(String args[]) throws CloneNotSupportedException {

  Employee employee = new Employee(1, "Ajay Kumar");
  Department department = new Department(1001, employee);
  System.out.println(" Department Details" + department);
  System.out.println(" Employee   Details" + department.getEmployee());
  // Shallow Cloning of Employee Object.

  Department department_clone_1 = (Department) department.clone();
  System.out.println(" Clone Department Details" + department_clone_1);

  // After cloning of Department object , Get Employee Object and made
  // changes in properties.
  Employee employee_clone_1 = department_clone_1.getEmployee();
  employee_clone_1.setName(" Ram Kumar ");
  /**
   * Deep Copy : So in our case deep copy will have a separate Person copy
   * so that changes in Clone1 doesn't get reflected in Original object.
   */
  System.out.println("  Real Object  : " + department);
  System.out.println("  Clone Object : " + department_clone_1);

 }

} 

Output :

Department DetailsDepartment [department=1001, employee=Employee [name=Ajay Kumar, id=1]]
Employee   DetailsEmployee [name=Ajay Kumar, id=1]
Clone Department DetailsDepartment [department=1001, employee=Employee [name=Ajay Kumar, id=1]]
Real Object  : Department [department=1001, employee=Employee [name=Ajay Kumar, id=1]]
Clone Object : Department [department=1001, employee=Employee [name= Ram Kumar , id=1]]

Friday, 23 August 2013

How to exclude jars generated by maven war plugin ?

There are various way to exclude jar files generated by Maven pom file.
1. Using <packagingExcludes> tags we can exclude files.
<plugin>
  <groupid>org.apache.maven.plugins</groupid>
  <artifactid>maven-war-plugin</artifactid>
  <configuration>
   <archive>
    <manifest>
     <mainclass>com.project</mainclass>
     <addclasspath>true</addclasspath>
    </manifest>
    <manifestentries>
     <mode>development</mode>
     <url>${project.url}</url>
     <splashscreen-image>Image-Filename.png</splashscreen-image>
    </manifestentries>
   </archive>
    <packagingexcludes>WEB-INF/lib/commons*.jar,WEB-INF/lib/dom4*.jar
   </packagingexcludes>
    <webxml>${basedir}/src/main/webapp/WEB-INF/web.xml</webxml>
    <warname>finalProject</warname>
   <warsourcedirectory>src/main/webapp</warsourcedirectory>
  </configuration>
</plugin>
2. We can excluded jar base on their artifactid or groupid.
<dependency>
 <groupId>org.apache.cxf</groupId>
 <artifactId>cxf-rt-frontend-jaxws</artifactId>
 <version>${cxf.version}</version>

 <exclusions>
  <exclusion>
   <groupId>org.apache.geronimo.specs</groupId>
   <artifactId>geronimo-javamail_1.4_spec</artifactId>
  </exclusion>
 </exclusions>
</dependency>
Hidden Commands of Maven

mvn tree

view the dependency hierarchy of the project currently being built.

mvn dependency:analyze

performs byte code analysis to determine missing or unused dependencies. This goal is meant to be launched from the command line. It will fork the build and execute test-compile so there are class files to analyze. If you want to bind analyze in your pom, use the dependency:analyze-only mojo instead.