Thursday, February 26, 2015

Multiple version of Node NVM or/ 'Home Brew'.

There are 2 ways to install Node: 
  1. Manually: use archive from Node web site.
    1. maintain version using NVM (Node version Manager).
  2. HomeBrew (Package Manager): '/usr/local/Cellar' with Base location: '/usr/local/'.
    1. Brew versions for node and other packages / formulas.

Manually Install: NVM - Node version manager

Step 1: Run following Command, by end of this command NVM will be installed
curl https://raw.githubusercontent.com/creationix/nvm/v0.11.1/install.sh | bash
Close and open your terminal, it's not necessary to log out, we just need to make sure changes nvm made to your part is actually reflected, by running following command:
$ source ~/.profile

Alternatively run the command suggested on output of script:
$ nvm ls-remote
Should you see the error, -bash: nvm: command not found it may be because git is not installed.

Go ahead and install git and return the script:
$ apt-get install git

Step 2: 
And you will be shown a list of all the available versions of node.js. You can always find out the latest stable release by heading to the node.js website, where it's printed in the center of the page.

To install version 0.10.13 (the latest as of this writing) type:
$ nvm install 0.10.13

If you type:
$ node --version

You will now see that node v0.10.13 is installed and active. If you had an older node app that only works with node v0.8.16, and wanted to downgrade, then you would input:
$ nvm install v0.8.16

To install and switch to v0.8.16.
When you're done and want to switch back to v0.10.13, you can do so with nvm's use command:
$ nvm use v0.10.13

Nvm is great and makes switching between node versions easy and convenient. However, there's one caveat. If you type:
$ which node


Home Brew (Package Manager)

Step 1:
LM-SJN-00874861:Library anudixit$ brew tap homebrew/versions
LM-SJN-00874861:0.12.0 anudixit$ brew tap homebrew/boneyard
Cloning into '/usr/local/Library/Taps/homebrew/homebrew-boneyard'...
remote: Counting objects: 747, done.
remote: Compressing objects: 100% (3/3), done.
remote: Total 747 (delta 0), reused 0 (delta 0), pack-reused 744
Receiving objects: 100% (747/747), 181.57 KiB | 156.00 KiB/s, done.
Resolving deltas: 100% (348/348), done.
Checking connectivity... done.
Tapped 74 formulae
LM-SJN-00874861:0.12.0 anudixit$ 


Step 2:
LM-SJN-00874861:0.12.0 anudixit$ brew versions node
Warning: brew-versions is unsupported and will be removed soon.
You should use the homebrew-versions tap instead:
  https://github.com/Homebrew/homebrew-versions
