Sunday 27 July 2014

How to change file extension in Windows 7?

Problem

Recently I wanted to enable USB debugging on my new Moto E.  But corresponding driver was missing which i needed to manually download. You can find the complete solution in following link


So the downloaded jar was Motorola_Mobile_Drivers_64bit.msi.img. It is not really a .img file. It is infact a .msi file. So I wanted to rename the file and execute it. But with normal settings windows does not allow you that. 

Even if you do a rename (F2) you will not see that .img extension and you cannot edit it.



So you need to do some settings so that you can edit the file extension.

Solution

In your Windows Explorer go to Organize -> Folder and search options. In that navigate to View tab and check uncheck Hide extensions for unknown file types.


Then simply click Apply and OK.

Now when you rename it file (F2) you should also see the .img extension. Simply rename it and save (Enter).

You will get a prompt whether you really want to change the file name. Click on Yes.



And you are done. You file extension should change. You can change it to whatever you like. I mean always know what you are doing... you may make some application unstable. Also never mess with system files unless you know what you are doing.




That's all!



Saturday 26 July 2014

Spring form controller with annotations example

Goal



In this post we will see hoe can we operate on simple html forms using Spring and Java Objects. Spring MVC provides a special controller SimpleFormController for this. 

[Note : This controller was deprecated in Spring 3.0 and is no longer available (I am using 4.0.4.RELEASE version). So we will strictly be using annotations based programming which is the future.]

DisplacherServlet looks for some default beans -
  1. HandlerMapping 
  2. HandlerAdapter
  3. ViewResolver 
  4. HanadlerExceptionResolver

How they work is depicted in following diagram


Project Structure


Code

ivy.xml


<?xml version="1.0" encoding="ISO-8859-1"?>
<!--
   Licensed to the Apache Software Foundation (ASF) under one
   or more contributor license agreements.  See the NOTICE file
   distributed with this work for additional information
   regarding copyright ownership.  The ASF licenses this file
   to you under the Apache License, Version 2.0 (the
   "License"); you may not use this file except in compliance
   with the License.  You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing,
   software distributed under the License is distributed on an
   "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
   KIND, either express or implied.  See the License for the
   specific language governing permissions and limitations
   under the License.    
-->
<ivy-module version="2.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:noNamespaceSchemaLocation="http://ant.apache.org/ivy/schemas/ivy.xsd">
    <info
        organisation="OpenSourceForGeeks"
        module="SpringDemoWebProject"
        status="integration">
    </info>
    
        <dependencies>
    
        <dependency org="org.springframework" name="spring-webmvc"
            rev="4.0.4.RELEASE">
            <exclude org="javax.servlet" name="javax.servlet-api" />
            <exclude org="javax.servlet.jsp" name="jsp-api" />
            <exclude org="javax.el" name="javax.el-api" />
        </dependency>
        
        <dependency org="com.google.code.gson" name="gson" rev="2.2.4"/>
        
    </dependencies>
    
</ivy-module>
 

web.xml

<web-app id="WebApp_ID" version="2.4" 
    xmlns="http://java.sun.com/xml/ns/j2ee" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
    http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

  <display-name>Test Spring App</display-name>
  
  
    <servlet>
        <servlet-name>action</servlet-name>
        <servlet-class>
            org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

  <servlet-mapping>
     <servlet-name>action</servlet-name>
        <url-pattern>*.htm</url-pattern>
  </servlet-mapping>
   


action-servlet.xml

<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://www.springframework.org/schema/beans"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
    http://www.springframework.org/schema/context 
    http://www.springframework.org/schema/context/spring-context-2.5.xsd" >

    <context:annotation-config />
    <context:component-scan base-package="controllers" />
    
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix">
            <value>/pages/</value>
        </property>
        <property name="suffix">
            <value>.jsp</value>
        </property>
    </bean>

</beans>

Employee.java

package model;

public class Employee {
    
    private String name;
    private int age;
    
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    
    
}
 

FormController.java

package controllers;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import model.Employee;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;

@Controller
@SessionAttributes({FormController.COMMAND_NAME})
public class FormController {
    
    public static final String EMPLOYEE_FORM= "employeeForm";
    public static final String COMMAND_NAME= "empForm";
    
    @RequestMapping(value="/getEmployeeInfoForm.htm",method=RequestMethod.GET)
    public String getEmployeeInfoForm(HttpServletRequest request, ModelMap modelMap){
        Employee empForm = new Employee();
        empForm.setName("DefaultName");
        empForm.setAge(18);
        modelMap.addAttribute(COMMAND_NAME, empForm);
        return EMPLOYEE_FORM;
    }

    

