Tuesday, July 28, 2009

Java : Get all Dates/Days between range of start date and end date

This is Simple java program to get all dates with days between range of start date and end date. Here date format used dd/MM/yyyy however any time you can customize it to your desire format. In below program just provide input start date and end date and see output.


/* ParseDate.java */

import java.util.*;
import java.text.*;

public class ParseDate
{
public static void main(String[] args)
{
String strdate = "25/07/2009";//any start date

String enddate = "03/08/2009";//any end date

SimpleDateFormat formatterDate = new SimpleDateFormat("dd/MM/yyyy");

SimpleDateFormat formatterDay = new SimpleDateFormat("dd/MM/yyyy EEEE");

Date st = null;
Date ed = null;

try
{
st = formatterDate.parse(strdate);
ed = formatterDate.parse(enddate);
}
catch (ParseException e)
{
System.out.println("Parse Exception :"+e);
}

Calendar ss=Calendar.getInstance();
Calendar ee=Calendar.getInstance();


ss.setTime(st);
ee.setTime(ed);
ee.add(Calendar.DATE,1);//just incrementing end date by 1

String day = "";

while(!ss.equals(ee))
{
day = formatterDay.format(ss.getTime());

System.out.println(day);

ss.add(Calendar.DATE,1);
}

}
}

/********INPUT************/

String strdate = "25/07/2009";//any start date

String enddate = "03/08/2009";//any end date

/********OUTPUT**********/

25/07/2009 Saturday
26/07/2009 Sunday
27/07/2009 Monday
28/07/2009 Tuesday
29/07/2009 Wednesday
30/07/2009 Thursday
31/07/2009 Friday
01/08/2009 Saturday
02/08/2009 Sunday
03/08/2009 Monday

Monday, July 20, 2009

JSP: Develop simple WAP page

WAP stands for Wireless Application Protocol. Basically wap pages are made for mobile browser. Lets try to understand how to make wap pages using JSP

Few terms required to understand before starting for developing a WAP site

MSISDN
MSISDN stands for "Mobile Subscriber Integrated Services Digital Network Number" is nothing but phone number.

USER AGENT
A user agent is the client application used with a particular network protocol.
When you visit a Web page, your browser sends the user-agent string to the server
hosting the site that you are visiting. This string indicates which browser you
are using, its version number, and details about your system, such as operating
system and version. The Web server can use this information to provide content that
is tailored for your specific browser.With the help of user agen we can detect user phone type (handset).

X WAP PROFILE
X Wap profile is mostly a xml file which contains complete details of a particular
mobile phone.X Wap profile contain details like screen size, midpi etc. etc.

Few examples of X Wap profile

Nokia 3110c"http://nds1.nds.nokia.com/uaprof/N3110cr100.xml"
NokiaE71"http://nds1.nds.nokia.com/uaprof/NE71-1r100.xml"
SonyEricssonK750c"http://wap.sonyericsson.com/UAprof/K750cR101.xml"
SAMSUNG-SGH-J210"http://wap.samsungmobile.com/uaprof/SGH-J210.xml"
LG-KG195"http://gsm.lge.com/html/gsm/LG-UAP-KG195-v0.1.xml"


if you want x wap profile of any handset just mail me at madan712@gmail.com


Lets look at a simple jsp code for a wap page.


<!DOCTYPE html PUBLIC "-//WAPFORUM//DTD XHTML Mobile 1.0//EN" "http://www.wapforum.org/DTD/xhtml-mobile10.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<%@ page import="java.net.*,java.io.*" %>
<%!
//This function is just used to get mobile Screen size
public static String getScreenSize(String x_wap_profile)
{
x_wap_profile = x_wap_profile.replaceAll("\"","");

String screen_size = "";

try
{
URL url= new URL(x_wap_profile);

URLConnection connection = url.openConnection();

BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));

String line = "";



while((line=in.readLine()) != null)
{
line = line.trim();
if(line.startsWith("<prf:ScreenSize>"))
{

line = line.replaceAll("<prf:ScreenSize>","");
line = line.replaceAll("</prf:ScreenSize>","");

screen_size = line;

break;
}
}

//closing resource
in.close();
connection=null;
}
catch(Exception ex)
{
//any default value
screen_size = "128x160";
}


//System.out.println("screen_size : "+screen_size);