0.12.0   git checkout 1580f8b /usr/local/Library/Formula/node.rb
0.10.36  git checkout 06b10bc /usr/local/Library/Formula/node.rb
0.10.35  git checkout 51c3f4d /usr/local/Library/Formula/node.rb
0.10.34  git checkout 656117c /usr/local/Library/Formula/node.rb
0.10.33  git checkout 13848bb /usr/local/Library/Formula/node.rb
0.10.32  git checkout 72d9b70 /usr/local/Library/Formula/node.rb
0.10.31  git checkout 51dbf0b /usr/local/Library/Formula/node.rb
0.10.30  git checkout fa636a8 /usr/local/Library/Formula/node.rb
0.10.29  git checkout 7b968c6 /usr/local/Library/Formula/node.rb
0.10.28  git checkout f7d75de /usr/local/Library/Formula/node.rb
0.10.26  git checkout 0901e77 /usr/local/Library/Formula/node.rb
0.10.25  git checkout bae051d /usr/local/Library/Formula/node.rb
0.10.24  git checkout 8c47ff7 /usr/local/Library/Formula/node.rb
0.10.23  git checkout 5ab4328 /usr/local/Library/Formula/node.rb
0.10.22  git checkout 72f61d1 /usr/local/Library/Formula/node.rb
0.10.21  git checkout f8e98c8 /usr/local/Library/Formula/node.rb
0.10.20  git checkout 653960e /usr/local/Library/Formula/node.rb
0.10.19  git checkout 7973d20 /usr/local/Library/Formula/node.rb
0.10.18  git checkout b74c1c9 /usr/local/Library/Formula/node.rb
0.10.17  git checkout f7bbdcc /usr/local/Library/Formula/node.rb
0.10.16  git checkout 1782834 /usr/local/Library/Formula/node.rb
0.10.15  git checkout 89e0a43 /usr/local/Library/Formula/node.rb
0.10.14  git checkout dbc76e5 /usr/local/Library/Formula/node.rb
0.10.13  git checkout f88d5b8 /usr/local/Library/Formula/node.rb
0.10.9   git checkout ec5f331 /usr/local/Library/Formula/node.rb
0.10.8   git checkout ee99542 /usr/local/Library/Formula/node.rb
0.10.7   git checkout e44f345 /usr/local/Library/Formula/node.rb
0.10.6   git checkout 8583540 /usr/local/Library/Formula/node.rb
0.10.5   git checkout 3b589c5 /usr/local/Library/Formula/node.rb
0.10.4   git checkout 10e219d /usr/local/Library/Formula/node.rb
0.10.3   git checkout 71fd5b1 /usr/local/Library/Formula/node.rb
0.10.2   git checkout 91636ea /usr/local/Library/Formula/node.rb
0.10.1   git checkout bfb5239 /usr/local/Library/Formula/node.rb
0.10.0   git checkout 687062f /usr/local/Library/Formula/node.rb
0.8.22   git checkout 3c4a714 /usr/local/Library/Formula/node.rb
0.8.21   git checkout a3ef032 /usr/local/Library/Formula/node.rb
0.8.20   git checkout 9f95fff /usr/local/Library/Formula/node.rb
0.8.19   git checkout 4824d7c /usr/local/Library/Formula/node.rb
0.8.18   git checkout 07783c3 /usr/local/Library/Formula/node.rb
0.8.17   git checkout 59c35b9 /usr/local/Library/Formula/node.rb
0.8.16   git checkout 8aeaf15 /usr/local/Library/Formula/node.rb
0.8.15   git checkout fc6441e /usr/local/Library/Formula/node.rb
0.8.14   git checkout 11b5459 /usr/local/Library/Formula/node.rb
0.8.12   git checkout 3ae0e38 /usr/local/Library/Formula/node.rb
0.8.11   git checkout f24a5f5 /usr/local/Library/Formula/node.rb
0.8.10   git checkout 4c0b143 /usr/local/Library/Formula/node.rb
0.8.9    git checkout fb8447d /usr/local/Library/Formula/node.rb
0.8.8    git checkout 52bdfa1 /usr/local/Library/Formula/node.rb
0.8.7    git checkout ae6acb4 /usr/local/Library/Formula/node.rb
0.8.6    git checkout bfc71f7 /usr/local/Library/Formula/node.rb
0.8.5    git checkout 7b00c66 /usr/local/Library/Formula/node.rb
0.8.4    git checkout 7b2f682 /usr/local/Library/Formula/node.rb
0.8.3    git checkout 31f8d9f /usr/local/Library/Formula/node.rb
0.8.2    git checkout 50ae8e4 /usr/local/Library/Formula/node.rb
0.8.1    git checkout 9ff0a1d /usr/local/Library/Formula/node.rb
0.8.0    git checkout 01f8006 /usr/local/Library/Formula/node.rb
0.6.19   git checkout 83988e4 /usr/local/Library/Formula/node.rb
0.6.18   git checkout 653fb77 /usr/local/Library/Formula/node.rb
0.6.17   git checkout a3ecde3 /usr/local/Library/Formula/node.rb
0.6.16   git checkout ed17582 /usr/local/Library/Formula/node.rb
0.6.15   git checkout e18b02f /usr/local/Library/Formula/node.rb
0.6.14   git checkout 30813c8 /usr/local/Library/Formula/node.rb
0.6.13   git checkout 3b771d0 /usr/local/Library/Formula/node.rb
0.6.12   git checkout 0e8ea8a /usr/local/Library/Formula/node.rb
0.6.11   git checkout 3eec1f4 /usr/local/Library/Formula/node.rb
0.6.10   git checkout 7e202eb /usr/local/Library/Formula/node.rb
0.6.9    git checkout f752570 /usr/local/Library/Formula/node.rb
0.6.8    git checkout 74bff39 /usr/local/Library/Formula/node.rb
0.6.7    git checkout 9a52dcf /usr/local/Library/Formula/node.rb
0.6.6    git checkout 97fce9a /usr/local/Library/Formula/node.rb
0.6.5    git checkout 911726f /usr/local/Library/Formula/node.rb
0.6.4    git checkout 67a2615 /usr/local/Library/Formula/node.rb
0.6.2    git checkout 05b94b9 /usr/local/Library/Formula/node.rb
0.6.1    git checkout b6eb4fc /usr/local/Library/Formula/node.rb
0.6.0    git checkout 6bec7fc /usr/local/Library/Formula/node.rb
0.4.12   git checkout 3eea412 /usr/local/Library/Formula/node.rb
0.4.11   git checkout b6aa338 /usr/local/Library/Formula/node.rb
0.4.10   git checkout 523d360 /usr/local/Library/Formula/node.rb
0.4.9    git checkout 10b3ded /usr/local/Library/Formula/node.rb
0.4.8    git checkout 8d45d93 /usr/local/Library/Formula/node.rb
0.4.7    git checkout cb6a4b4 /usr/local/Library/Formula/node.rb
0.4.6    git checkout 7c0f0d9 /usr/local/Library/Formula/node.rb
0.4.5    git checkout 8241b81 /usr/local/Library/Formula/node.rb
0.4.4    git checkout 83753a9 /usr/local/Library/Formula/node.rb
0.4.3    git checkout f4a925d /usr/local/Library/Formula/node.rb
0.4.2    git checkout 0476235 /usr/local/Library/Formula/node.rb
0.4.1    git checkout 8a60de4 /usr/local/Library/Formula/node.rb
0.4.0    git checkout b4497ec /usr/local/Library/Formula/node.rb
0.2.6    git checkout 8602eee /usr/local/Library/Formula/node.rb
0.3.2    git checkout 168cb3d /usr/local/Library/Formula/node.rb
0.2.5    git checkout f55f417 /usr/local/Library/Formula/node.rb
0.2.4    git checkout 89438ae /usr/local/Library/Formula/node.rb
0.2.3    git checkout 730f311 /usr/local/Library/Formula/node.rb
0.2.2    git checkout 981bb41 /usr/local/Library/Formula/node.rb
0.2.1    git checkout c963a35 /usr/local/Library/Formula/node.rb
0.2.0    git checkout fbb93d9 /usr/local/Library/Formula/node.rb
0.1.104  git checkout ed51a5b /usr/local/Library/Formula/node.rb
0.1.103  git checkout f3e7c1b /usr/local/Library/Formula/node.rb
0.1.20   git checkout 2baa60c /usr/local/Library/Formula/node.rb
0.1.17   git checkout ab7697f /usr/local/Library/Formula/node.rb
0.1.14   git checkout a82e823 /usr/local/Library/Formula/node.rb
LM-SJN-00874861:0.12.0 anudixit$

