Friday 27 June 2014

Javascript date validation

Insert below script into Head


<script LANGUAGE="JavaScript">

<!-- Begin
function isValidDate(dateStr) {
// Checks for the following valid date formats:
// MM/DD/YY   MM/DD/YYYY   MM-DD-YY   MM-DD-YYYY
// Also separates date into month, day, and year variables
var datePat = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{2}|\d{4})$/;
// To require a 4 digit year entry, use this line instead:
// var datePat = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{4})$/;
var matchArray = dateStr.match(datePat); // is the format ok?
if (matchArray == null) {
alert("Date is not in a valid format.")
return false;
}
month = matchArray[1]; // parse date into variables
day = matchArray[3];
year = matchArray[4];
if (month < 1 || month > 12) { // check month range
alert("Month must be between 1 and 12.");
return false;
}
if (day < 1 || day > 31) {
alert("Day must be between 1 and 31.");
return false;
}
if ((month==4 || month==6 || month==9 || month==11) && day==31) {
alert("Month "+month+" doesn't have 31 days!")
return false
}
if (month == 2) { // check for february 29th
var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
if (day>29 || (day==29 && !isleap)) {
alert("February " + year + " doesn't have " + day + " days!");
return false;
   }
}
return true;  // date is valid
}
//  End -->
</script>


Insert below in the body


<center>
<form onSubmit="return isValidDate(this.date.value);">
Your Birth Date:  <input type=text name=date size=10 maxlength=10> (in MM/DD/YYYY format)
<input type=submit value="Submit Date">
</form>
</center>
</div>

Wednesday 25 June 2014

Number Formatting Using JavaScript

Tested Approach:
number.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,');Short solution #2:

Alternate Solution:
number.toFixed(2).replace(/./g, function(c, i, a) {
return i && c !== "." && !((a.length - i) % 3) ? ',' + c : c;
});

Example:
5543.45 will be converted to 5,543.45.

Wednesday 21 May 2014

HTTP Request by using JSTL

<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %>
<html>
  <head>
    <title>Page Data Example</title>
  </head>
  <body>
    <h3>&#160;</h3>
    <table border="1" width="539">
      <tr>
        <td colspan="2" width="529" bgcolor="#0000FF">
          <b>
            <font color="#FFFFFF" size="4">HTTP
            Request(pageContext.request.)</font>
          </b>
        </td>
      </tr>
      <tr>
        <td width="210">Access Method</td>
        <td width="313">&#160;
        <c:out value="${pageContext.request.method}" />
        </td>
      </tr>
      <tr>
        <td width="210">Authentication Type</td>
        <td width="313">&#160;
        <c:out value="${pageContext.request.authType}" />
        </td>
      </tr>
      <tr>
        <td width="210">Context Path</td>
        <td width="313">&#160;
        <c:out value="${pageContext.request.contextPath}" />
        </td>
      </tr>
      <tr>
        <td width="210">Path Information</td>
        <td width="313">&#160;
        <c:out value="${pageContext.request.pathInfo}" />
        </td>
      </tr>
      <tr>
        <td width="210">Path Translated</td>
        <td width="313">&#160;
        <c:out value="${pageContext.request.pathTranslated}" />
        </td>
      </tr>
      <tr>
        <td width="210">Query String</td>
        <td width="313">&#160;
        <c:out value="${pageContext.request.queryString}" />
        </td>
      </tr>
      <tr>
        <td width="210">Request URI</td>
        <td width="313">&#160;
        <c:out value="${pageContext.request.requestURI}" />
        </td>
      </tr>
    </table>
  </body>
</html>

Wednesday 14 May 2014

Reading xls and xlsx in java using POI jars

Below Jars are Required for implemnetation:
   dom4j-1.6.1.jar
   poi-3.10-FINAL-20140208.jar
   poi-ooxml-3.10-FINAL-20140208.jar
   poi-ooxml-schemas-3.10-FINAL-20140208.jar
   stax-api-1.0.1.jar
   xmlbeans-2.3.0.jar
   commons-lang-2.6.jar