return screen_size;
}
%>
<%
// get phone number
String phone_number = request.getHeader("x-nokia-msisdn");
if(phone_number==null)
phone_number = request.getHeader("x-msisdn");
if(phone_number==null)
phone_number = request.getHeader("X-msisdn");
if(phone_number==null)
phone_number = request.getHeader("X-MSISDN");
if(phone_number==null)
phone_number = request.getHeader("msisdn");
if(phone_number==null)
phone_number = request.getHeader("Nokia-msisdn");

String user_agent = request.getHeader("USER-AGENT");

//String phone_type = user_user_agent.substring(0,user_user_agent.indexOf("/"));

String phone_type = "";

int in = user_agent.indexOf("/");
if(in > 0)
phone_type=user_agent.substring(0,in);

if(phone_type.toUpperCase().startsWith("MOZILLA") )
{
phone_type = user_agent.substring(user_agent.indexOf("Nokia"),user_agent.indexOf("/",user_agent.indexOf("Nokia")) );
}

String x_wap_profile = request.getHeader("x-wap-profile");

String screen_size = getScreenSize(x_wap_profile);
%>
<body align='left' topmargin='0' bottommargin='0' leftmargin='0' rightmargin='0' marginheight='0' marginwidth='0'>
<table border='1' cellspacing='0' cellpadding='0'>
<tr><td>Phone number</td><td><%= phone_number %></td></tr>
<tr><td>User agent</td><td><%= user_agent %></td></tr>
<tr><td>Phone type</td><td><%= phone_type %></td></tr>
<tr><td>X wap profile</td><td><%= x_wap_profile %></td></tr>
<tr><td>Screen size</td><td><%= screen_size %></td></tr>
</table>
</body>
</html>

Output of Nokia 3110c handset

Phone number919892558621
User agentNokia3110c/2.0(04.91)Profile/MIDP-2.0Configuration/CLDC-1.1
Phone typeNokia3110c
X wap profile"http://nds1.nds.nokia.com/uaprof/N3110cr100.xml"
Screen size128x160



Now two questions might have arise in your mind -
1. How do i test and debug these codes?
2. Mobiles screen are of different sizes, how same page get render in all handsets?

How to test and debug wap pages?

Answer of first question is simple, there is a tool available call Modify Headers which you can set in Mozilla fire fox browser by searching Add-ons. Just go to Tools -> Add-ons -> Get Add-ons. Search for Modify Headers.



Above shown screen shot show Modify Headers Add-ons, You can view it by clicking on Tools -> modify Headers.

Now atleast add two headers like
1. Name : user-agent
Value : Nokia3110c/Xyz (any handset name)
2. Name : msisdn
Value : 919892858621 (any mobile number)

Optionally u can also set x-wap-profile.

This is how you will get all features tested on browser same as it will work on mobile phone.

How to handle different screen sizes on different handsets?

Answer of the second question is still remaining. Here is how it goes...

Mostly Horizontal scroll is not allowed in a WAP page, to avoid you need to specify width of the page. if you modify above used function getScreenSize, you will get width of that particular handset. Different Screen sizes available are :

96x65,128x96,128x128,128x144,128x160,176x144,176x208,176x220,208x144,208x208,
208x320,240x320,320x240,322x320,350x380,352x416,360x640,400x340,400x400,505x190.

Lets look at another jsp code.

<!DOCTYPE html PUBLIC "-//WAPFORUM//DTD XHTML Mobile 1.0//EN" "http://www.wapforum.org/DTD/xhtml-mobile10.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<%@ page import="java.net.*,java.io.*" %>
<%!
//This function is just used to get screen width
public static String getScreenWidth(String x_wap_profile)
{
x_wap_profile = x_wap_profile.replaceAll("\"","");

String screen_size = "";

String width = "";

try
{
URL url= new URL(x_wap_profile);

URLConnection connection = url.openConnection();

BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));

String line = "";



while((line=in.readLine()) != null)
{
line = line.trim();
if(line.startsWith("<prf:ScreenSize>"))
{

line = line.replaceAll("<prf:ScreenSize>","");
line = line.replaceAll("</prf:ScreenSize>","");

screen_size = line;

break;
}
}

//closing resource
in.close();
connection=null;
}
catch(Exception ex)
{
//any default
screen_size = "128x160";
}

width=screen_size.substring(0,screen_size.indexOf("x"));


//System.out.println("screen_size : "+screen_size);

return width;
}
%>
<%

String user_agent = request.getHeader("USER-AGENT");

//String phone_type = user_user_agent.substring(0,user_user_agent.indexOf("/"));

