Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Friday, August 31, 2007

Sending emails through java

Just thought of linking my post containing "Code Sample" on Sun's SDN Share from here.

This is my post that answers this question: "How to send mails using Java API".

As on date, this post has received 1 comment saying "great work...", 0 freshness points, 22 goodness points, 5 votes saying "Very Cool" from java users all around the globe!

Thought this will be of use to you, the blog reader: you can visit this post here: http://www.sdnshare.com/view.jsp?id=535

Well, That's for now!
Samjosh

Tuesday, July 17, 2007

Paginate your Lists

Pagination is a bare necessity when it comes to handling lists in your web applications. And a good pagination always makes your application more user friendly. Google, the foremost search engine has one of the best Pagination for it. So this article helps you work out a pagination for your lists. Sit tight.



In this article, we will discuss the logic around paginating a list with the Google-Pagination like Look and Feel. As you would have noticed there in Google, the current page is always displayed at the centre of the links, unless otherwise it can't be so.



The scope of the article is just to give you a brief idea on how you can go about working a pagination around your data, and this does not cover retrieval of data and/or caching your data from the database. Right, Having known this let's make a list of requirements that our pagination has to meet.





Feature Analysis:



  • Links to show on the page
  • Showing previous and next Buttons when needed
  • Highlighting of current page number
  • Handling a random selection of page
  • Showing the current page link at the centre


(i) Defining the Properties:

Let's say right now we will allow only a maximum of 10 links to be displayed on a page. Clicking a link gets a page with say, 10 rows of data. So at a stretch a user can see 10 links/pages of 10 rows each. Doesn't matter if the total number of results is less than 100 rows of data. We will show them all. But if we get some 500 results as an example, we will not be showing 500/10=50 links. Rather we will show only the first 10 links. We will hold this in a global variable and this is a final one. Here goes the snippet:









public final static int TOTAL_LINKS = 5;



Deduce the total number of result pages to be listed. This in fact we will pre-determine at the beginning. Although we may have to change this at the later course. We will come back to that shortly, be rest assured.









public static int TOTAL_RESULT_PAGES = 9;


We also need to initialize certain variables like Current Page, Page to Start :the first link to show up on the page, Page to Finish :the last link to show up on the page, MidPosition :the middle link position.










private int CURR_PAGE = 1;

private int PAGE_TO_START = 1;

private final int MID_LINK_POSITION = (int) Math
.ceil((double) TOTAL_LINKS / 2);

private int PAGE_TO_FINISH = (TOTAL_RESULT_PAGES < TOTAL_LINKS) ? TOTAL_RESULT_PAGES
: PAGE_TO_START + (TOTAL_LINKS - 1);



Create the accessors/mutators for the above said variables.



(ii) Links to show on the page:

At the client side you have to know the starting-link/ending-link to display. You have to highlight the current page number while showing the links. The values for these variables have to be updated whenever you access any page links. The following code snippet demonstrates this.










public void getPagesToDisplay() {
if (TOTAL_RESULT_PAGES > TOTAL_LINKS) {
if (CURR_PAGE - MID_LINK_POSITION > 0) {
PAGE_TO_START = (CURR_PAGE - MID_LINK_POSITION) + 1;
PAGE_TO_FINISH = (PAGE_TO_START + TOTAL_LINKS) - 1;

while (PAGE_TO_FINISH > TOTAL_RESULT_PAGES) {
PAGE_TO_FINISH--;
PAGE_TO_START--;
}//end while
}//end if
if (CURR_PAGE <= MID_LINK_POSITION) {
PAGE_TO_START = 1;
PAGE_TO_FINISH = (PAGE_TO_START + TOTAL_LINKS) - 1;
}// end if
}//end if
}



(iii) Navigating through the Links

You need to track back one page on 'previous' action, and go forward one page from the current page for 'next' action. Then you have to update the links to display.











public void next() {
if (CURR_PAGE < TOTAL_RESULT_PAGES) {
CURR_PAGE++;
}
getPagesToDisplay();
}

public void previous() {
if (CURR_PAGE > 1) {
CURR_PAGE--;
}
getPagesToDisplay();
}



What if you want to access a page directly? Its so simple! Just set the current page number to the page you are going to access. Then don't forget to update the links to display.









public void gotoPage(int pageNumber) {
if (CURR_PAGE <= TOTAL_RESULT_PAGES) {
CURR_PAGE = pageNumber;
}// end if
getPagesToDisplay();
}



Before displaying Next/Previous links on your page, make sure they are available for you. This is a best practice.








public boolean hasNextPage() {
if (CURR_PAGE < TOTAL_RESULT_PAGES)
return true;
return false;
}

