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)
{
}

}
}
}

Java Socket – Client and Server Communication

/*  UDP – User Data Protocol – Client and server communication

A Graphical User Interface Program */

 

import java.net.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;

public class GUIClient extends JFrame
{

JButton send=new JButton(“Send”);
JTextField msg=new JTextField(20);
TextArea chat=new TextArea(20,20);
DatagramSocket ds=null;
DatagramPacket dp=null;

public class Receiver extends Thread
{
Thread t=null;
public Receiver()
{
t=new Thread(this);
t.start();
}
public void run()
{
String str1=”Server:”;
String str2;
byte data[]=new byte[1024];
try{
do{
DatagramPacket dp=new DatagramPacket(data,1024);
ds.receive(dp);
str2=dp.getData().toString();
chat.append(str1+str2+”\n”);

}while(!str2.equals(“end”));
}catch(Exception e)
{System.out.println(e);}
}
}

public static void main(String s[])
{
JFrame obj=new GUIClient();
obj.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
obj.setTitle(“CLIENT”);
obj.setVisible(true);
obj.setSize(400,400);
}

public GUIClient()
{
try{
ds=new DatagramSocket(7090);
}
catch(Exception e)
{
System.out.println(e);
}
components();
events();
Receiver r=new Receiver();
}

void components()
{
getContentPane().setLayout(null);
send.setBounds(270,20,80,30);
msg.setBounds(50,20,200,20);
chat.setBounds(20,60,320,300);
getContentPane().add(send);
getContentPane().add(msg);
getContentPane().add(chat);
}

void events()
{
send.addActionListener(new s());
}

public class s implements ActionListener
{
public void actionPerformed(ActionEvent ae)
{
String str3;
byte data2[]=new byte[1024];
try{
InetAddress ia=InetAddress.getByName(“localhost”);// or IP of server
str3=msg.getText();
data2=str3.getBytes();
dp=new DatagramPacket(data2,data2.length,ia,7000);
ds.send(dp);
//ds.close();
}catch(Exception e1)
{
System.out.println(e1);
}
}
}
}

—————————–

import java.net.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;

public class GUIServer extends JFrame
{

JButton send=new JButton(“Send”);
JTextField msg=new JTextField(20);
TextArea chat=new TextArea(20,20);
DatagramSocket ds=null;
DatagramPacket dp=null;

public class Receiver extends Thread
{
Thread t=null;
public Receiver()
{
t=new Thread(this);
t.start();
}
public void run()
{
String str1=”Client:”;
String str2;
byte data[]=new byte[1024];
try{
do{
DatagramPacket dp=new DatagramPacket(data,1024);
ds.receive(dp);
str2=dp.getData().toString();
chat.append(str1+str2+”\n”);
}while(!str2.equals(“end”));
}catch(Exception e)
{System.out.println(e);}
}
}

public static void main(String s[])
{
JFrame obj=new GUIServer();
obj.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
obj.setTitle(“SERVER”);
obj.setVisible(true);
obj.setSize(400,400);
}

public GUIServer()
{
try{
ds=new DatagramSocket(7000);
}
catch(Exception e)
{
System.out.println(e);
}
components();
events();
Receiver r=new Receiver();
}

void components()
{
getContentPane().setLayout(null);
send.setBounds(270,20,80,30);
msg.setBounds(50,20,200,20);
chat.setBounds(20,60,320,300);
getContentPane().add(send);
getContentPane().add(msg);
getContentPane().add(chat);
}

void events()
{
send.addActionListener(new s());
}

public class s implements ActionListener
{
public void actionPerformed(ActionEvent ae)
{
String str3;
byte data2[]=new byte[1024];
try{
InetAddress ia=InetAddress.getByName(“localhost”);
str3=msg.getText();
data2=str3.getBytes();
dp=new DatagramPacket(data2,data2.length,ia,7090);
ds.send(dp);
//ds.close();
}catch(Exception e1)
{
System.out.println(e1);
}
}
}
}

Dijkstra’s Shortest Path Algorithm Implementation

// Dijkstra’s Algorithm

#include<stdio.h>
#include<conio.h>
#include<process.h>
#include<alloc.h>
#include<ctype.h>

struct node
{
struct node *llink,*rlink;
int data,wt;
};

typedef struct
{
int wt,v,via;
}tab;

struct node *find(struct node *head,int s)
{
struct node *t;
t=head;
while(t!=NULL)
{
if(t->data==s)
return t;
t=t->rlink;
}
}

struct node * insert(struct node *head,int i)
{
struct node *t,*temp;
temp=head;
t=(struct node*)malloc(sizeof(struct node));
t->llink=NULL;
t->rlink=NULL;
t->data=i;
t->wt=0;
if(head==NULL)
return t;
while(temp->rlink!=NULL)
temp=temp->rlink;
temp->rlink=t;
return head;
}

void insertNode(struct node *head)
{
struct node *t,*temp,*head1=NULL;
char ch;
do
{
temp=head1;
t=(struct node*)malloc(sizeof(struct node));
t->llink=NULL;
t->rlink=NULL;
printf(”
Enter destination :”);
scanf(“%d”,&t->data);
printf(”
Enter Weight :”);
scanf(“%d”,&t->wt);
if(head1==NULL)
{
head->llink=t;
head1=t;
}
else
{
while(temp->rlink!=NULL)
temp=temp->rlink;
temp->rlink=t;
}
printf(”
Do u continue y/n : “);
fflush(stdin);
scanf(“%c”,&ch);
}while(tolower(ch)==’y’);
}

void path(struct node *head,int s,int n)
{
struct node *temp;
tab *t;
int d,k,cost=0,i=2,j=1,s1,f=0,c=0,via=0;
t=(tab *)malloc(n*sizeof(tab));
s1=s;
for(i=1;i<=n;i++)
{
t[i].v=0;
t[i].wt=9999;
t[i].via=0;
}
while(j<n)
{
temp=find(head,s1);
via=temp->data;
temp=temp->llink;
d=temp->data;
while(temp!=NULL)
{
if((t[d].v)==0 && (t[d].wt > (cost+temp->wt)))
{
t[d].wt=cost+temp->wt;
t[d].via=via;
}
temp=temp->rlink;
d=temp->data;
}
cost=9999;
for(i=1;i<=n;i++)
{
if(t[i].v==0 && i!=s)
{
if(t[i].wt<cost)
{
cost=t[i].wt;
k=i;f=1;
}
}
}
if(f==1)
{
t[k].v=1;
c=1;
f=0;
}
j=j+1;
s1=k;
}
printf(”
Sourse via destination Distance”);
for(i=1;i<=n;i++)
{
if(t[i].v==1)
if(t[i].via!=s)
printf(”
%d %d -> %d : %d”,s,t[i].via,i,t[i].wt);
else
printf(”
%d — -> %d : %d”,s,i,t[i].wt);
}
if(c==0)
printf(”
No way to travel from city – %d to other city..”,s);
}

void main()
{
struct node * head;
int i,n,s,t;char ch;
struct node * insert(struct node *head,int);
void insertNode(struct node *head);
struct node *find(struct node *head,int s);
void path(struct node *,int,int);
head=NULL;
clrscr();
do
{
printf(”
1-Insertion”);
printf(”
2-Path”);
printf(”
3-Exit”);
printf(”
Ur Choice:”);
scanf(“%d”,&s);
switch(s)
{
case 1: //Insertion
printf(”
No of CITIES.. :”);
scanf(“%d”,&n);
for(i=1;i<=n;i++)
head=insert(head,i);
for(i=1;i<=n;i++)
{
printf(”
Do u create path from city-%d :”,i);
fflush(stdin);
scanf(“%c”,&ch);
if(tolower(ch)==’y’)
insertNode(find(head,i));
}
break;

case 2: //Path define
printf(”
From which city u want to travel :”);
scanf(“%d”,&t);
if(t<=n)
path(head,t,n);
else
printf(”
Enter Correct data….”);
break;

case 3: //exit
exit(0);
}
}while(s<4||s>0);
getch();
}

Linux Signals

Signals

/* Program to  perform operations depending on external signals */

#include<stdlib.h>
#include<stdio.h>
#include<sys/types.h>
#include<unistd.h>
#include<signal.h>
int a,b;
void division(int sig)
{
int c=0;
c = a/b;
printf(“\n\t QUOTIENT = %d”,c);
printf(“\tSignal = %d\n”,sig);
(void)signal(SIGINT,SIG_DFL);
}
void mul(int sig)
{
int c=0;
c = a*b;
printf(“\n\t PRODUCT = %d”,c);
printf(“\tSignal = %d\n”,sig);
(void)signal(SIGINT,division);
}
void sub(int sig)
{
int c=0;
c = a-b;
printf(“\n\t DIFFERENCE = %d”,c);
printf(“\tSignal = %d\n”,sig);
(void)signal(SIGINT,mul);
}