String phone_type = "";

int in = user_agent.indexOf("/");
if(in > 0)
phone_type=user_agent.substring(0,in);

if(phone_type.toUpperCase().startsWith("MOZILLA") )
{
phone_type = user_agent.substring(user_agent.indexOf("Nokia"),user_agent.indexOf("/",user_agent.indexOf("Nokia")) );
}

String x_wap_profile = request.getHeader("x-wap-profile");

String width = getScreenWidth(x_wap_profile);
%>
<body align='left' topmargin='0' bottommargin='0' leftmargin='0' rightmargin='0' marginheight='0' marginwidth='0' style="width: <%=width%>px;">
<table border='1' cellspacing='0' cellpadding='0' width='<%=width%>'>
<tr><td>Phone: <%= phone_type %></td></tr>
<tr><td>Screen width : <%= width %></td></tr>
<tr><td>Put your contents here Put your contents here Put your contents here Put your contents here Put your contents here Put your contents here Put your contents here Put your contents here Put your contents here Put your contents here Put your contents here </td></tr>
</table>
</body>
</html>


Output on different Handsets

Phone: Nokia3110c
Screen width : 128
Put your contents here Put your contents here Put your contents here Put your contents here Put your contents here Put your contents here Put your contents here Put your contents here Put your contents here Put your contents here Put your contents here
Phone: Nokia6600
Screen width : 176
Put your contents here Put your contents here Put your contents here Put your contents here Put your contents here Put your contents here Put your contents here Put your contents here Put your contents here Put your contents here Put your contents here
Phone: NokiaN82
Screen width : 240
Put your contents here Put your contents here Put your contents here Put your contents here Put your contents here Put your contents here Put your contents here Put your contents here Put your contents here Put your contents here Put your contents here
Phone: NokiaE71
Screen width : 320
Put your contents here Put your contents here Put your contents here Put your contents here Put your contents here Put your contents here Put your contents here Put your contents here Put your contents here Put your contents here Put your contents here


My personal experience

Working with WAP pages (mobile browser) is more difficult than working with WEB pages (windows browser).

Few things to be noted to develop a wap pages, all tags must have its closing tags like <td>..</td> even for a single tags must be like <br/> and not <br>, <br> is wrong when you work on wap page.

All quotes must have be in single quotes '' and not double quotes "" for eg. <td colspan='2'> and not <td colspan="2">

ie. Follow XHTML convension

Also don't forget to include DOCTYPE

<!DOCTYPE html PUBLIC "-//WAPFORUM//DTD XHTML Mobile 1.0//EN" "http://www.wapforum.org/DTD/xhtml-mobile10.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

Because its painful when same things works on one phone and does not works on other phone. Also many other problems arises when you work on wap pages.

Plz do write your comments, any queries/help plz write me on madan712@gmail.com

Thursday, July 16, 2009

Java: Simple URLConnection program

Simple java program to Read from a URLConnection

/* SimpleURLConnection.java */

import java.net.*;
import java.io.*;

public class SimpleURLConnection
{
public static void main(String[] args) throws Exception
{
URL url= new URL("http://10.10.2.215/URLConnection/Test.jsp");//provide proper url

URLConnection connection = url.openConnection();

BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));

String line = "";

while((line=in.readLine()) != null)
{
System.out.println(line);
}

//closing resource
in.close();
connection=null;
}
}


Same above example in detail

/* SimpleURLConnection.java */


import java.net.URLConnection;
import java.net.URL;
import java.io.BufferedReader;
import java.io.InputStreamReader;

import java.net.MalformedURLException;
import java.io.IOException;

public class SimpleURLConnection
{
public static void main(String[] args)
{
//Class URL represents a Uniform Resource Locator, a pointer to a "resource" on the World Wide Web.
URL url = null;
/*The abstract class URLConnection is the superclass of all classes that represent a communications
link between the application and a URL. Instances of this class can be used both to read from and to
write to the resource referenced by the URL*/
URLConnection connection = null;
BufferedReader in = null;

try
{
//Creates a URL object from the String representation.
url= new URL("http://10.10.2.215/URLConnection/Test.jsp");

}
catch (MalformedURLException ex)
{
//If the string specifies an unknown protocol.
System.out.println(ex);
}

try
{
//Returns a URLConnection object that represents a connection to the remote object referred to by the URL.
connection = url.openConnection();

in = new BufferedReader(new InputStreamReader(connection.getInputStream()));

String line = "";

while((line=in.readLine()) != null)
{
System.out.println(line);
}
//closing BufferedReader
in.close();
}
catch (IOException ex)
{
//if an I/O exception occurs.
System.out.println(ex);
}

connection=null;
}
}