public boolean hasPreviousPage() {
if (CURR_PAGE > 1)
return true;
return false;
}



(iv) Handling page results

Using the currentPageNumber and pageSize, show the records on the page. I leave this as an exercise for you!



While this article guides you through a way of paginating your data, hundreds of open-source & commercial paging tools and tag libraries are available online. My favorite one is the Pager Tag Library. Other tools include the Display Tag Library among several others. Hope this helps and is of use to you.




EDIT:
JSP Part of the code.






<%
Pagination pagination = (Pagination) session.getAttribute("paginationCollection");

/**
* Display the Search results here
*
* <param> currentPageNumber
*
*
*/

// { //write the records here };



/**
* Displaying page navigation Links
*
*/

//get the value of PAGE_TO_START
int startPageNo = patientPage.getStartPageNumber();

//get the value of PAGE_TO_FINISH
int endPageNo = patientPage.getEndPageNumber();

//get the value of CURR_PAGE
int currentPageNo = patientPage.getCurrentPage();

//Variable that holds the total search result pages
int lastPageNo= patientPage.getTotalNoOfPages();


if (currentPageNo>1) {
%>
<a href='list!NavigateToPage.action?pageNumber=1' style="text-decoration:none">[Previous] </a>   
<%
}//end if showPreviousPageLink

for (int i = startPageNo; i <= endPageNo; i++) {
if (i==currentPageNo){
%>
<b><%= i %></b>    //Set the current page to BOLD. Not a Link.
<%
} else {
%>
//Pages with Links
<a href='list!NavigateToPage.action?pageNumber=<%=i%>' style="text-decoration:none"><%= i%></a>   
<%
}//end if else
}//end for : display the page Links

if (currentPageNo<lastPageNo) {
%>
<a href='list!NavigateToPage.action?pageNumber=<%= lastPageNo%>' style="text-decoration:none">[Next] </a>   
<%
}//end if showNextPageLink
%>



samjosh...

Friday, July 6, 2007

Eclipse Europa

Having read my recent blog on Netbeans, you should not demean the ultimate Eclipse Europa. Netbeans will NEVER be able to come up to Eclipse in terms of L&F (Look and Feel).

Eclipse Europa (the official name for Eclipse 3.3) comes with a whole lot of things including Mylyn. Eclipse is the IDE that I would love to work on.

Thursday, July 5, 2007

Netbeans Six

I’ve never been a big fan of Netbeans. There was always something about it that made my skin crawl. It never reached the same level of usability of Eclipse.

But now I have to admit that for the first time in my career I actually anticipated the release of a piece of software. I am even “ashamed” to say that I actually count down the hours and minutes of the official Netbeans Six release.

Coming back to Netbeans, It just works like a charm...! In just a while, when you go tell your interviewer "I know in and out of EJB 3.0" , the interviewer may respond "Oh! That's not a big deal, My Netbeans knows the same!". You may even stop calling yourself a EJB Specialist.

The new NetBeans 6.0 comes with powerful features that includes Easy Desktop GUI Development and Web/Enterprise development. You can order your Netbeans to do the software development for you! (In tamil, Ukkandha edathila erundhu nogama vela paarkiradhu)

Good innovative work by the Sun developers! I am afraid where the software world is heading towards. With a few customizations a non java developer can build the application he needs... and such a time is not very far.... Is this developer friendly? or customer friendly?
How can we call it?.

Thursday, May 17, 2007

Direct Web Remoting - A Tutorial


The DWR / Direct Web Remoting is an open source solution under the Apache license for the developer who wants to use AJAX and XMLHttpRequest in an easy way.



A Step by Step example:

1) Create the java service class :

package com.example.dwr;

public class DWRPersonService {

public Person[] getAllPersons() {

Person[] list = new Person[3];

/* .............................
Call your Ejb / DAO here
and populate values in the array
.............................
*/

Person info = null;
info = new Person();
info.setId(1L);
info.setName("sam");
info.setCity("bangalore");
info.setCountry("india");
list[0] = info;

return list;
}//end of getAllPersons

}//end of Class

2) Create the java bean class. (can be your Info or Transfer Object)

package com.example.dwr;

public class Person {

private Long id;
private String name;
private String city;
private String country;

/*
* Getters and Setters are defined here
*/

/**
* @return the id
*/
public Long getId() {
return id;
}

/**
* @param id the id to set
*/
public void setId(Long id) {
this.id = id;
}

/**
* @return the name
*/
public String getName() {
return name;
}

/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}

// ...............

}//end of Class

3) Configure DWR in WebXml

Start by specifying DWR's existence in the web.xml