    @RequestMapping(value="/submitEmployeeInfoForm.htm",method = RequestMethod.POST)
    public void saveEmployeeInfo(
            @ModelAttribute(COMMAND_NAME) Employee empForm,
            Errors errors, ModelMap model, HttpServletRequest request,
            HttpServletResponse response) {
        
        System.out.println("Receive Employee Information");
        System.out.println("Name : " + empForm.getName());
        System.out.println("Age :" + empForm.getAge());
    }
    

}


employeeForm.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"

    pageEncoding="ISO-8859-1"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Employee Information Form</title>
<script>

function submitForm(){
    var formVar = document.forms["form"];
    formVar.action="/SpringDemoWebProject/submitEmployeeInfoForm.htm";
    formVar.submit();
}

</script>
</head>
<body>

    <form:form id="form" name="form"
        method="post" commandName="empForm">
        
        <table>
            <tr>
                <td>Employee Name : </td>
                <td>
                <form:input path="name"/>
                </td>
            </tr>
            <tr>
                <td>Employee Age : </td>
                <td>
                <form:input path="age"/>
                </td>
            </tr>
        </table>
        <input type="submit" value="Submit" onclick="submitForm()"/>
        
    </form:form>
</body>

</html>
  

Screenshots


Important points

  • When you add a @ModelAttribute("empForm") controller method argument you're telling Spring MVC to look for it in the model or create a new instance if not found.  It is not necessary that your JSP pahe has a command object called empForm. Let's get this clear in next point.
  • When you add multiple attributes in your model map the commandName that you use can be any one of the attribute name. Now when you submit your form it is not necessary that the ModelAttribute is same as that of command name. The way it works is as follows - Spring will create a new object of that class (is not already present eg. in session by using @SessionAttributes tag). After creating it will try to scan request parameters and put in your new ModelAttribute Object created.
  • As mentioned above If you also add @SessionAttributes({"empForm"}), Spring MVC will not attempt to create a new instance and will expect the object to be either in the model or in the session.

Related Links


Sunday 20 July 2014

Testing Java programs with EasyMock and JUnit

Background

EasyMock has been the first dynamic Mock Object generator, relieving users of hand-writing Mock Objects, or generating code for them.

EasyMock provides Mock Objects by generating them on the fly using Java's proxy mechanism.

We are going to use this to write test cases in Java. For more details you can visit their official website.


Adding Dependencies

As usual I am going to use Ivy to add dependencies to my project (Installing and using Apache Ivy as dependency manager).  You ivy.xml should look something like the following - 

<?xml version="1.0" encoding="ISO-8859-1"?>
<!--
   Licensed to the Apache Software Foundation (ASF) under one
   or more contributor license agreements.  See the NOTICE file
   distributed with this work for additional information
   regarding copyright ownership.  The ASF licenses this file
   to you under the Apache License, Version 2.0 (the
   "License"); you may not use this file except in compliance
   with the License.  You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing,
   software distributed under the License is distributed on an
   "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
   KIND, either express or implied.  See the License for the
   specific language governing permissions and limitations
   under the License.    
-->
<ivy-module version="2.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:noNamespaceSchemaLocation="http://ant.apache.org/ivy/schemas/ivy.xsd">
    <info
        organisation="openSourceForGeeks"
        module="EasyMockDemo"
        status="integration">
    </info>

    <dependencies>
        <dependency org="junit" name="junit" rev="4.11"/>
        <dependency org="org.easymock" name="easymock" rev="3.1"/>
        
    </dependencies>

</ivy-module>


What we want to achieve via this testing and Why...

Consider you have developed a online shopping portal. You have a class Product that holds information of your individual product like  its name and quantity. When you shop you would purchase multiple products. So lets have a class ShoppingBasket that holds a List of Products. Also lets have a service ShoppingService that would calculate total cost of all the product in the ShoppingBasket. In production code you would probably have this service make a database call the get the price of the product but we cannot afford that in the tests. So we will mock this service and use it instead of an actual DB call.


To the code.....

First create a class Product.java

public class Product {
    
    private String name;
    private int quantity;
    
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getQuantity() {
        return quantity;
    }
    public void setQuantity(int quantity) {
        this.quantity = quantity;
    }

}


Then create a class name ShoppingBasket.java

