Spring Example

pom.xml

—————————————————-

<?xml version=”1.0″ encoding=”UTF-8″?><project>
<modelVersion>4.0.0</modelVersion>
<groupId>Spring3HibernateMaven</groupId>
<artifactId>Spring3HibernateMaven</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<description></description>
<build>

<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.5</source>
<target>1.5</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>2.0</version>
</plugin>
<plugin>
<groupId>org.mortbay.jetty</groupId>
<artifactId>maven-jetty-plugin</artifactId>
<version>6.1.9</version>
<configuration>
<contextPath>/Employee</contextPath>
<scanIntervalSeconds>3</scanIntervalSeconds>
<scanTargetPatterns>
<scanTargetPattern>
<directory>src/main/java</directory>
<excludes>
<exclude>**/*.jsp</exclude>
</excludes>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
</scanTargetPattern>
</scanTargetPatterns>
<!– webDefaultXml>src/main/resources/webdefault.xml
</webDefaultXml–>

</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!– dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>3.3.2.ga</version>
</dependency–>
<!– dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.4.2</version>
</dependency –>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
<!– dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.1.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.10</version>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>20030825.184428</version>
</dependency>
<dependency>
<groupId>commons-pool</groupId>
<artifactId>commons-pool</artifactId>
<version>20030825.183949</version>
</dependency–>
<dependency>
<groupId>org.mortbay.jetty</groupId>
<artifactId>jetty</artifactId>
<version>6.1.9</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.mortbay.jetty</groupId>
<artifactId>jsp-2.1</artifactId>
<version>6.1.9</version>
<scope>provided</scope>
</dependency>
</dependencies>
<properties>
<org.springframework.version>3.0.2.RELEASE</org.springframework.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
</project>

————————————————————–

/src/main/webapp/WEB-INF/web.xml

————————————-

<?xml version=”1.0″ encoding=”UTF-8″?>
<web-app xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance&#8221;
xmlns=”http://java.sun.com/xml/ns/javaee&#8221;
xmlns:web=”http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd&#8221;
xsi:schemaLocation=”http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd&#8221;
id=”WebApp_ID” version=”2.5″>
<display-name>Spring3-Hibernate</display-name>
<welcome-file-list>
<welcome-file>list.html</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>

———————————–

src/main/webapp/WEB-INF/spring-servlet.xml

—————————————————

<?xml version=”1.0″ encoding=”UTF-8″?>
<beans xmlns=”http://www.springframework.org/schema/beans&#8221;
xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance&#8221;
xmlns:aop=”http://www.springframework.org/schema/aop&#8221;
xmlns:context=”http://www.springframework.org/schema/context&#8221;
xmlns:jee=”http://www.springframework.org/schema/jee&#8221;
xmlns:lang=”http://www.springframework.org/schema/lang&#8221;
xmlns:p=”http://www.springframework.org/schema/p&#8221;
xmlns:tx=”http://www.springframework.org/schema/tx&#8221;
xmlns:util=”http://www.springframework.org/schema/util&#8221;
xsi:schemaLocation=”http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd”&gt;

<context:annotation-config />
<context:component-scan base-package=”…” />

<bean id=”jspViewResolver”
class=”org.springframework.web.servlet.view.InternalResourceViewResolver”>
<property name=”viewClass”
value=”org.springframework.web.servlet.view.JstlView” />
<property name=”prefix” value=”/WEB-INF/jsp/” />
<property name=”suffix” value=”.jsp” />
</bean>

<bean id=”messageSource”
class=”org.springframework.context.support.ReloadableResourceBundleMessageSource”>
<property name=”basename” value=”classpath:messages” />
<property name=”defaultEncoding” value=”UTF-8″ />
</bean>
<bean id=”propertyConfigurer”
class=”org.springframework.beans.factory.config.PropertyPlaceholderConfigurer”
p:location=”/WEB-INF/jdbc.properties” />

<bean id=”contactService”>
<property name=”contactDAO” ref=”contactDAO” />

</bean>
<bean id=”contactDAO”>

</bean>
<!–bean id=”dataSource”
class=”org.apache.commons.dbcp.BasicDataSource” destroy-method=”close”
p:driverClassName=”${jdbc.driverClassName}”
p:url=”${jdbc.databaseurl}” p:username=”${jdbc.username}”
p:password=”${jdbc.password}” />

<bean id=”sessionFactory”
class=”org.springframework.orm.hibernate3.LocalSessionFactoryBean”>
<property name=”dataSource” ref=”dataSource” />
<property name=”configLocation”>
<value>classpath:hibernate.cfg.xml</value>
</property>
<property name=”configurationClass”>
<value>org.hibernate.cfg.AnnotationConfiguration</value>
</property>
<property name=”hibernateProperties”>
<props>
<prop key=”hibernate.dialect”>${jdbc.dialect}</prop>
<prop key=”hibernate.show_sql”>true</prop>
</props>
</property>
</bean>

<tx:annotation-driven />

<bean id=”transactionManager”
class=”org.springframework.orm.hibernate3.HibernateTransactionManager”>
<property name=”sessionFactory” ref=”sessionFactory” />
</bean–>

</beans>

————————————————————-

/src/main/webapp/WEB-INF/jdbc.properties

——————————————————

jdbc.driverClassName= com.mysql.jdbc.Driver
jdbc.dialect=org.hibernate.dialect.MySQLDialect
jdbc.databaseurl=jdbc:mysql://localhost:3306/ContactManager
jdbc.username=root
jdbc.password=

————————————-

src/main/webapp/WEB-INF/jsp/contact.jsp

———————————————

<%@taglib uri=”http://www.springframework.org/tags&#8221; prefix=”spring”%>
<%@taglib uri=”http://www.springframework.org/tags/form&#8221; prefix=”form”%>
<%@taglib uri=”http://java.sun.com/jsp/jstl/core&#8221; prefix=”c”%>
<html>
<head>
<title>Spring 3 MVC Series – Contact Manager</title>
<style type=”text/css”>
body {
font-family: sans-serif;
}
.data, .data td {
border-collapse: collapse;
width: 100%;
border: 1px solid #aaa;
margin: 2px;
padding: 2px;
}
.data th {
font-weight: bold;
background-color: #5C82FF;
color: white;
}
</style>
</head>
<body>

<h2>Contact Manager</h2>

<form:form method=”post” action=”add.html” commandName=”contact”>

<table>
<tr>
<td><form:label path=”firstname”><spring:message code=”label.firstname”/></form:label></td>
<td><form:input path=”firstname” /></td>
</tr>
<tr>
<td><form:label path=”lastname”><spring:message code=”label.lastname”/></form:label></td>
<td><form:input path=”lastname” /></td>
</tr>
<tr>
<td><form:label path=”email”><spring:message code=”label.email”/></form:label></td>
<td><form:input path=”email” /></td>
</tr>
<tr>
<td><form:label path=”telephone”><spring:message code=”label.telephone”/></form:label></td>
<td><form:input path=”telephone” /></td>
</tr>
<tr>
<td>Country :</td>
<td><form:select path=”country”>
<form:option value=”NONE” label=”— Select —” />
<form:options items=”${countryList}” />
</form:select>
</td>

</tr>
<tr>
<td colspan=”2″>
<input type=”submit” value=”<spring:message code=”label.addcontact”/>”/>
</td>
</tr>
</table>
</form:form>

<h3>Contacts</h3>
<c:if test=”${!empty contactList}”>
<table>
<tr>
<th>Name</th>
<th>Email</th>
<th>Telephone</th>
<th>&nbsp;</th>
</tr>
<c:forEach items=”${contactList}” var=”contact”>
<tr>
<td>${contact.lastname}, ${contact.firstname} </td>
<td>${contact.email}</td>
<td>${contact.telephone}</td>
<td><a href=”delete/${contact.id}”>delete</a></td>
</tr>
</c:forEach>
</table>
</c:if>

</body>
</html>

—————————————————

src/main/resources/messages_en.properties

——————————————————

label.firstname=First Name
label.lastname=Last Name
label.email=Email
label.telephone=Telephone
label.addcontact=Add Contact

label.menu=Menu
label.title=Contact Manager
label.footer=&copy; …

——————————————-

src/main/resources/hibernate.cfg.xml

—————————————–

<?xml version=’1.0′ encoding=’utf-8’?>
<!DOCTYPE hibernate-configuration PUBLIC
“-//Hibernate/Hibernate Configuration DTD//EN”
http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd”&gt;

<hibernate-configuration>
<session-factory>
<mapping />
</session-factory>

</hibernate-configuration>

———————————–

src/main/java/net/contact/controller/ContactController.java

—————————————————————-

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

import net.contact.form.Contact;
import net.contact.service.ContactService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class ContactController {

@Autowired
private ContactService contactService;

@RequestMapping(“/index”)
public String listContacts(Map<String, Object> map) {

map.put(“contact”, new Contact());
map.put(“contactList”, contactService.listContact());

Map<String,String> country = new HashMap<String,String>();
country.put(“US”, “United Stated”);
country.put(“CHINA”, “China”);
country.put(“SG”, “Singapore”);
country.put(“MY”, “Malaysia”);
map.put(“countryList”, country);

return “contact”;
}

@RequestMapping(value = “/add”, method = RequestMethod.POST)
public String addContact(@ModelAttribute(“contact”)
Contact contact, BindingResult result) {

contactService.addContact(contact);

return “redirect:/index”;
}

@RequestMapping(“/delete/{contactId}”)
public String deleteContact(@PathVariable(“contactId”)
Integer contactId) {

contactService.removeContact(contactId);

return “redirect:/index”;
}
}

—————————————————————

/src/main/java/net/contact/form/Contact.java

———————————————————————-

package net.contact.form;

import java.util.Map;

public class Contact {

private Integer id;

private String firstname;

private String lastname;

private String email;

private String telephone;

private String country;

public String getEmail() {
return email;
}
public String getTelephone() {
return telephone;
}
public void setEmail(String email) {
this.email = email;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
public String getFirstname() {
return firstname;
}
public String getLastname() {
return lastname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}

}

——————————————-

/src/main/java/net/contact/service/ContactService.java

———————————————————————–

package net.contact.service;

import java.util.List;

import net.contact.form.Contact;

public interface ContactService {

public void addContact(Contact contact);
public List<Contact> listContact();
public void removeContact(Integer id);
}

————————————————-

src/main/java/net/contact/service/ContactServiceImpl.java

———————————————————–

package net.contact.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import net.contact.dao.ContactDAO;
import net.contact.form.Contact;

//@Service
public class ContactServiceImpl implements ContactService {

// @Autowired
private ContactDAO contactDAO;

public void setContactDAO(ContactDAO contactDAO) {
this.contactDAO = contactDAO;
}

// @Transactional
public void addContact(Contact contact) {
contactDAO.addContact(contact);
}

// @Transactional
public List<Contact> listContact() {

return contactDAO.listContact();
}

// @Transactional
public void removeContact(Integer id) {

}
}

————————————————————–

src/main/java/net/contact/dao/ContactDAO.java

—————————————————–

package net.contact.dao;

import java.util.List;

import net.contact.form.Contact;

public interface ContactDAO {

public void addContact(Contact contact);
public List<Contact> listContact();
public void removeContact(Integer id);
}

—————————————————–

src/main/java/net/contact/dao/ContactDAOImpl.java

——————————————–

package net.contact.dao;

import java.util.ArrayList;
import java.util.List;

import net.contact.form.Contact;

//import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

public class ContactDAOImpl implements ContactDAO {

public void addContact(Contact contact) {

System.out.println(contact.getFirstname());
//sessionFactory.getCurrentSession().save(contact);
}

public List<Contact> listContact() {

Contact c1 = new Contact();
c1.setFirstname(“Aju”);
c1.setId(1);
c1.setEmail(“test@gmail.com”);
c1.setLastname(“B”);
List<Contact> list = new ArrayList<Contact>();
list.add(c1);
return list;
// return sessionFactory.getCurrentSession().createQuery(“from Contact”)
// .list();
}

public void removeContact(Integer id) {
// Contact contact = (Contact) sessionFactory.getCurrentSession().load(
// Contact.class, id);
// if (null != contact) {
// sessionFactory.getCurrentSession().delete(contact);
// }

}
}

———————————————————-

MsgWaitForMultipleObjectsEx

The arguments to the functions are:

nCount [in]

The maximum number of object handles is MAXIMUM_WAIT_OBJECTS minus one.

pHandles [in]

The array can contain handles to multiple types of objects. It may not contain multiple copies of the same handle.

If one of these handles is closed while the wait is still pending, the function’s behavior is undefined.

dwMilliseconds

The function either waits for dwMilliseconds or until the object values

dwWakeMask [in]

The input types for which an input event object handle will be added to the array of object handles. T

Concept:

Let us assume that we have a thread named as ‘thread1′. The thread does some task and needs two values for further proceedings. Let the value required by this thread be processed by another two threads, say named as ‘threadN’ and ‘threadN+1′. Now thread1 has to wait until the values required [ Eg: Object A and Object B ] are filled by threads ‘threadN’ and ‘threadN+1′.

By using MsgWaitForMultipleObjectsEx, we can achieve this. This function makes the execution wait until the objects A and B are received /filled. If values are not filled within ‘dwMilliseconds’, the wait for object stops and the execution continues sequentially.

We can think of  MsgWaitForMultipleObjectsEx as an asynchronous mechanism. let us consider a scenario where we have a UI thread and logic processing thread, executing concurrently. Then we can display a busy icon in the UI until the logic thread manipulates the data values to be rendered on the UI. In this situation we can assume that the function MsgWaitForMultipleObjectsEx is placed in logic thread and it is waiting for threadN and threadN+1 to supply values in Objects A and B, The communication between the UI component and the logic procesing unit can occur asynchronusly. Wehn value is obtained from threadN and threadN+1 , the waiting process terminates and the object values can be rendered on UI.

J2ME get and post

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.io.*;
import java.io.*;

public class GetNpost extends MIDlet implements CommandListener
{
private Display display; // Reference to Display object
private Form fmMain; // The main form
private Alert alError; // Alert to error message
private Command cmGET; // Request method GET
private Command cmPOST; // Request method Post
private Command cmExit; // Command to exit the MIDlet
private TextField tfAcct; // Get account number
private TextField tfPwd; // Get password
private StringItem siBalance;// Show account balance
private String errorMsg = null;
public GetNpost()
{
display = Display.getDisplay(this);

// Create commands
cmGET = new Command(“GET”, Command.SCREEN, 2);
cmPOST = new Command(“POST”, Command.SCREEN, 3);
cmExit = new Command(“Exit”, Command.EXIT, 1);

// Textfields
tfAcct = new TextField(“Account:”, “”, 5, TextField.NUMERIC);
tfPwd = new TextField(“Password:”, “”, 10, TextField.ANY | TextField.PASSWORD);

// Balance string item
siBalance = new StringItem(“Balance: $”, “”);

// Create Form, add commands & componenets, listen for events
fmMain = new Form(“Account Information”);
fmMain.addCommand(cmExit);
fmMain.addCommand(cmGET);
fmMain.addCommand(cmPOST);
fmMain.append(tfAcct);
fmMain.append(tfPwd);
fmMain.append(siBalance);
fmMain.setCommandListener(this);
}

public void startApp()
{
display.setCurrent(fmMain);
}

public void pauseApp()
{ }
public void destroyApp(boolean unconditional)
{ }

public void commandAction(Command c, Displayable s)
{
if (c == cmGET || c == cmPOST)
{
try
{
if (c == cmGET)
lookupBalance_withGET();
else
lookupBalance_withPOST();
}
catch (Exception e)
{
System.err.println(“Msg: ” + e.toString());
}
}
else if (c == cmExit)
{
destroyApp(false);
notifyDestroyed();
}
}

/*————————————————–
* Access servlet using GET
*————————————————-*/
private void lookupBalance_withGET() throws IOException
{
HttpConnection http = null;
InputStream iStrm = null;
boolean ret = false;

// Data is passed at the end of url for GET
String url = “http://www.mycgiserver.com/servlet/corej2me.GetNpostServlet&#8221; + “?” +
“account=” + tfAcct.getString() + “&” +
“password=” + tfPwd.getString();
try
{
http = (HttpConnection) Connector.open(url);
//—————-
// Client Request
//—————-
// 1) Send request method
http.setRequestMethod(HttpConnection.GET);
// 2) Send header information – none
// 3) Send body/data – data is at the end of URL

//—————-
// Server Response
//—————-
iStrm = http.openInputStream();
// Three steps are processed in this method call
ret = processServerResponse(http, iStrm);
}
finally
{
// Clean up
if (iStrm != null)
iStrm.close();
if (http != null)
http.close();
}

// Process request failed, show alert
if (ret == false)
showAlert(errorMsg);
}

