Monday, October 21, 2013

Common git commands:


1. To cut a new branch from an existing one
       • git checkout -b "branch name"

2. To push the above created branch
       • git push –u origin “branch name”

3. To rename a branch 
       • git branch –m “old name” “new name”

4. To remove all the commits 
       • git reset –hard origin/branchName

5. To delete a branch (First remove remote)
       • git push origin :branchName

6. To delete a branch (Then Locally)
       • git branch –d branchName
       • git branch –D branchName (Forcefully)

7. To remove a file from staging area
       • git reset HEAD fileName

8. To remove commit 
  • git reset --hard HEAD
then
  • git push origin HEAD --force 

Monday, October 14, 2013

Replacing with new line in eclipse using regular expression:


Regular expression for the new line in eclipse:

For eg:

Convert from :

public String getAddress() {
              return address;
       }

To:

public String getAddress ()
{
return address;
}

Check the regular expression checkbox.

In Find:           \) \{

Replace with:           )\n\t\{
                                 OR
                              )\R\t\{










Saturday, May 11, 2013


To convert domain (POJO) object to Model (POJO) object

We can use spring converter but in that we need to create our own converter setting all the values.
So what required is i just need to put annotation on my domain and model objects and they should be mapped to each other. So instead of modelObj.setXXX(domainObj.getXXX) i want to use annotation.

So first I create a custom annotation:
Mapper.java
package main;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(value = ElementType.METHOD)
@Retention(value = RetentionPolicy.RUNTIME)
public @interface Mapper {
       String value();
}

My model:
Model.java
package main;

public class Model {
       private String firstname;
       private String lastName;
       private String age;
       private String place;
      
       public String getFirstname() {
              return firstname;
       }
      
       public String getLastName() {
              return lastName;
       }
       @Mapper(value="lastName")
       public void setLastName(String lastName) {
              this.lastName = lastName;
       }
       public String getAge() {
              return age;
       }

       public String getPlace() {
              return place;
       }
      
       public void setPlace(String place) {
              this.place = place;
       }
       @Mapper(value="firstname")
       public void setFirstname(String firstname) {
              this.firstname = firstname;
       }
       @Mapper(value="age")
       public void setAge(String age) {
              this.age = age;
       }
}

My Domain:
Domain.java:
package main;

public class Domain {
       private String firstname;
       private String lastName;
       private int age;
      
       @Mapper(value="age")
       public int getAge() {
              return age;
       }
       @Mapper(value="firstname")
       public String getFirstname() {
              return firstname;
       }
       public void setFirstname(String firstname) {
              this.firstname = firstname;
       }
       @Mapper(value="lastName")
       public String getLastName() {
              return lastName;
       }
       public void setLastName(String lastName) {
              this.lastName = lastName;
       }

       public void setAge(int age) {
              this.age = age;
       }

}

My Main class that also contains the convert method:
Main.java
package main;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

public class Main {

    public Object convert(Object source, Object target) {
       Object result = null;
        try {

              Class<? extends Object> myclass = source.getClass();
              Class<? extends Object> targetClass = target.getClass();
            //Use reflection to list methods and invoke them
            Method[] sourceMethods = myclass.getMethods();
            List<Method> methods = new ArrayList<>();
            Method[] tempTargetMethods = targetClass.getMethods();
            List<Method> targetMethods = new ArrayList<>();
            for(Method method : sourceMethods) {
              if(method.getName().startsWith("get"))
                {
                     methods.add(method);
                }
            }
            for(Method method : tempTargetMethods) {
              if(method.getName().startsWith("set"))
                {
                     targetMethods.add(method);
                }
            }
            for (int i = 0; i < methods.size(); i++) {
               for (int j = 0; j < targetMethods.size(); j++) {
                Mapper sourceAnnotations = (Mapper)methods.get(i).getAnnotation(Mapper.class);
                if(sourceAnnotations != null ){
                    try{
                   
                    Annotation annotation = methods.get(i).getAnnotation(Mapper.class);
                    Annotation targetAnnotation = targetMethods.get(j).getAnnotation(Mapper.class);
                    if(annotation instanceof Mapper){
                           if((Mapper)annotation != null && (Mapper)targetAnnotation != null){
                               if(((Mapper)annotation).value().equalsIgnoreCase(((Mapper)targetAnnotation).value())) {
                                  result = targetMethods.get(j).invoke(target, new Object[] {  String.valueOf(methods.get(i).invoke(source)) });
                                  break;
                           }
                            }
                    }
                    }catch(Exception e){
                        e.printStackTrace();
                    }
                }
            }
        }
            result = target;
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return result;
    }

    public static void main(String[] args) throws Exception {
       Domain source = new Domain();
       Model target = new Model();
       source.setFirstname("sourceName");
       source.setAge(55);
       source.setLastName("sourceLastName");
       Main myMain = new Main();
       try{
              Model articleModel = (Model)myMain.convert(source, target);
              System.out.println("Main:"+articleModel.getLastName());
              System.out.println("Main:"+articleModel.getAge());
              System.out.println("Main:"+articleModel.getFirstname());
       }
       catch(Exception e) {
              e.printStackTrace();
       }
    }
}

Sunday, February 10, 2013

Export to PDF using spring 3.2 & itextpdf-5.3.4


We used to extends AbstractPdfView an override the method protected void buildPdfDocument(Map model, Document document, PdfWriter writer, HttpServletRequest   request, HttpServletResponse response), But not anymore if we are using latest itextpdf Library. So in this class there is nothing spring specific, the spring in title is misnomer.

Controller class:

GeneratePdf.java :

package com.spring.package.controller;

import java.io.File;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.core.io.FileSystemResource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.itextpdf.text.Document;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;

@Controller
public class GeneratePdf{
      
       @RequestMapping(value = "/report.htm")
       public void pdfReport(ModelMap model, HttpServletResponse response, HttpServletRequest     request, OutputStream outputStream) throws Exception
       {
              response.setContentType("application/pdf");
              response.setHeader("Content-Disposition", "attachment; filename=file.pdf");
             
              Document document = new Document();
              PdfWriter.getInstance(document, outputStream);
              document.open();

              document.addTitle("Bank Statement");
              document.addSubject("Bank Statement");
              document.addKeywords("Report, PDF, iText");
              document.addAuthor("Satyam");
              document.addCreator("Satyam");

              document.add(new Paragraph(" "));
              document.add(new Paragraph(" "));
              document.add(new Paragraph(" "));

              Map<String,String> data = new HashMap<String,String>();
              data.put("1/20/2010", "$100,000");
              data.put("1/21/2010", "$200,000");
              data.put("1/22/2010", "$300,000");
              data.put("1/23/2010", "$400,000");
              data.put("1/24/2010", "$500,000");
             
              PdfPTable  table = new PdfPTable(2);
              table.addCell("Month");
              table.addCell("Amount");
             
              for (Map.Entry<String, String> entry : data.entrySet()) {

                     table.addCell(entry.getKey());
                     table.addCell(entry.getValue());
                    
        }
             
              document.add(table);
              document.close();
             
       }
}

In this method we can modularize the creation of pdf in some other utility class and will call it in our controller.

Call the above controller from your jsp by three ways:

1.  Form Submit
<form:form method="POST" commandName="user" action="report.htm">
       <table>
              <tr><td colspan="2"><input type="submit" value="show pdf"></div></td></tr>
       </table>
</form:form>

2. Ajax Call
<input type="button" value="Generate Pdf" onclick="doAjaxPost()">

Script Entry :

function doAjaxPost() { 
         // get the form values 
         var name = $('#name').val();
         var data;
         var url = "/SpringExportPdf/report.htm";
         $.ajax({

                type: "POST", url: url,
                data: "name=" + name, success: function(response, status, xhr){
                  var ct = xhr.getResponseHeader("content-type") || "";
                  if (ct.indexOf('xml') > -1) {
                         alert("xml");
                    // handle xml here
                  }
                  if (ct.indexOf('pdf') > -1) {
                     window.open(url);
                     //alert("pdf");
                  }   
                },
                   error: function(error, status){
                     window.alert("Problem retrieving PDF.\nThe error status is: " + status);
                 }
              });
       } 

For those who are trying to generate or retrieve the pdf file from ajax call must know that in the end you will have to hit the GET request only because ajax response only gives you text.

3.  Simple Get Call

<a href="/SpringExportPdf/report.htm">Show Pdf</a>


And we are done.