public class ShoppingBasket {
    
    private String basketName;
    private ShoppingService shoppingService;
    
    private List<Product> products = new ArrayList<Product>();
    
    public int getTotalCost() {
        int totalCost = 0;
        for(Product product: products) {
            totalCost = totalCost + shoppingService.getProductCost(product.getName());
        }
        return totalCost;
    }
    
    public void addProduct(Product product) {
        this.products.add(product);
    }

    public String getBasketName() {
        return basketName;
    }

    public void setBasketName(String basketName) {
        this.basketName = basketName;
    }

    public ShoppingService getShoppingService() {
        return shoppingService;
    }

    public void setShoppingService(ShoppingService shoppingService) {
        this.shoppingService = shoppingService;
    }

    public List<Product> getProducts() {
        return products;
    }

    public void setProducts(List<Product> products) {
        this.products = products;
    } 

}


Noe create a Service (which would be an interface / production code would have this implementation with DB logic) name ShoppingService.java.

public interface ShoppingService {
    
    int getProductCost(String productName);
    
}

Note : Methods in an interface are bu default public and abstract. Whereas variable are by default public, static and final.

Finally create a Test class that mocks the service and tests out the getProductCost() method.

import org.easymock.EasyMock;
import org.junit.Before;
import org.junit.Test;
import junit.framework.Assert;

import junit.framework.TestCase;


public class ShoppingBasketTest{
    
    private ShoppingBasket shoppingBasket;
    private ShoppingService shoppingServiceMock;
    
    @Before
    public void init(){
        shoppingBasket = new ShoppingBasket();
        shoppingBasket.setBasketName("myBaset");
        shoppingServiceMock = EasyMock.createMock(ShoppingService.class);
        shoppingBasket.setShoppingService(shoppingServiceMock);
    }
    
    @Test
    public void testTotalCost(){
        EasyMock.expect(shoppingServiceMock.getProductCost("Moto E Android Smartphone")).andReturn(7000);
        EasyMock.replay(shoppingServiceMock);
        
        Product motoE = new Product();
        motoE.setName("Moto E Android Smartphone");
        shoppingBasket.addProduct(motoE);
        Assert.assertEquals(7000, shoppingBasket.getTotalCost());
    }

} 
Thats it run the method with annotation @test  using junit. Your test should be successful.





Note : If you make your test class extend TestCase class @before annotation will not work. If you extend TestCase, JUnit treats your test class as an old (pre JUnit 4 class) and picks org.junit.internal.runners.JUnit38ClassRunner to run it. JUnit38ClassRunner does not know about @BeforeClass annotation. You have to put you logic in overridden method setUp().

Monday 14 July 2014

Using AirDroid to transfer files to and from your android device

Just came across this cool app to transfer data to and from your android smart phone. No cable required. All you need is your device and PC/Laptop to be on the same network.

  1. Install AirDroid - Best Device Manager.
  2. Opem the App and you should see a screen with a URL. It will look something like below -


  3. Next type the given URL in the browser of your Laptop/PC. You will get a request on your device to authenticate the connection.

  4. Then you can see your phone stats and file. You can then transfer files.

  5. You can do lot of other cool stuff like file transfer, view contacts, transfer apps use camera etc. Do explore it...

Saturday 12 July 2014

How to sort a Map on the values in Java?

Goal

In this post we will see how can we sort a Map based on its values. We will use Comparators.

Map overview in Java - 


Code :

 /*
 * author : athakur
 */

public class HelloWorld {


    public static void main(String args[]) {
       
        Map<String,Integer> nameAgeMap = new HashMap<String,Integer>();
        AgeComparator ageComparator =  new AgeComparator(nameAgeMap);
        Map<String,Integer> sortedNameAgeMap = new TreeMap<String,Integer>(ageComparator);

        nameAgeMap.put("Name1",21);
        nameAgeMap.put("Name2",16);
        nameAgeMap.put("Name3",10);
        nameAgeMap.put("Name4",23);

        System.out.println("Original Map : "+ nameAgeMap);
       
        sortedNameAgeMap.putAll(nameAgeMap);

        System.out.println("Sorted Name Age Map : "+ sortedNameAgeMap);
       
    }

}

class AgeComparator implements Comparator<String> {
   
    Map<String,Integer> mapToBeCompared;
   
    public AgeComparator(Map<String,Integer> mapToBeCompared){
        this.mapToBeCompared = mapToBeCompared;
    }