/*————————————————–
* Access servlet using POST
*————————————————-*/
private void lookupBalance_withPOST() throws IOException
{
HttpConnection http = null;
OutputStream oStrm = null;
InputStream iStrm = null;
boolean ret = false;
// Data is passed as a separate stream for POST (below)
String url = “http://www.mycgiserver.com/servlet/corej2me.GetNpostServlet&#8221;;
try
{
http = (HttpConnection) Connector.open(url);
oStrm = http.openOutputStream();
//—————-
// Client Request
//—————-
// 1) Send request type
http.setRequestMethod(HttpConnection.POST);
// 2) Send header information. Required for POST to work!
http.setRequestProperty(“Content-Type”, “application/x-www-form-urlencoded”);

// If you experience connection/IO problems, try
// removing the comment from the following line
// http.setRequestProperty(“Connection”, “close”);

// 3) Send data/body
// Write account number
byte data[] = (“account=” + tfAcct.getString()).getBytes();
oStrm.write(data);
// Write password
data = (“&password=” + tfPwd.getString()).getBytes();
oStrm.write(data);
// For 1.0.3 remove flush command
// See the note at the bottom of this file
// oStrm.flush();

//—————-
// Server Response
//—————-
iStrm = http.openInputStream();
// Three steps are processed in this method call
ret = processServerResponse(http, iStrm);
}
finally
{
// Clean up
if (iStrm != null)
iStrm.close();
if (oStrm != null)
oStrm.close();
if (http != null)
http.close();
}

// Process request failed, show alert
if (ret == false)
showAlert(errorMsg);
}

