Wednesday 21 August 2013

First Spring-3 RESTFull web services

This tutorial is for the beginners who are new to Spring RestFull web services


The Development Of Spring restfull web services are as follows -

Step 1- 

Make a project directory as show in figure with Selecting new project


Step 2- Add jars show in figure , Here jaxb-api-2.2.3.jar ,jackson-all-1.6.1.jar, commons-logging-1.1.jar and jars for spring -3 


Step-3 :

Make dispatcher-servlet.xml as show below code

****************************start*************************************************

<?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:util="http://www.springframework.org/schema/util"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:dwr="http://www.directwebremoting.org/schema/spring-dwr"
xmlns:lang="http://www.springframework.org/schema/lang"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://cxf.apache.org/configuration/beans http://cxf.apache.org/schemas/configuration/cxf-beans.xsd
http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-3.0.xsd
http://www.directwebremoting.org/schema/spring-dwr http://www.directwebremoting.org/schema/spring-dwr-3.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<!-- Annotation Based MVC Config Setup-->
<mvc:annotation-driven />
<context:annotation-config />
<context:component-scan base-package="com.webservice.controller.**" />
<!-- View Resolver Support For JSON & JSP at one place :-) -->
<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
  <property name="mediaTypes">
    <map>
      <entry key="html" value="text/html"/>
      <entry key="json" value="application/json"/>
    </map>
  </property>
   <property name="viewResolvers">
 <list>
   <bean 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>
 </list>
</property>
  <property name="defaultViews">
    <list>
      <bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView">
        <property name="prefixJson" value="true"/>
      </bean>
    </list>
  </property>
  <property name="order" value="2" />
</bean> 
</beans>

*********************************end*****************************************

Step 4-

Enter url for both .json as well as .htm entries in web.xml

*********************************start****************************************

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>SpringWebServiceDemo</display-name>
 <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <welcome-file-list>
  
    <welcome-file>home.jsp</welcome-file>
   
  </welcome-file-list>
  
  
  <context-param>
    <param-name>contextConfigLocation</param-name>
      <param-value>/WEB-INF/app-config.xml </param-value>
  </context-param>
  <servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>
              org.springframework.web.servlet.DispatcherServlet
         </servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.htm</url-pattern>
<url-pattern>*.json</url-pattern>
</servlet-mapping>
</web-app>

***********************end***************************************************

step 5--

Write controller for your web service

****************************start **********************************************

package com.webservice.controller;

import java.util.Date;
import java.util.Map;

import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;



@Controller
@RequestMapping("/my/neww")
public class MyfirstController {
@RequestMapping(value = "/my-new-service.json", method = RequestMethod.GET)
public @ResponseBody
Map<String, Object> topReadBook(Map<String, Object> modelMap, @RequestParam(value = "tenantId", required = false) Integer tenantId,
@RequestParam(value = "pageNo", required = false) Integer pageNo, @RequestParam(value = "recordsPerPage", required = false) Integer recordsPerPage,
@RequestParam(value = "schoolId", required = false) Integer schoolId,
@RequestParam(value = "fromDate", required = false) @DateTimeFormat(pattern = "MMM-dd-yyyy") Date fromDate,
@RequestParam(value = "toDate", required = false) @DateTimeFormat(pattern = "MMM-dd-yyyy") Date toDate) {
   String name="hi you have made new service !!!";
modelMap.put("data",name );

return modelMap;
}

}
***********************************end*************************************

default jsp i.e home.jsp

********************************start****************************************

<%@ 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">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Welcome to Spring web service</title>
</head>
<body>
<h1>Welcome to Spring web service</h1>
</body>
</html>
*********************************end*****************************************


run and see the results
















Thanks and enjoy, the joy of coding


Friday 2 August 2013

Fusion Charts Using Json Data

 fusioncharts.jsp

*********************************************************************************