    @Override
    public int compare(String o1, String o2) {
        Integer x = mapToBeCompared.get(o1);
        Integer y = mapToBeCompared.get(o2);
        if(x >= y) {
            return 1;
        }
        else {
            return -1;
        }
    }
   
}


Output :


The output is as expected

Original Map : {Name4=23, Name3=10, Name2=16, Name1=21}
Sorted Name Age Map : {Name3=10, Name2=16, Name1=21, Name4=23}

 Note

  1. Above comparator imposes orderings that are inconsistent with equals. 
  2. Do not return 0 from the comparator as it will merge the keys. Given that all keys in a Map are unique. Duplicate key entry over writes the old entry.
  3. If you have your own class instead of Integer in the map then it makes sense for your class to implement comparable interface and use compareTo() directly in compare() method. 
  4. Collection APIs provide sort method that takes comparator as an argument. You can use that for the sorting criteria that suits your requirement. 
To summarize if you want to sort objects based on natural order then use Comparable in Java and if you want to sort on some other attribute of object then use Comparator in Java.

Using Comparator on Entry 

You can create a comparator on Entry which is datastructure that HashMap internally uses - 

public class SortMapByValue
{
    public static boolean ASC = true;
    public static boolean DESC = false;

    public static void main(String[] args)
    {

        // Creating dummy unsorted map
        Map<String, Integer> unsortMap = new HashMap<String, Integer>();
        unsortMap.put("B", 55);
        unsortMap.put("A", 80);
        unsortMap.put("D", 20);
        unsortMap.put("C", 70);

        System.out.println("Before sorting......");
        printMap(unsortMap);

        System.out.println("After sorting ascending order......");
        Map<String, Integer> sortedMapAsc = sortByComparator(unsortMap, ASC);
        printMap(sortedMapAsc);


        System.out.println("After sorting descindeng order......");
        Map<String, Integer> sortedMapDesc = sortByComparator(unsortMap, DESC);
        printMap(sortedMapDesc);

    }

    private static Map<String, Integer> sortByComparator(Map<String, Integer> unsortMap, final boolean order)
    {

        List<Entry<String, Integer>> list = new LinkedList<Entry<String, Integer>>(unsortMap.entrySet());

        // Sorting the list based on values
        Collections.sort(list, new Comparator<Entry<String, Integer>>()
        {
            public int compare(Entry<String, Integer> o1,
                    Entry<String, Integer> o2)
            {
                if (order)
                {
                    return o1.getValue().compareTo(o2.getValue());
                }
                else
                {
                    return o2.getValue().compareTo(o1.getValue());

                }
            }
        });

        // Maintaining insertion order with the help of LinkedList
        Map<String, Integer> sortedMap = new LinkedHashMap<String, Integer>();
        for (Entry<String, Integer> entry : list)
        {
            sortedMap.put(entry.getKey(), entry.getValue());
        }

        return sortedMap;
    }

    public static void printMap(Map<String, Integer> map)
    {
        for (Entry<String, Integer> entry : map.entrySet())
        {
            System.out.println("Key : " + entry.getKey() + " Value : "+ entry.getValue());
        }
    }
}

This will sort your HashMap.

Important Links

Sunday 6 July 2014

Installing Mercurial on Linux

Background

There are many source code versioning tools. Some of them which I have previously used are perforce(p4), git, svn. There are more like cvs, mercurial and the list goes on.... In this post we will see how to install and configure mercurial.

Mercurial is a free, distributed source control management tool. It efficiently handles projects of any size and offers an easy and intuitive interface. (official site)

Mercurial is a cross-platform, distributed revision control tool for software developers. It is mainly implemented using the Python programming language, but includes a binary diff implementation written in C. It is supported on MS Windows and Unix-like systems, such as FreeBSD, Mac OS X and Linux. Mercurial is primarily a command line program but graphical user interface extensions are available. All of Mercurial's operations are invoked as arguments to its driver program hg, a reference to the chemical symbol of the element mercury. (More on Wiki)

Installation

You can easily to the installation using a package manager

sudo apt-get install mercurial

But for me it installed a very old version (2.0.2) which is clearly not the way to go. So you can install the latest version as follows - 


sudo apt-get install python-setuptools python-dev build-essential
sudo easy_install -U mercurial

This installed the latest version for me (3.0.1). You can view the version installed by

hg version


Configuration file for the same can be found in  /etc/mercurial/hgrc. You can edit it to suit your requirements.

