Talks on .NET, Java, Agile Programming Bangalore, January 15, 2010

Venkat Submramaniam Talks on .NET, Java, Agile Programming at India’s No.1 Forum for Software Developers
Great Indian Developer Summit 2010 – Biggest Event in Asia for IT Professionals

Bangalore, January 15, 2010: Over 6500 attendees have benefited from two game changing editions of Great Indian Developer Summit. In 2010, the biggest independent summit for software developers in India is bringing together over 100 sessions encompassing the full range of Microsoft computing, Java, Agile, RIA, Rich Web, open source/standards, languages, frameworks and platforms, practical tutorials that deep dive into technical skill and best practices, inspirational keynote presentations, an Expo Hall featuring dozens of the latest projects and products activities, Awards to honor software excellence, engaging networking events, and over 80 of the best and brightest of speakers from around the world. The summit will be held 20-23 April 2010 at the IISc in Bangalore (http://www.developersummit.com).

Dr. Venkat Subramaniam, a Great Indian Developer Summit Alumni, is coming back this summer to the summit to conduct focused conference sessions, a keynote and a workshop on topics ranging from .NET, Java, Groovy, functional programming to pointy haired bosses and pragmatic programmers.

On 20th April, at GIDS dot NET Conference, he will delve into what the functional style of programming offers and how you can utilize that using the F# language on the .NET CLR. He will move on to discuss pragmatic ways to deal with dependencies, and how, using mocks, effectively carryout unit tests; the focused session will also cover reasons to use mock vs. not using them, hand tossing mocks, and using frameworks to create them.

At the GIDS Java Conference on 21st April, Venkat will conduct a Jeopardy style presentation, where attendees will drive the topics to discuss various features of Java that require extra care and caution in everyday programming. We will pick a sample code, identify the problems in it, and figure out how to do it right. Later in the day you can attend a session on how to use patterns in Groovy and go beyond the GOF patterns in Groovy and Java. Venkat’s next talk will take a deep dive into Generics, introduced in the 1.5 version (Java 5).

Venkat’s keynote will address the fact that corporate developers have to constantly contend with fallacies often delivered to them as facts. However, each of us has a professional responsibility to be objective and make decisions that will help us and our teams be productive and deliver results. His talk will pick on some fallacies, lay down facts, and discuss how to stay professional and objective in our daily efforts.

On 23rd April, at the full-day GIDS Workshops, Dr. Subramaniam conducts hands-on training about functional programming — take some familiar problems, solve it using traditional style and then refactor it to functional style. Although the training will use Scala and Erlang as vehicle to get the examples working, you don’t have to be familiar with the syntax. You will participate to write pseudo code in these styles and the speaker will help you translate those into practical working examples in these languages.

More over, you can interact with Venkat at the summit to gain from his significant experience in architecture, design, and development of software applications, and in having  mentored thousands of software developers in the US, Canada, Europe, and Asia. Overall seats are limited, so register early for the conference’s focused sessions and workshops here: http://www.developersummit.com/registration.html.

About Great Indian Developer Summit

Great Indian Developer Summit is the gold standard for India’s software developer ecosystem for gaining exposure to and evaluating new projects, tools, services, platforms, languages, software and standards. Packed with premium knowledge, action plans and advise from been-there-done-it veterans, creators, and visionaries, the 2010 edition of Great Indian Developer Summit features focused sessions, case studies, workshops and power panels that will transform you into a force to reckon with. Featuring 3 co-located conferences: GIDS.NET, GIDS.Web, GIDS.Java and an exclusive day of in-depth tutorials – GIDS.Workshops, from 20 April to 24 April at the IISc campus in Bangalore.

At GIDS you’ll participate in hundreds of sessions encompassing the full range of Microsoft computing, Java, Agile, RIA, Rich Web, open source/standards, languages, frameworks and platforms, practical tutorials that deep dive into technical skill and best practices, inspirational keynote presentations, an Expo Hall featuring dozens of the latest projects and products activities, engaging networking events, and the interact with the best and brightest of speakers from around the world.

For further information on GIDS 2010, please visit the summit on the web http://www.developersummit.com/

A Saltmarch Media Press Release
E: info@saltmarch.com

Ph: +91 80 4005 1000

Now Available: Top Resources from Sun

Get an insight into the latest Sun technology with free downloads of the TOP most requested White Papers, Videos, Blueprints, Webinars and more…

Servers, Storage, Software, Solaris… It’s all there in an invaluable collection of resources pointing the way towards solutions you should know more about.

» Access the instant download page here.

Thank you,
Sun Microsystems

Spring MVC Tutorial – Paging Through Hibernate and Selection

In this installment, I’m expanding the project done in Spring MVC Tutorial – Hibernate Integration to include:

  1. Browsing/paging through a table with a navigation bar found in various forum sites and ASP.NET GridView (e.g. First 3 4 5 6 7 Last)
  2. Showing checkboxes against each row of the table for selective action

The related project code download is ibank-v2.zip

Handling Navigation/Pagination/Paging

There are free libraries out there like Google’s Jmesa, DisplayTag, etc. and also Spring has support through PagedListHolder and such. But I was in a different mood and decided to go for my own implementation.

Also, this helped me understand the logics of displaying a navigation bar. Maybe I’ll learn about the libraries later and share with you.

NavigationInfo

This is the workhorse for the navigation bar:

package org.himu.ibank.service.vo;

public class NavigationInfo {

private int currentPage;
private int pageSize;
private int rowCount;
private int maxIndices;

public NavigationInfo() {
currentPage = 0;
rowCount = 0;
maxIndices= 5;
pageSize = 5;
}

public int getCurrentPage() {
return currentPage;
}

public void setCurrentPage(int currentPage) {
if (currentPage < 0)
this.currentPage = 0;
else if (currentPage > getPageCount() – 1)
this.currentPage = getPageCount() – 1;
else
this.currentPage = currentPage;
}

public int getPageSize() {
return pageSize;
}

public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}

public int getRowCount() {
return rowCount;
}

public void setRowCount(int rowCount) {
this.rowCount = rowCount;
}

public int getMaxIndices() {
return maxIndices;
}

public void setMaxIndices(int maxIndices) {
this.maxIndices = maxIndices;
}

public int getPageCount() {
return (int) Math.ceil((double) rowCount / pageSize);
}

public int getPrevIndex() {
int prev = currentPage – 1;
return prev < 0 ? 0 : prev;
}

public int getNextIndex() {
int lastIndex = getPageCount() – 1;
int next = currentPage + 1;
return next > lastIndex ? lastIndex : next;
}
public boolean isFirstPage() {
return 0 == currentPage;
}
public boolean isLastPage() {
return (getPageCount() – 1) == currentPage;
}

public int[] getIndexList() {
int[] range = getIndexRange();
int[] ilist = new int[range[1] – range[0] + 1];
for (int i = 0; i < ilist.length; i++) {
ilist[i] = range[0] + i;
}
return ilist;
}
public int[] getIndexRange() {
// determine the standard window
int start = currentPage – maxIndices / 2;
int end = start + maxIndices – 1;
// shift to right if start underflows 0
if (start < 0) {
end -= start; // end – -start = end + start = shift right
start = 0;
}
// now maybe the window overflows pageCount – so shift to left again
int lastIndex = getPageCount() – 1;
if (end > (lastIndex)) {
start -= (end – lastIndex);
end = lastIndex;
}
// we have finalized end, now if start < 0 then truncate it
if (start < 0)
start = 0;
return new int[] {start, end};
}
}