/*————————————————–
* Process a response from a server
*————————————————-*/
private boolean processServerResponse(HttpConnection http, InputStream iStrm) throws IOException
{
//Reset error message
errorMsg = null;
// 1) Get status Line
if (http.getResponseCode() == HttpConnection.HTTP_OK)
{
// 2) Get header information – none
// 3) Get body (data)
int length = (int) http.getLength();
String str;
if (length != -1)
{
byte servletData[] = new byte[length];
iStrm.read(servletData);
str = new String(servletData);
}
else // Length not available…
{
ByteArrayOutputStream bStrm = new ByteArrayOutputStream();
int ch;
while ((ch = iStrm.read()) != -1)
bStrm.write(ch);

str = new String(bStrm.toByteArray());
bStrm.close();
}
// Update the string item on the display
siBalance.setText(str);
return true;
}
else
// Use message from the servlet
errorMsg = new String( http.getResponseMessage());

return false;
}

/*————————————————–
* Show an Alert
*————————————————-*/
private void showAlert(String msg)
{
// Create Alert, use message returned from servlet
alError = new Alert(“Error”, msg, null, AlertType.ERROR);

// Set Alert to type Modal
alError.setTimeout(Alert.FOREVER);

// Display the Alert. Once dismissed, display the form
display.setCurrent(alError, fmMain);
}
}