I have added external diff program called kdiff3 ( How to Install Kdiff3 on Ubuntu  ). So my hgrc file contents are as follows

# system-wide mercurial configuration file
# See hgrc(5) for more information

[merge-tools]
kdiff3.args=--auto -L1 base --L2 local --L3 other $base $local $other -o $output
kdiff3.regkey=Software\KDiff3
kdiff3.regappend=\kdiff3.exe
kdiff3.fixeol=True
kdiff3.gui=True 

Important Links

How to Install Kdiff3 on Ubuntu

Background

Subversion, Git, Mercurial and others support three-way merges (combining mine, theirs, and the "base" revision) and support graphical tools to resolve conflicts.

Which tool do we use ?  In this post I will show how can we install KDiff3.
 It is an open source cross platform tool.


 

Installation

  1. Download the Kdiff3 tar file from the sourceforge repos, then extract the tar file. The sourceforge link for the Kdiff3 project.
  2. Extract the tar.gz file using tar command

    tar -xzf kdiff3-0.9.98.tar.gz
  3. Make sure you have QT4 installed . If not installed you can install it with following command -

    sudo apt-get install libqt4-dev
  4. After extracting go into the “src-QT4″ directory and compile

    cd kdiff3-0.9.98/src-QT4
    qmake kdiff3.pro
    make
    sudo make install
  5. Now you should be able to launch the program by typing kdiff3 in the console.




Important Links

Saturday 5 July 2014

Resolving issue with Ubuntu installation getting stuck at VMware tools installation.

Background of the problem

I was installing Ubuntu 12.04 LTS on VMware.
I used the "Easy Mode" option while installation.
When I finish the installation, the VMware automatically tried to install VMware Tools and it was stuck. No graphical interface could be loaded. Restarting the VM and rebooting Ubuntu did not help.

You will get something like following


******************************************************************
******************************************************************
Vmware Easy Install

PLEASE WAIT! VMware Tools is currently being 
installed on your system. Depending on the 
version of Ubuntu you are installing, you may 
log in below and use the system during 
intallation. Otherwise, please wait for the 
graphical environment to launch. Thank you.

******************************************************************
******************************************************************
ubuntu login:_


Some random Screenshot I picked up from the net as I already resolved my issue :) . It looked same as below -



Solution


Follow 3 steps mentioned below

  1. Restore the /etc/issue file:

    Use the command : sudo mv /etc/issue.backup /etc/issue
  2. Restore the /etc/rc.local file:

    Use the command :  sudo mv /etc/rc.local.backup /etc/rc.local
  3. Restore the /etc/init/lightdm.conf file:

    Use the command : sudo mv /opt/vmware-tools-installer/lightdm.conf /etc/init

And then simply reboot your machine. You should see graphical interface coming up now.

But this also leds to another problem. This does not install your vmware tools. On trying you would get the following error.






To fix this delete and re add drives


    1. Power off the virtual machine.
    2. Go to VM > Settings
    3. Select CD/DVD.
    4. Make a note of the current settings for this device, then click Remove.
    5. Click Add.
    6. Select CD/DVD, and click Next.
    7. Select the settings you noted previously (or you can set them later), and click Next > Finish.
    8. Select Floppy.
    9. Make a note of the current settings for this device, then click Remove.
    10. Click Add.
    11. Select Floppy, and click Next.
    12. Select the settings you noted previously (or you can set them later), and click Next > Finish.
    13.Power on the virtual machine and install VMware Tools.

This should install vmware tools.

Note : To install the vmware tools if you get popup saying CD is read only don't worry. Copy the tar.gz file to your home folder. Extract folder contents using tar -xvf filename  and then install it. There is a python script in the extracted folder (ends with extension .py). Simply run it sudo ./filename.py and your vmware tools should get installed.

Friday 4 July 2014

How to permanently set $PATH on Linux?

Goal

Very basic information that every Linux user needs to know - How to export $PATH . This variable contains all the paths which may have executables that will be recognized throughout the System. For example lets say you installed java. You want to compile a program and so you do javac TestClass.java and you get javac is not a recognized command. One way to resolve this is to do pathtojdk/bin/javac TestClass.java but this is not the best way. You can add path pathtojdk/bin to that $PATH environment variable and then you can access all commands in bin folder from anywhere in your System. So lets see how can we achieve this...

Getting Started...

So lets say I want to add following 3 paths to $PATH env variable
  1. $HOME/mozilla/adt-bundle-linux/sdk/tools
  2. $HOME/mozilla/adt-bundle-linux/sdk/build-tools
  3. $HOME/mozilla/adt-bundle-linux/sdk/platform-tools