import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
public class ExcelMainProgram {
 public static void main(String[] args) throws Exception {
  //
  // An excel file name. You can create a file name with a full path
  // information.
  //
  System.out.println(new Date());
  String filename = "Template.xls";//xls or xlsx
  //
  // Create an ArrayList to store the data read from excel sheet.
  //
  ArrayList<ArrayList<Cell>> sheetData = new ArrayList<ArrayList<Cell>>();
  FileInputStream fis = null;
  try {
   //
   // Create a FileInputStream that will be use to read the excel file.
   //
   fis = new FileInputStream(filename);
   //
   // Create an excel workbook from the file system.
   //
   Workbook workbook = WorkbookFactory.create(fis);;
   //
   // Get the first sheet on the workbook.
   //
   Sheet sheet = workbook.getSheetAt(0);
   //
   // When we have a sheet object in hand we can iterator on each
   // sheet's rows and on each row's cells. We store the data read
   // on an ArrayList so that we can printed the content of the excel
   // to the console.
   //
   Iterator<Row> rows = sheet.rowIterator();
   while (rows.hasNext()) {
    Row row =rows.next();
    if(row.getRowNum()==2)
    {continue;}
   }
   while (rows.hasNext()) {
    Row row =rows.next();
    Iterator<Cell> cells = row.cellIterator();
    System.out.println(row.getRowNum());
    ArrayList<Cell> data = new ArrayList<Cell>();
    while (cells.hasNext()) {
     Cell cell =  cells.next();
     data.add(cell);
    }
    sheetData.add(data);
   }
  } catch (IOException e) {
   e.printStackTrace();
  } finally {
   if (fis != null) {
    fis.close();
   }
  }
  showExelData(sheetData);
  System.out.println(new Date());
 }
 private static void showExelData(List<ArrayList<Cell>> sheetData) {
  //
  // Iterates the data and print it out to the console.
  //
  for (int i = 0; i < sheetData.size(); i++) {
   List<Cell> list = (List<Cell>) sheetData.get(i);
   for (int j = 0; j < list.size(); j++) {
    Cell cell =list.get(j);
    cell.setCellType(Cell.CELL_TYPE_STRING);//To get the cell value as string set the cell type as String
    System.out.print(cell.getStringCellValue() + "\t\t");
    if (j < list.size() - 1) {
     //System.out.print("SPACE");
    }
   }
   System.out.println("");
  }
 }
}

JavaScript/Ajax file upload with Jquery iframe post

Demo code
<script type="text/javascript" src="jQueryAjaxUpload.js"></script>

<form method="post" action="" enctype="multipart/form-data" id="example_form">
<input type="file" name="file"/>
<input type="submit"/>
</form>
<script>

$('#example_form').ajaxUpload({

post :
function (){

alert('posted');
},


complete :
function() {

alert('Upload complete');
}


});
</script> In case of using spring add below bean to spring beans
<bean id="multipartResolver"

class="org.springframework.web.multipart.commons.CommonsMultipartResolver">

<!-- one of the properties available; the maximum file size in bytes -->

<property name="maxUploadSize" value="1000000"/>
</bean>
 Follow the below link to download jQueryAjaxUpload.js file

http://www.jainaewen.com/files/javascript/jquery/iframe-post-form.html

Monday 3 February 2014

Create a Simple Spring MVC application along with Java Script or JQuery Datatables

The main reason for writing this tutorial is i found many examples online but all are either very basic or more complicated(i felt) so i wanted to share my knowledge in creating a sample spring MVC application that will display some data using JQuery Datatables.


Prerequisites :

        To do this tutorial we need to have any version eclipse that have an option to create dynamic web project and Apache Tomcat or Similar Server to run the application.
         

 Step by Step Procedure:
  1.  Lets start creating a dynamic web project by name Spring3MVC as shown in below image.
   


 2. Once we create the dynamic web project we have the skeleton for web app, we need to add the jars under lib folder of WEB-INF required for Spring that are mentioned in the Jars Required Section .

  3. You need to add the below entries in your web.xml to configure theDispatcher servlet of spring 

<display-name>Spring3MVC</display-name>
            <servlet>    <servlet-name>spring</servlet-name>    <servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class> <load-on-startup>1</load-on-startup>          </servlet>         <servlet-mapping> <servlet-name>spring</servlet-name> <url-pattern>*.action</url-pattern>       </servlet-mapping>


 if you observer the above XML code servlet name is specified as spring  which means  the spring container will search for the spring-servlet.xml  for loading the beans and other spring specific configurations.

4.  Create a file with name spring-servlet.xml  under WEB-INF folder and copy the below XML content to that file.

<?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:mvc="http://www.springframework.org/schema/mvc"
 xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">

 <context:component-scan base-package="com.sample.spring3mvc.controller" />

 <bean id="viewResolver"
  class="org.springframework.web.servlet.view.UrlBasedViewResolver">
  <property name="viewClass"
   value="org.springframework.web.servlet.view.JstlView" />
  <property name="prefix" value="/WEB-INF/pages/" />
  <property name="suffix" value=".jsp" />
 </bean>

 <bean id="productFacade"
  class="com.sample.spring3mvc.facade.impl.ProductFacadeImpl">
 </bean>
 <bean id="productDao"
  class="com.sample.spring3mvc.dao.impl.ProductDaoImpl">
 </bean>
 <mvc:annotation-driven />
 <mvc:annotation-driven>
  <mvc:message-converters>
    <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean>
  </mvc:message-converters>
</mvc:annotation-driven>
</beans>