void add(int sig)
{
int c=0;
c= a+b;
printf(“\n\t SUM = %d”,c);
printf(“\tSignal = %d\n”,sig);
(void)signal(SIGINT,sub);
}
int main()
{
printf(“\n\t Enter first no. : “);
scanf(“%d”,&a);
printf(“\n\t Enter second no. : “);
scanf(“%d”,&b);
(void)signal(SIGINT,add);
while(1){sleep(1);}
return 0;
}

Shared Memory – Linux O.S

/* Program using shared memory */

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

int main()
{
key_t key1 = 1000,key2 = 2000,key3 = 3000,shmid1,shmid2,shmid3;
int *A,*B,*C,i,j,k,m,n,p,q;

shmid1=shmget(key1,100*sizeof(int),IPC_CREAT);
if(shmid1==-1)
{
printf(“\n\t ERROR : ALLOCATION FAILED \n”);
exit(0);
}

shmid2=shmget(key2,100*sizeof(int),IPC_CREAT);
if(shmid2==-1)
{
printf(“\n\t ERROR : ALLOCATION FAILED \n”);
exit(0);
}

shmid3=shmget(key3,100*sizeof(int),IPC_CREAT);
if(shmid3==-1)
{
printf(“\n\t ERROR : ALLOCATION FAILED \n”);
exit(0);
}

A = shmat(shmid1,NULL,0);
B = shmat(shmid2,NULL,0);
C = shmat(shmid3,NULL,0);

printf(“\n\t ROWS for matrix A : “);
scanf(“%d”,&m);
printf(“\n\t COLUMNS for matrix A : “);
scanf(“%d”,&n);
printf(“\n\t Enter the elements : “);
for(i = 0;i<m;i++)
for(j = 0;j<n;j++)
scanf(“%d”,(A+(n*i)+j));

printf(“\n\t MATRIX A : “);
for(i = 0;i<m;i++)
{
printf(“\n”);
for(j = 0;j<n;j++)
printf(“\t%d”,*(A+(n*i)+j));
}

printf(“\n”);

printf(“\n\t ROWS for matrix B : “);
scanf(“%d”,&p);
printf(“\n\t COLUMNS for matrix B : “);
scanf(“%d”,&q);
printf(“\n\t Enter the elements : “);
for(i = 0;i<p;i++)
for(j = 0;j<q;j++)
scanf(“%d”,(B+(q*i)+j));

printf(“\n\t MATRIX B : “);
for(i = 0;i<p;i++)
{
printf(“\n”);
for(j = 0;j<q;j++)
printf(“\t%d”,*(B+(q*i)+j));
}

if(n != p)
{
printf(“\n\n\t ERROR : MATRICES NOT COMPATIBLE FOR MULTIPLICATION \n”);
printf(“\n\t\t\t PROGRAM TERMINATED \n\n”);
exit(0);
}

for(i = 0;i<m;i++)
{
for(j = 0;j<q;j++)
{
*(C+(q*i)+j) = 0;
for(k = 0;k<n;k++)
*(C+(q*i)+j) = *(C+(q*i)+j) + (*(A+(n*i)+k)) * (*(B+(q*k)+j));
}
}

printf(“\n\t THE PRODUCT OF matrices A & B are : \n”);
for(i = 0;i<m;i++)
{
printf(“\n”);
for(j = 0;j<q;j++)
printf(“\t%d”,*(C+(q*i)+j));
}

printf(“\n\n”);

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

return 0;
}

Chat program using Java RMI

A Chat program using Remote Method Invocation ( RMI )

import java.rmi.*;
public interface Chat extends java.rmi.Remote
{

public String send()throws RemoteException;
public void receive(String str)throws RemoteException;

}

—–

import java.rmi.*;
import java.rmi.ServerError.*;
import java.io.*;
public class ChatImpl extends java.rmi.server.UnicastRemoteObject implements Chat
{
public ChatImpl() throws java.rmi.RemoteException
{
super();

}
public String send()throws java.rmi.RemoteException

{try
{
BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
String str=br.readLine();System.out.println(str);
return str;
}catch(Exception e)
{
String str1=”some error”;
return str1;
}

}
public void receive(String str)throws java.rmi.RemoteException

{
System.out.println(str);
}
}

————

import java.rmi.*;
import java.io.*;
public class ChatClient implements Runnable{
static Chat c;
public static void main(String args[])throws IOException
{System.out.println(“enter static main”);

try
{
c=(Chat)Naming.lookup(“rmi://localhost/Chat”);
System.out.println(“lookupdone”);
}catch(Exception e){System.out.println(e);}
new ChatClient();
}
public ChatClient()
{
run();
}
public void run()
{

try{

String str=send();
System.out.println(“String is “+str);
c.receive(str);
System.out.println(c.send());
run();
}catch(Exception e){}
}
public String send()throws java.rmi.RemoteException

{try
{
BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
String str=br.readLine();

return str;
}catch(Exception e)
{
String str1=”some error”;
return str1;
}

}
public void receive(String str)throws java.rmi.RemoteException

{
System.out.println(str);
send();
}
}

—————-

import java.rmi.*;
import java.io.*;
public class ChatServer1
{
public ChatServer1() {

try{
ChatImpl c=new ChatImpl();
Naming.rebind(“//localhost:4444/Chat”,c);
}catch(Exception e){}
}
public static void main(String args[])throws IOException
{
try
{

new ChatServer1();
}catch(Exception e){}
}

}

Epsilon Closure (E-Closure) to Convert NFA to DFA

Epsilon closure and transitions on input symbols for a set of NFA States

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void eclose(int);
void trans(int,int);
struct nfastates
{
int initial;
int final;
char inputsym;
}nfa[50];
int abtrans[50],ai=0,bi=0,ei=0,eclosure[50],queue[50],n,start;

void main()
{
int i;
clrscr();
printf(“\n Enter the no: of states\n”);
scanf(“%d”,&n);

printf(“\n Enter initial state,inputsymbol,finalstate\n”);
for(i=0;i<n;i++)
{
scanf(“%d”,&nfa[i].initial);
nfa[i].inputsym= getche();
scanf(“%d”,&nfa[i].final);
}
printf(“\n Enter the start state\n”);
scanf(“%d”,&start);
printf(“\n THE ECLOSURE is\n”);
eclose(start);
for(i=0;i<ei;i++)
{
printf(“%d\t”,eclosure[i]);
}
printf(“\n THE a-transitions are\n”);
trans(1,1);
for(i=0;i<ai;i++)
{
printf(“%d\t”,abtrans[i]);
}
printf(“\n THE b-transitions are\n”);
trans(2,2);
for(i=0;i<bi;i++)
{
printf(“%d\t”,abtrans[i]);
}
getch();
}
void eclose(int start)
{

int f=0,r=0,i;
eclosure[ei]=start;
ei++;
queue[r]=start;
r++;
do
{
start=queue[f];
f++;
for(i=0;i<n;i++)
{
if(nfa[i].initial==start && nfa[i].inputsym==’e’)
{
queue[r]=nfa[i].final;
r++;
eclosure[ei]=nfa[i].final;
ei++;
}
}
}while(f<r);
}
void trans(int a,int flag)
{
int i,f=0,r=0,j;
for(j=0;j<ei;j++)
{
f=0,r=0;
queue[r]=eclosure[j];
r++;
do
{
start=queue[f];
f++;
for(i=0;i<n;i++)
{
if(nfa[i].initial==start && nfa[i].inputsym==’a’)
{
queue[r]=nfa[i].final;
r++;
if(flag==1)
{
abtrans[ai]=nfa[i].final;
ai++;
}
else if(flag==2)
{
abtrans[bi]=nfa[i].final;
bi++;
}
}
}
}while(f<r);
}
}

C++ Constructors

Let us consider an exmaple:
1. Multilevel Inheritance – Order of Constructor invocation
class A
{
public:
A()
{
cout<<“Constructor of base class Invoked “;
}
}
class B: public A
{
public:
B()
{
cout<<“Constructor of derived class Invoked “;
}
}
main()
{
B objB;
}

The questions is wether the constructor of base class will be invoked first or derived class first?
Obviously the base class parameters has to be arranged and organised first, so the base class constructor will be invoked before invoking the constructor of derived class.

2. Mulitple constructors in base class and derived class
class A
{
public:
A()
{
cout<<“Constructor of base class Invoked “;
}
A(int x)
{
cout<<“Argument Constructor of base class Invoked “;
}
}
class B: public A
{
public:
B()
{
cout<<“Constructor of derived class Invoked “;
}
B(int x)
{
cout<<“Argument Constructor of derived class Invoked “;
}
}
main()
{
B objB(5);
}
In this case our questions is , wether the argument constructor of base class will be invoked or not. It has to be understood that the argument constructor of base class is not invoked if it is not explicitly specified as:
B(int x):A(x)
{
cout<<“Argument Constructor of derived class Invoked “;
}

J2ME – Bluetooth Chat – Full source code

/*
* BTC.java
*
* Created on March 7, 2008, 11:28 AM
*/

import com.sun.midp.lcdui.Text;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;

/**
*
* @author raymond
* @version
*/
public class BTC extends MIDlet {
Displayable d1;
graphics g;
login l=new login();
newuser n=new newuser();
listuser lu=new listuser();
Form f=null;
Display m=null;
Command newuser=new Command(“NEW USER”,Command.EXIT,2);
Command listuser=new Command(“LIST USERS”,Command.EXIT,3);
Command login=new Command(“LOGIN”,Command.EXIT,1);
Command exit=new Command(“EXIT”,Command.EXIT,0);

public void startApp() {

m=Display.getDisplay(this);
g=new graphics();

d1=g;
d1.addCommand(newuser);
d1.addCommand(login);
d1.addCommand(exit);
d1.addCommand(listuser);
m.setCurrent(d1);

d1.setCommandListener(new CommandListener()
{
public void commandAction(Command command, Displayable displayable) {
if(command==exit)
notifyDestroyed();
else if(command==login)
l.display(m);
else if(command==newuser)
n.display(m);
else if(command==listuser)
lu.display(m);

}
}
);
}

public void pauseApp() {
}

public void destroyApp(boolean unconditional) {
}
}