<html>
  <head>        
    <title>My First chart using FusionCharts XT - JSON data URL</title>         
    <script type="text/javascript" src="FusionCharts/FusionCharts.js"></script>
  </head>   
  <body>     
    <div id="chartContainer">FusionCharts XT will load here!</div>          
    <script type="text/javascript"><!--         

      var myChart = new FusionCharts( "FusionCharts/Column3D.swf", 
                   "myChartId", "400", "300", "0" );
      myChart.setJSONUrl("Data.json");
      myChart.render("chartContainer");
      
    // -->     
    </script>      
  </body> </html>


Put this file parallel to fusion charts folder containing  Column3D.swf with name FusionCharts.

Now make a new file

Data.json

{ 
    "chart": { 
          "caption" : "Weekly Sales Summary" ,
          "xAxisName" : "Week",
          "yAxisName" : "Sales",
          "numberPrefix" : "$"
    },
        
    "data" : 
     [
          { "label" : "Week 1", "value" : "14400" },
          { "label" : "Week 2", "value" : "19600" },
          { "label" : "Week 3", "value" : "24000" },
          { "label" : "Week 4", "value" : "15700" }
     ]
}

or

you can provide this json either by url service or json directly

in jsp

<html>
  <head>        
    <title>My First chart using FusionCharts XT - JSON data URL</title>         
    <script type="text/javascript" src="FusionCharts/FusionCharts.js"></script>
  </head>   
  <body>     
    <div id="chartContainer">FusionCharts XT will load here!</div>          
    <script type="text/javascript"><!--         

      var myChart = new FusionCharts( "FusionCharts/Column3D.swf", 
                   "myChartId", "400", "300", "0" );
      myChart.setJSONUrl(service url);
      myChart.render("chartContainer");
      
    // -->     
    </script>      
  </body> </html>










Using Fusion Charts in java Web Application

Jar Download : FusionChart Jar
To be kept parallel to Web-Inf :  FusionChart Folder

BasicChart.jsp
****************************Start********************************************

<html>
    <head>
        <title>My First FusionCharts</title>
        <SCRIPT LANGUAGE="Javascript" SRC="../FusionCharts/FusionCharts.js"></SCRIPT>       
    </head>
    <body bgcolor="#ffffff">
         
        First Way :
         
        <object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
                codebase="<%=request.getContextPath()%>/FusionCharts/swflash.cab#version=8,0,0,0"
                width="900" height="300" id="Column3D" >
            <param name="movie" value="<%=request.getContextPath()%>/FusionCharts/FCF_Column3D.swf" />
            <param name="FlashVars" value="&dataURL=Data.xml&chartWidth=900&chartHeight=300">
            <param name="quality" value="high" />
            <embed src="<%=request.getContextPath()%>/FusionCharts/FCF_Column3D.swf"
                   flashVars="&dataURL=Data.xml&chartWidth=900&chartHeight=300"
                   quality="high" width="900" height="300"
                   name="Column3D" type="application/x-shockwave-flash"
                   pluginspage="http://www.macromedia.com/go/getflashplayer" />
        </object>
             <hr/>
              
        Second Way :
              
             <%
                String strXML="";
                strXML += "<graph caption='Monthly Unit Sales' xAxisName='Month' yAxisName='Units' decimalPrecision='0' formatNumberScale='0'>";
                strXML += "<set name='Jan' value='445' color='AFD8F8'/>";
                strXML += "<set name='Feb' value='857' color='F6BD0F'/>";
                strXML += "<set name='Mar' value='671' color='8BBA00'/>";
                strXML += "<set name='Apr' value='494' color='FF8E46'/>";
                strXML += "<set name='May' value='761' color='008E8E'/>";
                strXML += "<set name='Jun' value='960' color='D64646'/>";
                strXML += "<set name='Jul' value='629' color='8E468E'/>";
                strXML += "<set name='Aug' value='622' color='588526'/>";
                strXML += "<set name='Sep' value='376' color='B3AA00'/>";
                strXML += "<set name='Oct' value='494' color='008ED6'/>";
                strXML += "<set name='Nov' value='761' color='9D080D'/>";
                strXML += "<set name='Dec' value='960' color='A186BE'/>";
                strXML += "</graph>";
             %>
             <jsp:include page="FusionChartsRenderer.jsp" flush="true">
                <jsp:param name="chartSWF" value="/FusionCharts/Pie3D.swf" />
                <jsp:param name="strURL" value="" />
                <jsp:param name="strXML" value="<%=strXML %>" />
                <jsp:param name="chartId" value="productSales" />
                <jsp:param name="chartWidth" value="600" />
                <jsp:param name="chartHeight" value="300" />
                <jsp:param name="debugMode" value="false" />
                <jsp:param name="registerWithJS" value="false" />
            </jsp:include>
        <h1>this is a sample</h1>
    </body>