<servlet>
<servlet-name>dwr-invoker</servlet-name>
<servlet-class>org.directwebremoting.servlet.DwrServlet</servlet-class>
<init-param>
<param-name>debug</param-name>
<param-value>true</param-value>
</init-param> </servlet>
<servlet-mapping>
<servlet-name>dwr-invoker</servlet-name>
<url-pattern>/dwr/*</url-pattern>
</servlet-mapping>
</servlet>


Include dwr.jar in the WEB-INF/lib folder.

Place the scripts and css files in the respective folders.

You can download the latest jar from DWR Site

For support of autocomplete feature download the script.aculo.us-js-1.x.zip

4) Configure the dwr.xml

<!DOCTYPE dwr PUBLIC
"-//GetAhead Limited//DTD Direct Web Remoting 1.0//EN"
"http://www.getahead.ltd.uk/dwr/dwr10.dtd">
<dwr>
<allow>
<create creator="new" javascript="JDate">
<param name="class" value="java.util.Date"/>
</create>

<create creator="new" javascript="DWRPersonService">
<param name="class" value="com.example.dwr.DWRPersonService"/>
<include method="getAllPersons" />
</create>

<convert converter="bean" match="com.example.dwr.Person"></convert>
</allow>
</dwr>

We specify here to create a new js file for DWRPersonService.
The DWR engine will generate a file DWRPersonService.js at runtime
with the function getAllPersons.

The DWRPersonService.js created at run time by DWR Engine, looks as follows:

// Provide a default path to dwr.engine
if (dwr == null) var dwr = {};

if (dwr.engine == null) dwr.engine = {};

if (DWREngine == null) var DWREngine = dwr.engine;

if (DWRPersonService == null) var DWRPersonService = {};

DWRPersonService._path = '/dwr-sample/dwr';

DWRPersonService.getAllPersons = function(callback) {
dwr.engine._execute(DWRPersonService._path, 'DWRPersonService', 'getAllPersons', callback);
}

5) Create your Jsp.

Include the following js files from DWR.

<script type='text/javascript'
src='<%= request.getContextPath() %>/dwr/engine.js' />
<script type='text/javascript'
src='<%= request.getContextPath() %>/dwr/util.js' />

Also include the js file created for you, as defined in dwr.xml

<script type='text/javascript'
src='<%= request.getContextPath() %>/dwr/interface/DWRPersonService.js' />

Include the following js and css files for AutoComplete feature.

<link rel="stylesheet" type="text/css"
href="<%=request.getContextPath() %>/styles/autocomplete.css"/>
<script type="text/javascript" src="<%= request.getContextPath() %>/scripts/prototype/prototype.js"/>
<script type="text/javascript" src="<%= request.getContextPath() %>/scripts/script.aculo.us/effects.js"/>
<script type="text/javascript" src="<%= request.getContextPath() %>/scripts/script.aculo.us/controls.js"/>
<script type="text/javascript" src="<%= request.getContextPath() %>/scripts/autocomplete.js"/>

Create a text field with id personName. Create a div with the class auto_complete.
Instantiate the function AutoCompleter which takes the following arguments.
i)Id of the textField
ii)Id of the autocomplete Div for this textField
iii)function to populate the list – uses DWR
iv)Optional arguments like valueSelector – property to be listed from the Bean object, chioces – maximum number of choices to be displayed etc.
Finally, call the method DWRUtil.useLoadingMessage on body onLoad.

<script language="javascript">
function updatePersonList(autocompleter, token) {
DWRPersonService.getAllPersons(function(data) { autocompleter.setChoices (data); });
}
</script>

<body onload="DWRUtil.useLoadingMessage();">

Search Person: <input id="personName" type="text" style="width:250px;" / >

< div id="personListDiv" class="auto_complete" > </div>

<script type="text/javascript">
new Autocompleter.DWR('personName', 'personListDiv', updatePersonList,
{ valueSelector: function(obj){ return obj.name; }, partialChars: 1, choices: 10 });
</script>
</body>

In the above method the arguments are as follows :

new AutoCompleter.DWR(textFieldName, associatedDivName, methodForPopulatingList, optionalParams)

OptionalParams:
ValueSelector : the property of the bean that has to be shown in the autocomplete list. For example, 'name' property from 'Employee' bean.

PartialChars : Minimum number of characters to be entered in order to begin matching. Default value is 2.

Choices : Maximum number of items to be shown in the drop down.

Run your application and see DWR in action !!!

Friday, April 27, 2007

Hands on Struts 2

Struts 2 has been evolved from Webwork.

Struts + Webwork2 = Struts2

watch here for more on it....