6 Nov 2014

How to get the method name of the current method that is running in JAVA?

The following code helps you to identify what is the method that is being executed in JAVA at runtime:


StackTraceElement[] ste = Thread.currentThread().getStackTrace();
String strMethodName = ste[1].getMethodName(); // Get this method name

If you specify 2 in place of 1 in the second statement, it will give you the method that has called this method and so on in the stack.

10 Jul 2014

Pass by reference in JAVA methods

This post will deal with how the objects passed to a JAVA method will be accessed inside the method and what the method can actual do with the arguments and what it cannot do.

    Consider the following example:

/*
    This is a plane Java object we will be using to express how this object is referenced and how the        String inside this class will be accessed
*/

class Obj
{
    String strVal;

    public Obj()
    {
      
    }
  
    public Obj(String str)
    {
        this.strVal = str;
    }
  
    public String getStrVal()
    {
        return strVal;
    }

    public void setStrVal(String strVal)
    {
        this.strVal = strVal;
    }
  
}

/*
    This is the main class where we will be playing with Objects of Obj class to learn how Java considers the pass arguments. This class mainly tries to exchange the objects, inturn the strings the objects holder to swap the contents.
*/
public class PassByRef
{
   /*
      This method tries to swap the objects that are being passed as arguments to this method.
   */
    public void exchange(Obj objA1, Obj objB1)
    {
        Obj objTemp = new Obj();
        objTemp = objA1;
        objA1 = objB1;
        objB1 = objTemp;       




   













    }
    
  /*
     This method tries to swap the String in the passed arguments to this method.
  */
    public void exchangeString(Obj objA2, Obj objB2)
    {
        String strTemp = objA2.getStrVal();
        objA2.setStrVal(objB2.getStrVal());
        objB2.setStrVal(strTemp);




   













    }
  
    public static void main(String[] args)
    {
        Obj objA = new Obj("FirstString");
        Obj objB = new Obj("SecondString");




       














       PassByRef pbr = new PassByRef();
        pbr.exchange(objA, objB);



      













        
        System.out.println("String in objA="+objA.getStrVal()+" String in objB="+objB.getStrVal());
        pbr.exchangeString(objA, objB);
        System.out.println("String in objA="+objA.getStrVal()+" String in objB="+objB.getStrVal());
    }
}
   The output of the above program being as follows:

 String in objA=FirstString String in objB=SecondString
 String in objA=SecondString String in objB=FirstString


 In the above main method after initializing the objA and objB with String "FirstString" and "SecondString" respectively, we pass these objects into method exchange of class
PassByRef, here the method tries to change the object references that are passed to this method, but this will not be taken back to the calling method. So the new reference is not reflected in the method main.
Where as in the method exchangeString, the String contents of the object that is passed by main  is changed and the main method is referencing the same object, so the changed contents can be got from main.



12 Feb 2014

Beat the Afternoon Slump at work!!!

Beat the Afternoon Slump at work!!!

I always feel as sleepy as I try not to in the afternoons, well browsed and found something useful.

1. Head outside and sit in the daylight for 10 minutes. Better still, have your lunch outside and divide your break between eating and a walk. It will help reset your chronological clock, keep down the amount of melatonin (the sleep hormone) your body produces during this circadian dip and give you a valuable boost of beneficial vitamin D, reducing your risk of osteoporosis as well as various cancers.

2. Choose activating protein not energy-sapping carbs. Eggs, poultry, Fruits, beans,Avocados(Butter fruit), cauliflower, Dates, Broccoli, Spinach, Sweet corn, coconut, bananas,Soy  milk,Apples.
3. Make an “I was thinking of you” phone call. To your wife, child, siblings, parents, a friend or a retired colleague. A 5 minute keep-in-touch call will lift your spirits for hours and reinvigorate you to get your work done.
4. Clean your desk and clear out your email inbox. Plan some dumb work that doesnot need more of your concentration and involvement in this span of time.
5. Consider a morsel of dark chocolate. This is not a license to overindulge, but dark chocolate does have some unique advantages.

6. Keep a rosemary plant in your office. Not only will sharing your space with a live, growing thing provide its own mood boost, but studies find the scent of rosemary to be energizing. Whenever you need a boost, just rub a sprig between your fingers to release the fragrance into the air. Or, if you’re really wiped out, rub a sprig on your hands, face and neck.

7. Have an afternoon snack designed to get the blood flowing.


16 Jan 2014

Create a jar from folder and how to run the jar in the console on LINUX