/*
The call to flush() uses a feature of HTTP 1.1 that allows data to be
sent in smaller loads. When calling flush() or sending a large
amount of data (in version 1.0.3) chunked encoding is used.

If you are using an HTTP 1.0 server or proxy server the chunked
transfer may cause problems.

You can avoid the chunking behavior with small transactions by just
calling close() where you were using flush(). For larger transactions
you need to buffer your output so a single write() and close() are
issued to the output stream.
*/
/*————————————————–
* GetNpostServlet.java
*
* Show how GET and POST from client can access and
* process the same data.
* Account information is maintained in a database
* (connecting with jdbc)
*
* Table: acctInfo
* Columns:
* account – integer
* password – varchar
* balance – integer
*
* Example from the book: Core J2ME Technology
* Copyright John W. Muchow http://www.CoreJ2ME.com
* You may use/modify for any non-commercial purpose
*————————————————-*/
//package corej2me; // Required for mycgiserver.com

import java.util.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;

public class GetNpostServlet extends HttpServlet
{
protected void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
{
// Same code appears in doPost()
// Shown both places to emphasize that data is received thru
// different means (environment variable vs stream),
// yet processed the same inside the servlet
String acct = req.getParameter(“account”),
pwd = req.getParameter(“password”);

String balance = accountLookup(acct, pwd);

if (balance == null)
{
res.sendError(res.SC_BAD_REQUEST, “Unable to locate account.”);
return;
}

res.setContentType(“text/plain”);
PrintWriter out = res.getWriter();
out.print(balance);
out.close();
}
protected void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
{
// Same code appears in doGet()
// Shown both places to emphasize that data is received thru
// different means (stream vs environment variable),
// yet processed the same inside the servlet
String acct = req.getParameter(“account”),
pwd = req.getParameter(“password”);

String balance = accountLookup(acct, pwd);

if (balance == null)
{
res.sendError(res.SC_BAD_REQUEST, “Unable to locate account.”);
return;
}
res.setContentType(“text/plain”);
PrintWriter out = res.getWriter();
out.print(balance);
out.close();
}

/*————————————————–
* Lookup bank account balance in database
*————————————————-*/
private String accountLookup(String acct, String pwd)
{
Connection con = null;
Statement st = null;
StringBuffer msgb = new StringBuffer(“”);

try
{
// These will vary depending on your server/database
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
con = DriverManager.getConnection(“jdbc:odbc:acctInfo”);

Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(“Select balance from acctInfo where account = ” +
acct + “and password = ‘” + pwd + “‘”);
if (rs.next())
return rs.getString(1);
else
return null;
}
catch (Exception e)
{
return e.toString();
}
}
/*————————————————–
* Information about servlet
*————————————————-*/
public String getServletInfo()
{
return “GetNpostServlet 1.0 – John W. Muchow – http://www.corej2me.com”;
}
}

