Sunday, August 19, 2012

Building JAVA Based Localized Web Applications

Posted by Shiva Gouraram | Sunday, August 19, 2012 | Category: | 8 comments


This tutorial describes how to develop your applications which can be available in different number of local languages like Hindi, Telugu, Tamil or any other language available in this world.
Dont you think your application if available in different languages attract the visitors or users which makes them easy to understand without learning or having trouble in learning and understanding only English???
Yes....to make it possible this is a tutorial which does not make use of any other 3rd party applications like Google Translator or Microsoft Translator in your application.
O.K let us start our tutorial,This tutorial is a simple tutorial which describes the conversion of one message into 2 different languages Telugu and Hindi.
After this tutorial you can develop your java based web applications for different languages.

Before describing the code i will explain few JAVA classes which helps to develop these kind of applications.

1) Locale Object:

Def: A Locale object represents a specific geographical, political, or cultural region. An operation that requires a Locale to perform its task is called locale-sensitive and uses the >Locale to tailor information for the user. For example, displaying a number is a locale-sensitive operation--the number should be formatted according to the customs/conventions of the user's native country, region, or culture.
i.e a Locale object can be used for specific country or region to get the country details like language,currency and percentages.
to know more click on the below link

Locale Object from Oracle website

2) ResourceBundle Object:


Resource bundles contain locale-specific objects. When your program needs a locale-specific resource, a String for example, your program can load it from the resource bundle that is appropriate for the current user's locale. In this way, you can write program code that is largely independent of the user's locale isolating most, if not all, of the locale-specific information in resource bundles.
This allows you to write programs that can:
  • be easily localized, or translated, into different languages
  • handle multiple locales at once
  • be easily modified later to support even more locale
to know more about ResourceBundle Class click on the below link


OK these are the 2 classes by which we are going to develop localized applications.


As i said i am going to develop an application which can be customized for 3 languages we need to have 3 text files generally called as properties file which contains name value pairs by which we can access them in our application.

open notepad or notepad++ and create three types of text file

1) Locale_en_EN.properties
2 )Locale_hi_HI.properties
3) Locale_te_TE.properties

Note:
Please paste these three files in classes folder of WEB-INF directory.

these three files holds the "HTML" equivalent values of Hindi and Telugu language code.
to generate HTML  equivalen  code for specific language we have few tools which generate the code according to given English input.Click on the below links to convert English to other languages which generates HTML code.

Telugu Converter            Hindi Converter 

for instance just paste this code in below files

Locale_hi_HI.properties 



 Locale_te_TE.properties 



Locale_en_EN.properties

OK now we have properties file which consists of equivalent code for the english message.

Now create a Dynamic Web Project in Eclipse and Create a java file "index.jsp" and "Locale.jsp".
index.jsp is the index page which displays the message in three languages and "Locale.jsp" is the page which is used to create HttpSession by which we can know which language is chosen by the user at this point of time.

index.jsp
---------------


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@page import="java.util.*"%>
<%
String locale = (String) session.getAttribute("locale");
if (locale == null)
locale = "en";
Locale c = new Locale(locale, locale);
ResourceBundle captions = ResourceBundle.getBundle("Locale", c);
%>
<!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>JSP Localization</title>
</head>
<body>
<div id="langholder" style="top:15px;">

<a href="Locale.jsp?lang=en">English</a>
<a href="Locale.jsp?lang=te">Telugu</a>
<a href="Locale.jsp?lang=hi">Hindi</a>
</div>
<center>
<%=captions.getString("msg")%>
</center>
</body>
</html>






Locale.jsp
-----------
<?xml version="1.0" encoding="ISO-8859-1" ?>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%
String lang = request.getParameter("lang");
if (lang != null) {
session.setAttribute("locale", lang);
}
response.sendRedirect("index.jsp");
%>

Preview:




Download Localization Example
That;s it friends...now you can develop applications for any number of localized language.





Friday, August 17, 2012

JSP database connectivity according to Model View Controller (MVC) Model 2

Posted by Shiva Gouraram | Friday, August 17, 2012 | Category: | 1 comments



