Monday, October 13, 2008

Do u know Daknet??? Wireless Point to Point Connectivity??

Information delivery and communication efficiency in rural and remote areas in a developing country is the main concern of this article. Here we see how wirelless networks can achieve this point to point conectivity while providing the broadband access to remote areas at very low prices. "Daknet" is an initiative of this kind which has been successfully implemented and functioning even in some rural parts on India.

DakNet, is an ad hoc network that uses wireless technology to provide asynchronous digital connectivity,is an evidence that the marriage of wireless and asynchronous service may be the beginning of a road to universal broadband connectivity. Developed by MIT Media Lab researchers, DakNet has been successfully deployed in remote parts of both India and Cambodia. The DakNet wireless network takes advantage of the existing communications and transportation infrastructure to distribute digital connectivity to outlying villages lacking a digital communications infrastructure. How is that achieved?



The above figure illustrates the Daknet concept that has been applied in real time. Instead of relaying information over long distances which would be expensive and consume more power, Daknet makes use of short point -to-point links to transmit data between the Kiosks in each village and portable storage devices call Mobile Access Points (MAP). Mounted on and powered by a bus, a motorcycle, or even a bicycle with a small generator, a MAP physically transports data among public kiosks and private communications devices (as an intranet) and between kiosks and a hub (for nonreal- time Internet access). Low-cost WiFi radio transceivers automatically transfer the data stored in the MAP at high bandwidth for each point-topoint connection.

1)As the MAP-equipped vehicle comes within range of a village WiFi-enabled kiosk, it automatically senses the wireless connection and then uploads and downloads tens of megabytes of data.

2)When a MAP-equipped vehicle comes within range of an Internet access point (the hub), it automatically synchronizes the data from all the rural kiosks, using the Internet.

These steps are repeated each time a MAP equipped vehicle passes through the village which enables low cost wireless network and seamless connectivity. Even a single vehicle passing by a village once per day is sufficient to provide daily information services and the connection quality is also high. Daknet also incorporates means for seamless scalability in future when the village's ecconomy grows and people can afford to spend more and they will also be able to obtain real time communication services.

Even local entrepreneurs currently are using DakNet connections to make e-services like e-mail and voice mail available to residents in rural villages. Daknet concept has helped many more initiatives in India like the Bhoomi initiative. Bhoomi, an initiative to computerize land records. Daknet helps on this a lot. A detailed article on Daknet and other initiatives which has enabled digital connectivity in remote areas through wireless networks is available here.

http://www.keepandshare.com/doc/view.php?id=867331&da=y






Tuesday, September 16, 2008

Using Sun's Wireless ToolKit for CDLC to develop a simple J2ME App

The Sun Java Wireless Toolkit (formerly known as J2ME Wireless Toolkit) is a set of tools for creating Java applications that run on devices compliant with the Java Technology for the Wireless Industry (JTWI, JSR 185) specification and the Mobile Service Architecture (MSA, JSR 248) specification. It consists of build tools, utilities, and a device emulator. The application, a MIDlet, was designed for the Mobile Information Device Profile, one of the Java ME specifications. here we write and deploy a normal servlet and hook it up with a MIDlet to run the same app in a mobile device. we can test it using the emulator provided in the toolkit.

First prepare for a normal web app deployment using Tomcat 4.1 or above. the folowing code just counts the number of hits and displays it to the user.
import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;

public class HitServlet extends HttpServlet {
private int mCount;

public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String message = "Hits: " + ++mCount;

response.setContentType("text/plain");
response.setContentLength(message.length());
PrintWriter out = response.getWriter();
out.println(message);
}
}
Compile and deploy the servlet using configurations in the web.xml as its done usually.Test the application by providing the URL specified in the web.xml.now we'l connect the servlet with the MIDlet.Install the wireless Toolkit and create a new project HelloSuite. The following shows the Toolkit interface.

The window will show where you have to store the source code files after creating the project.
Savethe below code as HitMIDlet.java inside the apps/HelloSuite/src directory underneath the Sun Java Wireless Toolkit root directory.
import java.io.*;

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

