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