After spending some time on JSP section of this forum as many before me, I come to the conclusion that we are in need of "proper" tutorial on this topic. This tutorial is not intended to teach you everything from top to bottom, it is just a starting point to show you what we mean by "DO NOT USE JSP FOR DIRECT DATABASE CONNECTIVITY!". In simple terms and examples I will try to explain the basics of MVC model 2. Therefore content has been kept as simple as possible to make it easier for beginners to grasp the basics without getting into a lot of application design jargon. That being said, there are many ways for this application being designed in a better manner and it's left as an exercise to the reader.

Read More here      Download as PDF

Saturday, August 11, 2012

Web Services Development using Eclipse, Apache CXF 2 Part-2

Posted by Shiva Gouraram | Saturday, August 11, 2012 | Category: | 1 comments

Hi TGMCians this is a second part of tutorial series of WebServices development using Eclipse and CXF2.
if you have not read the first part please read it here.

Web Services Development using Eclipse, Apache CXF 2

O.K...in this tutorial we are going to develop a servlet which acts as a client for the developed webservice.
this tutorial is not available in the internet...so i am trying to do that for TGMCians.
Before developing our you have to check whether your service deployed correctly in tomcat or not..for checking that point your browser to locate the URL 
here you will find all the available web services which are developed using CXF in your application.

You can find a screen like this where you will find your WebServices WSDL URL.Click on it.


After clicking on the link a WSDL file opens in the browser which is typically a XML file which contains the binding details of the web service its port numbers and other details.

Your WSDL File looks like the below one.

This XML file does not appear to have any style information associated with it. The document tree is shown below.
<?xml version="1.0" encoding="UTF-8"?>

<wsdl:definitions name="MultiplyWSService"

 targetNamespace="http://shiva.com/" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"

 xmlns:tns="http://shiva.com/" xmlns:xsd="http://www.w3.org/2001/XMLSchema"

 xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/">

 <wsdl:types>

  <xs:schema elementFormDefault="unqualified" targetNamespace="http://shiva.com/"

   version="1.0" xmlns:tns="http://shiva.com/" xmlns:xs="http://www.w3.org/2001/XMLSchema">

   <xs:element name="mul" type="tns:mul" />

   <xs:element name="mulResponse" type="tns:mulResponse" />

   <xs:complexType name="mul">

    <xs:sequence>

     <xs:element name="arg0" type="xs:int" />

     <xs:element name="arg1" type="xs:int" />

    </xs:sequence>

   </xs:complexType>

   <xs:complexType name="mulResponse">

    <xs:sequence>

     <xs:element name="return" type="xs:int" />

    </xs:sequence>

   </xs:complexType>

  </xs:schema>

 </wsdl:types>

 <wsdl:message name="mulResponse">

  <wsdl:part name="parameters" element="tns:mulResponse">

  </wsdl:part>

 </wsdl:message>

 <wsdl:message name="mul">

  <wsdl:part name="parameters" element="tns:mul">

  </wsdl:part>

 </wsdl:message>

 <wsdl:portType name="MulSEI">

  <wsdl:operation name="mul">

   <wsdl:input name="mul" message="tns:mul">

   </wsdl:input>

   <wsdl:output name="mulResponse" message="tns:mulResponse">

   </wsdl:output>

  </wsdl:operation>

 </wsdl:portType>

 <wsdl:binding name="MultiplyWSServiceSoapBinding" type="tns:MulSEI">

  <soap:binding style="document"

   transport="http://schemas.xmlsoap.org/soap/http" />

  <wsdl:operation name="mul">

   <soap:operation soapAction="urn:Mul" style="document" />

   <wsdl:input name="mul">

    <soap:body use="literal" />

   </wsdl:input>

   <wsdl:output name="mulResponse">

    <soap:body use="literal" />

   </wsdl:output>

  </wsdl:operation>

 </wsdl:binding>

 <wsdl:service name="MultiplyWSService">

  <wsdl:port name="MultiplyWSPort" binding="tns:MultiplyWSServiceSoapBinding">

   <soap:address

    location="http://localhost:9083/WebServices/services/MultiplyWSPort" />

  </wsdl:port>

 </wsdl:service>

</wsdl:definitions>







Now we need to create a Servlet which invokes a web service method from a web browser.
Create a servlet Names "ServletClient" in "com.servlet" package.

package com.shiva.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.shiva.MulSEI;
import com.shiva.MultiplyWSService;

/**
 * Servlet implementation class ServletClient
 */
@WebServlet("/ServletClient")
public class ServletClient extends HttpServlet {
 private static final long serialVersionUID = 1L;