The page indices are 0-based. The class has some defaults which can be overridden if required.

The starting point for this class is setRowCount(). Once the number of rows is determined you can use getPageCount() which in turn allows all other navigation methods to work.

setCurrentPage(), getPrevIndex() and getNextIndex() make sure you don’t fall out of valid page indices.

getIndexRange() is where all the muscle is. It uses currentPage and maxIndices (maximum number of links to be displayed in the navigation bar) to determine the start and end of page links in the navigation bar.

getIndexList() is a convenience method for generating the entire list of navigation indices from the range calculated by getIndexRange().

PagedCustView

This class is used to send the navigation information and the current page of customers to the view.

package org.himu.ibank.service.vo;

import java.util.List;

import org.himu.ibank.domain.Customer;

/**
* Hold necessary information for paged view of customer list
*/
public class PagedCustView {

private NavigationInfo navInfo = new NavigationInfo();
private List<Customer> customers;

public NavigationInfo getNavInfo() {
return navInfo;
}

public void setNavInfo(NavigationInfo navInfo) {
this.navInfo = navInfo;
}

public List<Customer> getCustomers() {
return customers;
}

public void setCustomers(List<Customer> customers) {
this.customers = customers;
}

public Customer getCustomer(int i) {
return (Customer) customers.get(i);
}

public void setCustomer(int i, Customer customer) {
this.customers.add(i, customer);
}
}

The actual page of customers is fetched in the controller and the navigation information is set accordingly.

Writing the Controller

You’re going to browse all registered but unauthorized customers.

The NewCustListController expects a page parameter in the query string of its calling URL. If this is not found then page 0 (the first page) is assumed.

package org.himu.ibank.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.himu.ibank.service.CustomerRegistrationService;
import org.himu.ibank.service.vo.PagedCustView;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

public class NewCustListController extends AbstractController {

private CustomerRegistrationService custRegService;
public void setCustRegService(CustomerRegistrationService custRegService) {
this.custRegService = custRegService;
}

@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request,
HttpServletResponse response) throws Exception {
Map<Object, Object> model = new HashMap<Object, Object>();
PagedCustView pcustv = new PagedCustView();

pcustv.getNavInfo().setRowCount(custRegService.getUnauthorizedCustomerCount());

String page = (String)request.getParameter("page");
if (null == page)
pcustv.getNavInfo().setCurrentPage(0);
else
pcustv.getNavInfo().setCurrentPage(Integer.parseInt(page));

pcustv.setCustomers(custRegService.getUnauthorizedCustomers(
pcustv.getNavInfo().getCurrentPage(), pcustv.getNavInfo().getPageSize()));

request.getSession().setAttribute("pagedcust", pcustv);
model.put("pagedcust", pcustv);

return new ModelAndView("admin/newcustlist", model);

}
}
  1. First you determine the customer count and tell it to NavigationInfo.
  2. Then you set the current page.
  3. Based on the current page and page size as specified in NavigationInfo, you then fetch the only the specific page of customers through Hibernate. This is the reason I opted for my own implementation.
  4. Return the model and view name as usual.

The Service and DAO Classes

I’ve refactored CustomerRegistrationService and CustomerDao interfaces and their implementations a bit. Also note that I’ve corrected a mistake in HibernateCustomerDao’s paging code.

CustomerRegistrationService

public interface CustomerRegistrationService {

Long registerCustomer(Customer c);
void authorizeCustomer(Customer c);
Customer getCustomer(Long id);
List<Customer> getUnauthorizedCustomers(int startPage, int pageSize);
List<Customer> getCustomers(int startPage, int pageSize);
List<Customer> getAllCustomers(int startPage, int pageSize);
public int getUnauthorizedCustomerCount();
}

StandardCustomerRegistrationService