Producer Consumer problem using shared memory

/* Producer-Consumer program to accept data into shared memory and perform operations using semaphores */
// Producer part.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/shm.h>
#include <sys/sem.h>
#include <sys/types.h>
#include <unistd.h>
#include <semaphore.h>

int main()
{
int key1 = 1000,shmid1,key2 = 2000,shmid2,key3 = 3000,shmid3;
int sem_key = 4000,semid;
int *roll,*m,i,count = 0;
char *name;

shmid1 = shmget(key1,10,IPC_CREAT);
if(shmid1 == -1)
{
printf(“\n\t 1st ERROR : ALLOCATION FAILED >>> \n\n\t\t PROGRAM TERMINATED \n\n”);
exit(0);
}
roll = shmat(shmid1,NULL,0);

shmid2 = shmget(key2,100,IPC_CREAT);
if(shmid2 == -1)
{
printf(“\n\t 2nd ERROR : ALLOCATION FAILED >>> \n\n\t\t PROGRAM TERMINATED \n\n”);
exit(0);
}
name = shmat(shmid2,NULL,0);

shmid3 = shmget(key3,100,IPC_CREAT);
if(shmid3 == -1)
{
printf(“\n\t 3rd ERROR : ALLOCATION FAILED >>> \n\n\t\t PROGRAM TERMINATED \n\n”);
exit(0);
}
m = shmat(shmid3,NULL,0);

semid = semget(sem_key,1,IPC_CREAT);
if(semid == -1)
{
printf(“\n\t semaphore ERROR : SEMAPHORE CREATION FAILED >>> \n\n\t\t PROGRAM TERMINATED \n\n”);
exit(0);
}

struct sembuf lock_it;

lock_it.sem_flg = IPC_NOWAIT;
lock_it.sem_op = -1; // lock.
lock_it.sem_num = 0;
semop(semid,&lock_it,1);

do
{
count = count + 1;
printf(“\n\t Enter the details of student%d \n”,count);
printf(“\n\t ROLL NO. : “);
scanf(“%d”,roll);
if(*roll <= 0)
{
printf(“\n\n\t\t ERROR : INVALID ENTRY >>> \n\n\t\t PROGRAM TERMINATED \n\n”);
exit(0);
}
printf(“\n\t NAME : “);
scanf(“%s”,name);
printf(“\n\t Enter MARKS achieved for the subjects : “);
for(i = 0;i < 5;i++)
{
printf(“\n\t SUBJECT %d : “,i+1);
scanf(“%d”,m+i);
}
printf(“\n\n”);

lock_it.sem_flg = 0;
lock_it.sem_op = +1; // unlock.
lock_it.sem_num = 0;
semop(semid,&lock_it,1);

}while(*roll != 0);

shmctl(shmid1,IPC_RMID,NULL);
shmctl(shmid2,IPC_RMID,NULL);
shmctl(shmid3,IPC_RMID,NULL);

return 0;
}

….

// Consumer part.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/shm.h>
#include <sys/sem.h>
#include <sys/types.h>
#include <unistd.h>
#include <semaphore.h>

int main()
{
int key1 = 1000,shmid1,key2 = 2000,shmid2,key3 = 3000,shmid3;
int sem_key = 4000,semid;
int *roll,*m,i,count = 0,total,avg;
char *name;

shmid1 = shmget(key1,100,IPC_CREAT);
if(shmid1 == -1)
{
printf(“\n\t 1st ERROR : ALLOCATION FAILED >>> \n\n\t\t PROGRAM TERMINATED \n\n”);
exit(0);
}
roll = shmat(shmid1,NULL,0);

shmid2 = shmget(key2,100,IPC_CREAT);
if(shmid2 == -1)
{
printf(“\n\t 2nd ERROR : ALLOCATION FAILED >>> \n\n\t\t PROGRAM TERMINATED \n\n”);
exit(0);
}
name = shmat(shmid2,NULL,0);

shmid3 = shmget(key3,100,IPC_CREAT);
if(shmid3 == -1)
{
printf(“\n\t 3rd ERROR : ALLOCATION FAILED >>> \n\n\t\t PROGRAM TERMINATED \n\n”);
exit(0);
}
m = shmat(shmid3,NULL,0);

semid = semget(sem_key,1,IPC_CREAT);
if(semid == -1)
{
printf(“\n\t ERROR : SEMAPHORE CREATION FAILED >>> \n\n\t\t PROGRAM TERMINATED \n\n”);
exit(0);
}

struct sembuf lock_it;

do
{
lock_it.sem_flg = 0;
lock_it.sem_op = -1; //lock
lock_it.sem_num = 0;
semop(semid,&lock_it,1);

total = 0;
count = count + 1;

printf(“\n\n\t DETAILED RECORD FOR STUDENT%d “,count);
printf(“\n\t NAME : %s”,name);
printf(“\n\t ROLL : %d”,*roll);
printf(“\n\t MARKS ACHIEVED “);
for(i = 0;i < 5;i++)
{
total = total + *(m+i);
printf(“\n\t SUBJECT%d : %d”,i+1,*(m+i));
}
avg = total / 5;
printf(“\n\t TOTAL MARKS : %d”,total);
printf(“\n\t AVERAGE PERCENT : %d”,avg);
printf(“\n\n”);
sleep(1);

}while(*roll != 0);

shmctl(shmid1,IPC_RMID,NULL);
shmctl(shmid2,IPC_RMID,NULL);
shmctl(shmid3,IPC_RMID,NULL);

return 0;
}