 /**
  * @see HttpServlet#HttpServlet()
  */
 public ServletClient() {
  super();
  // TODO Auto-generated constructor stub
 }

 /**
  * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
  */
 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  // TODO Auto-generated method stub


  MultiplyWSService service = new MultiplyWSService();//Creating 
  MulSEI port = service.getMultiplyWSPort(); 
  PrintWriter out=response.getWriter();
  
  out.println(port.mul(Integer.parseInt(request.getParameter("one")), Integer.parseInt(request.getParameter("two"))));  
  out.flush();



 }

 /**
  * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
  */
 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  // TODO Auto-generated method stub
 }

}




Here we have to notice three main statements which are used to Invoke a webService method.

 1) MultiplyWSService service = new MultiplyWSService();

Which is used to instantiate the servicing class of the Web Service ...here it is "MultiplyWSService".



2)MulSEI port = service.getMultiplyWSPort();

to get the port number of the WebService we have to call the "getMultiplyWSPort()" on the service object of "MultiplyWSService".



3)port.mul(Integer.parseInt(request.getParameter("one")), Integer.parseInt(request.getParameter("two")))

Here we are invoking the actual method of a WebServe which serves us...here we are calling mul method on the Service End Point Interface object "port".

That's it...we have now created our servlet which acts as web service client.


Now you can open this servlet to test whether we have developed correctly or not
http://localhost:9083/WebServices/ServletClient?one=3&two=5






Here you can see the actual communication between our client and server is in the form of SOAP messages which is an XML based protocol through which our application communicates to the server or a web service.