public class StandardCustomerRegistrationService implements CustomerRegistrationService { private CustomerDao custDao; public void setCustDao(CustomerDao custDao) { this.custDao = custDao; } @Override public Long registerCustomer(Customer c) { return custDao.addNew(c); } @Override public void authorizeCustomer(Customer c) { if (c.getStatus() == Customer.STATUS_REGISTERED) { c.setStatus(Customer.STATUS_ACTIVE); custDao.update(c); // … mailer code for notifying customer … } } @Override public Customer getCustomer(Long id) { return custDao.findById(id); } /** * Get registered but unauthorized customers using optional paging. * * @param startPage Starting page number, first page is 0 * @param pageSize Size of a single page, <=0 means no paging */ @Override public List<Customer> getUnauthorizedCustomers(int startPage, int pageSize) { Customer c = new Customer(); c.setStatus(Customer.STATUS_REGISTERED); return custDao.listByExample(c, startPage, pageSize); } @Override public int getUnauthorizedCustomerCount() { return custDao.countCustomers(Customer.STATUS_REGISTERED); } /** * Get registered and authorized customers using optional paging. * * @param startPage Starting page number, first page is 0 * @param pageSize Size of a single page, <=0 means no paging */ @Override public List<Customer> getCustomers(int startPage, int pageSize) { Customer c = new Customer(); c.setStatus(Customer.STATUS_ACTIVE); return custDao.listByExample(c, startPage, pageSize); } @Override public List<Customer> getAllCustomers(int startPage, int pageSize) { return custDao.listAll(startPage, pageSize); } }

CustomerDao

public interface CustomerDao {

Long addNew(Customer c);
void delete(Customer c);
void update(Customer c);
Customer findById(Long id);
Customer findByUserId(String uid);
List<Customer> listAll();
List<Customer> listAll(int startPage, int pageSize);
List<Customer> listByExample(Customer c);
List<Customer> listByExample(Customer c, int startPage, int pageSize);
int countCustomers(int status);
}

HibernateCustomerDao

public class HibernateCustomerDao extends HibernateDaoSupport implements
CustomerDao {

@Override
public Long addNew(Customer c) {
return (Long) getHibernateTemplate().save(c);
}

@Override
public void delete(Customer c) {
getHibernateTemplate().delete(c);
}

@Override
public void update(Customer c) {
getHibernateTemplate().update(c);
}

@Override
public Customer findById(Long id) {
return (Customer) getHibernateTemplate().get(Customer.class, id);
}

@SuppressWarnings("unchecked")
@Override
public Customer findByUserId(String uid) {
List<Customer> clist =  getHibernateTemplate().find("from Customer c where c.userId = ?", uid);
if (clist.isEmpty())
return null;
else
return clist.get(0);
}

@SuppressWarnings("unchecked")
@Override
public List<Customer> listAll() {
return getHibernateTemplate().find("from Customer c");
}

@SuppressWarnings("unchecked")
@Override
public List<Customer> listAll(int startPage, int pageSize) {
DetachedCriteria criteria = DetachedCriteria.forClass(Customer.class);
criteria.addOrder(Order.asc("id"));
return getHibernateTemplate().findByCriteria(criteria, startPage * pageSize, pageSize);
}

@SuppressWarnings("unchecked")
@Override
public List<Customer> listByExample(Customer c) {
return getHibernateTemplate().findByExample(c);
}

@SuppressWarnings("unchecked")
@Override
public List<Customer> listByExample(Customer c, int startPage, int pageSize) {
return getHibernateTemplate().findByExample(c, startPage * pageSize, pageSize);
}

@Override
public int countCustomers(int status) {
DetachedCriteria criteria = DetachedCriteria.forClass(Customer.class)
.add(Restrictions.eq("status", status))
.setProjection(Projections.rowCount());
return (Integer)getHibernateTemplate().findByCriteria(criteria).get(0);
}
}

The Browsing JSP

The Model and Controller codes are done. Now you write the view – newcustlist.jsp. Create it by copying admin.jsp as usual. Following is the relevant additions you need to write:
<div id="content"> <div align="center"> <c:if test="${!pagedcust.navInfo.firstPage}"> <a href="newcustlist.htm?page=0">First</a>&nbsp; </c:if> <c:forEach var="i" items="${pagedcust.navInfo.indexList}"> <c:choose> <c:when test="${i != pagedcust.navInfo.currentPage}"> <a href="newcustlist.htm?page=${i}">${i}</a>&nbsp; </c:when> <c:otherwise> <b>${i}</b>&nbsp; </c:otherwise> </c:choose> </c:forEach> <c:if test="${!pagedcust.navInfo.lastPage}"> <a href="newcustlist.htm?page=${pagedcust.navInfo.pageCount – 1}">Last</a> </c:if> </div> <form action="<%=request.getContextPath()%>/authorizecust.htm" method="post"> <table> <thead> <tr> <td>User ID</td> <td>First Name</td> <td>Last Name</td> <td>Email</td> </tr> </thead> <tbody> <c:forEach var="cust" items="${pagedcust.customers}"> <tr> <td>${cust.userId}</td> <td>${cust.firstName}</td> <td>${cust.lastName}</td> <td>${cust.email}</td> <td><input type="checkbox" value="${cust.id}" name="authorized"/></td> </tr> </c:forEach> </tbody> </table> <input type="hidden" name="linkBackIndex" value="${pagedcust.navInfo.currentPage}"/> <input type="submit" value="Authorize"/> </form> </div>
  1. First, generate the navigation banner aligned in the center of the page. It shows optional First and Last links based on the current page. The center <c:forEach> loops through the index list taken from navInfo and generates the necessary page links excluding the current page.
  2. Declare a form which allows us to submit authorization approvals of selected customers. The code for authorization will be written later in another controller.
  3. Looping through the customer list is trivial. The important thing is generating a checkbox against each customer for selecting for approval. The name of the checkboxes must be same (authorize in the above code) but there values will be different – the internal ID of each customer. This ID is required for Hibernate.
  4. A hidden input field linkBackIndex is also declared which helps us to return to the current page after authorization is made. It will be clear in the authorization controller.

Processing Actual Authorization and Returning to the New Customer Browser

First, the code:

package org.himu.ibank.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.himu.ibank.domain.Customer;
import org.himu.ibank.service.CustomerRegistrationService;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;
import org.springframework.web.servlet.view.RedirectView;

public class AuthorizeCustController extends AbstractController {

private CustomerRegistrationService custRegService;

public void setCustRegService(CustomerRegistrationService custRegService) {
this.custRegService = custRegService;
}

@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request,
HttpServletResponse response) throws Exception {
String[] custids = request.getParameterValues("authorized");
String linkBackIndex = request.getParameter("linkBackIndex");
System.out.println("################### INSIDE AuthorizeCustController #############");
for (String custid: custids) {
Customer cust = custRegService.getCustomer(Long.parseLong(custid));
custRegService.authorizeCustomer(cust);
System.out.println("## Authorized: " + custid);
}
return new ModelAndView(new RedirectView(request.getContextPath() + "/newcustlist.htm?page=" + linkBackIndex));
}
}

The logic is simple:

  1. Get the list of selected customer IDs using request.getParameterValues(“authorized”). It will contain only those IDs whose checkboxes are marked.
  2. Iterate through the list as ask our service class to make the authorizations.
  3. We use the linkBackIndex to redirect the flow to NewCustListController using its Spring MVC defined URL, i.e. /newcustlist.htm.

Notice how we are redirecting in the return statement. The RedirectView class helps us to go to back to the new customer browser and also pass the last page used as a query parameter. An alternative is to define the view in the bean configuration file using the pattern ‘redirect:<url>’, e.g. ‘redirect:/newcustlist.htm’ but we cannot pass the query parameter then.

Modified ibank-servlet.xml

Finally, our gluing file. I won’t be discussing it as there is nothing special.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

<bean id="simpleUrlMapping">
<property name="mappings">
<props>
<prop key="/home.htm">homePageController</prop>
<prop key="/adminhome.htm">adminHomePageController</prop>
<prop key="/createcust.htm">newCustomerController</prop>
<prop key="/newcustlist.htm">newCustomerListController</prop>
<prop key="/authorizecust.htm">authorizeCustController</prop>
</props>
</property>
</bean>
<bean id="viewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
<bean id="homePageController"/>
<bean id="adminHomePageController">
<property name="viewName" value="admin/admin"/>
</bean>
<bean id="newCustomerController">
<property name="custRegService" ref="customerRegService"/>
<property name="formView" value="admin/newcustomer"/>
<property name="successView" value="admin/newcustomer-success"/>
<property name="commandName" value="customer"/>
<property name="commandClass" value="org.himu.ibank.domain.Customer"/>
</bean>
<bean id="newCustomerListController">
<property name="custRegService" ref="customerRegService"/>
</bean>
<bean id="authorizeCustController">
<property name="custRegService" ref="customerRegService"/>
</bean>
</beans>

Hope to hear from you.

JQuery Effects in a JSF Application

Introduction

Nowadays whenever I surf the net, I am crossing an article about Jquery. The reason is JQuery relishes our application in a fascinated manner that tempts me to ponder the internet to find the ways to implement JQuery in a JSF application. Eventually I found that Richfaces component library provides an easiest way to implement JQuery in a JSF application. In this article let us learn how to invoke the JQuery effects in a JSF application with the use of Richfaces. Before proceeding in to the topic, Let us see what are the prerequisites for this article.

Things You’ll Need

  • Your Favourite IDE
  • Tomcat 6.x/Glassfish/Jboss
  • JDK 1.5 and above

I assume that you have all the prerequisites needed for this article and now let us see how to implement the following JQuery effects in a JSF application with the use of Richfaces,

  1. Basic Effects
  2. Sliding Effects
  3. Fading Effects

First Thing to know

The following library should be included in the head tag of a JSP document(JSF Application) or a xhtml document(Facelet Application) to use the feature of the JQuery in a JSF application,

1 <a4j:loadScript src="resource://jquery.js"/>

Note: To implement Jquery, the function jQuery()should be used instead of $().

1. Basic Effects
For Basic Effects, Let us see an example to show and hide a div with the use of JQuery.

01 <%--
02 Document   : JQueryEffects
03 Author     : Giftsam
04 --%>
05
06 <%@page contentType="text/html" pageEncoding="UTF-8"%>
07 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
09 <%@ taglib uri="http://java.sun.com/jsf/html" prefix="h"%>
10 <%@ taglib uri="http://java.sun.com/jsf/core" prefix="f"%>
11 <%@ taglib uri="http://richfaces.org/a4j" prefix="a4j"%>
12 <%@ taglib uri="http://richfaces.org/rich" prefix="rich"%>
13
14 <f:view>
15 <html>
16 <head>
17 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
18 <title>JQuery Effects</title>
19 <a4j:loadScript src="resource://jquery.js"/>
20 <script type="text/javascript">
21
22 <!-- JQuery to show/hide a div -->
23 function showHideDiv()
24 {
25 jQuery(document).ready(function() {
26 var $ = jQuery;
27 if ($("#panelDiv").is(":hidden"))
28 {
29 $("#panelDiv").show("slow");
30 }
31 else
32 {
33 $("#panelDiv").hide("slow");
34 }
35 });
36 }
37 </script>
38 </head>
39 <body>
40 <h:form id="formId">
41 <rich:panel header="Jquery Effects" style="position: relative; width: 350px;">
42 <a4j:commandLink id="showLinkId" value="Click Here" onclick="showHideDiv()" reRender="panelDiv"/>
43 <div id="panelDiv">
44 <rich:panel style="position: relative; top: 4px;">
45 <p> JQuery relishes our application in a fascinated manner.
46 jQuery is a lightweight JavaScript library that emphasizes
47 interaction between JavaScript and HTML. It was released in January 2006 at
48 BarCamp NYC by John Resig.</p>
49 </rich:panel>
50 </div>
51 </rich:panel>
52 </h:form>
53 </body>
54 </html>
55 </f:view>

The preceding Jquery is used to apply the show/hide effects when the user clicks the “Click here” command link and the arguments can be either represented as (“slow”, “normal”, or “fast”) or in the Milliseconds(Eg: 500) to determine the predefined speed of the effects. Next we shall learn how to implement sliding effects in a JSF application with the use of JQuery.

2. Sliding Effects

For sliding effects, let us see the same example for implementing the SlideUp and SlideDown effects and the following Jquery should be added in the head tag of the JSP document.

01 <script type="text/javascript">
02 function slideUpAndDown()
03 {
04 jQuery(document).ready(function() {
05 var $ = jQuery;
06 if ($("#panelDiv").is(":hidden"))
07 {
08 $("#panelDiv").slideDown("slow");
09 }
10 else
11 {
12 $("#panelDiv").slideUp("slow");
13 }
14 });
15 }
16 </script></pre>

Arguments can be either represented as (“slow”, “normal”, or “fast”) or in the Milliseconds(Eg: 500) to determine the predefined speed of the effects. And finally let us learn how to implement fading effects in a JSF application with the use of JQuery.

3. Fading Effects
For Fading effects, let us again see the same example to implement FadeIn, FadeOut and FadeTo effects in a JSF application.

FadeIn
The Following JQuery should be wrapped inside the head tag of the JSP document to implement fadeIn effects for a JSF application.

1 <script type="text/javascript">
2 function fadeIn()
3 {
4 jQuery(document).ready(function() {
5 jQuery("#panelDiv").fadeIn("slow");
6 });
7 }
8 </script>

FadeOut
The Following JQuery should be wrapped inside the head tag of the JSP document to implement fadeOut effects for a JSF application.

1 <script type="text/javascript">
2 function fadeOut()
3 {
4 jQuery(document).ready(function() {
5 jQuery("#panelDiv").fadeOut("slow");
6 });
7 }
8 </script>

FadeTo
The Following JQuery should be wrapped inside the head tag of the JSP document to implement fadeTo effects for a JSF application.

1 <script type="text/javascript">
2 function fadeTo()
3 {
4 jQuery(document).ready(function() {
5 jQuery("#panelDiv").fadeTo("slow", 0.33);
6 });
7 }
8 </script>

Arguments can be either represented as (“slow”, “normal”, or “fast”) or in the Milliseconds(Eg: 500) to determine the predefined speed of the effects. The coding section to implement various effects is completed and the effects are applied when the user clicks the “Click Here” command link of our example page and now let us have a look at the snap of our example.

Snap Shot

I hope this article clearly explains how to implement various JQuery effects in a JSF application. If you find this article is useful to you dont forget to give your valuable comments. Have a joyous code day.

Proxisoft preps Java code to support Web services


November 13, 2009 — Proxisoft, a startup, has unveiled a middleware solution called Netrifex, which automates the creation of Web services from Java applications.

Netrifex takes existing Java code and creates a mirror image of bytecode at runtime, then modifies it to support Web services, said company founder Mark Hansen. It uses special class libraries and does not require a special Java Virtual Machine, he said.

Supported Java EE containers include Apache Tomcat and Oracle WebLogic Server. JBoss, WebSphere and others will be added soon, according to the company.

“This approach allows Web service development best practices to be bundled into product…It knows how to generate services that make sense and are robust as services created under the Spring [framework] or [Apache] Struts,” said Hansen.

The SOAP Web services that Netrifex generates use HTTP and SSL authentication, and they preserve the security that is wrapped into the original application, Hansen said. That is done without modifying the underlying application.

Transactions from the Web services are delegated down to the original Java application from the Netrifex middleware, which is invoked through XML conversion, Hansen explained. “The application executes as it normally would,” he added.

Developers can offload the XML processing from the Java application server onto a separate machine or virtual machine, and Netrifex is compatible with appliances that accelerate XML processing, Hansen said.

Pricing is per CPU, and US$20,000 is the entry-level price for a dual-core CPU, according to Hansen.

Flickr example to upload photos using Java

Its all for now. Stop reading any other articles on how to post a photo in flickr using Java.

I too spent a lot of time publish a image on flickr. At last I thought to post a article on this.

Step1:

Get Flickr API Keys from here http://www.flickr.com/services/api/misc.api_keys.html

Apply for a key
View your keys

Here we will get API key and Secret Key.

Step2:

Download Flickrj Library

http://flickrj.sourceforge.net/

Step3:

Execute the following program to get the Token by completing the authentication.

Authentication Type / Application deployment environment

Flickr provides different methods for authenticating your application depending on your deployment environment. For each method/environment, Flickr needs to know different information.

Web application and Callback URL
To use web authentication:

  • Direct the user to a Flickr page; the exact URL is created using the API.
  • The user will authorize your application on Flickr; or Flickr will remember an old authorization.
  • Flickr redirects the user to your callback URL; the frob is sent as a GET attribute.

The frob is necessary to complete the authentication process. So, practically speaking, your callback URL should use technology which can fetch and store the frob; e.g., JSP or PHP. More on the frob later. For more details on web authorization, consult the Flickr web authentication howto.

Desktop application
Authentication for desktop applications is similar to web authentication. However, that falls outside the scope of this Wiki page, as this is for CISC474 – Advanced Web Technologies.

Mobile application
See desktop applications.

Getting authenticated

Flickr provides some pretty good write-ups on user authentication. This Wiki page will show it in context of some real code.

WARNING: Which frob is which?

During the authentication process, your application encounters two distinct frobs:

  1. The first is generated and sent to Flickr.
  2. Flickr sends back a different one which is used to authenticate your application.

Don’t get confused — and don’t use the first frob to authenticate your application.

Java code example

This simple Java class, modelled on flickrj’s AuthExample class, shows the basic authentication process in interactive, command-line mode. This demo code is designed for web application authorization.

Make sure to download the flickrj package and include flickrj-xxx.jar in your classpath.

For a real webapp, the main should be in two servlets. The break is indicated in the code.

  1. Prompt the user to authorize the app on Flickr.com
  2. Complete the authorization

To create a Flickr object after having authenticated in the same session, then get the token from the original authentication and set the new Flickr object’s token to that (shown at the bottom of the code).

// To save space, we're using wildcard masks for the imports.  You really only need about 30 classes total for this.
import java.io.*;
import java.net.*;
import java.util.*;
import javax.xml.parsers.ParserConfigurationException;
import org.xml.sax.SAXException;
import com.aetrion.flickr.*;
import com.aetrion.flickr.auth.*;
import com.aetrion.flickr.blog.*;

/**
 * Example class to illustrate the authentication process
 * based on AuthExample from flickrj.  main() runs an interactive,
 * command-line authentication process.
 */
class AuthExample
{
    static String restHost = "www.flickr.com";
    /* Every external application for Flickr needs an API key.
     * Change the apiKey and the sharedSecret to the values given to you by Flickr.
     * You can get and edit yours at http://flickr.com/services/api/keys/
     * Ideally, these are defined elsewhere, e.g. in web.xml.
     */
    static String apiKey = "yourAPIkey";		// used to ID the application
    static String sharedSecret = "yourSharedSecret"; 	// used for signed calls

    /* Of course, we need a Flickr object to work with.  Like any good poppa class, class Flickr
     * provides several methods to fetch various xxxInterface objects, saving you the trouble
     * of instantiating them manually.  That is incidental to this example, but cool nonetheless.
     */
    Flickr flickr;

    /* Flickr supports several request methods, but the flickrj package only supports REST so far.
     * So, the Flickr object needs a REST object to handle its requests.
     */
    REST rest;
    String token;	// Generated via authentication process, for tracking the session and making signed calls
    /* Flickr requires the application to send its shared secret for any signed calls.
     * This RequestContext will manage that for us, if we use it for those calls.
     * RequestContext is from the com.aetrion.flickr package.
     */
    RequestContext requestContext;	// Used for making signed calls to Flickr