1. Create a JAR from folder

 jar -cf NameYouNeed.jar ./FolderYouWantToCreateJAR

c - Create a new Archive
f - file name of the archive is specified here

2. The above command creates a NameYouNeed.jar with MANIFEST.MF file which will have details like java version, entry point(main class name) etc.

3. The above MANIFEST.MF will not have the entry point(main class), to add an entry point you should use

jar -cfe NameYouNeed.jar ./FolderYouWantToCreateJAR Main.class

e - entry point

4. JAVA can run this jar file as below

java -jar Main.jar

5. When using a package you need to specify the path, can you either . or /

jar -cfe Main.jar foo/Main foo

Here foo/Main is for Manifest main class, second foo is for path where the files to be taken for jarring.

If you want to use any library jars then you should specify the parameter "Class-Path" because the usage of -jar option with java will ignore the default classpath, even if you use -cp option the jar in -cp is ignored.For manipulating the "Class-Path" in the manifest file we will use "-m" where we need to use a temporary file from which the jar will take parameters to overwrite the default Manifest file it generates, We'll see below how to do it.


Create a file myManifest.MF with the following content




Main.jar being your jar location.

We can also add "Main-Class" into myManifest.MF which goes into Manifest file  the jar created.







The following command

jar -cmf myManifest.MF Main.jar Main.class 




will create the Manifest file appropriately with proper classpath so the library will be located by java while executing.







8 Jan 2014

Dtrx

What is Dtrx?

Dtrx stands for “Do The Right Extraction“, it’s an open source and very effective command-line application for *nix systems that simplify your job of archive extraction easier.
The dtrx command is an replacement of “tar -zxvf” or “tar -xjf” commands and it provides a one single command to extract archives in a number of different formats including tar, zip, rpm, deb, gem, 7z, cpio, rar and many more. It can also used to decompress files compressed with bzip2, gzip etc.
By default, dtrx extract contents to a dedicated directory and also fixes permission issues (like permission denied) faced by user while extracting content to ensure that the owner can read and write all those files.

Dtrx Features

  1. Handles many archive types: It provides only one simple command to extract tar, zip, rar, gz, bz2, xz, rpm, deb, gem, self-extracting zip files and many other formats of exe files.
  2. Keeps everything organized: It will extract archives into their own dedicated directories.
  3. Sane permissions: It also make sure, user can read and write all those files after extraction, keeping permission intact.
  4. Recursive extraction: It can find archives inside the archive and extract those too.

How to Install Dtrx in Linux

The dtrx tool is by default included in Ubuntu repositories, all you’ve to do is simple do a apt-get to install in on your system.

On Debian/Ubuntu/Linux Mint

$ sudo apt-get install dtrx

On RHEL/CentOS/Fedora

On Red Hat based systems, dtrx is not available via default repositories, you need to download a dtrx script and install the program system-wide using below commands as root user.
# wget http://brettcsmith.org/2007/dtrx/dtrx-7.1.tar.gz
# tar -xvf dtrx-7.1.tar.gz 
# cd dtrx-7.1
# python setup.py install --prefix=/usr/local
Sample Output
running install
running build
running build_scripts
creating build
creating build/scripts-2.6
copying and adjusting scripts/dtrx -> build/scripts-2.6
changing mode of build/scripts-2.6/dtrx from 644 to 755
running install_scripts
copying build/scripts-2.6/dtrx -> /usr/local/bin
changing mode of /usr/local/bin/dtrx to 755
running install_egg_info
Creating /usr/local/lib/python2.6/site-packages/
Writing /usr/local/lib/python2.6/site-packages/dtrx-7.1-py2.6.egg-info

How to Use dtrx Command

The dtrx command is sort of like the one ring to rule them all in the Lord of The Rings. Instead of having to remember syntax for each archive, all you have to remember is dtrx command.

1. Extracting Single Archive

For example, I want to extract a archive file called “tecmint27-12-2013.gz“, I only execute dtrx command without using any flags.
[root@tecmint]# dtrx tecmint27-12-2013.gz
Other than simplifying the extraction, it has a bunch of other options like extracting the file to a folder and recursively extracting all other archives inside a given archive.

2. Extracting Multiple Archives