Aug 11, 2012 7:47:19 PM org.apache.cxf.service.factory.ReflectionServiceFactoryBean buildServiceFromWSDL
INFO: Creating Service {http://shiva.com/}MultiplyWSService from WSDL: http://localhost:9083/WebServices/services/MultiplyWSPort?wsdl
Aug 11, 2012 7:47:19 PM org.apache.cxf.services.MultiplyWSService.MultiplyWSPort.MulSEI
INFO: Inbound Message
----------------------------
ID: 6
Address: http://localhost:9083/WebServices/services/MultiplyWSPort
Encoding: UTF-8
Http-Method: POST
Content-Type: text/xml; charset=UTF-8
Headers: {Accept=[*/*], cache-control=[no-cache], connection=[keep-alive], Content-Length=[186], content-type=[text/xml; charset=UTF-8], host=[localhost:9083], pragma=[no-cache], SOAPAction=["urn:Mul"], user-agent=[Apache CXF 2.5.1]}
Payload: 35
--------------------------------------
Aug 11, 2012 7:47:19 PM org.apache.cxf.services.MultiplyWSService.MultiplyWSPort.MulSEI
INFO: Outbound Message
---------------------------
ID: 6
Encoding: UTF-8
Content-Type: text/xml
Headers: {}
Payload: 15
--------------------------------------
That's it we are now developed a WebService and a servlet based client for invoking the service from a web interface you can develop any type of applications by making this tutorial as base. Here I am providing you the sample web application which we have developed now..It is a war file just directly deploy it in tomcat server.

Download WebServices.war

Hope it will be helpful to everyone.

.



Web Services Development using Eclipse, Apache CXF 2

Posted by Shiva Gouraram | | Category: | 20 comments




Hi TGMCians,From past few days onwards I am hearing the word called “Web Services” in out TGMC forums and other places.Many of you are not aware of WebServices and how to develop them.
This is a tutorial for introduction of Web Services and how to implement that for our TGMC Project, It will be in normal language so that everyone can understand.
Our Ajenda:
1) What is Web Services
2) Web Services Generation by using Eclipse and CXF 2
3) Creating a Web Services Client.
4) Creating a Servlet as Web Services Client.
What is Web Services
Web Services are modern Client-Server  model to develop business applications, It is a specification given based on Service Oriented Architecture. Web Services is not a new technology rather it is a combination of technologies, concepts, specifications and protocols together to develop distributed applications.
                Web Services are…
o   Language Independent
o   Platform independent
o   Architecture Independent

o   Web Based Distributed Technology
o   Web services are application components
o   Web services communicate using open protocols
o   Web services are self-contained and self-describing
o   Web services can be discovered using UDDI
o   Web services can be used by other applications
o   XML is the basis for Web services
o   Web Services can convert your applications into Web-applications.
o   Web Services are published, found, and used through the Web.


Web Services are used mainly for intercommunication between the incompatible software applications. For ex: If we need to communicate to an application developed using ASP.net can be communicated with an application developed using JAVA technology because of Web Services.
I.e in webServices based distributed application server can be developed in any type of language and client can be developed in any language as the communication between the applications are based on XML technology.
Different Types of technologies, protocols used for developing a Web Service
                XML
                SOAP (Simple Object Oriented Protocol)
                HTTP
                WSDL
                UDDI
                JAVA/J2EE APIs
                . NET API’s etc.
In web Services we have different types of components
                Service Provider – It is the server application that contains interoperability business components, it is the actual component where we perform business logic and can be accessed by other clients.
                Service Client – It is the client application that invokes the business methods of the business component.
                Service Interface – It is a WSDL Document which contains all the data in the form of XML through which we can communicate to the service.
                Service Registry – It is a UDDI Registry in which our service is registered with the server.
O.K…. We got some info on what are webServices and where to use them, Now we move into the process of development of these observances with a sample application.
                               



Web Services Generation by using Eclipse, CXF 2 and Tomcat Server
Before developing our webservices we need to have a Eclipse IDE,Eclipse Web Tools Package installed in it and Apacke CXF2 WebServices Runtime.
If you don’t have Eclipse WTP installed in your Eclipse please add a repository to Eclipse Update Site and Install it “http://download.eclipse.org/webtools/repository/indigo/” and install it.
After Installing Eclipse WTP
Download Apache CXF2 and extract it in a temporary directory
Now Go to Window->Preferences->WebServices->CXF2.x Preferences
In CXF Runtime Tab click on “add” and specify the home directory of CXF(Just now which is extracted). Click on finish.
Now select the CXF Runtime and click on apply and click on OK.
That’s it now we can develop our WebService and Test it using a WebServices Explore.
Note:Please see the below images if u are not understood.





Developing our First WebService and its client to Test the Service.
We will now develop our first WebService which calculates the sum and multiplication of two numbers.
Note:Please follow step by step procedure with utmost care and same as I said..after few developments you can use your own comfortable way.

1)Create a Dynamic Web Project in Eclipse names “WebServices”(You can put your own name).


2) Select a target run time  (Here Tomcat 7) and In Configuration click on modifying and select CXF2 WebServices as Project Facets to our application. Click on OK and click on finish

3) Create a new class as I have shown below with a name “MultiplicationWS”,Default code will be generated as below.


4) Create a code for multiplication with a method name called “mul” with int a,int b as parameters.Right click on MultiplicationWS.java -> Web Services -> Create Web Service



5) Select Web Service Type as Bottom Up Java Bean Service and Check configuration… Check Server runtime, Web Service Runtime(If it is other than CXF2 as shown below….click on it and change runtime to CXF2) 

6)Click on Next Check Use a Service Endpoint Interface,Check on Create an SEI and name “MulSEI” and select the methods “mul” and click on next.

7)Leave this default and click on next.

8)Here you will select the type of SOAP binding and what to generate check on “generate wrapper and fault beans and generate WSDL”. Click on finish.
Note:Before doing this please ensure that the server is running.


9)Now to test the developed WebService right click on WebContent->wsdl->MultiplicationWS.wsdl->WebServices->Test With Web Services Explorer.

10) This is a web service explorer where we can find the end points and methods…click on mul method to test it.

11)Here provide parameters ‘a’ and ‘b’ and click on the go …now you can find the answer of multiplication of a & b;


12)Now we are going to create a JAVA Based client for testing our service… Click on WSD File ->WebServices->Generate Client

 13)click on next.
14)Here we have to specify the package name leave as default or change as I did…! and click next.

15)leave the default and click finish.

16)Now you can see the generated java files for client implementation in the package “com.shiva.client” and open “MulSEI_MultiplyWSPOrt_client.java” there u can find the  default values for arguments of methods…change the def values as you need and run that as java application…that’s it now we have created a service and tested with the client.




Hmm….the post became too long so I will stop this post here and I will continue next post which contains invoking a web service method using a servlet and passing data through a web based interface.

Please follow the second part of this tutorial which explains how to create a servlet as a client for our created webService.


Web Services Development using Eclipse, Apache CXF 2 Part-2

Please do comments if you have any doubts or any queries.