Maven Spring Hibernate MySQL

I would like to discuss , a sample working program using Maven, Hibernate, Spring ad MySQL
The development IDE is eclipse.
Step 1:

If we do not have Maven plugin, we can download from eclipse Market place. [ Help -> MarketPlace ]

Step 2:

As our objective is to interact with MySQL, we shall create a database with a name [ Eg: raymond]. create a table Item with 3 fields ItemId, ItemCode and ItemName . ItemId is auto increment and Item Code is primary key. We shall create a POJO java class [ in Step 5 ] with getters and setters that corresponds to ItemId, ItemCode and ItemName in the data base table.

Step 3:

Once our IDE is ready, we can create a new maven project using eclipse. Select Maven archetype as : maven-archetype-quickstart. The Artifactid will be the project name. [ Eg; SampleMavenProject ]. The eclipse IDE will generate the folder structure and the main folders is : src/main/java. We can create our packages inside this folder. As a convention we can create separate packages for:

1. App.java,

Create a package for eg: com.myname.SampleMavenProject. Create a java file and name it as App.java. This program would contain ‘public static void main’ function to run our sample application. The aim of the file would be to create an object of POJO class and set its members with values and we can call save , update and delete functions to save the POJO value into database.The code for App.java id:

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;

public class App
{
public static void main( String[] args )
{
ApplicationContext appContext =
new ClassPathXmlApplicationContext(“resources/config/BeanLocations.xml”);

}

}

2. Buisness Logic or buisness operations

For our business operations, we can create two packages. (a) for interface that prescribes the functionality (b) for implementing the interface.Eg: com.myname.SampleMavenProject.item.bo and com.myname.SampleMavenProject.item.bo.impl.

Inside the package intended for interface, we can create a java interface file (ItemBo.java) with following code:

import com.myname.SampleMavenProject.item.model.Item;// Location of POJO

public interface ItemBo {

void save(Item item);
void update(Item item);
void delete(Item item);
Item findByItemCode(String itemCode);
}

Inside com.myname.SampleMavenProject.item.bo.impl, create a java file with name: ItemBoImpl.java

public class ItemBoImpl implements ItemBo{

ItemDao itemDao;

public void setItemDao(ItemDao itemDao) {
this.itemDao = itemDao;
}

public void save(Item item){
itemDao.save(item);
}

public void update(Item item){
itemDao.update(item);
}

public void delete(Item item){
itemDao.delete(item);
}

public Item findByItemCode(String itemCode){
return itemDao.findByItemCode(itemCode);
}
}

In this file we have implemented save, update, delete functions and also invoked the data access function and passed the pojo object to it.

3. Data Access Object or Database interaction.

we can create two packages for defining database related operations. Name the packages as com.myname.SampleMavenProject.item.dao and com.myname.SampleMavenProject.item.dao.impl

create a interface inside com.myname.SampleMavenProject.item.dao

import com.myname.SampleMavenProject.item.model.Item;// Location of POJO

public interface ItemDao {

void save(Item item);
void update(Item item);
void delete(Item item);
Item findByItemCode(String itemCode);
}

create implementation file inside the package : com.myname.SampleMavenProject.item.dao.impl

import java.util.List;

import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

public class ItemDaoImpl extends HibernateDaoSupport implements ItemDao{

public void save(Item item){
getHibernateTemplate().save(item);
}

public void update(Item item){
getHibernateTemplate().update(item);
}

public void delete(Item item){
getHibernateTemplate().delete(item);
}

public Item findByItemCode(String itemCode){
List list = getHibernateTemplate().find(
“from Item where itemCode=?”,itemCode
);
return (Item)list.get(0);
}

}

Step 4: creating POJO class

create package : “com.myname.SamplemavenProject.item.model.Item”
import java.io.Serializable;