    static void main(String[] args) throws ParserConfigurationException, IOException, SAXException
    {
	REST rest = new REST();
	rest.setHost(restHost);
	Flickr flickr = new Flickr(AuthExample.apiKey, rest);

	/* Flickr requires the shared secret for any signed calls. RequestContext will store and send it. */
	requestContext = RequestContext.getRequestContext();
	requestContext.setSharedSecret(AuthExample.sharedSecret);

	/* To authorize this application, generate an authentication URL and direct the user to it. */
	// First, generate a frob...
	AuthInterface authInterface = flickr.getAuthInterface();
	String firstFrob = "";
	try {
	    firstFrob = authInterface.getFrob();
	} catch(FlickrException e) {
	    e.printStackTrace();
	}
	/* ... then generate a URL with that frob, asking for a certain level of permissions ...
	 *    -- Permission.READ     (private photos)
	 *    -- Permission.WRITE    (edit info and photos; upload photos)
	 *    -- Permission.DELETE   (photos)
	 */
        URL url = authInterface.buildAuthenticationUrl(Permission.WRITE, firstFrob);
	// ... and direct the user to it.
	System.out.println("Authorize this application at the following URL:");
	System.out.println(url.toExternalForm());   // Make sure to use URL.toExternalForm()!

	// =================================================================================
	// If this were a real webapp, you would break into another servlet after this point
	// =================================================================================

	/* After the user authorizes the application, s/he will be redirected to the
	 * callback URL associated with the API key for the application; the URL
	 * will include a rehashed frob that the application can use for authentication.
	 * If this were a real web application, it would fetch the frob itself from that page.
	 * This demo merely prompts the user to fetch it for us.
	 */
	System.out.println("After you were redirected, what was the frob? (Check your URL: ...?frob=XXX)");
	BufferedReader userInput = new BufferedReader( new InputStreamReader(System.in));
	String fetchedFrob = userInput.readLine();

	/* This is the last bit of the authentication process.
	 * Take the frob that Flickr gave back to us and use it
	 * to generate an Auth(enticated widget).
	 */
        Auth auth;
	try {
	    auth = authInterface.getToken(fetchedFrob);
	    System.out.println("Authentication success");
	} catch(FlickrException e) {
	    System.out.println("Authentication failed");
	    e.printStackTrace();
	}

	/* That frob was only valid for one authentication.  The token is good for
         * making new Flickr's in a single session.
         * I don't really know how long a session lasts -- perhaps forever.
	 * To maintain the session, keep the token in memory: auth.getToken()
	 */
        System.out.println("Token: "+auth.getToken());
	System.out.println("nsid: "+auth.getUser().getId());
	/* In addition to authorizing the application, the authentication process
	 * gives us quick access to who is the logged-in user.
	 */
	System.out.println("Realname: "+auth.getUser().getRealName());
	System.out.println("Username: "+auth.getUser().getUsername());
	/* Flickr has three tiers of permissions:
	 *  -- read (private photos)
	 *  -- write (edit info and photos; upload photos)
	 *  -- delete (photos)
	 */
	System.out.println("Permission: "+auth.getPermission().getType());

	// =================================================================================
	// Use the token to create another Flickr object with this authentication
	// =================================================================================
        Flickr sameSession = new Flickr();
        sameSession.getAuth().setToken(flickr.getAuth().getToken());

}

Step4:

Publish the photo on flickr.

Use the below program to post the picture on flickr.

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.xml.sax.SAXException;

import com.aetrion.flickr.Flickr;
import com.aetrion.flickr.FlickrException;
import com.aetrion.flickr.REST;
import com.aetrion.flickr.RequestContext;
import com.aetrion.flickr.auth.Auth;
import com.aetrion.flickr.auth.AuthInterface;
import com.aetrion.flickr.auth.Permission;
import com.aetrion.flickr.contacts.ContactsInterface;
import com.aetrion.flickr.people.PeopleInterface;
import com.aetrion.flickr.photosets.PhotosetsInterface;
import com.aetrion.flickr.uploader.UploadMetaData;
import com.aetrion.flickr.uploader.Uploader;

public class flcikruploadeg1 {

	 public static void main(String[] args) throws IOException, NoSuchAlgorithmException{

	String apiKey = "YOUR API KEY";
	String token = "YOURTOKEN";
	String secretKey = "YOUR SECERET";
	String title=" Steven";
	String photo = "D:/Steven/Steven0003.jpg";
	String description="This is photo description";

	Flickr f;
	ContactsInterface c;
	PeopleInterface p;
	PhotosetsInterface o;
	Uploader up = new Uploader(apiKey,secretKey);
	REST rest;

	RequestContext requestContext;

	AuthInterface authInterface;
	String frob = "";
	//void setup() 

	   InputStream in = new FileInputStream(photo);
       ByteArrayOutputStream out = new ByteArrayOutputStream();
       int i;
       byte[] buffer = new byte[1024];
       while ((i = in.read(buffer)) != -1) {
           out.write(buffer, 0, i);
       }
       in.close();
    //   byte[] result = out.toByteArray();

	byte data[] = out.toByteArray();
	//size(500, 500);
	f= new Flickr(apiKey,secretKey,(new Flickr(apiKey)).getTransport());
	up=f.getUploader();
	authInterface=f.getAuthInterface();
	requestContext = RequestContext.getRequestContext();
	requestContext.setSharedSecret(secretKey);

	try {
	frob = authInterface.getFrob();
	System.out.println(frob);
	URL joep = authInterface.buildAuthenticationUrl(Permission.WRITE, frob);
	System.out.println(joep.toExternalForm());
	System.out.println("Press return after you granted access at this URL:");

	} catch (IOException e) {
	// TODO Auto-generated catch block
	e.printStackTrace();
	} catch (SAXException e) {
	// TODO Auto-generated catch block
	e.printStackTrace();
	} catch (FlickrException e) {
	// TODO Auto-generated catch block
	e.printStackTrace();
	}

	try {
	Auth auth = new Auth();
	requestContext.setAuth(auth);
	//authInterface.addAuthToken();
	auth.setToken(token);
	   auth.setPermission(Permission.WRITE);
	 System.out.println("Token Is: " + auth.getToken());
	System.out.println("Permission for token: " + auth.getPermission());
	f.setAuth(auth);
	UploadMetaData uploadMetaData = new UploadMetaData(); uploadMetaData.setTitle("hello Satish");
	up.upload(data,uploadMetaData);

	} catch (IOException e) {
	// TODO Auto-generated catch block
	e.printStackTrace();
	} catch (SAXException e) {
	// TODO Auto-generated catch block
	e.printStackTrace();
	} catch (FlickrException e) {
	// TODO Auto-generated catch block
	e.printStackTrace();
	}

	}
}

That's it check your photo on flickr,
If you have any questions please post I will help you

-Steven

Post Image on Facebook using java api to publish on Wall

First Follow the listed Steps from my Previous post http://blog.theunical.com/facebook-integration/facebook-java-api-example-to-publish-on-wall/ then in last program include the below code to publish a photo and also meta data on a facebook wall.

In the same way we can even publish MP3, Videos, Flash on facebook.

Publishing a Post Containing an Image, Action Links and Custom Metadata.

package com.unical;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpState;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpClientParams;

import com.google.code.facebookapi.Attachment;
import com.google.code.facebookapi.AttachmentMediaImage;
import com.google.code.facebookapi.FacebookException;
import com.google.code.facebookapi.FacebookJsonRestClient;
import com.google.code.facebookapi.FeedFacebookPhoto;
import com.google.code.facebookapi.Permission;
import com.google.code.facebookapi.TemplatizedAction;

public class SendtoFacebook {