public class HitMIDlet
extends MIDlet
implements CommandListener {
private Display mDisplay;
private Form mMainForm;
private StringItem mMessageItem;
private Command mExitCommand, mConnectCommand;

public HitMIDlet() {
mMainForm = new Form("HitMIDlet");
mMessageItem = new StringItem(null, "");
mExitCommand = new Command("Exit", Command.EXIT, 0);
mConnectCommand = new Command("Connect",
Command.SCREEN, 0);
mMainForm.append(mMessageItem);
mMainForm.addCommand(mExitCommand);
mMainForm.addCommand(mConnectCommand);
mMainForm.setCommandListener(this);
}

public void startApp() {
mDisplay = Display.getDisplay(this);
mDisplay.setCurrent(mMainForm);
}

public void pauseApp() {}

public void destroyApp(boolean unconditional) {}

public void commandAction(Command c, Displayable s) {
if (c == mExitCommand)
notifyDestroyed();
else if (c == mConnectCommand) {
Form waitForm = new Form("Waiting...");
mDisplay.setCurrent(waitForm);
Thread t = new Thread() {
public void run() {
connect();
}
};
t.start();
}
}

private void connect() {
HttpConnection hc = null;
InputStream in = null;
String url = getAppProperty("HitMIDlet.URL");

try {
hc = (HttpConnection)Connector.open(url);
in = hc.openInputStream();

int contentLength = (int)hc.getLength();
byte[] raw = new byte[contentLength];
int length = in.read(raw);

in.close();
hc.close();

// Show the response to the user.
String s = new String(raw, 0, length);
mMessageItem.setText(s);
}
catch (IOException ioe) {
mMessageItem.setText(ioe.toString());
}
mDisplay.setCurrent(mMainForm);
}
}

There are two other things to configure to get HitMIDlet working. First, you need to tell the toolkit about this new MIDlet. Click on Settings..., then select the MIDlets tab. Click on Add and fill in "HitMIDlet" for both the MIDlet name and class name. You can leave Icon blank. Click on OK and you should see HitMIDlet listed.

click on
Settings..., then select the User Defined tab. Click on the Add button. Fill in the property name as HitMIDlet.URL; the value should be the URL that invokes HitServlet, the same URL you used in a browser to test the servlet. When you're finished, click on OK to dismiss the project settings window.
Click on Build button and then Run button to run the application. you will see the emulator now..launch and connect and u will see the same result you saw in the webbrowser earlier as shown below..



Sunday, August 3, 2008

Mounting Devices on Linux

Before accessing a hard disk or any other storage medium in Linux or UNIX they should be mounted. Note that there is no concept of mounting in windows platforms. Mount allows you to merge two file systems. Mounting of file systems are done with mount command.


The figure shows the unix file system before mounting and after mounting.

The Mount command
Mount command has many options and hence little complex. But most of the time you will be able to mount file systems easily with few options. Mount command takes following general format.
mount -t filesystem_type -o mount_options /dev/device_file /mnt/mount_point

Usually we don't specify t option because kernel can usually identify the file system type by looking at partition table. The o options are also optional.We can unmount a device by it's device file name or by the mount point.
#umount /dev/sda
#umount /mnt/flash

Mounting a CD ROM/DVD ROM
Following command tells the kernel to auto detect (t auto) file system type and mount the device /dev/cdrom on /mnt/cdrom.
#mount -t auto /dev/cdrom /mnt/cdrom

If mounting fails, check whether you have a /mnt/cdrom directory, you can do it by using ,
#ls -l /mnt/cdrom

If it is not there then create it,
#mkdir /mnt/cdrom

Now try the mount command if it fails again check whether you have /dev/cdrom. If it does not exist, try
#dmesg | grep -i cdrom to find out the device file.

Now you can retry the command assuming that /dev/hdb is your CD ROM drive.
#mount -t auto /dev/hdb /mnt/cdrom.

Mounting a floppy, USB drive and windows partition
You can mount floppy as root user with following command.
#mount -t auto /dev/fd0 /mnt/floppy

If you get any error follow steps given earlier.
For USB drive, as root user
#mount -t vfat /dev/sda1 /mnt/usb

If you get any error follow steps given above. If you still get error saying that /dev/sda is not a valid block device then check whether the disk is partitioned. You can do this with fdisk command.
#fdisk -l /dev/sda

If you still find problems restart your hotplug sub system and remove and reinsert the device.
#/etc/init.d/hotplug restart

When mounting DOS/Windows partitions first make sure whether it is fat formated or ntfs the following commands can be used.
#mount -t vfat /dev/hda1 /mnt/windows
#mount -t ntfs /dev/hda5 /mntwinxp

If you want to mount so that all users can read and write, you may want to try:
#mount -t vfat -o user,rw,exec,umask=000 /dev/hda1 /mnt/c

“-o user,rw,exec,umask=000” gives every body all the permission to all the files on your partition.

Mounting a loopback device
Create a file containing all zeros. A 10MB file.
#dd if=/dev/zero of=myblock.img bs=1k count=1024