 ——————

import com.sun.midp.io.j2me.storage.File;
import java.io.IOException;

import javax.microedition.io.Connector;
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;

import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;

import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.TextField;
import javax.microedition.lcdui.StringItem;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.ChoiceGroup;
import javax.microedition.lcdui.Choice;

import javax.bluetooth.LocalDevice;
import javax.bluetooth.RemoteDevice;
import javax.bluetooth.DiscoveryAgent;
import javax.bluetooth.UUID;
import javax.bluetooth.ServiceRecord;
import javax.bluetooth.L2CAPConnectionNotifier;
import javax.bluetooth.L2CAPConnection;

import javax.bluetooth.BluetoothStateException;
import javax.microedition.rms.RecordEnumeration;
import javax.microedition.rms.RecordStore;

public class ChatController extends MIDlet implements CommandListener
{
private Alert a,a1=null;
private Displayable dis,d2= null;
private Form mainForm = null;
private ChoiceGroup devices = null;

private TextField outTxt = null;
private Command exit = null;
private Command start = null;
private Command connect = null;
private Command send = null;
private Command select = null;
private Command schat=null;
private StringItem status = null;
private StringItem chat = null;
private Display d1;

private LocalDevice local = null;
private RemoteDevice rDevices[];
private ServiceRecord service = null;
private DiscoveryAgent agent = null;
private DiscoveryAgent agentPC = null;

private L2CAPConnectionNotifier notifier;
private L2CAPConnectionNotifier notifierPC;

private L2CAPConnection connection = null;
private L2CAPConnection connectionPC = null;

private static final String UUID_STRING = “112233445566778899AABBCCDDEEFF”;
private static final String UUID_STRING_PC = “112233445566778899AABBCCDDEECF”;

private boolean running = false;
//private static int flag,chatflag=0;
private Command view;

private String s;
private TextField age = null;
private TextField name = null;
private TextField sex = null;
private TextField hobb = null;

private String s1;

private TextField occu = null;
private TextField qual= null;

private String dt=null;
private String dtPC=null;

public ChatController()
{
//super();

}
public void display(final Display d,final String user)
{
dis=d.getCurrent();
s=user;

mainForm = new Form(“CHAT”);
devices = new ChoiceGroup(null,Choice.EXCLUSIVE);
outTxt = new TextField(“outgoing msg:”,””,256,TextField.ANY);
exit = new Command(“EXIT”,Command.EXIT,1);
start = new Command(“START”,Command.SCREEN,2);
connect = new Command(“CONNECT”,Command.SCREEN,2);
send = new Command(“SEND”,Command.SCREEN,2);
select = new Command(“SELECT”,Command.SCREEN,2);
view=new Command(“VIEW PROFILE”,Command.SCREEN,1);
schat=new Command(“START CHAT”,Command.SCREEN,2);
status = new StringItem(“status : “,null);
chat=new StringItem(“\n”,null);

name = new TextField(“Name:”,””,256,TextField.ANY);
age = new TextField(“Age:”,””,256,TextField.ANY);
sex = new TextField(“Sex:”,””,256,TextField.ANY);
hobb = new TextField(“Hobbies:”,””,256,TextField.ANY);
qual = new TextField(“Qualification:”,””,256,TextField.ANY);
occu = new TextField(“Occupation:”,””,256,TextField.ANY);

mainForm.append(status);
mainForm.append(chat);

mainForm.addCommand(exit);
mainForm.setCommandListener(this);

try
{
RecordStore rs2= RecordStore.openRecordStore(“chat”,true);
RecordEnumeration re=null;
re=rs2.enumerateRecords(null,null,false);

while(re.hasNextElement())
{
byte []data=re.nextRecord();
String str1=new String(data);
System.out.println(str1);
}

rs2.closeRecordStore();
}
catch(Exception e)
{

}

running = true;
mainForm.addCommand(start);
mainForm.addCommand(connect);

try
{
local = LocalDevice.getLocalDevice();
agent = local.getDiscoveryAgent();
agentPC = local.getDiscoveryAgent();

}
catch(BluetoothStateException bse)
{
status.setText(“BluetoothStateException unable to start:”+bse.getMessage());
try
{
Thread.sleep(1000);
}
catch(InterruptedException ie)
{}
notifyDestroyed();
}
d1=d ;
d1.setCurrent(mainForm);
d2=d1.getCurrent();
}

protected void startApp() throws MIDletStateChangeException
{
}

protected void pauseApp()
{
running = false;
releaseResources();
}

protected void destroyApp(boolean uncond) throws MIDletStateChangeException
{
running = false;
releaseResources();
}

public void commandAction(Command cmd,Displayable disp)
{
if(cmd==exit)
{
System.out.println(“inside exit”);
try
{
RecordStore rs=RecordStore.openRecordStore(“chat”,true);
if(!chat.getText().equals(“”))
{

byte []data1=(s+”|\n”+chat.getText()).getBytes();
rs.addRecord(data1,0,data1.length);
Alert a3= new Alert(“”,”SAVED”,null,AlertType.INFO);
d1.setCurrent(a3);
rs.closeRecordStore();
}
}
catch(Exception e)
{

}
running = false;
releaseResources();
d1.setCurrent(dis);
}
else if(cmd==start)
{
new Thread()
{
public void run()
{
startServer();

}
}.start();
}
else if(cmd==connect)
{

status.setText(“searching for devices…”);
mainForm.removeCommand(connect);
mainForm.removeCommand(start);
mainForm.append(devices);

DeviceDiscoverer discoverer = new DeviceDiscoverer(ChatController.this);
try
{
agent.startInquiry(DiscoveryAgent.GIAC,discoverer);
agentPC.startInquiry(DiscoveryAgent.GIAC,discoverer);

}

catch(IllegalArgumentException iae)
{
status.setText(“BluetoothStateException :”+iae.getMessage());
}
catch(NullPointerException npe)
{
status.setText(“BluetoothStateException :”+npe.getMessage());
}
catch(BluetoothStateException bse1)
{
status.setText(“BluetoothStateException :”+bse1.getMessage());
}
}
else if(cmd==select)
{
status.setText(“searching devices for service…”);
int index = devices.getSelectedIndex();

mainForm.removeCommand(select);
mainForm.addCommand(view);
mainForm.addCommand(schat);
ServiceDiscoverer serviceDListener = new ServiceDiscoverer(ChatController.this);
int attrSet[] = {0x0100}; //returns service name attribute
UUID[] uuidSet = {new UUID(UUID_STRING,false)};
ServiceDiscoverer serviceDListenerPC = new ServiceDiscoverer(ChatController.this);
int attrSetPC[] = {0x0100}; //returns service name attribute
UUID[] uuidSetPC = {new UUID(UUID_STRING_PC,false)};

try
{

agentPC.searchServices(attrSetPC,uuidSetPC,rDevices[0],serviceDListener);

agent.searchServices(attrSet,uuidSet,rDevices[index],serviceDListener);
}
catch(IllegalArgumentException iae1)
{
status.setText(“BluetoothStateException :”+iae1.getMessage());
}
catch(NullPointerException npe1)
{
status.setText(“BluetoothStateException :”+npe1.getMessage());
}
catch(BluetoothStateException bse11)
{
status.setText(“BluetoothStateException :”+bse11.getMessage());
}
}
else if(cmd==send)
{
// status.setText(“Connected…”);
new Thread()
{
public void run()
{
sendMessage();
}
}.start();
}

else if(cmd==view)
{
mainForm.delete(mainForm.size()-1);//deletes choiceGroup
mainForm.removeCommand(view);
System.out.println(“View prof…..”);
vprofilercv();
}
else if(cmd==schat)
{
mainForm.removeCommand(schat);
mainForm.removeCommand(view);

mainForm.deleteAll();
mainForm.append(status);
mainForm.append(chat);
s1=s;
System.out.println(“..”+s);

new Thread()
{
public void run()
{
try
{

System.out.println(“Inside thread”);
String message1 = “Hi”;
byte[] data = message1.getBytes();
int transmitMTU = connection.getTransmitMTU();
if(data.length <= transmitMTU)
{
connection.send(data);
}
status.setText(“waiting for connection….”);
String prof=vprofile();
System.out.println(“Profile……..”+prof);
sendMessage(prof);

startReciever();
System.out.println(“startrcvr inside serv search finished”);

}
catch(Exception e1)
{

}
}

}.start();

}
}

//this method is called from DeviceDiscoverer when device inquiry finishes
public void deviceInquiryFinished(RemoteDevice[] rDevices,String message)
{
this.rDevices = rDevices;
String deviceNames[] = new String[rDevices.length];
String PC ;
for(int k=0;k<rDevices.length;k++)
{
try
{
PC =rDevices[0].getFriendlyName(false);

deviceNames[k] = rDevices[k].getFriendlyName(false);
}
catch(IOException ioe)
{
status.setText(“IOException :”+ioe.getMessage());
}
}
for(int l=0;l<deviceNames.length;l++)
{
devices.append(deviceNames[l],null);
}
mainForm.addCommand(select);

status.setText(message);
}

//called by ServiceDiscoverer when service search gets completed
public void serviceSearchFinished(ServiceRecord service,String message)
{
String url = “”;
this.service = service;
status.setText(message);
try
{
url = service.getConnectionURL(ServiceRecord.NOAUTHENTICATE_NOENCRYPT,false);
}
catch (IllegalArgumentException iae1)
{}
try
{

connection = (L2CAPConnection)Connector.open(url);
connectionPC = (L2CAPConnection)Connector.open(url);

// sendMessage(prof);
}
catch(IOException ioe1)
{
status.setText(“IOException :”+ioe1.getMessage());
}
}

// this method starts L2CAPConnection chat server from server mode
public void startServer()
{

status.setText(“server starting…”);
mainForm.removeCommand(connect);
mainForm.removeCommand(start);
try
{
local.setDiscoverable(DiscoveryAgent.GIAC);

notifier = (L2CAPConnectionNotifier)Connector.open(“btl2cap://localhost:”+UUID_STRING+”;name=L2CAPChat”);
notifierPC = (L2CAPConnectionNotifier)Connector.open(“btl2cap://localhost:”+UUID_STRING_PC+”;name=L2CAPChat”);

ServiceRecord record = local.getRecord(notifier);
String conURL = record.getConnectionURL(ServiceRecord.NOAUTHENTICATE_NOENCRYPT,false);
status.setText(“server running…”);

dt=vprofile();
System.out.println(dt);
connection = notifier.acceptAndOpen();
connectionPC = notifierPC.acceptAndOpen();

sendMessage(dt);
int receiveMTU = connection.getReceiveMTU();
byte[] data1 = new byte[receiveMTU];
int length = connection.receive(data1);
String message2 = new String(data1,0,length);
if(message2.equals(“Hi”))
{
System.out.println(“INSIDE IF”);
final Command accept=new Command(“Accept”,Command.SCREEN,1);
final Command deny=new Command(“Deny”,Command.SCREEN,2);
final Command vw=new Command(“ViewProfile”,Command.EXIT,1);
a=new Alert(“Alert”,”Remote user wants 2 chat… accept/deny”,null,AlertType.CONFIRMATION);
a.setTimeout(Alert.FOREVER);
a.addCommand(accept);
a.addCommand(deny);
a.addCommand(vw);
d1.setCurrent(a);
a.setCommandListener(new CommandListener(){
public void commandAction(Command c,Displayable d)
{
if(c==accept)
{

new Thread()
{
public void run()
{
d1.setCurrent(mainForm);
System.out.println(“startrcvr inside accept”);
//flag=1;
startReciever();

}
}.start();

}
else if(c==deny)
{

d1.setCurrent(d2);
System.out.println(“startrcvr inside deny”);

try
{
String message1 = “aaa”;
byte[] data = message1.getBytes();
int transmitMTU = connection.getTransmitMTU();
if(data.length <= transmitMTU)
{
connection.send(data);
System.out.println(“deny……..”);

}
new Thread()
{
public void run()
{
d1.setCurrent(d2);
System.out.println(“startrcvr inside deny”);
//flag=1;
startReciever();

}
}.start();

}
catch(Exception e)
{

}
}
else if(c==vw)
{
System.out.println(“insie view…..”);
Form f1=new Form(“profile”);
Command ok=new Command(“OK”,Command.OK,1);
TextField name = new TextField(“Name:”,””,256,TextField.ANY);
TextField age = new TextField(“Age:”,””,256,TextField.ANY);
TextField sex = new TextField(“Sex:”,””,256,TextField.ANY);
TextField hobb = new TextField(“Hobbies:”,””,256,TextField.ANY);
TextField qual = new TextField(“Qualification:”,””,256,TextField.ANY);
TextField occu = new TextField(“Occupation:”,””,256,TextField.ANY);
int index;
f1.append(name);
f1.append(age);
f1.append(sex);
f1.append(hobb);
f1.append(qual);
f1.append(occu);
f1.addCommand(ok);
d1.setCurrent(f1);
try
{
{
System.out.println(“inside view pro…….rcv….”);
int receiveMTU = connection.getReceiveMTU();
byte[] data = new byte[receiveMTU];
int length = connection.receive(data);
String message = new String(data,0,length);
System.out.println(message);
String str1=new String(message);

System.out.println(str1);

// flag=1;
for(int i=0;i<=5;i++)
{
index = str1.indexOf(“|”);
if(i==0)
name.setString(str1.substring(0,index));
else if(i==1)
age.setString(str1.substring(0,index));
else if(i==2)
sex.setString(str1.substring(0,index));
else if(i==3)
hobb.setString(str1.substring(0,index));
else if(i==4)
qual.setString(str1.substring(0,index));
else if(i==5)
occu.setString(str1.substring(0,index));

str1=str1.substring(index+1,str1.length());

}
}
}
catch(Exception e)
{

}
d1.setCurrent(f1);
f1.setCommandListener(new CommandListener(){
public void commandAction(Command c,Displayable d)
{
d1.setCurrent(a);
}
});

}
}
});
}
}

catch(IOException ioe3)
{
status.setText(“IOException :”+ioe3.getMessage());
}
}

//starts a message reciever listening for incomming message
public void startReciever()
{

mainForm.removeCommand(view);

mainForm.addCommand(send);
mainForm.append(outTxt);
while(running)
{
try
{
if(connection.ready())
{

int receiveMTU = connection.getReceiveMTU();
byte[] data = new byte[receiveMTU];
int length = connection.receive(data);
String message = new String(data,0,length);
System.out.println(message);

if(message.equals(“aaa”))
{

System.out.println(“denied……………..INSIDE IF”);
a1=new Alert(“Denied”,”Has denied the request for chat”,null,AlertType.INFO);
a1.setTimeout(Alert.FOREVER);
d1.setCurrent(a1);
a1.setCommandListener(new CommandListener(){
public void commandAction(Command c,Displayable d)
{
d1.setCurrent(d2);
releaseResources();
}
});
}
else
{
int l=message.lastIndexOf(‘|’);
System.out.println(“………”+l);
if(l!=-1)
chat.setText(“”);

else
{
if(chat.getText()!=null)
chat.setText(chat.getText()+”\n”+ message);
else
chat.setText(message);

status.setText(“Connected……”);
}
}
}
}
catch(IOException ioe4)
{
status.setText(“IOException :”+ioe4.getMessage());
}

}

}
//sends a message over L2CAP
public void sendMessage()
{
try
{
if(chat.getText()!=null)
chat.setText(chat.getText()+”\n”+s+”:”+outTxt.getString());
else
chat.setText(s+”:”+outTxt.getString());
String message = s+”:”+outTxt.getString();
outTxt.setString(“”);
byte[] data = message.getBytes();
int transmitMTU = connection.getTransmitMTU();
if(data.length <= transmitMTU)
{
connection.send(data);
connectionPC.send(data);
}
else
{
status.setText(“message ….”);
}
}
catch (IOException ioe5)
{
status.setText(“IOException :”+ioe5.getMessage());
}
}
public void sendMessage(String msg)
{
try
{
//System.out.println(msg);

String message =msg;
File fr = new File() ;//new FileWriter(“c:/a.csv”);

byte[] data = message.getBytes();
int transmitMTU = connection.getTransmitMTU();
if(data.length <= transmitMTU)
{
connection.send(data);
connectionPC.send(data);

}
else
{
status.setText(“message ….”);
}
}
catch (IOException ioe5)
{
status.setText(“IOException :”+ioe5.getMessage());
}
}

//closes L2CAP connection
public void releaseResources()
{
try
{

if(connection != null)
connection.close();
System.out.println(“conn close”);
if(notifier != null)
notifier.close();
System.out.println(“notifier close”);
}
catch(IOException ioe6)
{
status.setText(“IOException :”+ioe6.getMessage());
}
}

public String vprofile()
{
int index;
String dat = null;
try
{
System.out.println(s);
RecordStore rs= RecordStore.openRecordStore(“btc5”,true);
RecordEnumeration re=null;
re=rs.enumerateRecords(null,null,false);
while(re.hasNextElement())
{
byte []data=re.nextRecord();
String str1=new String(data);
index = str1.indexOf(“|”);
String s1=str1.substring(0,index);
str1=str1.substring(index+1,str1.length());
if(s1.equals(s))
{
System.out.println(“readyyyy”);

dat=str1;

}

}
rs.closeRecordStore();
}
catch(Exception e)
{

}

return(dat);

}

private void vprofilercv() {
int index;
mainForm.append(name);
mainForm.append(age);
mainForm.append(sex);
mainForm.append(hobb);
mainForm.append(qual);
mainForm.append(occu);
try
{
{
String message=null ;
System.out.println(“inside view pro…….rcv….”);
int receiveMTU = connection.getReceiveMTU();
byte[] data = new byte[receiveMTU];
int length = connection.receive(data);
message = new String(data,0,length);
System.out.println(message);
String str1=new String(message);
System.out.println(str1);
if(message!=null)
{
for(int i=0;i<=5;i++)
{
index = str1.indexOf(“|”);
if(i==0)
name.setString(str1.substring(0,index));
else if(i==1)
age.setString(str1.substring(0,index));
else if(i==2)
sex.setString(str1.substring(0,index));
else if(i==3)
hobb.setString(str1.substring(0,index));
else if(i==4)
qual.setString(str1.substring(0,index));
else if(i==5)
occu.setString(str1.substring(0,index));

str1=str1.substring(index+1,str1.length());

}
}
else
{
name.setString(“”);
age.setString(“”);
sex.setString(“”);
hobb.setString(“”);
qual.setString(“”);
occu.setString(“”);
}
}
}
catch(Exception e)
{

}
return;
}
}

—————

import java.util.Vector;

import javax.bluetooth.RemoteDevice;
import javax.bluetooth.DeviceClass;

import javax.bluetooth.DiscoveryListener;
import javax.bluetooth.ServiceRecord;

public class DeviceDiscoverer implements DiscoveryListener
{
private ChatController controller = null;
private Vector devices = null;
private RemoteDevice[] rDevices = null;

public DeviceDiscoverer(ChatController controller)
{
super();
this.controller = controller;
devices = new Vector();
}

public void deviceDiscovered(RemoteDevice remote,DeviceClass dClass)
{
devices.addElement(remote);
}

public void inquiryCompleted(int descType)
{
String message = “”;

switch(descType)
{
case DiscoveryListener.INQUIRY_COMPLETED:
message = “INQUIRY_COMPLETED”;
break;
case DiscoveryListener.INQUIRY_TERMINATED:
message = “INQUIRY_TERMINATED”;
break;
case DiscoveryListener.INQUIRY_ERROR:
message = “INQUIRY_ERROR”;
break;
}

rDevices = new RemoteDevice[devices.size()];
for(int i=0;i<devices.size();i++)
rDevices[i] = (RemoteDevice)devices.elementAt(i);

controller.deviceInquiryFinished(rDevices,message);//call of a method from ChatController class
devices.removeAllElements();

controller = null;
devices = null;
}

public void servicesDiscovered(int transId,ServiceRecord[] services)
{}

public void serviceSearchCompleted(int transId,int respCode)
{}

}

——————-

import javax.microedition.lcdui.*;
import javax.microedition.lcdui.Graphics;
import java.io.*;
/*
* graphics.java
*
* Created on March 7, 2008, 11:38 AM
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/

/**
*
* @author raymond
*/
public class graphics extends Canvas{

/** Creates a new instance of graphics */
public graphics() {
}

public void paint(Graphics g) {
int h=getHeight();
int w=getWidth();
g.setColor(0x000000);
g.fillRect(0,0,w,h);

g.drawImage(LoadImage(“/btc1.JPG”),w/2+10,h+40, Graphics.BOTTOM | Graphics.HCENTER);

}

private Image LoadImage(String st) {
Image img=null;
try
{
img=Image.createImage(st);

}
catch(Exception e)
{
System.out.println(e);

}
return img;

}

}

——————-

import javax.microedition.lcdui.*;
/*
* help.java
*
* Created on March 7, 2008, 3:17 PM
*
*/

/**
*
* @author raymond
*/
public class help {
Displayable d1;
Displayable d2=null;
Command back=new Command (“BACK”,Command.SCREEN,0);
StringItem help;

/** Creates a new instance of help */
public help() {
}
public void display1(final Display d)
{
d2=d.getCurrent();
Form f=new Form(“Help”);

help=new StringItem(“Use LOOK FOR FRIENDS to find friends around.\nYou can create private Chat sessions by selecting one of the devices listed.\n\tVIEW PROFILE can be used to identify the user on the selected remote device.\n\tSTARTCHAT is used to begin the chat session\n\nMY PROFILE is for setting your profiles which will be viewed by friends.\n\nCHAT HISTORY can be used for viewing the previous chats of the logged in user..”,null);
// d1=d.getCurrent();
//d1.addCommand(back);
//d1.
f.append(help);
f.addCommand(back);
d.setCurrent(f);
f.setCommandListener(new CommandListener()
{
public void commandAction(Command c,Displayable di)
{
d.setCurrent(d2);
}
});
}
}

——————

/*
* listuser.java
*
* Created on March 29, 2008, 11:21 PM
*
*/

/**
*
* @author Administrator
*/
import javax.microedition.lcdui.*;
import javax.microedition.rms.*;
import javax.microedition.midlet.*;
import java.io.*;

public class listuser extends MIDlet{

Displayable d1=null;
int flag=0,i,index;
RecordEnumeration re=null;
RecordStore rs=null;
Command next=new Command(“NEXT”,Command.SCREEN,0);
Command cancel=new Command(“CANCEL”,Command.EXIT,0);
TextField user,email,phone,addr;
/** Creates a new instance of listuser */
public listuser() {
}
public void display(final Display d)
{
d1=d.getCurrent();
Form f=new Form(“Users”);
user=new TextField(“USERNAME”,””,32,TextField.ANY);
email=new TextField(“E-MAIL”,””,32,TextField.ANY);
phone=new TextField(“PHONE NO”,””,32,TextField.ANY);
addr=new TextField(“ADDRESS”,””,32,TextField.ANY);
f.append(user);
f.append(email);
f.append(phone);
f.append(addr);
f.addCommand(next);
f.addCommand(cancel);
try {
rs= RecordStore.openRecordStore(“btc”,true);

re=rs.enumerateRecords(null,null,false);
}
catch (RecordStoreException ex) {
ex.printStackTrace();
}

f.setCommandListener(new CommandListener()
{
public void commandAction(Command c,Displayable di)
{

if(c==next)
{

try
{

if(re.hasNextElement())
{
byte []data=re.nextRecord();
String str1=new String(data);
for(i=0;i<5;i++)
{
index = str1.indexOf(“|”);
if(i==0)
user.setString(str1.substring(0,index));
else if(i==1)
{

}
else if(i==2)
email.setString(str1.substring(0,index));
else if(i==3)
phone.setString(str1.substring(0,index));
else if(i==4)
addr.setString(str1.substring(0,index));

str1=str1.substring(index+1,str1.length());
}

}
else
{
Alert a1= new Alert(“ALERT”,” no more users.. “,null,AlertType.INFO);
d.setCurrent(a1);
rs.closeRecordStore();
rs=RecordStore.openRecordStore(“btc”,true);
}
}
catch(Exception e)
{

}
}
else if(c==cancel)
{
d.setCurrent(d1);
}
}
});
d.setCurrent(f);
}

protected void startApp() throws MIDletStateChangeException {
}

protected void pauseApp() {
}

protected void destroyApp(boolean b) throws MIDletStateChangeException {
}
}

——————–

/*
* login.java
*
* Created on February 9, 2008, 10:45 AM
*/

//package chat;

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.rms.*;

/**
*
* @author Administrator
* @version
*/
public class login extends MIDlet
{
TextField user,pass;
Displayable d1=null;
menu mn=new menu();
Command ok=new Command(“OK”,Command.OK,0);
Command back=new Command(“BACK”,Command.BACK,0);
public void startApp()
{

}

public void pauseApp()
{

}
public void destroyApp(boolean unconditional)
{
}

public void display(final Display d) {
d1=d.getCurrent();
Form f= new Form(“LOGIN”);
user=new TextField(“USERNAME”,””,32,TextField.ANY);
pass=new TextField(“PASSWORD”,””,32,TextField.PASSWORD);
f.append(user);
f.append(pass);
f.addCommand(ok);
f.addCommand(back);
f.setCommandListener(new CommandListener(){
public void commandAction(Command c,Displayable s)
{
if(c==ok)
{
String Uname=user.getString();
String Pword=pass.getString();
RecordStore rs=null;
int count=0,flag=0;
try
{

rs= RecordStore.openRecordStore(“btc”,true);
RecordEnumeration re=null;
re=rs.enumerateRecords(null,null,false);
while(re.hasNextElement())
{
count++;
byte []data=re.nextRecord();
String str1=new String(data);
int index = str1.indexOf(“|”);
String s1=str1.substring(0,index);
str1=str1.substring(index+1,str1.length());
index = str1.indexOf(“|”);
String s2=str1.substring(0,index);

if(s1.equals(Uname))
{
flag=1;
if(s2.equals(Pword))
{
// Alert a3= new Alert(“LOGGED IN”,” YOU HAVE SUCCESSFULLY LOGGED IN!!!!!!!”,null,AlertType.INFO);
// d.setCurrent(a3);
String u=user.getString();

user.setString(“”);
pass.setString(“”);
mn.display1(d,u);
}
else
{
Alert a2= new Alert(“ALERT”,” WRONG PASSWORD”,null,AlertType.INFO);
d.setCurrent(a2);
}
}

}

if(flag==0)
{
Alert a1= new Alert(“ALERT”,” USERNAME DONOT EXISTS”,null,AlertType.INFO);

d.setCurrent(a1);
}
rs.closeRecordStore();
}
catch(Exception e)
{
e.printStackTrace();
}

}
else if(c==back)
d.setCurrent(d1);
}

});
d.setCurrent(f);
}
}

————————

/*
* lookforfriends.java
*
* Created on April 14, 2008, 4:52 PM
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/

/**
*
* @author Administrator
*/
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.bluetooth.*;
import java.util.*;
import java.io.*;
public class lookforfriends extends MIDlet implements CommandListener,Runnable,DiscoveryListener{

private Command discover,exit,select;
LocalDevice local;
private DiscoveryAgent discoveryagent;
private Hashtable bluetoothdevices=new Hashtable();
List devicelist;
Displayable d1;
private Display dis;
/** Creates a new instance of lookforfriends */
public lookforfriends() {
}
public void display(final Display d)
{
d1=d.getCurrent();
discover=new Command(“Discover”,Command.SCREEN,0);
exit=new Command(“Exit”,Command.EXIT,0);
select=new Command(“Select”,Command.OK,0);
devicelist=new List(“Select device”,List.IMPLICIT);
devicelist.addCommand(exit);
devicelist.setCommandListener(new CommandListener(){
public void commandAction(Command command, Displayable displayable) {
if(command==exit)
{
d.setCurrent(d1);
}
}
}
);
Form f=new Form(“Devices”);
f.addCommand(discover);
f.addCommand(exit);
f.setCommandListener(new CommandListener(){
public void commandAction(Command command, Displayable displayable) {
if(command==exit)
{
d.setCurrent(d1);
}
if(command==discover)
{
doBluetoothDiscovery();

}
}
});
d.setCurrent(f);
dis=d;
}
private void doBluetoothDiscovery()
{
printString(“doBluetoothdisc”);
Thread t=new Thread(this);
t.start();
// bluetoothDiscovery(d);
}
public void printString(String s)
{
System.out.println(s);
}
private void bluetoothDiscovery()
{
printString(“Bluetooth!!!!!!!!!!!!”);
LocalDevice localdevice;
try
{
localdevice=LocalDevice.getLocalDevice();
}
catch(BluetoothStateException e)
{
printString(“BluetoothStateException:”+e);
return;
}
discoveryagent=localdevice.getDiscoveryAgent();
RemoteDevice devices[];
try
{
devices=discoveryagent.retrieveDevices(DiscoveryAgent.CACHED);
if(devices!=null)
{
for(int i=0;i<devices.length;i++)
{
bluetoothdevices.put(devices[i].getFriendlyName(false),devices[i]);
printString(“Device(cached):”+devices[i].getFriendlyName(false)+””+devices[i].getBluetoothAddress());
}

}
devices=discoveryagent.retrieveDevices(DiscoveryAgent.PREKNOWN);
if(devices!=null)
{
for(int i=0;i<devices.length;i++)
{
bluetoothdevices.put(devices[i].getFriendlyName(false),devices[i]);
printString(“Device(cached):”+devices[i].getFriendlyName(false)+””+devices[i].getBluetoothAddress());
}

}

}
catch(IOException e)
{
printString(“Exception(b2):”+e);
}
try
{
discoveryagent.startInquiry(DiscoveryAgent.GIAC,this);

}
catch(BluetoothStateException e)
{
printString(“Exception(b3):”+e);
}
printString(“Return from bluetoothDiscovery()”);

}

protected void startApp() throws MIDletStateChangeException {
}

protected void pauseApp() {
}

protected void destroyApp(boolean b) throws MIDletStateChangeException {
}
private void bluetoothCopyDeviceTableToList()
{
printString(“Bluetoothcopy!!!!!!”);
//Remove old entries
for(int i=devicelist.size();i>0;i–)
{
devicelist.delete(i-1);
}
//append keys from table
for(Enumeration e=bluetoothdevices.keys();e.hasMoreElements();)
{
try
{
String name=(String)e.nextElement();
devicelist.append(name,null);
}
catch(Exception e1)
{

}
}
dis.setCurrent(devicelist);
}

public void run() {
printString(“Bluetoothrun!!!”);
bluetoothDiscovery();
}

public void deviceDiscovered(RemoteDevice remoteDevice, DeviceClass deviceClass) {
try
{
if(!remoteDevice.getFriendlyName(false).equals(“PC”))
printString(“Devicediscovered:”+remoteDevice.getFriendlyName(false));
//add device to table
bluetoothdevices.put(remoteDevice.getFriendlyName(false),remoteDevice);
}
catch(Exception e2)
{
printString(“Exception(b4):”+e2);
}
}

public void servicesDiscovered(int i, ServiceRecord[] serviceRecord) {
}

public void serviceSearchCompleted(int i, int i0) {
}

public void commandAction(Command command, Displayable displayable) {
}
public void inquiryCompleted(int i) {
printString(“Inquiry Completed!!”+i);
bluetoothCopyDeviceTableToList();
}

}

——————————

import javax.microedition.lcdui.*;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;
import java.io.*;
/*
* menu.java
*
* Created on March 7, 2008, 2:06 PM
*
*/

/**
*
* @author raymond
*/
public class menu extends MIDlet {

//lookforfriends l=new lookforfriends();
ChatController l=new ChatController();
help h=new help();
profile p=new profile();

chathistory ch=new chathistory();

Command help=new Command (“HELP”,Command.EXIT,0);
String []selements ={“Look for Friends”,”Chat History”,”My Profile”,”LOGOUT”};

Displayable d1=null;
List s =new List(“LIST”,List.IMPLICIT,selements,null);

/** Creates a new instance of menu */
public menu() {
}

protected void startApp() throws MIDletStateChangeException {

}
public void display1(final Display d,final String user)
{
d1=d.getCurrent();
s.addCommand(help);
s.setCommandListener(new CommandListener()
{
public void commandAction(Command command, Displayable displayable) {

if(command==help)
{
h.display1(d) ;
}
else
{
String str=s.getString(s.getSelectedIndex());
System.out.println(str);
if(str.equals(“Look for Friends”))
{
l.display(d,user);
}
else if(str.equals(“Chat History”))
{
ch.display(d,user);
}
else if(str.equals(“My Profile”))
{
p.display(d,user);
}
else if(str.equals(“LOGOUT”))
{
d.setCurrent(d1);
}
}

}
});
d.setCurrent(s);
}
protected void pauseApp() {
}

protected void destroyApp(boolean b) throws MIDletStateChangeException {
}

}

————————-

/*

* newuser.java

*

* Created on February 9, 2008, 9:46 AM

*

*/

package chat;

import javax.microedition.midlet.*;

import javax.microedition.lcdui.*;

import javax.microedition.rms.*;

/**

*

* @author raymond

* @version

*/

public class newuser extends MIDlet

{ // int flag=0,l=0;

Displayable d1=null;

TextField user,pass,retype,email,address,phone;

Command ok=new Command(“OK”,Command.OK,0);

Command back=new Command(“BACK”,Command.BACK,0);

public void display(final Display d)

{

d1=d.getCurrent() ;

Form f= new Form(“NEWUSER”);

user=new TextField(“USERNAME”,””,32,TextField.ANY);

pass=new TextField(“PASSWORD”,””,32,TextField.PASSWORD);

retype=new TextField(“RETYPE PASSWORD”,””,32,TextField.PASSWORD);

email=new TextField(“EMAIL”,””,32,TextField.ANY);

address=new TextField(“ADDRESS”,””,32,TextField.ANY);

phone=new TextField(“PHONE NO”,””,32,TextField.NUMERIC);

f.append(user);

f.append(pass);

f.append(retype);

f.append(email);

f.append(phone);

f.append(address);

f.addCommand(ok);

f.addCommand(back);

f.setCommandListener(new CommandListener()

{

public void commandAction(Command c,Displayable s)

{

int flag=0;

if(c==ok)

{

String uname=user.getString();

String pword=pass.getString();

String ret=retype.getString();

String str =uname+”|”+pword;

if(!pword.equals(ret))

{

Alert a1= new Alert(“ALERT”,”PASSWORD ENTRIES DOESNT MATCH”,null,AlertType.INFO);

d.setCurrent(a1);

}

else

{

// flag=0;

try

{

RecordStore rs= RecordStore.openRecordStore(“btc”,true);

RecordEnumeration re=null;

re=rs.enumerateRecords(null,null,false);

while(re.hasNextElement())

{

byte []data=re.nextRecord();

String str1=new String(data);

int index = str1.indexOf(“|”);

String s1=str1.substring(0,index);

System.out.println(s1+” “+uname);

if(s1.equals(uname))

{

flag=1;

Alert a2= new Alert(“ALERT”,”USERNAME EXISTS”,null,AlertType.INFO);

d.setCurrent(a2);

return;

}

}

if(flag==0)

{

try

{

String em=email.getString();

String addr=address.getString();

String phno=phone.getString();

if(!em.equals(“”)&&!addr.equals(“”)&&!phno.equals(“”))

{

str=str+”|”+em+”|”+phno+”|”+addr+”|”;

byte []data1=str.getBytes();

RecordStore rs1= RecordStore.openRecordStore(“btc”,true);

rs1.addRecord(data1,0,data1.length);

Alert a3= new Alert(“ALERT”,”REGISTERED”,null,AlertType.INFO);

d.setCurrent(a3);

user.setString(“”);

pass.setString(“”);

retype.setString(“”);

email.setString(“”);

address.setString(“”);

phone.setString(“”);

}

else

{

Alert a4= new Alert(” ALERT”,”The fields cannot be left

blank..”,null,AlertType.INFO);

d.setCurrent(a4);

}

}

catch(Exception e)

{

System.out.println(e);

}

}

rs.closeRecordStore();

}

catch(Exception e)

{

System.out.println(e);

}

}

}

else if(c==back)

{

d.setCurrent(d1);

}

}

});

d.setCurrent(f);

}

public void startApp()

{

}

public void pauseApp() {

}

public void destroyApp(boolean unconditional) {

}

}

———————–

/*
* profile.java
*
* Created on March 14, 2008, 1:04 PM
*/

/**
*
* @author raymond
*/
import javax.microedition.lcdui.*;
import javax.microedition.rms.*;
import javax.microedition.midlet.*;
import java.io.*;

public class profile extends MIDlet{

Displayable d1=null;
int flag=0,i,index;
// byte[]dat;

Command save=new Command(“SAVE”,Command.SCREEN,0);

TextField id,name,age,sex,hobb,qual,occu;
Command cancel=new Command(“CANCEL”,Command.EXIT,0);
/** Creates a new instance of profile */
public profile() {
}
public void display(final Display d,final String u)
{
d1=d.getCurrent();
Form f=new Form(“Profile”);
id=new TextField(“Loginid: “,””,32,TextField.ANY);
name=new TextField(“Name: “,””,32,TextField.ANY);
age=new TextField(“Age: “,””,32,TextField.NUMERIC);
sex=new TextField(“Sex: “,””,32,TextField.ANY);
hobb=new TextField(“Hobbies: “,””,100,TextField.ANY);
qual=new TextField(“Qualification: “,””,100,TextField.ANY);
occu=new TextField(“Occupation: “,””,100,TextField.ANY);
f.append(id);
f.append(name);
f.append(age);
f.append(sex);
f.append(hobb);
f.append(qual);
f.append(occu);
f.addCommand(save);
f.addCommand(cancel);
id.setString(u);
try
{
RecordStore rs2= RecordStore.openRecordStore(“btc5”,true);
RecordEnumeration re=null;
re=rs2.enumerateRecords(null,null,false);
System.out.println(“inside btc………”);
while(re.hasNextElement())
{
byte []data=re.nextRecord();
String str1=new String(data);
System.out.println(str1);
}
rs2.closeRecordStore();
}
catch(Exception e)
{

}
String s=id.getString();
System.out.println(s);
RecordStore rs=null;
try
{
rs= RecordStore.openRecordStore(“btc5”,true);
RecordEnumeration re=null;
re=rs.enumerateRecords(null,null,false);
while(re.hasNextElement())
{
byte []data=re.nextRecord();
String str1=new String(data);
index = str1.indexOf(“|”);
String s1=str1.substring(0,index);
str1=str1.substring(index+1,str1.length());
if(s1.equals(s))
{

flag=1;
for(i=0;i<=5;i++)
{
index = str1.indexOf(“|”);
if(i==0)
name.setString(str1.substring(0,index));
else if(i==1)
age.setString(str1.substring(0,index));
else if(i==2)
sex.setString(str1.substring(0,index));
else if(i==3)
hobb.setString(str1.substring(0,index));
else if(i==4)
qual.setString(str1.substring(0,index));
else if(i==5)
occu.setString(str1.substring(0,index));

str1=str1.substring(index+1,str1.length());

}

}

}
rs.closeRecordStore();
}
catch(Exception e)
{

}

f.setCommandListener(new CommandListener()
{
public void commandAction(Command c,Displayable di)
{
if(c==save)
{

String s=id.getString();
String na=name.getString();
String ag=age.getString();
String se=sex.getString();
String ho=hobb.getString();
String qu=qual.getString();
String oc=occu.getString();
RecordStore rs=null;
try
{
rs= RecordStore.openRecordStore(“btc5”,true);

RecordEnumeration re=null;

re=rs.enumerateRecords(null,null,false);

if(re.numRecords()==0)
{
System.out.println(“No record”);

if(!na.equals(“”)&&!ag.equals(“”)&&!se.equals(“”)&&!ho.equals(“”)&&!qu.equals(“”)&&!oc.equals(“”))
{
s=s+”|”+na+”|”+ag+”|”+se+”|”+ho+”|”+qu+”|”+oc+”|”;
byte []data1=s.getBytes();
rs.addRecord(data1,0,data1.length);
Alert a3= new Alert(“”,”SAVED”,null,AlertType.INFO);
d.setCurrent(a3);
rs.closeRecordStore();
}
}
while(re.hasNextElement())
{
byte []data=re.nextRecord();
String str1=new String(data);
index = str1.indexOf(“|”);
String s1=str1.substring(0,index);
if(s1.equals(s))
{
int n=rs.getNextRecordID();
System.out.println(n);
rs.deleteRecord(n-1);

if(!na.equals(“”)&&!ag.equals(“”)&&!se.equals(“”)&&!ho.equals(“”)&&!qu.equals(“”)&&!oc.equals(“”))
{
s1=s1+”|”+na+”|”+ag+”|”+se+”|”+ho+”|”+qu+”|”+oc+”|”;
byte []data1=s1.getBytes();
rs.addRecord(data1,0,data1.length);
Alert a3= new Alert(“”,”SAVED”,null,AlertType.INFO);
d.setCurrent(a3);
rs.closeRecordStore();
}

}
else
{

if(!na.equals(“”)&&!ag.equals(“”)&&!se.equals(“”)&&!ho.equals(“”)&&!qu.equals(“”)&&!oc.equals(“”))
{
s=s+”|”+na+”|”+ag+”|”+se+”|”+ho+”|”+qu+”|”+oc+”|”;
byte []data1=s.getBytes();
rs.addRecord(data1,0,data1.length);
Alert a3= new Alert(“”,”SAVED”,null,AlertType.INFO);
d.setCurrent(a3);
rs.closeRecordStore();
}

}

}
}

catch(Exception e)
{
e.printStackTrace();
}

}
else if(c==cancel)
{
d.setCurrent(d1);
}
}
});
d.setCurrent(f);
}
protected void startApp() throws MIDletStateChangeException {

}

protected void pauseApp() {
}

protected void destroyApp(boolean b) throws MIDletStateChangeException {
}

}

8086 Assemly

A simple 8086 program to check if a string is palindrome or not, using macros.

message macro arg
lea dx,arg
mov ax,0900h
int 21h
endm

data segment
cr equ 0dh
lf equ 0ah
sent db 25 dup(‘$’)
msg1 db “Enter the sentenc:$”
msg2 db cr,lf,”Sentence is not a palindrome$”
msg3 db cr,lf,”Sentence is a palindrome$”
data ends

code segment
assume cs:code,ds:data
start: mov ax,data
mov ds,ax
message msg1
mov ax,0000h
lea si,sent
read: mov ax,0100h
int 21h
cmp al,0dh
je next
cmp al,7ah
jg read
cmp al,60h
jg ahead
cmp al,5ah
jg read
add al,20h
ahead: mov [si],al
inc si
inc cl
jmp read
next: dec si
lea di,sent
check: mov bl,[di]
cmp [si],bl;
jne notpali
inc di
dec si
cmp di,si
jge paliok
jmp check
notpali: message msg2
jmp pgend
paliok: message msg3
pgend: mov ah,4ch
int 21h
code ends
end start

8086 Assembly program

A simple and complete 8086 assembly program to add numbers, using macros.

message macro arg
lea dx,arg
mov ax,0900h
int 21h
endm

number macro arg
mov ax,arg
mov cx,0000h
mov bx,000ah
conv: mov dx,0000h
div bx
add dx,30h
push dx
inc cx
cmp ax,0000h
jnz conv
mov ax,0200h
disp: pop dx
int 21h
loop disp
endm
data segment
cr equ 0dh
lf equ 0ah
msg1 db cr,lf,”Enter a number:$”
msg2 db cr,lf,”the sum is:$”
num1 dw 1
num2 dw 1
num3 dw 1
data ends
code segment
assume cs:code,ds:data
start: mov ax,data
mov ds,ax
message msg1
mov ax,0100h
int 21h
sub al,30h
cmp al,0ah
jnc store1
sub al,07h
store1: mov num1,ax
message msg1
mov ax,0100h
int 21h
sub al,30h
cmp al,0ah
jnc store2
sub al,07h
store2: mov num2,ax
mov ax,num1
add ax,num2
mov num3,ax
message msg2
number num3
pgend: mov ah,4ch
int 21h
code ends
end start

Binary Search Tree

A complete working program of binary search tree.

#include<stdio.h>
#include<conio.h>
#define null 0
struct tree
{
int info;
struct tree*lchild;
struct tree*rchild;
};

struct tree* Insert(struct tree *root,int x)
{
struct tree*newnode,*p,*q;
newnode=(struct tree*)malloc(sizeof(struct tree));
newnode->info=x;
newnode->lchild=null;
newnode->rchild=null;
p=root;
q=p;
while(p!=null&&q->info!=x)
{
q=p;
if(p->info>x)
p=p->lchild;
else
p=p->rchild;
}
if(q->info>x)
q->lchild=newnode;
else if(q->info<x)
q->rchild=newnode;
else if(q->info==x)
printf(“duplicate”);
return root;
}
struct tree* Delete(struct tree*root,int x)
{
struct tree*prev,*node,*p,*temp;
p=root;
while(p->info!=x&&p!=null)
{
prev=p;
if(p->info>x)
p=p->lchild;
else
p=p->rchild;
}
if(p->info==x)
{
if(p->lchild==null)
node=p->rchild;
else if(p->rchild==null)
node=p->lchild;
else
{
node=p->lchild;
temp=node;
while(temp->rchild!=null)
{
temp=temp->rchild;
temp->rchild=p->rchild;
}
if(p==root)
root=node;
else if(prev->lchild==p)
prev->lchild=node;
else if(prev->rchild==p)
prev->rchild=node;
free(p);
}
}
return root;
}
void Pre_order(struct tree*p)
{
if(p!=null)
{
printf(“%d”,p->info);
Pre_order(p->lchild);
Pre_order(p->rchild);
}
getch();
}
void main()
{
struct tree *root=null,*p,*q,*newnode,*temp;
int n,x,count,choice;
clrscr();
printf(“enter no of nodes\n”);
scanf(“%d”,&n);
printf(“enter the values\n”);
scanf(“%d”,&x);
root=(struct tree*)malloc(sizeof(struct tree));
root->info=x;
root->lchild=null;
root->rchild=null;
count=1;
while(count<n)
{
printf(“enter a value\n”);
scanf(“%d”,&x);
newnode=(struct tree*)malloc(sizeof(struct tree));
newnode->info=x;
newnode->lchild=null;
newnode->rchild=null;
p=root;
q=p;
while(p!=null&&q->info!=x)
{
q=p;
if(p->info>x)
p=p->lchild;
else
p=p->rchild;
if(q->info>x)
q->lchild=newnode;
else if(q->info<x)
q->rchild=newnode;
else if(q->info==x)
printf(“duplicate”);

}
count++;
}
do
{
printf(“\n1.Insert\n2.Delete\n3.Pre_order\n4.exit\n”);
printf(“enter your choice\n”);
scanf(“%d”,&choice);
switch(choice)
{
case 1: printf(“enter the element to be inserted\n”);
scanf(“%d”,&x);
root=Insert(root,x);
break;
case 2: printf(“enter the element to be deleted\n”);
scanf(“%d”,&x);
root=Delete(root,x);
break;
case 3: Pre_order(p);
break;
case 4: break;
default:printf(“invalid choice\n”);
}
}while(choice!=4);
}

Processor and its programming aspects

The first Intel processor, as we all know is 4004, where 4 signifies the word length or the number of bits that the processor can execute at a particular point of time. Let us discuss on the programming aspects of the processor. The processor contains a decoder also called Instruction decoder which accepts a numerical value and finds out the circuit corresponding to the value. For Example if D4 is the opcode of ADD instruction, the decoder on accepting the value activates the ADD logic. When programs where writing in machine language , the programmer had to find the op code of each task to be accomplished such as read from device, add, multiply etc. and enter it into primary memory and thereafter send to processor sequentially for execution. I presume this is the first generation of programming.

Video memory

Video memory is the memory area corresponding to the monitor i.e what is written on the video memory is displayed on the monitor. The example that I would like to illustrate is a little old fashioned and workable in DOS O.S.

char far *scr = 0xb8000000;

main()

{

int i,j;

for(i=0; i < 2000; i++)

for(j=0; j < 2000 ; j++)

*(scr + (2000 * i ) + )  = ‘A’;

}//end

I just wanted to display ‘A’ all over screen which other wise would have done using printf ( any inbuilt function) also. The time difference noticed while executing the program using print and using video memory access method is astonishing. By directly writing on the video memory we by pass 2000 X 2000 function call and the efficiency is remarkable.

regarding the pointer details – as we know intel architecture fllows segment memory model. memory is divided into Code Segment, Data Segment, Extra Segment, Stack Segment. A usual pointer such as int *ptr can point only within data /extra segment. To point to a location outside this segment we have to use far pointer.