	public static void main (String a[]) throws FacebookException{ 

	SendtoFacebook sfb=new SendtoFacebook();
	sfb.send("From My App: publish steven on facebook");
	}
	public void send(String message)throws FacebookException{

		String FB_APP_API_KEY = new String("YOUR APIKEY");
		String FB_APP_SECRET = new String("YOUR SECRET");
		String FB_SESSION_KEY = new String("YOUR SESSION KEY");
		FacebookJsonRestClient facebook = new FacebookJsonRestClient( FB_APP_API_KEY, FB_APP_SECRET, FB_SESSION_KEY );

		//FacebookJsonRestClient facebookClient2 = (FacebookJsonRestClient)facebook.getFacebookRestClient();
		FacebookJsonRestClient facebookClient = (FacebookJsonRestClient)facebook;
		Attachment attachment = new Attachment();
		attachment.setCaption("Caption for attachment");
		attachment.setDescription("Description for attachment");
		attachment.setHref("http://blog.unical.com");
		attachment.setName("Hopefully this works");

		AttachmentMediaImage  attach_media = new AttachmentMediaImage( );
		attach_media.addImage("http://profile.ak.fbcdn.net/v229/868/86/q518210788_2085.jpg", "http://blog.theunical.com");

		attachment.setMedia(attach_media);

		facebookClient.stream_publish(message, attachment, null, null, null);

			System.out.println("successfully updated");
	}
}


Facebook Java api example to publish on Wall

According to facebook Wiki posting on a  wall is very confusing and very difficult to write a program to publish on a wall. And it Don’t even support or document any methods on how to publish on wall using JAVA, and thanks to Google for giving a JAVA library to post on facebook.

Download Library from http://code.google.com/p/facebookjavaapi/

Don’t confuse and don’t use old libraries only use facebook-java-api-3.0.1-bin.zip or greater.

I spent around 2 weeks reading many articles and many documents, Wiki on facebook but in vein and tried many ways and finally I got one workable model. Below are simple steps to publish on a Facebook wall using JAVA.

Step1: Login to Facebook

First login to Facebook and goto the url http://www.facebook.com/developers/ then

Click on “+ Set Up New Application” button to start creating the application as shown below.

start application

Provide the application name, click agree for facebook terms and click on “Create Application” button.

Fill in application Name

create app step1

Now Application is created for you. Just copy the Application API Key, Application Secret and Application ID details which will be used to write the application code.

application page

Now goto Canvas link and enter any url.

canvaspage

Next goto Connect URL link and enter the same url.

connecturl

Then click on Save. That’s it we have created a facebook application with an Iframe.

Now Copy Application API Key, Application Secret and Application ID details which will be used to write the application code.

Now download the php library from facebook “http://blog.theunical.com/wp-content/uploads/2010/05/facebook-platform.tar1.gz”. For now we will use this library for generating one time session key.

Step2: Generate One Time Token key

How to generate One Time Token key:

Run below URL to get temporary token for the particular user by logging into Facebook.

https://login.facebook.com/code_gen.php?api_key=API_KEY&v=1.0

Note: Please replace “API_KEY” with your application API key from above page.

Then we will get a temporary token key.

allowaccess

generatemylogin info

savemyinfo

This is one time token key that we can use to generate a permanent session key. Careful! Don’t try to execute this programs many times

Step3: Generate one time session key

Below is the sample JAVA code to generate one time session key.

/**
 * FacebookClient
 *
 */
public class FacebookClient {
 public static String API_KEY = “YOUR API KEY”;
 public static String SECRET = “YOUR SECRET”;
 public static void main(String args[]) {
 // Create the client instance
 FacebookRestClient client =       new FacebookRestClient(API_KEY, SECRET);
 client.setIsDesktop(true); // is this a desktop app

 try {
 String token = client.auth_createToken();
 // Build the authentication URL for the user to fill out
 String url = “http://www.facebook.com/login.php?api_key=”
 + API_KEY + “&v=1.0″
 + “&auth_token=” + token;
 // Open an external browser to login to your application
 Runtime.getRuntime().exec(“open ” + url); // OS X only!
 // Wait until the login process is completed
 System.out.println(“Use browser to login then press return”);
 System.in.read();

 // fetch session key
 String session = client.auth_getSession(token,true );
// obtain temp secret
String tempSecret = client.getSessionSecret();
// new facebook client object
client = new FacebookJaxbRestClient(API_KEY, tempSecret, sessionKey);

 System.out.println(“Session key is ” + session);

 // keep track of the logged in user id
 Long userId = client.users_getLoggedInUser();
 System.out.println(“Fetching friends for user ” + userId);

 // Get friends list
 client.friends_get();
 FriendsGetResponse response = (FriendsGetResponse) client.getResponsePOJO();
 List<Long> friends = response.getUid();

 // Go fetch the information for the user list of user ids
client.users_getInfo(friends, EnumSet.of(ProfileField.NAME));

UsersGetInfoResponse userResponse = (UsersGetInfoResponse) client.getRepsonsePOJO();
 // Print out the user information
 List<User> users = userResponse.getUser();
 for (User user : users) {
 System.out.println(user.getName());
 }
 } catch (FacebookException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
 } catch (IOException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
 }
 }
}

(OR)

For example, the full URL for logging in a user could be:

http://www.facebook.com/login.php?api_key=YOURAPIKEY&connect_display=popup&v=1.0&next=http://www.facebook.com/connect/login_success.html&cancel_url=http://www.facebook.com/connect/login_failure.html&fbconnect=true&return_session=true&session_key_only=true&req_perms=read_stream,publish_stream,offline_access

If the user is redirected to the URL specified by the next parameter, then Facebook grants your application a session. This session is appended to the URL as a JSON-decodable object of the form:

&session={“session_key”:”SESSIONKEY”, “uid”:USERID, “expires”:0 || UNIXTIME, “secret”:”SESSIONSECRET”}

In continuing with the above example, the redirect for a successful login would be:

http://www.facebook.com/connect/login_success.html?session=%7B%22session_key%22%3A%223.kxhAu6W0qo_bLGjmdWrgfw__.86400.1243443600-688626964%22%2C%22uid%22%3A%22688626964%22%2C%22expires%22%3A1243443600%2C%22secret%22%3A%220NVNMxpO6jVyDcVCvVv_PA__%22%2C%22sig%22%3A%22ac1c0c77c137567389defea70481b7aa%22%7D

If the user grants your application the offline_access extended permission, 0 gets returned for expires and the session never expires unless the user removes the application. In this case, you should store the session key so the user doesn’t have to log in the next time he or she launches your application.

Once the browser has been redirected successfully and you have your session information, you should automatically close the browser window.
Note: The above code will execute only once. We should note down the above session key, This will be used to auto login into the application.

Note: The above code will execute only once. We should note down the above session key, This will be used to auto login into the application.

If you don’t save these session key values you should generate other token key to create one time session key.

We can use the token only once.

Step4: Setting Permission for wall

Giving Permission to your application to publish on facebook wall. To give permission just replace the your API key in below URL and execute in browser.

http://www.facebook.com/login.php?api_key=APIKEYXxxxxxxxxxxxxxxxxx&connect_display=popup&v=1.0&next=http://www.facebook.com/connect/login_success.html&cancel_url=http://www.facebook.com/connect/login_failure.html&fbconnect=true&return_session=true&req_perms=read_stream,publish_stream,offline_access

Then you must see the below 3 Screens

If you don’t see the below then your call back URL or Canvas URL must be incorrect, please check again your application settings and execute the URL again.

allowpermission

allowpublishing

Then on final page, you will see a success message.  That’s it you have given permission for read_stream,publish_stream and offline_access.

Step5: Publishing the message on Facebook Wall

Java Code to create facebook object with onetime session key and publishing the message on Facebook Wall.

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpState;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpClientParams;

import com.google.code.facebookapi.Attachment;
import com.google.code.facebookapi.AttachmentMediaImage;
import com.google.code.facebookapi.FacebookException;
import com.google.code.facebookapi.FacebookJsonRestClient;
import com.google.code.facebookapi.FeedFacebookPhoto;
import com.google.code.facebookapi.Permission;
import com.google.code.facebookapi.TemplatizedAction;

public class SendtoFacebook {