5. Explanation of Entries in spring-servlet.xml
     <context:component-scan base-package="com.sample.spring3mvc.controller" /> : This entry will tell spring container where  the controller classes are available, all the files/packages under the above package will scanned for controllers.
   viewreolver bean  used to configure the prefix path and suffix extension of the views returned, so that we dont need to return these values in controller.
  <mvc:annotation-driven> : This entry is required if we are going to use any annotations in the bean classes. For example @Autowired.
  <mvc:message-converters>
    <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean>
  </mvc:message-converters> 
         The above entry is required for automatic conversion of normal objects to JSON when @Responsebody is used in any of the controller method which we will see in the later parts of the tutorial.
  The rest of the entries are just beans that we gonna use in application.

With this we are done with the configuration part and now we jump into real coding stuff.

Java and JSP Coding

  Create a index.jsp and place it under WebContent/webroot folder and the content would be something like this.

<html>
<head>     <title>Spring 3.0 MVC Series: Index - </title> </head> <body>     <a href="home.action"> Home</a> </body> </html>
    The below jsp would be a simple one if you do not want the Datatable in it.
 Create home.jsp under Web-INF/pages with the below content
  <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
<head>
<link
href="//datatables.net/download/build/nightly/jquery.dataTables.css"
rel="stylesheet" type="text/css" />
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script> <script src="//datatables.net/download/build/nightly/jquery.dataTables.js"></script> <meta charset=utf-8 /> <title>Spring MVC -DataTables Example</title> </head> <body> <div class="container"> <h2>Directly Loaded Data and added Datatable after load</h2> <table id="example" class="display" width="100%"> <thead> <tr> <th align="left">Name</th> <th align="left">Color</th> <th align="left">Price</th> </tr> </thead> <tfoot> <tr> <th align="left">Name</th> <th align="left">Color</th> <th align="left">Price</th> </tr> </tfoot> <tbody> <c:forEach items="${products}" var="product"> <tr> <td>${product.name}</td> <td>${product.color}</td> <td>${product.price}</td> </tr> </c:forEach> </tbody> </table> </div> <div class="container"> <h2>Loaded Data through ajax after page Load</h2> <table id="example1" class="display" width="100%"> <thead> <tr> <th align="left">Name</th> <th align="left">Color</th> <th align="left">Price</th> </tr> </thead> <tbody> <tr> <td></td> <td></td> <td></td> </tr> </tbody> </table> </div> </body> <script> $(document).ready(function() { var table1 = $('#example').DataTable(); var table2 = $('#example1').DataTable({ "ajax" : "${pageContext.request.contextPath}/getAllProds.action", }); }); </script>
</html>


If you observe in the above code we are directly referencing the javascript files it works only if u have internet connection. If you have downloaded those javascript files you can refer it locally as well.


Datatable usage in Spring Explanation

In the above jsp code i gave two examples for Datatable                  I. Applying Datatable to already loaded HTML table with id example1, the js code for this is as simple as $('#example').DataTable();                 II. In the second case we are directly loading data using an ajax call associated with Datatable which is  $('#example1').DataTable({ "ajax":"${pageContext.request.contextPath}/getAllProds.action"});                  but for doing the above step the data returned from the controller should be in a particular form of JSON as suggested in the site, which is done using getJSONForProd  method in the controller and returning aaData  from the controller.               For Live Examples on Datatables you can go here Live Datatables Example.
Controller Code    Create a Controller with name HomeController.java and use the below code.    ProductData is just a POJO .
   productFacade.getAllProducts() will return list of ProductData  which u can just mock it.
package com.sample.spring3mvc.controller;

import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.sample.spring3mvc.data.ProductData;
import com.sample.spring3mvc.facade.ProductFacade;


@Controller
public class HomeController {

    @RequestMapping("/home")
    public ModelAndView helloWorld(final Model model) {
        model.addAttribute("products",productFacade.getAllProducts());
        return new ModelAndView("home", "message", model);
    }
    @Autowired
 private ProductFacade productFacade;
 
    @ResponseBody
    @RequestMapping("/getAllProds")
 public Map<String, Object[]> getAllProducts()
 {
     List<ProductData> aaData= productFacade.getAllProducts();
  return Collections.singletonMap("aaData", getJSONForProd(aaData));
 }
  
    /**
     * I only want certain product info..
     */
     public Object[] getJSONForProd(Collection<ProductData> prods){
         Object[] rdArray = new Object[prods.size()];
         int i = 0;
         for(ProductData u:prods){
             // [ name, id,arn,groups ]
             Object[] us = new String[]{u.getName(),u.getColor(),Double.toString(u.getPrice())};
             rdArray[i] = us;
             i++;           
         }
         return rdArray;
     }
}

Run the application on server
  Once all the above steps are completed successfully you run the application by right clicking on the application as shown below
Run on server
Once you run you can see the associated server will start and then you can key in the below link in any of the qualified browser ex:Chrome and test: http://localhost:8080/Spring3MVC/


In case of any doubts/clarifications/Suggestions you are welcome @vinaytaj2006@gmail.com



Run Postman API remote or code or command line

POSTMAN is used to run the APIs generally. What if we want to create a collection in postman and run it from some other code or command l...