MS SQL: Join tables of different database

Assume you have two database, Db1 and Db2.

Employee table is in Db1 and Department in Db2

Query:

select emp_name, dept_name from Db1.dbo.Employee a, Db2.dbo.Department b where a.dept_id = b.dept_id

Syntax is Database name followed by .dbo. followed by table name

eg. Db1.dbo.Employee

Similarly you can use above syntax for any type of query.

Saturday, July 11, 2009

Javascript : Creating Back button

Back buttons are used to return to the previous page. This is the same as using the back button on your browser.

You can use below codes in HTML/JSP etc pages.

Creating Back Button

<FORM><INPUT TYPE="button" VALUE="Back" onClick="history.go(-1);return true;"> </FORM>

The javascript:history.go(-1) code displays the previous page.Change the value of -1 to any number of pages you would like to send your visitors back

Instead of Button you can also used it for any link or image.

An image used as back button.

<A HREF="javascript:history.go(-1)">
<IMG SRC="images/back.gif"
BORDER="0"></A>


A standard link as back button.

<A HREF="javascript:history.go(-1)"> [Go Back]</A>



MS SQL: Get Day/Month of Date



1.This is simple query, which gives Date
select GETDATE()
output:
2009-07-11 19:56:18.543

2.This query give day and month
select DATENAME(dw,GETDATE()) as Day, DATENAME(mm,GETDATE()) as Month
output:
Saturday July

3:This query gives individual date, month, year
select DAY(GETDATE()) as Date,MONTH(GETDATE()) as Month,YEAR(GETDATE()) as Year
output:
11 7 2009


Friday, July 10, 2009

Java: URL Encoder/Decoder

/* Simple java program for Encoding and Decoding URL
Below is complete tested code, directly you can run this program
*/

//SimpleURLEncoder.java

import java.net.*;

public class SimpleURLEncoder
{
public static void main(String[] args) throws Exception
{
String userUrl = "http://10.10.3.24/Product.jsp?username=scott&password=tiget";
URL url = url = new URL(userUrl);
String encodedUrl = encodedUrl = URLEncoder.encode(url.toString(),"UTF-8");
String decodedUrl = decodedUrl = URLDecoder.decode(encodedUrl,"UTF-8");

System.out.println("userUrl : "+userUrl);

System.out.println("encodedUrl : "+encodedUrl);
System.out.println("decodedUrl : "+decodedUrl);

}
}


/***************OUTPUT*****************/


userUrl : http://10.10.3.24/Product.jsp?username=scott&password=tiget
encodedUrl : http%3A%2F%2F10.10.3.24%2FProduct.jsp%3Fusername%3Dscott%26password
%3Dtiget
decodedUrl : http://10.10.3.24/Product.jsp?username=scott&password=tiget




//Same above example in detail


import java.net.*;//for URL
import java.io.*;//for UnsupportedEncodingException

public class SimpleURLEncoder
{
public static void main(String[] args)
{
String userUrl = "http://10.10.3.24/Product.jsp?username=scott&password=tiget";
URL url = null;
String encodedUrl = "";
String decodedUrl = "";

try
{
//Creates a URL object from the String representation.
url = new URL(userUrl);
}
catch (MalformedURLException ex)
{
//If the string specifies an unknown protocol.
System.out.println("MalformedURLException : "+ex);
}

try
{
encodedUrl = URLEncoder.encode(url.toString(),"UTF-8");
//UTF-8 : The name of a supported character encoding.
//The World Wide Web Consortium Recommendation states that UTF-8 should be used. Not doing so may introduce incompatibilites.
}
catch (UnsupportedEncodingException ex)
{
//If the named encoding is not supported
System.out.println("UnsupportedEncodingException : "+ex);
}

try
{
decodedUrl = URLDecoder.decode(encodedUrl,"UTF-8");
}
catch (UnsupportedEncodingException ex)
{
//If the named encoding is not supported
System.out.println("UnsupportedEncodingException : "+ex);
}

System.out.println("userUrl : "+userUrl);

System.out.println("encodedUrl : "+encodedUrl);
System.out.println("decodedUrl : "+decodedUrl);

}
}