	public static void main (String a[]) throws FacebookException{ 

	SendtoFacebook sfb=new SendtoFacebook();
	sfb.send("From My App: publish steven on facebook");
	}
	public void send(String message)throws FacebookException{

		String FB_APP_API_KEY = new String("YOUR_APIKEY");
		String FB_APP_SECRET = new String("YOUR_SECRET");
		String FB_SESSION_KEY = new String("YOUR_ONETIMESESSIONKEY");
		FacebookJsonRestClient facebook = new FacebookJsonRestClient( FB_APP_API_KEY, FB_APP_SECRET, FB_SESSION_KEY );

		//FacebookJsonRestClient facebookClient2 = (FacebookJsonRestClient)facebook.getFacebookRestClient();
		FacebookJsonRestClient facebookClient = (FacebookJsonRestClient)facebook;
facebookClient.stream_publish(message, null, null, null, null);

			System.out.println("successfully updated");

	}
}

Now you will see the post on wall Great.

published on facebook

So thrilling isn’t we can also publish photos videos on wall.

http://wiki.developers.facebook.com/index.php/Stream.publish

have a great day

– Steven

Steven Fan Page on Facebook

Please don’t copy this content to any site. This is fully protected by TheUnical Technologies

Install Java Runtime Environment (JRE) in Ubuntu 9.10 (Karmic

Java is an object-oriented programming language developed by Sun Microsystems in the early 1990s. Java applications are compiled to bytecode, which at runtime is either interpreted or compiled to native machine code for execution.

The language itself derives much of its syntax from C and C++ but has a simpler object model and fewer low-level facilities. JavaScript, a scripting language, shares a similar name and has similar syntax, but is not directly related to Java.

Currently Ubuntu has the following Java packages

sun-java6-bin – Contains the binaries

sun-java6-demo – Contains demos and examples

sun-java6-doc – Contains the documentation

sun-java6-fonts – Contains the Lucida TrueType fonts from the JRE

sun-java6-jdk – Contains the metapackage for the JDK

sun-java6-jre – Contains the metapackage for the JRE

sun-java6-plugin – Contains the plug-in for Mozilla-based browsers

sun-java6-source – Contains source files for the JDK

Installing the Java Runtime Environment

First you need to check multiverse repository enabled or not after that open a terminal window. Since you are going to be installing the JRE and the web browser plug-in, you’ll be using the following command from a terminal

sudo apt-get install sun-java6-jre sun-java6-plugin sun-java6-fonts

Once it downloads the packages and begins the installation, you’ll get a screen that contains the Sun Operating System Distributor License for Java and hit Enter to continue.

1

You’ll see a dialog that asks you if you agree with the DLJ license terms. Select Yes, and hit Enter; the JRE will finish installing.

2

Testing Java Runtime Environment

You’ll want to confirm that your system is configured properly for Sun’s JRE. This is a two-step process.

First, check that the JRE is properly installed by running the following command from a terminal.

java -version

You should get similar output

3

Testing Java Plugin for Firefox

open Firefox and typing about:plugins in the address bar and check for java plugin

4