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.]

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

<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>

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"

        enctype="multipart/form-data">

        

        <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.  
  • But 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.

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.

Important Links

t> UA-39527780-1 back to top