</html>

*********************************************************************************

                                                         preview



Data.xml
****************************Start********************************************
<graph caption='Monthly Sales Summary' subcaption='For the year 2006'
xAxisName='Month' yAxisName='Sales' numberPrefix='$'>
    <set name='January' value='22222' />
    <set name='February' value='19800' />
    <set name='March' value='21800' />
    <set name='April' value='23800' />
    <set name='May' value='29600' />
    <set name='June' value='27600' />
    <set name='July' value='31800' />
    <set name='August' value='39700' />
    <set name='September' value='37800' />
    <set name='October' value='21900' />
    <set name='November' value='32900' />
    <set name='December' value='39800' />

</graph>
****************************************************************************************

FusionChartsRenderer.jsp
****************************Start********************************************

  String chartSWF = request.getContextPath() +request.getParameter("chartSWF");

            String strURL = request.getParameter("strURL");
            String strXML = request.getParameter("strXML");
            String chartId = request.getParameter("chartId");
            String chartWidthStr = request.getParameter("chartWidth");
            String chartHeightStr = request.getParameter("chartHeight");
            String debugModeStr = request.getParameter("debugMode");
            String registerWithJSStr = request.getParameter("registerWithJS");
            int chartWidth = 600;
            int chartHeight = 300;
            boolean debugMode = false;
            boolean registerWithJS = false;
            int debugModeInt = 0;
            int regWithJSInt = 0;
            if (null != chartWidthStr && !chartWidthStr.equals("")) {
                chartWidth = Integer.parseInt(chartWidthStr);
            }
            if (null != chartHeightStr && !chartHeightStr.equals("")) {
                chartHeight = Integer.parseInt(chartHeightStr);
            }
            if (null != debugModeStr && !debugModeStr.equals("")) {
                debugMode = new Boolean(debugModeStr).booleanValue();
                debugModeInt = boolToNum(new Boolean(debugMode));
            }
            if (null != registerWithJSStr && !registerWithJSStr.equals("")) {
                registerWithJS = new Boolean(registerWithJSStr).booleanValue();
                regWithJSInt = boolToNum(new Boolean(registerWithJS));
            }
%>
<div id='<%=chartId%>Div' align='center'>Chart</div>
<script type='text/javascript'>
    var chart_<%=chartId%> = new FusionCharts("<%=chartSWF%>", "<%=chartId%>", "<%=chartWidth%>", "<%= chartHeight%>", "<%= debugModeInt%>", "<%= regWithJSInt%>");
    <%
            if (strXML.equals("")) {
    %>
        //<!-- Set the dataURL of the chart-->
        chart_<%=chartId%>.setDataURL("<%=strURL%>");
    <%} else {%>
        // Provide entire XML data using dataXML method
        chart_<%=chartId%>.setDataXML("<%=strXML%>");
    <%}%>
        //<!-- Finally, render the chart.-->
        chart_<%=chartId%>.render("<%=chartId%>Div");
</script>
<%!
    /**
     * Converts a Boolean value to int value<br>
     *
     * @param bool Boolean value which needs to be converted to int value
     * @return int value correspoding to the boolean : 1 for true and 0 for false
     */
    public int boolToNum(Boolean bool) {
        int num = 0;
        if (bool.booleanValue()) {
            num = 1;
        }
        return num;
    }
%>

************************************************************************************