Now attach this to loop back device and format.
#losetup /dev/loop0 myblock.img
#mkfs -t vfat /dev/loop0

Now we can mount the device by using the file as the device.
#mount -o loop myblock.img /mnt/loop

How can you allow a normal user to mount a device?
All you have to do is adding an entry to the /etc/fstb file It has the following format.
<file> <mount> <type> <options> <dump> <pass>
/dev/sda1 /mnt/usb vfat user,rw 0 0

Sunday, July 20, 2008

A complete chat program

ChatClient.java

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

public class ChatClient implements Runnable
{
static String command;
Socket socket;
static final int portNumber=1666;
Thread commReader=null;

BufferedReader input;
PrintStream output;

String alias=null;
boolean logging=true;

public static void main(String[] argv) throws IOException
{
InetAddress clientAddr;
if(argv.length==0)
clientAddr=InetAddress.getLocalHost();
else
clientAddr=InetAddress.getByName(argv[0]);
System.out.println("Connecting to Chat Server at "+clientAddr);
ChatClient cc=new ChatClient(clientAddr);
Thread t=new Thread(cc);
t.start();
}

public ChatClient(InetAddress adx)
{
CommandReader cr=new CommandReader(this);
commReader=new Thread(cr);
command="xXx";
try
{
socket=new Socket(adx,portNumber);
input=new BufferedReader(new InputStreamReader(socket.getInputStream()));
output=new PrintStream(socket.getOutputStream());
commReader.start();
}
catch(IOException e)
{
System.out.println("Abnormal chat client socket condition:"+e);
}
}

public void run()
{
try
{
doLoop();
input.close();
output.close();
socket.close();
System.exit(0);
}
catch(IOException e)
{
System.out.println("Abnormal chat client socket condition:"+e);;
}

}

public void doLoop() throws IOException
{
String nullString=new String("xXx");
String data=nullString;
while(true)
{

synchronized(command)
{

if(!command.equals("xXx"))
{
data=command;
//reset
command="xXx";

}
} //end synch

if(!data.equals("xXx"))
{
if(logging)
{
//first msg
logging=false;
alias=data;
System.out.println(">>Logging as:"+alias);
output.println("S"+alias); //Starting new chat
}
else
{
if(data.equals("exit"))
{
System.out.println(">>Exiting Chat.");
output.println("X"+alias);
break;
}
else if(data.equals("/list"))
{
System.out.println(">>list of connected users:");
output.println("L"+alias);
break;
}
else if(data.equals("/help"))
{
System.out.println(">>Help on Chat commands:");
output.println("H"+alias);
break;
}
else
{
System.out.println(">>Sending msg:"+data);
output.println("D"+data); //sending data
}
}

}

data=input.readLine();
if(!data.equals("xXx"))
{
System.out.println("<<"+data);
}
data=nullString;
}
}

}


ChatDaemon.java

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

public class ChatDaemon implements Runnable
{
static final int maxClients=20;
static final int portNumber=1666;
static int numClients=0;
ChatServer[] chatters;
Thread me;

SharedMsg sharedMsg;

public static void main(String[] argv)
{
ChatDaemon cd=new ChatDaemon();
}

public ChatDaemon()
{
sharedMsg=new SharedMsg(this);
chatters=new ChatServer[maxClients];
//start sending
me=new Thread(this);
me.start();

try
{
listen();
}
catch(IOException e)
{
System.out.println("Abnormal socket condition:"+e);
}
}

public void listen() throws IOException
{
ServerSocket ss=null;
ss=new ServerSocket(portNumber);
Socket chatSocket=null;
System.out.println("...listening for connections..");
while(true)
{
chatSocket=ss.accept();
ChatServer ct=allocThread(chatSocket);
synchronized(System.out)
{
System.out.println("Allocated new chat server");
}
}

}

ChatServer allocThread(Socket s)
{
if(numClients<maxClients)
{
ChatServer ct=new ChatServer(s,sharedMsg,numClients);
chatters[numClients]=ct;
Thread t=new Thread(ct);
t.start();
numClients++;
return ct;
}
else
return null;
}

public void run()
{
char broad=(char)-1;
String dataNull=new String(broad+"xXx");
while(true)
{

for(int i=0;i<numClients;i++)
if(chatters[i].alive())
chatters[i].newMsg(dataNull);
}
}

public void refresh()
{
String data=sharedMsg.get();
synchronized(System.out)
{
System.out.println("RECEIVED:"+data);
}
for(int i=0;i<numClients;i++)
{
if(chatters[i].alive())
chatters[i].newMsg(data);
}
}
}