Consider you’ve a file “dtrAll.zip“, consisting of dtr1.zip, dtr2.zip and dtr3.zip each consisting of dtr1,dtr2 and dtr3 respectively. Instead of having to manually first extract the dtrAll zip and then extracting each one of the dtr1, dtr2 and dtr3 you can directly extract it in respective folders by using dtrx and by selecting option “a“, it extracts all the zip files recursively.
[root@tecmint]# dtrx dtrAll.zip
Sample Output
dtrx: WARNING: extracting /root/dtrAll.zip to dtrAll.1
dtrAll.zip contains 3 other archive file(s), out of 3 file(s) total.
You can:
 * _A_lways extract included archives during this session
 * extract included archives this _O_nce
 * choose _N_ot to extract included archives this once
 * ne_V_er extract included archives during this session
 * _L_ist included archives
What do you want to do?  (a/o/N/v/l) a
After, extraction, the contents of the extracted directory can be verified using ls command.
[root@tecmint]# cd dtrAll
[root@tecmint]# ls 
 
dtr1  dtr1.zip  dtr2  dtr2.zip  dtr3  dtr3.zip

3. Extracting Specific Archive

Let’s say you want to extract the first archive and not archives inside it. By selecting N, it only extracts the given archive and not other archives inside it.
[root@tecmint]# dtrx dtrAll.zip
Sample Output
dtrx: WARNING: extracting /root/dtrAll.zip to dtrAll.1
dtrAll.zip contains 3 other archive file(s), out of 3 file(s) total.
You can:
 * _A_lways extract included archives during this session
 * extract included archives this _O_nce
 * choose _N_ot to extract included archives this once
 * ne_V_er extract included archives during this session
 * _L_ist included archives
What do you want to do?  (a/o/N/v/l) N
The contents of extracted directory can be verified using ls command as shown.
[root@tecmint]# cd dtrAll
[root@tecmint]# ls
 
dtr1.zip dtr2.zip dtr3.zip

4. Extract Each Layer of Archive

To extract each layer of archive inside archive on a case by case basis i.e., if you want to extract 2nd layer of archives but not the 3rd layer, you can use the “o” option.
Consider you’ve a zip file “dtrNewAll.zip“, which has “dtrAll.zip” and “dtrNew” as it’s contents. Now if you want to extract the contents of “dtrNewAll” and “dtrAll” as well but not of dtr1.zip, dtr2.zip and dtr3.zip, you can use “o” and “n” options as shown below.
# dtrx dtrNewAll.zip
Sample Output
dtrNewAll.zip contains 1 other archive file(s), out of 2 file(s) total.
You can:
 * _A_lways extract included archives during this session
 * extract included archives this _O_nce
 * choose _N_ot to extract included archives this once
 * ne_V_er extract included archives during this session
 * _L_ist included archives
What do you want to do?  (a/o/N/v/l) o
dtrAll.zip contains 3 other archive file(s), out of 3 file(s) total.
You can:
 * _A_lways extract included archives during this session
 * extract included archives this _O_nce
 * choose _N_ot to extract included archives this once
 * ne_V_er extract included archives during this session
 * _L_ist included archives
What do you want to do?  (a/o/N/v/l) n
The contents of extracted directory can be verified using ls command as shown.
[root@tecmint]# cd dtrNewAll
[root@tecmint]# ls
 
dtrAll  dtrAll.zip  dtrNew
[root@tecmint]# cd dtrAll
[root@tecmint]# ls
 
dtr1.zip dtr2.zip dtr3.zip
We first select the “o” option which means that all archives inside dtrNewAll will be extracted. Later we select the “n” option for dtrAll.zip which means that the archives inside it dtr1.zip , dtr2.zip and dtr3.zip will not be extracted.

5. Extract meta-data from .deb, .rpm and .gem files

The “-m” option extract the meta-data from .deb, .rpm and .gem archives, instead of their normal contents. Here is an example of the command.
[root@tecmint]# dtrx -m openfire_3.8.2_all.deb 
[root@tecmint]# dtrx -m openfire-3.8.2-1.i386.rpm
[root@tecmint]# ls
 
conffiles  control  md5sums  postinst  postrm  prerm
There are lot more dtrx options to explore, just run the “dtrx –help” to list the available options.
[root@tecmint]# dtrx  --help
 
Usage: dtrx [options] archive [archive2 ...]
 
Intelligent archive extractor
 
Options:
  --version                    show program's version number and exit
  -h, --help                   show this help message and exit
  -l, -t, --list, --table             list contents of archives on standard output
  -m, --metadata               extract metadata from a .deb/.gem
  -r, --recursive              extract archives contained in the ones listed
  -n, --noninteractive         don't ask how to handle special cases
  -o, --overwrite              overwrite any existing target output
  -f, --flat, --no-directory    extract everything to the current directory
  -v, --verbose                be verbose/print debugging information
  -q, --quiet                  suppress warning/error messages