public class Item implements Serializable {

private static final long serialVersionUID = 1L;

private Long itemId;
private String itemCode;
private String itemName;
public Long getItemId() {
return itemId;
}
public void setItemId(Long itemId) {
this.itemId = itemId;
}
public String getItemCode() {
return itemCode;
}
public void setItemCode(String itemCode) {
this.itemCode = itemCode;
}
public String getItemName() {
return itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
}

Step 5: resources

Stetting up resources using xml files for Maven. Since this is a ‘maven-archetype-quickstart’ project, we should create a folder/package ‘resources’ in src/main/java. Maven expects xml files to be placed in ‘resources’ folder.

Inside ‘resources’ folder we can create separate packages for different purpose. Let us create config, database, hibernate, properties and spring packages inside ‘resources’.

1. Inside config package, let us create BeanLocations.xml

<beans xmlns=”http://www.springframework.org/schema/beans&#8221;
xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance&#8221;
xsi:schemaLocation=”http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd”&gt;

<!– Database Configuration –>
<import resource=”../database/DataSource.xml”/>
<import resource=”../database/Hibernate.xml”/>

<!– Beans Declaration –>
<import resource=”../spring/Item.xml”/>

</beans>

2. Inside database package, create ‘DataSource.xml’

<beans xmlns=”http://www.springframework.org/schema/beans&#8221;
xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance&#8221;
xsi:schemaLocation=”http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd”&gt;

<bean
class=”org.springframework.beans.factory.config.PropertyPlaceholderConfigurer”>
<property name=”location”>
<value>resources/properties/database.properties</value>
</property>
</bean>

<bean id=”dataSource” destroy-method=”close” class=”org.springframework.jdbc.datasource.DriverManagerDataSource”>
<!– class=”org.apache.commons.dbcp.BasicDataSource”>–>

<property name=”driverClassName” value=”${jdbc.driverClassName}” />
<property name=”url” value=”${jdbc.url}” />
<property name=”username” value=”${jdbc.username}” />
<property name=”password” value=”${jdbc.password}” />

<!– <property name=”defaultAutoCommit” value=”true” /> –>
</bean>

</beans>

3. Inside database package, create ‘Hibernate.xml’

<?xml version=”1.0″ encoding=”UTF-8″?>
<beans xmlns=”http://www.springframework.org/schema/beans&#8221;
xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance&#8221;
xsi:schemaLocation=”http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd”&gt;

<!– Hibernate session factory –>
<bean id=”sessionFactory”
class=”org.springframework.orm.hibernate3.LocalSessionFactoryBean”>

<property name=”dataSource”>
<ref bean=”dataSource”/>
</property>

<!– org.hibernate.dialect.MySQLDialect –>
<property name=”hibernateProperties”>
<props>
<prop key=”hibernate.dialect”>org.hibernate.dialect.MySQL5InnoDBDialect</prop>
<prop key=”hibernate.show_sql”>true</prop>
<prop key=”hibernate.connection.autocommit”>false</prop>
<prop key=”hibernate.transaction.factory_class”>
org.hibernate.transaction.JDBCTransactionFactory
</prop>

</props>
</property>

<property name=”mappingResources”>
<list>
<value>resources/hibernate/Item.hbm.xml</value>
</list>
</property>

</bean>
</beans>

Now we have defined the database connection parameters in DataSource.xml and Hibernate properties in Hibernate.xml. In Hibernate.xml, we define the dialect with database. Since our data base is MySQL, we have used org.hibernate.dialect.MySQL5InnoDBDialect. properties like auto commit is handled here. Regarding MySQL database, auto commit in Hibernate.xml does not have any implications (pertaining to my knowledge).

4. create hibernate package and inside the package create Item.hbm.xml file.

In this file we define the database structure.

<?xml version=”1.0″?>
<!DOCTYPE hibernate-mapping PUBLIC “-//Hibernate/Hibernate Mapping DTD 3.0//EN”
http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd”&gt;

<hibernate-mapping>
<class name=”com.myname.SampleMavenProject.item.model.Item” table=”item” catalog=”raymond”>
<id name=”itemId” type=”java.lang.Long”>
<column name=”ITEM_ID” />
<generator class=”identity” />
</id>
<property name=”itemCode” type=”string”>
<column name=”ITEM_CODE” length=”10″ not-null=”true” unique=”true” />
</property>
<property name=”itemName” type=”string”>
<column name=”ITEM_NAME” length=”20″ not-null=”true” unique=”true” />
</property>
</class>
</hibernate-mapping>

We have now mapped the database table item inside the database ‘raymond’ to hibernate.

5. create ‘properties’ package inside resources. create database.properties file in the package.

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/raymond
jdbc.username=raymond
jdbc.password=raymond

We have defined the connection Url, Driver class, username and password. It is better we create a new user in database with all necessary privilages. For this example, I have create a new user with user name as ‘raymond’ and password also as ‘raymond’

6. Create spring package inside resources. Add spring.xml file to it.

<beans xmlns=”http://www.springframework.org/schema/beans&#8221;
xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance&#8221;
xsi:schemaLocation=”http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd”&gt;

<!– Item business object –>
<bean id=”itemBo” class=”com.myname.SamplemavenProject.item.bo.impl.ItemBoImpl” >
<property name=”itemDao” ref=”itemDao” />
</bean>

<!– Item Data Access Object –>
<bean id=”itemDao”.myname.SamplemavenProject.item.dao.impl.ItemDaoImpl” >
<property name=”sessionFactory” ref=”sessionFactory”></property>
</bean>

</beans>

In this file we mention the bean id to spring frame work for auto wiring facility. The java business class and its corresponding data access object class are defined. The session factory property is also defined.

Step 6: External dependencies

Now we are almost complete with eclipse IDE, please check if you have

apache-maven-2.2.1

if not download one and place it in a drive [ Eg:C:\apache-maven-2.2.1 ]

In Windows O.S, create the following Environment variables:

1. M2_HOME

C:\apache-maven-2.2.1

2. M2

%M2_HOME%\bin

3. Path

%M2%;

Now we can execute Maven from command line.

Step 7. Run the application

In eclipse project, in Run Configuration, add/set Maven Runtime as Eg:C:\apache-maven-2.2.1

Now to download the dependency jar files for the project, we should define pom.xml

Some of the dependencies that , i have mentioned is extra ( may be useful in future examples)

<project xmlns=”http://maven.apache.org/POM/4.0.0&#8243; xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance&#8221;
xsi:schemaLocation=”http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd”&gt;
<modelVersion>4.0.0</modelVersion>

<groupId>com.myname</groupId>
<artifactId>SampleMavenProject</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>

<name>Maven3</name>
<url>http://maven.apache.org</url&gt;

<repositories>
<repository>
<id>spring-milestone</id>
<name>Spring Portfolio Milestone Repository</name>
<url> http://s3.amazonaws.com/maven.springframework.org/milestone
</url>
</repository>
<repository>
<id>maven2-repository.dev.java.net</id>
<name>Java.net Repository for Maven</name>
<url> https://maven2-repository.dev.java.net/nonav/repository</url&gt;
</repository>

</repositories>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>

<dependencies>
<dependency>
<groupId>org.codehaus.mojo</groupId>
<artifactId>sql-maven-plugin</artifactId>
<version>1.5</version>
</dependency>
<!– Spring framework –>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring</artifactId>
<version>2.5.6</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-dao</artifactId>
<version>1.2.7</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>2.5.6</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>2.5.6</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>2.5.6</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>3.0.2.RELEASE</version>
</dependency>
<!– Spring AOP dependency –>
<!– <dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>2.2</version>
</dependency> –>
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib-nodep</artifactId>
<version>2.2.2</version>
</dependency>
<!– MySQL database driver –>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.9</version>
</dependency>

<!– Hibernate framework –>
<dependency>
<groupId>hibernate</groupId>
<artifactId>hibernate-tools</artifactId>
<version>3.2.3.GA</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.6.1</version>
</dependency>

<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.6.1</version>
</dependency>
<dependency>
<groupId>javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.4.GA</version>

</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.5.2</version>
</dependency>

<!– Hibernate library dependecy start –>
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.1</version>
</dependency>

<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.1</version>
</dependency>

<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>3.2.1</version>
</dependency>

<dependency>
<groupId>antlr</groupId>
<artifactId>antlr</artifactId>
<version>2.7.7</version>
</dependency>

<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate</artifactId>
<version>3.2.1.ga</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-annotations</artifactId>
<version>3.2.1.ga</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager
</artifactId>
<version>3.2.1.ga</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-tools</artifactId>
<version>3.2.0.beta9a</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>3.3.1.GA</version>
</dependency>
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>persistence-api</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.2.2</version>
</dependency>
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1</version>
</dependency>
<dependency>
<groupId>com.jolbox</groupId>
<artifactId>bonecp-provider</artifactId>
<version>0.7.1.RELEASE</version>
</dependency>
<!– Hibernate library dependecy end –>

<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.13</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>

</dependencies>

</project>

Now the program is ready to run and we can execute, the App.java.

Web Browser using Java

import java.io.*;
import java.net.*;
import javax.swing.*;
import javax.swing.event.*;
import java.awt.event.*;
public class WebBrowser extends JFrame{
String temp,urlQueue[]=new String[20];
int F=0,R=-1;
JButton go=new JButton(“Go”);
JButton prev=new JButton(“Prev”);
JButton next=new JButton(“Next”);
JTextField url=new JTextField(30);
JEditorPane page=new JEditorPane();
public static void main(String args[]){
JFrame obj=new WebBrowser();
obj.setTitle(“Browser”);
obj.setSize(800,500);
obj.setVisible(true);
}
public WebBrowser(){
Components();
Events();
}
public void Components(){
getContentPane().setLayout(null);
url.setBounds(20,400,200,20);
go.setBounds(240,400,20,20);
prev.setBounds(100,440,40,20);
next.setBounds(160,440,40,20);
page.setBounds(10,10,790,375);
getContentPane().add(page);
getContentPane().add(url);
getContentPane().add(go);
getContentPane().add(next);
getContentPane().add(prev);
}
public void Events(){
this.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent we){
System.exit(0);
}
}
);
go.addActionListener(new Browser());
prev.addActionListener(new Browser());
next.addActionListener(new Browser());
page.setEditable(false);
page.addHyperlinkListener(new HyperlinkListener()
{
public void hyperlinkUpdate(HyperlinkEvent he){
if(he.getEventType()==HyperlinkEvent.EventType.ACTIVATED)
{
try{
temp= he.getURL().toString();
page.setPage(temp);
R++;
urlQueue[R]=temp;
url.setText(temp);
}
catch(Exception e)
{

}
}
}
}
);
}
public class Browser implements ActionListener{
public void actionPerformed(ActionEvent ae) {
try{

if(ae.getSource()==go){
temp=url.getText();
page.setPage(temp);
R++;
urlQueue[R]=temp;
}
else if(ae.getSource()==prev){
R–;
temp=urlQueue[R];
page.setPage(temp);
}
else if(ae.getSource()==next){
R++;
temp=urlQueue[R];
page.setPage(temp);
}
}
catch(IOException e)
{
}

}
}
}