Step 3:
LM-SJN-00874861:0.12.0 anudixit$ cd $( brew --prefix )
LM-SJN-00874861:local anudixit$ pwd
/usr/local


Step 4:
LM-SJN-00874861:local anudixit$ git checkout fa636a8 /usr/local/Library/Formula/node.rb

Step 5:
LM-SJN-00874861:local anudixit$ brew install node
Error: node-0.12.0 already installed
To install this version, first `brew unlink node'
LM-SJN-00874861:local anudixit$

Step 6:
LM-SJN-00874861:local anudixit$ brew unlink node
Unlinking /usr/local/Cellar/node/0.12.0... 8 symlinks removed
LM-SJN-00874861:local anudixit$

Step 7:
LM-SJN-00874861:local anudixit$ brew install node
==> Downloading https://homebrew.bintray.com/bottles/node-0.10.30.mavericks.bottle.2.tar.gz
curl: (22) The requested URL returned error: 404 Not Found
Error: Failed to download resource "node"
Download failed: https://homebrew.bintray.com/bottles/node-0.10.30.mavericks.bottle.2.tar.gz
Warning: Bottle installation failed: building from source.
==> Downloading http://nodejs.org/dist/v0.10.30/node-v0.10.30.tar.gz
######################################################################## 100.0%
==> ./configure --prefix=/usr/local/Cellar/node/0.10.30 --without-npm
==> make install
==> Downloading http://registry.npmjs.org/npm/-/npm-1.4.9.tgz
######################################################################## 100.0%
==> make install
==> /usr/local/bin/npm update npm -g --prefix /usr/local
  /usr/local/Cellar/node/0.10.30: 1547 files, 19M, built in 2.4 minutes
LM-SJN-00874861:local anudixit$

Step 8:
LM-SJN-00874861:local anudixit$ cd /usr/local/Cellar/node
LM-SJN-00874861:node anudixit$ ls
0.10.30 0.12.0

Step 9:
LM-SJN-00874861:local anudixit$ brew unlink node
Unlinking /usr/local/Cellar/node/0.10.30... 5 symlinks removed
LM-SJN-00874861:local anudixit$ git checkout -- Library/Formula/node.rb
LM-SJN-00874861:local anudixit$ brew install node
Warning: node-0.10.30 already installed, it's just not linked
LM-SJN-00874861:local anudixit$ brew link node
Linking /usr/local/Cellar/node/0.10.30... 5 symlinks created
LM-SJN-00874861:local anudixit$ node -v
v0.10.30
LM-SJN-00874861:local anudixit$

Step 10: Switch Versions
LM-SJN-00874861:node anudixit$ brew switch node 0.12.0
Cleaning /usr/local/Cellar/node/0.10.30
Cleaning /usr/local/Cellar/node/0.12.0
6 links created for /usr/local/Cellar/node/0.12.0
LM-SJN-00874861:node anudixit$ node -v
v0.12.0
LM-SJN-00874861:node anudixit$ brew switch node 0.10.30
Cleaning /usr/local/Cellar/node/0.10.30
Cleaning /usr/local/Cellar/node/0.12.0
5 links created for /usr/local/Cellar/node/0.10.30
LM-SJN-00874861:node anudixit$ node -v
v0.10.30




Sunday, January 18, 2015

Application Specific Password - "iphone : imap.gmail.com is incorrect"

How to fix Gmail incorrect password/user name error on iPhone?

Sometimes the iPhone mail app will intermittently stop getting Gmail and the dialog box below will appear. The message "The user name or password for imap.gmail.com is incorrect" can show up even if you have made no changes to your Gmail account settings on the iPhone.

Here are instructions on how to fix this problem should it occur on your device:

  1. Quit all mail clients that are accessing the affected Gmail account. This means the Mail app on the iPhone and any other place you are accessing your Gmail from such as a computer.
  2. Open Safari on the affected iPhone and navigate to this page: http://www.google.com/accounts/DisplayUnlockCaptcha to create application specific password.
  3. Enter your full Gmail address, password and type the characters you see in the picture. Touch the unlock button to verify your account.
  4. Open the Mail app and your Gmail access should be restored.


Tips:

  1. Disable iCloud (Apple) and configure Gmail from Setting > Email .. to get your contact & Calendar from Google Account (you need to setup google's "Application Specific Password").

Sunday, January 11, 2015

No separate schema definition for p-namespace and c-namespace.



  1. p-namesapce (Parameter namespace)
  2. c-namespace (Constructor namespace)

p-namesapce (Parameter namespace)

p-namespace simplifies the setter-based dependency injection code by enabling you to use the parameters to be injected as attributes of bean definition instead of the nested <property> elements.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean id="addr1" class="com.ixi.samples.spring.cpns.Address">
        <property name="houseNo" value="2106"/>
        <property name="street" value="Newbury St"/>
        <property name="city" value="Boston"/>
        <property name="zipCode" value="02115-2703"/>
    </bean>
    <bean id="constArgAnotherBean" class="com.pfl.samples.spring.cpns.Person">
        <property name="firstName" value="Joe"/>
        <property name="lastName" value="John"/>
        <property name="age" value="35"/>
        <property name="address" ref="addr1"/>
    </bean>
</beans> 

with p-namespace, you can write this as:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean name="addr1" class="com.ixi.samples.spring.cpns.Address" 
             p:houseNo="2106" 
             p:street="Newbury St" 
            p:city="Boston" 
            p:zipCode="02115-2703"/>
    <bean name="person1" class="com.ixi.samples.spring.cpns.Person" 
            p:firstName="Joe" 
            p:lastName="John" 
            p:age="35" 
           p:address-ref="addr1"/>     
</beans>  

It is simple! All you need to do is

  1. Add the p namespace URI (xmlns:p="http://www.springframework.org/schema/p") at the configuration xml with namespace prefix p. Please note that it is not mandatory that you should use the prefix p, you can use your own sweet namespace prefix :)
  2. For each nested property tag, add an attribute at the bean with name having a format of p:<property-name> and set attribute value to the value specified in the nested property element.
  3. If one of your property is expecting another bean, then you should suffix -ref to your property name while constructing the attribute name to use in bean definition. For eg, if you property name is address then you should use attribute name as address-ref

c-namespace (Constructor namespace)

c-namespace is similar to p-namespace but used with constructor-based dependency injection code. It simplifies the constructor-based injection code by enabling you to use the constructor arguments as attributes of bean definition rather than the nested <constructor-arg> elements.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
 <bean id="addr1" class="com.pfl.samples.spring.cpns.Address">
  <constructor-arg name="houseNo" value="2106"/>
  <constructor-arg name="street" value="Newbury St"/>
  <constructor-arg name="city" value="Boston"/>
  <constructor-arg name="zipCode" value="02115-2703"/>
 </bean>
 <bean id="constArgAnotherBean" class="com.pfl.samples.spring.cpns.Person">
  <constructor-arg name="firstName" value="Joe"/>
  <constructor-arg name="lastName" value="John"/>
  <constructor-arg name="age" value="35"/>
  <constructor-arg name="address" ref="addr1"/>
 </bean>  
</beans> 

and with c-namespace, it can be written as
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:c="http://www.springframework.org/schema/c"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean name="addr1" class="com.pfl.samples.spring.cpns.Address"
        c:houseNo="2106" c:street="Newbury St"
        c:city="Boston" c:zipCode="02115-2703"/>
    <bean name="person1" class="com.pfl.samples.spring.cpns.Person"
        c:firstName="Joe" c:lastName="John"
        c:age="35" c:address-ref="addr1"/>
</beans>    

It is same as p-namespace. All you need to do is
Add the c namespace URI (xmlns:c="http://www.springframework.org/schema/c") at the configuration xml with namespace prefix c. The prefix is not mandatory like p-namespace
For each nested constructor-arg eleemnt, add the attribute with name c:<argument-name> to the bean definition and set the actual argument value as attribute value.
If one of your constructor argument is expecting another bean, then you should suffix -ref to your argument name while constructing the attribute name to use in bean definition (like p-namespace). For eg, if you argument name is address then you should use address-ref

Well, the above code has an issue though. It is using the constructor argument names and that will be available only if the code is compiled with debug enabled which may not be the case with production code. So, you will have to use the index rather than the argument names. With index, we can rewrite the above code as follows.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean id="addr1" class="com.pfl.samples.spring.cpns.Address">
        <constructor-arg index="0" value="2106"/>
        <constructor-arg index="1" value="Newbury St"/>
        <constructor-arg index="2" value="Boston"/>
        <constructor-arg index="3" value="02115-2703"/>
    </bean>
    <bean id="constArgAnotherBean" class="com.pfl.samples.spring.cpns.Person">
        <constructor-arg index="0" value="Joe"/>
        <constructor-arg index="1" value="John"/>
        <constructor-arg index="2" value="35"/>
        <constructor-arg index="3" ref="addr1"/>
    </bean>
</beans> 

With c-namespace:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:c="http://www.springframework.org/schema/c" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean name="addr1" class="com.pfl.samples.spring.cpns.Address"
        c:_0="2106" c:_1="Newbury St"
        c:_2="Boston" c:_3="02115-2703"/>
    <bean name="person1" class="com.pfl.samples.spring.cpns.Person"
        c:_0="Joe" c:_1="John"
        c:_2="35" c:_3-ref="addr1"/>
</beans> 

You may notice that there is not much difference rather than using index in the place of argument name. Also, the index should be prefixed by _(underscore) to make it as a valid xml attribute name.

You can use both p-namespace and c-namespace in together in bean definition( see below):
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:c="http://www.springframework.org/schema/c" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">     
    <bean name="person3" class="com.pfl.samples.spring.cpns.Person" 
         c:_0="Mary" 
         c:_1="Joe" 
         c:_2="30" 
         p:address-ref="address2"/>
</beans> 

You may also have noticed that there is no separate schema definition for p-namespace and c-namespace.

Saturday, January 10, 2015

AOP - Aspect Oriented Programming

AOP basics: Before discussing Spring’s AOP implementation, we cover the basics of AOP as a technology. Most of the concepts covered in this section are not specific to Spring and can be found in any AOP implementation.

  • Types of AOP: There are two distinct types of AOP: static and dynamic. In static AOP, like that provided by AspectJ’s (http://eclipse.org/aspectj/) compile-time weaving mechanisms, the crosscutting logic is applied to your code at compile time, and you cannot change it without modifying the code and recompiling. With dynamic AOP, such as Spring AOP, crosscutting logic is applied dynamically at runtime. This allows you to make changes to the AOP configuration without having to recompile the application. These types of AOP are complementary, and, when used together, they form a powerful combination that you can use in your applications.
  • Spring AOP architecture: Spring AOP is only a subset of the full AOP feature set found in other implementations such as AspectJ. In this section, we take a high-level look at which features are present in Spring, how they are implemented, and why some features are excluded from the Spring implementation.
  • Proxies in Spring AOP: Proxies are a huge part of how Spring AOP works, and you must understand them to get the most out of Spring AOP. In this section, we look at the two kinds of proxy: the JDK dynamic proxy and the CGLIB proxy. In particular, we look at the different scenarios in which Spring uses each proxy, the performance of the two proxy types, and some simple guidelines to follow in your application to get the most from Spring AOP.
  • Using Spring AOP: In this section, we present some practical examples of AOP usage. We start off with a simple “Hello World” example to ease you into Spring’s AOP code, and we continue with a detailed description of the AOP features that are available in Spring, complete with examples.
  • Advanced use of pointcuts: We explore the ComposablePointcut and ControlFlowPointcut classes, introductions, and the appropriate techniques you should employ when using pointcuts in your application.
  • AOP framework services: The Spring Framework fully supports configuring AOP transparently and declaratively. We look at three ways (the ProxyFactoryBean class, the aop namespace, and @AspectJ-style annotations) to inject declaratively defined AOP proxies into your application objects as collaborators, thus making your application completely unaware that it is working with advised objects.
  • Integrating AspectJ: AspectJ is a fully featured AOP implementation. The main difference between AspectJ and Spring AOP is that AspectJ applies advice to target objects via weaving (either compile-time or load-time weaving), while Spring AOP is based on proxies. The feature set of AspectJ is much greater than that of Spring AOP, but it is much more complicated to use than Spring. AspectJ is a good solution when you find that Spring AOP lacks a feature you need.

AOP Concepts

  • Joinpoints: A joinpoint is a well-defined point during the execution of your application. Typical examples of joinpoints include a call to a method, the method invocation itself, class initialization, and object instantiation. Joinpoints are a core concept of AOP and define the points in your application at which you can insert additional logic using AOP.
  • Advice: The code that is executed at a particular joinpoint is the advice, defined by a method in your class. There are many types of advice, such as before, which executes before the joinpoint, and after, which executes after it.
  • Pointcuts: A pointcut is a collection of joinpoints that you use to define when advice should be executed. By creating pointcuts, you gain fine-grained control over how you apply advice to the components in your application. As mentioned previously, a typical joinpoint is a method invocation, or the collection of all method invocations in a particular class. Often you can compose pointcuts in complex relationships to further constrain when advice is executed.
  • Aspects: An aspect is the combination of advice and pointcuts encapsulated in a class. This combination results in a definition of the logic that should be included in the application and where it should execute.
  • Weaving: This is the process of inserting aspects into the application code at the appropriate point. For compile-time AOP solutions, this weaving is generally done at build time. Likewise, for runtime AOP solutions, the weaving process is executed dynamically at runtime. AspectJ supports another weaving mechanism called load-time weaving (LTW), in which it intercepts the underlying JVM class loader and provides weaving to the bytecode when it is being loaded by the class loader.
  • Target: An object whose execution flow is modified by an AOP process is referred to as the target object. Often you see the target object referred to as the advised object.
  • Introduction: This is the process by which you can modify the structure of an object by introducing additional methods or fields to it. You can use introduction AOP to make any object implement a specific interface without needing the object’s class to implement that interface explicitly.



Static AOP: in static AOP, the weaving process forms another step in the build process for an application. In Java terms, you achieve the weaving process in a static AOP implementation by modifying the actual bytecode of your application, changing and extending the application code as necessary. This is a well-performing way of achieving the weaving process because the end result is just Java bytecode, and you do not perform any special tricks at runtime to determine when advice should be executed.
The drawback of this mechanism is that any modifications you make to the aspects, even if you simply want to add another joinpoint, require you to recompile the entire application. AspectJ’s compile-time weaving is an excellent example of a static AOP implementation.


Dynamic AOP: Dynamic AOP implementations, such as Spring AOP, differ from static AOP implementations in that the weaving process is performed dynamically at runtime. How this is achieved is implementation-dependent, but as you will see, Spring’s approach is to create proxies for all advised objects, allowing for advice to be invoked as required. The drawback of dynamic AOP is that, typically, it does not perform as well as static AOP, but the performance is steadily increasing. The major benefit of dynamic AOP implementations is the ease with which you can modify the entire aspect set of an application without needing to recompile the main application code.


Advice Name:
1. Before: org.springframework.aop.MethodBeforeAdvice
2. After-returning: org.springframework.aop.AfterReturningAdvice
3. After (finally): org.springframework.aop.AfterAdvice
4. Around: org.aopalliance.intercept.MethodInterceptor
5. Throws: org.springframework.aop.ThrowsAdvice
6. Introduction:org.springframework.aop.IntroductionInterceptor

Friday, January 9, 2015

Spring boot Jersey

Part 1 : Spring

Spring boot aims towards simplicity and convention over configuration. First step is to include the necessary configuration in your pom.xml :
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.2.1.RELEASE</version>
</parent>
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
</dependencies>
<repositories>
    <repository>
        <id>spring-milestones</id>
        <name>Spring Milestones</name>
        <url>http://repo.spring.io/milestone</url>
        <snapshots>
            <enabled>false</enabled>
        </snapshots>
    </repository>
</repositories>

One of the good ideas of spring boot is to provide all the 'boilerplate' configuration for you by letting you inherit their parent configuration.
Then, you'll select a starter, in this case, we are going to develop a web application, so starter-web is fine.
Now, we'll create a main function for our application :

@EnableAutoConfiguration
public class Application {

    public static void main(String[] args) throws Exception {
        new SpringApplicationBuilder(Application.class)
                .showBanner(false)
                .run(args);
    }
}

We will just add an index.html file in the webapp directory and we should be ok. With this configuration, you can run the main function and you'll see your index file.

Runnable JAR

Spring boot allows you to package your application as a runnable jar. Include the following in your pom.xml :
<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>
<pluginRepositories>
    <pluginRepository>
        <id>spring-milestones</id>
        <url>http://repo.spring.io/milestone</url>
    </pluginRepository>
</pluginRepositories>

With this, when running mvn package, you will generate the runnable jar. Just java -jar it to launch an embedded Tomcat containing your webapp !

Part 2: Integrating jersey

Jersey has a spring support project jersey-spring-3. Despite what its name suggests, the project is (still?) compatible with spring 4.0 so we'll use it. It basically allows you to inject spring beans in your jersey controllers.

To complete our configuration we'll add the jersey servlet to our application together with a small class to configure it.

In the Application :
@Bean
public ServletRegistrationBean jerseyServlet() {
    ServletRegistrationBean registration = new ServletRegistrationBean(new ServletContainer(), "/rest/*"); 
    // our rest resources will be available in the path /rest/*
    registration.addInitParameter(ServletProperties.JAXRS_APPLICATION_CLASS, JerseyConfig.class.getName());
    return registration;
}

We also need to add the @ComponentScan annotation to indicate where our spring services and components can be found (including jersey)
Next, we'll create the JerseyConfig class :
public class JerseyConfig extends ResourceConfig {
    public JerseyConfig() {
        register(RequestContextFilter.class);
        packages("com.geowarin.rest");
        register(LoggingFilter.class);
    }
}

Here we are providing the package(s) in which our rest resources we be located.
Speaking about our rest resources, we'll create a very simple one :

@Path("/")
@Component
public class RestResource {
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    @Path("/hello")
    public String hello() {
        return "Hello World";
    }
}

There you have it : the dreadful hello world !

= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = 

Complete Example

In the complete example, I show you how to generate JSON from a domain class.

Basically all you have to do is provide classes with the @XmlRootElement annotation, add the getters and setters for the properties you want serialized and don't forget to provide a default constructor (see here).

To show that dependency injection works, we'll add a very tiny service :
@Singleton
@Service
public class MessageService {
    List<Message> messages = Collections.synchronizedList(new ArrayList<Message>());

    @PostConstruct
    public void init() {
        messages.add(new Message("Joe", "Hello"));
        messages.add(new Message("Jane", "Spring boot is cool !"));
    }

    public List<Message> getMessages() {
        return messages;
    }
}
We can now autowire it to our Jersey controller !
@Path("/")
@Component
public class RestResource {
    @Autowired
    private MessageService messageService;

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    @Path("/messages")
    public List<Message> message() {
        return messageService.getMessages();
    }
}
With moxy in your classpath, it will automatically be converted to JSON.

Testing: Real programmers do tests. We want to test our controller right ? There is a framework for that : jersey-test.

The Problem ? it does not (yet) support annotated configuration.

So, I'm providing a little hack of my own to override the `SpringComponentProvider` class of _jersey-spring3_ and allow this configuration. See the class on github. It is important to place it in the same package as the original one obviously.
Update : I submitted a pull request which has been accepted by Jersey. I updated the project to use the 2.6 snapshot release of jersey which includes the modified SpringComponentProvider.

Now the test :
public class RestResourceTest extends JerseyTest {
    @Override
    protected Application configure() {
        ApplicationContext context = new AnnotationConfigApplicationContext(TestConfig.class);
        return new JerseyConfig().property("contextConfig", context);
    }
    @Test
    public void testHello() {
        final String hello = target("hello").request().get(String.class);
        assertThat(hello).isEqualTo("Hello World");
    }

    @Test
    public void testMessages() throws JSONException {
        final String messages = target("messages").request().get(String.class);
        String expected = "[ " +
                "{ 'author': 'Joe', 'contents': 'Hello'}," +
                "{ 'author': 'Jane', 'contents': 'Spring boot is cool !'}" +
                "]";
        JSONAssert.assertEquals(expected, messages, JSONCompareMode.LENIENT);
    }
}
Jersey Test will automatically select a provider from your classpath, in the example I'm using the in memory provider which I believe to be the fastest but you can also use grizzly and others instead.

I'm using JSONassert to test json results.

In the example, we are providing a very simple, lighter TestConfig :

@Configuration
@ComponentScan(basePackageClasses = RestResource.class)
public class TestConfig {
}
Conclusion

Testing with Jersey Test is fast and intuitive.

Spring boot is a very nice addition to the spring ecosystem. Now that everything should be accessible from the cloud, so should be spring webapps !

References:

Spring Boot
Complete Example

Thursday, January 1, 2015

Mac Install Brew and Mongo DB on MAC

Install Home Brew:

# Paste this in terminal, script (http://brew.sh/) will tell you what is doing.
$ ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

HomeBrew: missing package manager for Apple
= = = = = = = = = = =  = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
-MacBook-Pro:~ daft$ ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
==> This script will install:
/usr/local/bin/brew
/usr/local/Library/...
/usr/local/share/man/man1/brew.1
==> The following directories will be made group writable:
/usr/local/.
/usr/local/bin
/usr/local/include
/usr/local/lib
/usr/local/share
/usr/local/share/man
/usr/local/share/man/man1
==> The following directories will have their group set to admin:
/usr/local/.
/usr/local/bin
/usr/local/include
/usr/local/lib
/usr/local/share
/usr/local/share/man
/usr/local/share/man/man1

Press RETURN to continue or any other key to abort
==> /usr/bin/sudo /bin/chmod g+rwx /usr/local/. /usr/local/bin /usr/local/include /usr/local/lib /usr/local/share /usr/local/share/man /usr/local/share/man/man1
Password:
==> /usr/bin/sudo /usr/bin/chgrp admin /usr/local/. /usr/local/bin /usr/local/include /usr/local/lib /usr/local/share /usr/local/share/man /usr/local/share/man/man1
==> /usr/bin/sudo /bin/mkdir /Library/Caches/Homebrew
==> /usr/bin/sudo /bin/chmod g+rwx /Library/Caches/Homebrew
==> Downloading and installing Homebrew...
remote: Counting objects: 223958, done.
remote: Compressing objects: 100% (58932/58932), done.
remote: Total 223958 (delta 163779), reused 223958 (delta 163779)
Receiving objects: 100% (223958/223958), 51.01 MiB | 2.55 MiB/s, done.
Resolving deltas: 100% (163779/163779), done.
From https://github.com/Homebrew/homebrew
 * [new branch]      master     -> origin/master
HEAD is now at a9ea56b curl: update 7.40.0 bottle.
==> Installation successful!
==> Next steps
Run `brew doctor` before you install anything
Run `brew help` to get started
-MacBook-Pro:~ daft$ 
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = 
1. Update Home Brew package database:
-MacBook-Pro:~ daft$ brew update
Already up-to-date.
2. Install wget:
-MacBook-Pro:~ daft$ brew install wget
3. Install Maven: $ brew install maven [Brew install maven in '/usr/local/Cellar/maven/3.2.5']
==> Downloading http://www.apache.org/dyn/closer.cgi?path=maven/maven-3/3.2.5/binaries/apache-maven-3.2.5-bin.tar.gz

==> Best Mirror http://www.webhostingjams.com/mirror/apache/maven/maven-3/3.2.5/binaries/apache-maven-3.2.5-bin.tar.gz
######################################################################## 100.0%
==> Patching /usr/local/Cellar/maven/3.2.5: 82 files, 9.1M, built in 2 seconds

The Path to Homebrew

The home page and documentation for Homebrew show how to install and use Homebrew. However, they currently don't seem to explain exactly how pathing works. This can trip up a lot of newcomers, who might give up on Homebrew or fumble around the internet and land on bad advice - such as using sudo and editing /etc/paths. All of this is unnecessary and potentially dangerous.

You just really need to understand a few basic concepts:
1. Never run brew as sudo. Not "sudo brew install" nor "sudo brew link".
2. The "Cellar" is a place that all your "kegs". Homebrew installs packages to their own directory (in the Cellar) and then symlinks their files into /usr/local/.
3. Change /usr/local/* to be owned by $USER, not root, so you can have write permissions and not need sudo.
4. The $PATH entry for /usr/local/bin should occur before /usr/bin.

Here's an example of installing Python and setting paths correctly. I'm using OS X 10.9.2 (Mavericks) and Homebrew 0.9.5:
$ sudo chown -R $USER /usr/local/*
$ brew doctor
$ brew update
$ brew install python --with-brewed-openssl
$ ls /usr/local/Cellar/python
2.7.6
$ python
>> 2.7.5

Wait, I expected to see python 2.7.6 now. What happened? 
$ which python
/usr/bin/python

But the Homebrew docs said we will be using a symlink from /usr/local/bin/ that points at the Cellar instead of using /usr/bin: 
$ ls -l /usr/local/bin/python
# /usr/local/bin/python -> ../Cellar/python/2.7.6/bin/python

okay so it must be path issue:
$ echo $PATH
/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin

$ cat /etc/paths
/usr/bin
/bin
/usr/sbin
/sbin
/usr/local/bin

When using Homebrew, we actually now want to change the position of /usr/local/bin to be before /usr/bin in $PATH. But don't edit /etc/paths. Instead edit ~/.bashrc and prepend /usr/local/bin to $PATH, like:
PATH=/usr/local/bin:$PATH

Next, run: 
$ source ~/.bashrc

Now check: [$ echo $PATH] # don't worry about duplicate entry of "/usr/local/bin" it does not matter, what matter is you modified your path in cleaner way.
/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin

Now check: [$ ls -l $(which python)]
# /usr/local/bin/python -> ../Cellar/python/2.7.6/bin/python

Yay! And if you ever want to use the old python you can just run: /usr/bin/python.

Best of all from now on whenever you need to install anything with brew, you can just run: [$ brew install whatever] and not have to fumble with permissions or worry about overwriting any global system files.

I also like to source ~/.bashrc from ~/.bash_profile. For why see: .bash_profile vs .bashrc

According to the bash man page, .bash_profile is executed for login shells, while .bashrc is executed for interactive non-login shells.

.bash_profile:
When you login (type username and password) via console, either sitting at the machine, or remotely via ssh: .bash_profile is executed to configure your shell before the initial command prompt.

.bashrc
But, if you’ve already logged into your machine and open a new terminal window (xterm) inside Gnome or KDE, then .bashrc is executed before the window command prompt. .bashrc is also run when you start a new bash instance by typing /bin/bash in a terminal.

MAC OS X - Exception: Terminal.app execute everytime terminal app is executed.

Recommendation:
Most of the time you don’t want to maintain two separate config files for login and non-login shells — when you set a PATH, you want it to apply to both. You can fix this by sourcing .bashrc from your .bash_profile file, then putting PATH and common settings in .bashrc. To do this, add the following lines to .bash_profile:
if [ -f ~/.bashrc ]; then
   source ~/.bashrc
fi

Now when you login to your machine from a console .bashrc will be called.

MongoDB Installation

Automatic. Install Mongo DB

= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
 -MacBook-Pro:~ daft$ brew install mongodb
==> Downloading https://downloads.sf.net/project/machomebrew/Bottles/mongodb-2.6.6.yosemite.bottle.tar.gz
######################################################################## 100.0%
==> Pouring mongodb-2.6.6.yosemite.bottle.tar.gz
==> Caveats
To have launchd start mongodb at login:
    ln -sfv /usr/local/opt/mongodb/*.plist ~/Library/LaunchAgents
Then to load mongodb now:
    launchctl load ~/Library/LaunchAgents/homebrew.mxcl.mongodb.plist
Or, if you don't want/need launchctl, you can just run:
    mongod --config /usr/local/etc/mongod.conf
==> Summary
  /usr/local/Cellar/mongodb/2.6.6: 17 files, 332M
-MacBook-Pro:~ daft$
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
4. Build MongoDB from Source with SSL Support
$ brew install mongodb --devel # install latest development release of mongo
This will install mongodb in homebrew default package location (/usr/local/Cellar/mongodb/2.6.6).

Mongo DB Manual Installation:

1. Download binaries of mongo db(https://www.mongodb.org/downloads.) 
  $ curl -O http://downloads.mongodb.org/osx/mongodb-osx-x86_64-2.8.0-rc3.tgz
2. Extract the files from downloaded Archive
  $ tar -zxvf mongodb-osx-x86_64-2.8.0-rc3.tgz
3. Copy the extracted archive to targetted directory:
  $ mkdir -p mongodb
  $ cp -R -n mongodb-osx-x86_64-2.8.0-rc3/ mongodb
4. Ensure the location of binary is in the PATH variable, Replace <mongodb-install-directory> with the path to the extracted MongoDB archive in below line.
  $ export PATH=<mongodb-install-directory>/bin:$PATH

Run MongoDB:

1. Create the Data Directory: 
 -MacBook-Pro:~ daft$ mkdir -p /data/db
2. Set permission to data directory: before running mongo db for first time ensure user running mongodb have read and write permission to 'Data Directory'.
3. Run MongoDB:
  3.a: If MongodDB binary is in $PATH location and data directory is default "/data/db" then $ mongod
  3.b: If mongod library not in $PATH then specify full path of mongod binary. $<path_to_binary>/mongod
  3.c: specify path of data directory: mongod --dbpath <path_to_data_directory>



References & Courses

Mongo DB Web Site
   1.   Courses for Mongo DB for:
   2.   Java Developers: https://university.mongodb.com/courses/M101J/about
   3.   Node JS Developers: https://university.mongodb.com/courses/M101JS/about
   4.   Python Developers: https://university.mongodb.com/courses/M101P/about
   5.   DBA: https://university.mongodb.com/courses/M102/about
   6.   Mongo DB Advance deployment and operations: https://university.mongodb.com/courses/M202/about
   7.   Data Wrangling with Mongo DB: https://www.udacity.com/course/ud032

Saturday, December 27, 2014

Java 6 New Features

Java SE 6 incorporates a broad range of enhancements to the infrastructure of Java rather than specific syntax enhancements (unlike Java 5)

• Java SE 6 features include:
– XML and Web services support
– JDBC 4.0 support
– More Annotation types
– More flexible annotation processing
– Jave compiler APIs accessible from programs
– Application client GUI enhancements for both AWT and Swing

• Javas SE 6 address the growth of Web services and XML processing in the Java community
including support for:
– Web Services client stack
– Streaming API for XML (StAX)
– Java Architecture for XML Binding (JAXB) 2.0
– Java API for XML-based Web services (JAXWS) 2.0 Web services metadata
– XML digital signature API

• Java SE 6 includes JDBC 4.0; designed to improve ease of JDBC development by:
– Simplified access to relational data sources with utility classes
– Use of generics and annotations
– Addition of JDBC 4.0 wrapper pattern
– Safe access to vendor-specific APIs
– Automatic driver discovery
– Enhanced connection management
– New data types (including XML and SQL ROWID)


• Annotations were in Java 5.0 allowing developers to embed metadata in Java source code

• Java SE 6 includes additional built-in annotation types and annotation-processing APIs including:
– Web services metadata for the Java Platform (JSR 181)
– Common Annotations for the Java Platform (JSR 250)
– Pluggable Annotation Processing API (JSR 269)

• Java command-line compilers receive input from the file system and report errors using a stream

• Java SE 6 allows the compiler to receive input and/or send output to an abstraction of the file system

• Java programs may now specify compiler directives and process compiler output (this feature was add mostly due to software vendor
requests)

• Java SE 6 enhances application GUI capabilities with changes to both AWT and Swing

• AWT
– Faster splash screens (using native code)
– System tray support (icons & messages)
– Access to browsers and other desktop application “helpers”

• Swing
– Improved drag-and-drop support
– Enhanced layout customization
– Simplified multi-thread programming
– Writing of GIF images

• Changes to Java class file specification (JSR 202)

• Framework to connect Java programs to scripting-language interpreters (JSR 223)

• New bi-directional (allowing backward navigation) collection classes