Friday, March 21, 2014

How To Use Git Behind Proxy


If you would like to use git behind proxy, you will have to instruct Git to use proxy . Note that setting http_proxy environment variable alone is not sufficient since the variable is ignored by git.

The below mentioned commands would create a user-specific git configuration file (~/.gitconfig) updated with proxy details:

$ export http_proxy=http://myproxy.com:portnumber
$ git config --global http.proxy $http_proxy

or

$ git config --global http.proxy http://myproxy.com:portnumber

You can ofcourse replace myproxy.com with an IP address too.

In case your proxy needs authentication then you will have to supply the authentication details (i.e. your proxy's username/password) to the GIT's configuration file and this can be done as follows:
$ export http_proxy=http://proxyuser:proxypassword@myproxy.com:portnumber
$ git config --global http.proxy $http_proxy

or

$ git config --global http.proxy http://proxyuser:proxypassword@myproxy.com:portnumber

Thursday, December 26, 2013

Immutable Class in Java

An immutable class is a class whose instances cannot be modified. All of the information contained in each instance is provided when it is created and is fixed for the lifetime of the object.

The biggest advantage of immutable objects is that they are inherently thread-safe; and therefore they do not require any synchronization. Therefore, immutable objects can be shared freely. Immutable classes are easier to design, implement, and use in comparison to mutable classes. They are less prone to error and are more secure.

To make a class immutable, follow the following rules:

1. Don’t provide any mutator methods, i.e. the methods that modify the object’s state.

2. Ensure that the class can’t be extended. This prevents careless or malicious
subclasses from compromising the immutable behavior of the class by behaving
as if the object’s state has changed. Preventing subclassing is generally accomplished
by making the class final or having a private constructor with a public static factory method.

3. Make all fields final. It is necessary to ensure correct behavior if a reference
to a newly created instance is passed from one thread to another without
Synchronization.

4. Make all fields private. This prevents clients from obtaining access to mutable
objects referred to by fields and modifying these objects directly.

5. Ensure exclusive access to any mutable components. If the class has any
fields that refer to mutable objects, ensure that clients of the class cannot obtain
references to these objects. Make defensive copies and return them instead.

Lets Take an example:











public final class Planet {



    public Planet (double masss, String namee, Date datee) {

       mass = masss;

       name = namee;

      //Make a defensive copy of the Mutable object Date

       date = new Date(datee.getTime());

    }



    public double getMass() {

      return mass;

    }



    public String getName() {

      return name;

    }



    /**

    * Returns a defensive copy of mutable object

    */

    public Date getDate() {

      return new Date(date.getTime());

    }



    private final double mass;



    private final String name;



    private final Date date;

  }





The above code snippet is an example of an Immutable class. Notice, how we have made defensive copies of the mutable state ‘date’.

The only real disadvantage of immutable classes is that they require a
separate object for each distinct value. Creating these objects can be costly,
especially if they are large.

As discussed in rule 2 above, one alternative of creating an immutable object is to use a public static factory method to return the immutable instances rather than using a constructor. The real advantage that you get out of this approach is the flexibility of creating strategies like, reusing instances or caching instances etc instead of creating a new instance every time. Sometimes, this flexibility also aids performance. Static factory is a preferred way of creating immutable objects.

Tuesday, December 10, 2013

It is a common use case to create an activity which returns a particular state for a specific amount of time and then revert back to its original state. For example you want to suspend a particular user on your website for say, 60 seconds (maybe because he’s submitting a form too fast – a strategy a lot of forms support). There are many such use cases possible especially when that application is using huge amount of cache. One way to do it would be with database which is not only highly in-efficient but way too cumbersome. If we could create a data structure that could retain its state for a specific time and then revert back, it would be killer.

I would present such a Boolean data structure that could be used to validate a condition for a specific time and then it would revert back to its original status.

One of the important design decisions has been to make this data structure immutable. One instance would represent just one state. Also, in this implementation I have used constructors rather than static factory method to return state objects, but nothing stops us from having a static factory method for our state objects.

Lets look at our class now:








public class AutoRevertingBoolean {



  //the present status

  private final boolean present;

  

  //This is the default status and this is what

  // the object would be reverted to. Since this is boolean

  //it can be either true/fase, but why this property

  //is important would be explained in subsequent posts.

  private final boolean revertTo;

  

  //the time till which the present state would

  //be preserved before reverting back

  private final long waitInMillisBeforeReverting;

  

  //time that preserves the invocation time

  //of this data structure

  private long time = 0;



  /**

   * Constructor that creates the state object but the users

   * would need to explicitly start the ticker by invoking

   * the {@link #startMeasuring()} method

   @param present

   @param revertTo

   @param waitInMillisBeforeReverting long time in milliseconds

   */

  public AutoRevertingBoolean(final boolean present, final boolean revertTo,

      final long waitInMillisBeforeReverting) {

    this.present = present;

    this.revertTo = revertTo;

    this.waitInMillisBeforeReverting = waitInMillisBeforeReverting;

  }



  /**

   * Constructor that also starts the ticker as soon as this

   * object is created.

   @param present boolean

   @param revertTo boolean 

   @param waitInMillisBeforeReverting long time in milliseconds

   @param startNow

   */

  public AutoRevertingBoolean(final boolean present, final boolean revertTo,

      final long waitInMillisBeforeReverting, final boolean startNow) {

    this(present, revertTo, waitInMillisBeforeReverting);

    this.startMeasuring();

  }



  /**

   * Returns the present state of the object

   @return boolean Will return the present state if the 

   * specified time has not elapsed or else would return the

   * default state of the object. 

   */

  public boolean get() {

    return System.currentTimeMillis() < time + waitInMillisBeforeReverting ? present

        : revertTo;

  }



  /**

   * starts the timer for this data structure

   */

  public void startMeasuring() {

    if(!(time > ))

      time = System.currentTimeMillis();

  }



  public static void main(String[] args) {



    AutoRevertingBoolean obj = new AutoRevertingBoolean(true, false, 3000);

    //need to explicitly call this for the constructor that we have used.

    obj.startMeasuring();

    foo(obj);

    obj = new AutoRevertingBoolean(true, false, 5000,true);

    //need not explicitly start measuring the time

    foo(obj);

  }



  private static void foo(AutoRevertingBoolean obj) {

    System.out.println("Starting.....");

    long startTime = System.currentTimeMillis();

    for (int i = 0; i < Integer.MAX_VALUE; i++) {

      if (!obj.get())

        break;

    }

    System.out.println("Done in:" (System.currentTimeMillis() - startTime)+" milliseconds.");

  }



}




The code is pretty self-explanatory. The main method gives away its usage pattern. There are several ways to extend this data structure and as we move forward we would try to improve and evolve this data structure.

Monday, November 25, 2013

Marker Interfaces Vs Marker Annotations as Type definers

When it comes to defining types, there's always some debate between using Marker Interfaces vs Marker Annotations. To appreciate the discussion its important to understand what are marker interfaces. Well, a marker interface is merely an interface that contains "no" method declaration and it just designates the implementing class as having some unique characteristic, e.g. the Serializable interface. On the other hand, Marker annotations are just annotations whose sole purpose is also to designate a class/method/variable to have a certain characteristic. So when do you use marker interface and when would you use an annotation to define a type in java?

The key here is to understand the intent of the usage. Let me elaborate on this. We know that only classes and interfaces that implement/extend other interfaces. Clearly you must use an annotation if the marker applies to any
program element other than a class or interface, as only classes and interfaces can
be made to implement or extend an interface. But if we believe that our end requirement of type definition could be such wherein I have to supply an class of a specific type as an argument to method, one should use a Marker interface for defining this type as it would also help in comple-time checking of the client code (remember this could be achieved even with Marker Annotation but since annotation processing does not happen till run-time there is no way to know at compile time of the contract was honoured by the client class). As an extension of this point if we believe that we want to limit the use of this marker interface to elements of a particular interface the it makes sense to define the marker as a subinterface of that interface. Therefore, marker interfaces are targeted more precisely.

But its unfair to assume that Marker annotations do not have their use. Their main advantage is that Annotations are evolutionary and this is precisely a major problem with interfaces. Interfaces cannot evolve over time. Once the contract is published especially the public interfaces, its nearly impossible to change it. On the other hand annotations can evolve into a richer annotation type over time. Annotations should be used as meta-definitions and this usage also helps to create much better code processing tools.

Friday, July 19, 2013

Taking Backup of MySQL Database with stored procedures and functions.

mysqldump is a utility to take a backup of MySQL database. With MySQL 5 new features like stored procedures and triggers were introduced. mysqldump by default backups only the triggers and not the stored procedures or functions. This behaviour can however be controlled by the following two parameters:

1. routines (--routines)
2. triggers (--triggers)

routines option is by default false while triggers option is by default true.

An example to take a backup of your database along with stored procedures, functions and triggers:
    # mysqldump --routines -u 'username' -p'password' > mysqldummpfile.sql

Let’s assume we want to backup only the stored procedures,functions and triggers and not the mysql tables and data , then we should run something like this:

   # mysqldump --routines --no-create-info --no-data --no-create-db --skip-opt -u 'username' -p'password' > mysqldumpwithoutanytablesanddata.sql

This will backup only the procedures triggers and functions of the Database.

For importing this backup procedure remains the same (irrespective of whether the backup was taken with or without routines):

   mysql -u 'username' -p'password' < mysqldumpwithoutanytablesanddata.sql


Wednesday, November 21, 2012

Debugging Shell Scripts in Unix

Debugging is an important part of your overall development process. Unfortunately not many developers know that even shell scripts can be debugged. The good thing is debugging shell scripts is just about knowing a few options of the 'sh' command. Lets see how we can debug the shell scripts.

To see exactly where the script produces an error use the 'sh' command with a 'x' option:

sh -x myscript.sh your-arguments-if-you-hahve

When you run the above command you can see each statement with their output printed in the next line.

For example if i have a script which does addition of two numbers given by the user like:

#!/bin/sh
echo $1
echo $2
echo $(($1 + $2))

The output of 'sh -x myscript.sh 3 4' would be

+ echo 3
3
+ echo 4
4
+ echo 7
7

So, we see the statement and its output in the next line.

Other options are:

-e in non-interactive mode, exit immediately if a command fails.

-v print shell input lines as they are read.

-n read commands but do not execute them.

In the other options 'v' is probably a really good option to explore. If i run my above script with '-v' option then the following output would be seen:

sh -v myscript.sh 3 4

#!/bin/sh
echo $1
3
echo $2
4
echo $(($1 + $2))
7

This is again a good option to explore.


Thursday, September 13, 2012

Recursive Automatic download of FTP files in Unix

With unix there comes numerous built in beautiful utilities. If one understands these utilities fully, he/she can accomplish seemingly difficult tasks in a jiffy.

One such thing that we always try to do it downloading a bunch of files from a FTP site. This becomes even tricky if there are many sub folders.

One such utility is wget.

A command line to recursively download all the files from an FTP location:

wget -r ftp://user:password@myremotehost -o /tmp/log &

'&' will make the process background, and output in /tmp/log file.

Easy money.