Creating Project in Github

Lets say we are creating a project name library and username of the github account is ruby.

Step 1: Create a project in Github named library.

Step 2: Generate ssh key

https://help.github.com/articles/connecting-to-github-with-ssh/

Step 3: Create library project in your local machine and commit using git

git init
git add .
git commit -m 'Initial Commit'
git remote add origin https://github.com/ruby/library.git
# for using ssh
git remote set-url origin git@github.com:ruby/library.git
git push -u origin master

 

 

Advertisements

Loading Gradle Libraries in Intellij Idea

Add following line in build.gradle

apply plugin: "idea"

Run following command in applications’ root directory

gradle idea --refresh-dependencies

It may take some time to download all the libraries added in build.gradle. Wait with patience until the downloads finish.

Now go to Intellij Idea and it will prompt to reload the project with the libraries.

 

Enabling Debug for Gradle Application with Embedded Jetty Server

It’s pretty easy to enable debug for Gradle while running on embedded Jetty server. Just enter the following line in command line and run jetty with Gradle command.

$ export GRADLE_OPTS="-Xdebug -Xrunjdwp:transport=dt_socket,address=9898,server=y,suspend=n"

Now run jetty with command line:

$ gradle jettyRunWar

You will see the following information while running jetty:

Listening for transport dt_socket at address: 9898

Now connect to the debug port 9898 with your IDE. And you are all set.

 

Decorator Design Pattern

According to wiki “decorator pattern is a design pattern that allows behavior to be added to an existing object dynamically.” But its lots more flexible than static inheritance. This pattern is also known as wrapper.

Consider different types of kindle packages. User may wants to know the price, descriptions of their custom package.  Say, a user like to have a kindle with a bag and an adapter. So how will you do it? This pattern solves this problem.

public class Kindle {

    public String getDescription() {
        return "kindle";
    }

    public double getWeight() {
        return 80.5;
    }

    public double getPrice() {
        return 199;
    }
}

Now create a decorator class to decorate kindle with bag and adapter.

public class KindleDecorator extends Kindle {
    Kindle kindle;

    public KindleDecorator(Kindle kindle) {
        this.kindle = kindle;
    }

    @Override
    public String getDescription() {
        return kindle.getDescription();
    }

    @Override
    public double getWeight() {
        return kindle.getWeight();
    }

    @Override
    public double getPrice() {
        return kindle.getPrice();
    }
}

Now the decorators are:

public class Bag extends KindleDecorator {
    public Bag(Kindle kindle) {
        super(kindle);
    }

    @Override
    public String getDescription() {
        return kindle.getDescription() + ", bag";
    }

    @Override
    public double getWeight() {
        return kindle.getWeight() + 20;
    }

    @Override
    public double getPrice() {
        return kindle.getPrice() + 40;
    }
}

public class Adapter extends KindleDecorator {
    public Adapter(Kindle kindle) {
        super(kindle);
    }

    @Override
    public String getDescription() {
        return kindle.getDescription() + ", adapter";
    }

    @Override
    public double getWeight() {
        return kindle.getWeight() + 50;
    }

    @Override
    public double getPrice() {
        return kindle.getPrice() + 30;
    }
}

Let see how it is used by the client:

Kindle kindleWithBagAndAdapter = new Adapter(new Bag(new Kindle()));
System.out.println("Package: Kindle With Bag And Adapter");
System.out.println("Description: " + kindleWithBagAndAdapter.getDescription());
System.out.println("Weight: " + kindleWithBagAndAdapter.getWeight() + " gm");
System.out.println("Price: $" + kindleWithBagAndAdapter.getPrice());

The output is:

Package: Kindle With Bag And Adapter
Description: kindle, bag, adapter
Weight: 150.5 gm
Price: $269.0

The pattern is different from Strategy in the way that Decorator Pattern is used to change the skin of object and Strategy Pattern is used to change the guts of Object.

Useful Links:

https://www.youtube.com/watch?v=j40kRwSm4VE
http://en.wikipedia.org/wiki/Decorator_pattern

Factory and Abstract Factory Design Patterns

Factory Design Pattern

Factory Design Pattern is one of the simple Design Pattern. A factory takes responsibility to create objects. Thus removes logic duplication and creational logics from code. So, lets start with code.

public class DocumentFactory {
    private String documentType;

    public DocumentFactory(String documentType) {
        this.documentType = documentType;
    }

    public Document createDocument() {

        if (documentType.equals("ACCESS")) {
            return new AccessDocument();
        } else if (documentType.equals("EXCEL")) {
            return new ExcelDocument();
        } else if (documentType.equals("WORD")) {
            return new WordDocument();
        }

        return null;
    }
}

Another variation of GoF Factory method is:

public class DocumentFactory {

    public Document createDocument(String documentType) {

        if (documentType.equals("ACCESS")) {
            return new AccessDocument();
        } else if (documentType.equals("EXCEL")) {
            return new ExcelDocument();
        } else if (documentType.equals("WORD")) {
            return new WordDocument();
        }

        return null;
    }
}

It allows client to create different type of objects with same factory.

Problem with Factory Pattern

DocumentFactory wordDocumentFactory = new DocumentFactory("WORD");
Document wordDocument = wordDocumentFactory.createDocument();

WriterFactory writerFactory = new WriterFactory("ACCESS");
Writer writer = writerFactory.createWriter();

wordDocument.addWriter(writer);
document.write();