You can view your existing $PATH variable by just typing echo $PATH . To add it you can do the following. Execute the following on command line

export PATH=$PATH:$HOME/mozilla/adt-bundle-linux/sdk/tools:$HOME/mozilla/adt-bundle-linux/sdk/build-tools:$HOME/mozilla/adt-bundle-linux/sdk/platform-tools

then again you can check the $PATH variable using echo.



But wait a second. Restart the console and if you notice the exported PATH is gone. Yes it is lasts only for that console session. So lets see how can we export this $PATH permanently.


  1. Edit your ~/.bashrc file and add the export line there.
  2. Save the file.
  3. Lastly execute source ~/.bashrc
Note : source command is basically to make your console aware of the changes that you have made in the file.


and thats it. Those PATHS should be in your $PATH environment variable permanently from there on.

Caution

  • It's often considered a security hole to leave a trailing colon at the end of your bash PATH because it makes it so that bash looks in the current directory if it can't find the executable it's looking for.  
  • Consider the scenario when you unpack a tarball, then cd to the directory you unpacked it in, then run ls---and then realize that the tarball had a malicious program called ls in it.
  • There can be other, more nasty versions. For instance, creating a malicious script called sl and waiting for someone to mistype ls.   

Related Links

Tuesday 1 July 2014

Getting Started with MongoDB

Introduction

From Wiki

MongoDB (from "humongous") is a cross-platform document-oriented database. Classified as a NoSQL database, MongoDB eschews the traditional table-based relational database structure in favor of JSON-like documents with dynamic schemas (MongoDB calls the format BSON), making the integration of data in certain types of applications easier and faster. Released under a combination of the GNU Affero General Public License and the Apache License, MongoDB is free and open-source software.


Getting Started

  1. Download MongoDB from their website and install it. You have installer file for windows or zip file. Either way you should get MongoDB 2.6 Standard  folder installed. My folder location is C:\Program Files\MongoDB 2.6 Standard. You can find a bin file inside this folder. Add it to the %PATH% environment variable (windows) or export it by adding in .bashrc file(Linux).
  2. Next open command prompt and run MongoDB server. To do so execute command

    mongod --dbpath C:\Users\athakur\Softwares\MongoDB

    Replace the path after --dbpath with your path. It basically says where your db files will be stored. If you do not provide db path your server will not start and will show that dbpath was missing.


    After starting the server with --dbpath


    You may be asked to allow network access to mongo db. Provide the required access.

  3. Next start the client by typing

    mongoThat should open the Mongo shell.


    By default, mongo looks for a database server listening on port 27017 on the localhost interface. To connect to a server on a different port or interface, use the --port and --host options.
  4. Lets create a new database. Type the following command

    use mydb

    and then type

    db

    This should show mydb database. Now try doing

    show dbs

    Nothing? Surprised? Don't be. It is the way Mongo DB behaves. MongoDB will not permanently create a database until you insert data into that database.

    Note :
    Unlike MySQL database you do not create tables and then insert data. Infact there is no relational model here. You simply switch db using use dbName syntax and add data. When you actually add the data the database is created.

  5. Lets go ahead and insert some data in our database. First create documents doc1 and doc2 using

    doc1 = {name : "Aniket"}
    doc2 = {org : "openSourceForGeeks"}


    Then add these documents to the collection (lets call it testDataCollection) database using

    db.testDataCollection.insert( doc1 )
    db.testDataCollection.insert( doc2 )


        When you insert the first document, the mongod will create both the mydb database and the testDataCollection collection.

    You can view your collections by

    show collections

    Confirm that your testDataCollection collection is created.

    The mongo shell will return the list of the collections in the current (i.e. mydb) database. At this point, the only collection is testDataCollection . All mongod databases also have a system.indexes collection.

    Also confirm the database is created ( by show dbs).

  6. Data Stored in MongoDB is essentially JSON. If you wish to see the data in the collection you can use command

    db.testDataCollection.find()

  7. That;s all for basics of mongo db. We say how to create database, collections and insert data in it. We also saw how can we retrieve the data.


Important commands

  1. db - shows current db in use
  2. help - show help
  3. cls - clear screen
  4. exit - exit Mongo shell
  5. show dbs - Show list of databases
  6. use mydb - use some other database
  7. show collections - Show all collection for the db. 

Important Links

t> UA-39527780-1 back to top