ChatServer.java

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

public class ChatServer implements Runnable
{
int index=-1;
SharedMsg sharedMsg;
Socket socket;

DataInputStream input;
PrintStream output;

String alias="";
boolean running=false;

boolean alive()
{
return running;
}

public ChatServer(Socket s,SharedMsg sm,int idx)
{
index=idx;
sharedMsg=sm;
socket=s;
try
{
input=new DataInputStream(socket.getInputStream());
output=new PrintStream(socket.getOutputStream(),true);

}
catch(IOException e)
{
System.out.println("Abnormal chat server socket condition 1:"+e);;
}
}

public void run()
{
try
{
doLoop();
input.close();
output.close();
socket.close();
}
catch(IOException e)
{
System.out.println("Abnormal chat server socket condition 2:"+e);;
}
}

public void doLoop() throws IOException
{
String line=null;
String data=null;
char command='W';
char ind=(char)index; //index of sender of msg
char broad=(char)-1; //goes to everybody

running=true;
while(true)
{
//loop: reads in msg, write it onto sharedmsg
line=input.readLine();
command=line.charAt(0);
data=line.substring(1);

if(command=='X')
{
sharedMsg.put(broad+"User: "+data+" Logged Out");
break;
}
else if(command=='S')
{
//first msg
alias=data;
sharedMsg.put(broad+"New User Logged: "+alias);
}
else
{
sharedMsg.put(ind+"From "+alias+": "+data);
}
}
//exiting
running=false;
}

//new message arrived, send it over the socket
public void newMsg(String msg)
{
char mitt=msg.charAt(0);
String data=msg.substring(1);

if(mitt!=(char)index)
{
//send
output.println(data);
output.flush();

synchronized(System.out)
{
System.out.print(".\b");
System.out.flush();
}
}
}
}


CommandReader.java

import java.io.*;

/**
* Reads from keyboard (STDIN)
*/
class CommandReader implements Runnable
{
ChatClient chatClient;
DataInputStream user;

public CommandReader(ChatClient cc)
{
chatClient=cc;
user=new DataInputStream(System.in);
}

public void run()
{
System.out.println("Waiting for client side commands...");

String com=null;
while(true)
{
//reads from keyboard
try
{
com=user.readLine();
}
catch(IOException e)
{
System.out.println("Abnormal reading from user:"+e);
}

synchronized(chatClient.command)
{
chatClient.command=com;
}
}
}
}


SharedMsg.java

public class SharedMsg
{
String data="";
ChatDaemon chatDaemon=null;

SharedMsg(ChatDaemon cd)
{
chatDaemon=cd;

}

synchronized String get()
{
return data;
}

synchronized void put(String s)
{
data=s;
chatDaemon.refresh();
}
}

Saturday, July 12, 2008

Creating 2D Shapes in Java

The Java2D API provides advanced two-dimensional graphics capabilities for programmers who require detailed and complex graphical manipulations. it includes features for processing line art, text and images in packages java.awt, java.awt.image, java.awt.color, java.awt.font, java.awt.geom, java.awt.print and java.awt.image.renderable.

The code shown below constructs a ring of five pointed stars constructed from straight lines and complex curves.

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.GeneralPath;

import javax.swing.JFrame;

public class shapes extends JFrame{

//set window's title bar string, background color and dimensions
public shapes(){

super("Drawing 2D shapes");

getContentPane().setBackground(Color.WHITE);
setSize(400,400);
setVisible(true);
}

//draw general paths
public void paint(Graphics g){
super.paint(g);
int xPoints[]={55,67,109,73,83,55,27,37,1,43};
int yPoints[]={0,36,36,54,96,72,96,54,36,36};

Graphics2D g2d = (Graphics2D)g;

//create a star from a series of points
GeneralPath star = new GeneralPath();

//set the initials coordinates of the General Path
star.moveTo(xPoints[0],yPoints[0]);

//create the star
for(int count =1; count<xPoints.length; count++)
star.lineTo(xPoints[count],yPoints[count]);

//close the shape
star.closePath();

//translate the origin to (200,200)
g2d.translate(200,200);

//rotate around origin and draw stars in random colors
for(int count =1; count<=20; count++){


//rotate coordinate system
g2d.rotate(Math.PI/10.0);

//set random drawing color
g2d.setColor(new Color(
(int)(Math.random()*256),
(int)(Math.random()*256),
(int)(Math.random()*256)));

//draw filled star
g2d.fill(star);
}
}

public static void main(String args[]){

shapes application = new shapes();
application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

}

}

Run the program and view the result!!!