So, a Access Writer can be attached with a Word Document which is undesirable if objects are interdependable. Abstract Factory Pattern solves this.

Abstract Factory Pattern

public class abstract DocumentFactory {
    abstract public Document createDocument();
    abstract public Writer createWriter();
}

public class WordDocumentFactory extends DocumentFactory {

    public Document createDocument() {
        return new WordDocument();
    }

    public Writer createWriter() {
        return new WordWriter();
    }
}

public class AccessDocumentFactory extends DocumentFactory {
    ...
}

public class ExcelDocumentFactory extends DocumentFactory {
    ...
}

public class DocumentFactoryBuilder {
    public static DocumentFactory createDocumentFactory(String documentType) {
        if (documentType.equals("ACCESS")) {
            return new AccessDocumentFactory();
        } else if (documentType.equals("EXCEL")) {
            return new ExcelDocumentFactory();
        } else if (documentType.equals("WORD")) {
            return new WordDocumentFactory();
        }

        return null;
    }
}

Now client will use this as:

DocumentFactory wordDocumentFactory
        = DocumentFactoryBuilder.createDocumentFactory("WORD");
Document document = wordDocumentFactory.createDocument();
Writer writer = wordDocumentFactory.createWriter();
document.addWriter(writer);
document.write();

Abstract Factory Pattern with Template Pattern

public class abstract DocumentFactory {
    abstract public Document createDocument();
    abstract public Writer createWriter();

    // Template Method
    public Document getDocument() {
        Document document = createDocument();
        Writer writer = createWriter();
        document.addWriter(writer);
        return document;
    }
}

public class WordDocumentFactory extends DocumentFactory {

    protected Document createDocument() {
        return new WordDocument();
    }

    protected Writer createWriter() {
        return new WordWriter();
    }

}

public class AccessDocumentFactory extends DocumentFactory {
    ...
}

public class ExcelDocumentFactory extends DocumentFactory {
    ...
}

public class DocumentFactoryBuilder {
    // Factory Method
    public static DocumentFactory createDocumentFactory(String documentType) {
        if (documentType.equals("ACCESS")) {
            return new AccessDocumentFactory();
        } else if (documentType.equals("EXCEL")) {
            return new ExcelDocumentFactory();
        } else if (documentType.equals("WORD")) {
            return new WordDocumentFactory();
        }

        return null;
    }
}

Now client will use this as:

DocumentFactory wordDocumentFactory
        = DocumentFactoryBuilder.createDocumentFactory("WORD");
Document document = wordDocumentFactory.getDocument();
document.write();

Lazy Initialization Problem With Hibernate One-To-One Mapping

There are different ways for lazy initialisation in Hibernate. One of the common practices is:

public class Student {
    @OneToMany(fetch = FetchType.LAZY)
    private List<Book> books;

    @OneToOne(fetch = FetchType.LAZY)
    private Address address;
}

public class Book {
    @ManyToOne(fetch = FetchType.LAZY)
    private Student student;
}

So, what happens with this lazy initialisation? Lets look in deep one by one.

@OneToMany

Considering the above example when Student is loaded from DB a proxy of empty Book list is returned instead of book list. It is only loaded when the Book list is accessed.

@ManyToOne

In case of ManyToOne, when Book is loaded from DB, hibernate checks the foreign key. If the foreign key is not null a proxy is injected instead of Student from DB.

@OneToOne

The lazy initialisation doesn’t work with above OneToOne mapping example. The reason is when hibernate loads Student it doesn’t know whether Address should be injected by proxy or keep it null.

The bytecode instrumentation (compile time instrumentation) is the solution for this.

Another solution is to make it required as:

@OneToOne(fetch = FetchType.LAZY, optional = false)

When it constrained, the hibernate can easily inject a proxy. So, lazy initialisation works fine. But the issue arise when it doesn’t fit with business requirement. Therefore we must find another way to keep it lazy.

Another hackish way is making it a @OneToMany relationship and then hibernate can inject a proxy of empty list.

Or you can keep foreign key in both side of the one-to-one relation.

Be lazy, be happy… 🙂

Installing and mounting exFAT in Linux (with write option)

To install ExFat support in Ubuntu, pull up a console (‘Applications > Accessories > Terminal’) and run:

sudo -s
apt-add-repository ppa:relan/exfat
sudo apt-get update
apt-get install fuse-exfat

The driver uses the FUSE (filesystem in userspace) framework. For it to work, FUSE needs to be enabled in the kernel. If you use the stock Ubuntu kernels then this is the default, so you don’t have to do anything else. If you roll your own drill down to ‘Filesystems > FUSE’ and either compile it in statically or enable it as a ‘M’odule, then compile and install your kernel.

While available as a module, Ubuntu won’t know to automatically use the driver when you insert an exFAT device. For now you’ll need to manually mount the device and specify the exFAT filesystem. Plug in your device and run:

cat /proc/partitions

Chances are your USB device will be the last partition listed. You can also check by looking at its size and seeing if it matches the size of your USB key.

Next make a temporary directory where you can mount the device. Ubuntu by default attaches removable media under the /media directory, so you might as well do the same. Enter the following:

cd /media
sudo -s
mkdir usbdrive
mount -t exfat /dev/sdd1 usbdrive

The drive will appear on your desktop, and you can read and write to it like any other. To safely unmount it before removing, use following command:

sudo umount usbdrive