Tuesday, December 25, 2007

Java Simple thread program

/* Example for thread in java .
* Two types of thread creation can be done
* One- by extend the thread class
* two- by implement runnable
* below I used runnable.
*/
/* Class 1*/
public class TcpServer implements Runnable {

public static void main(String[] args) {
/* Creating instances for Class 1 and class 2 */
TcpServer ser1=new TcpServer();
TcpServer ser2=new TcpServer();
arun an=new arun();

/* Declaring thread for instance */
Thread t1=new Thread(ser1);
Thread t2=new Thread(ser2);
Thread t3=new Thread(an);
/*
* Thread can be created for any number of instances
*Thread t2=new Thread(ser2);
*/
/*thread started */
t1.start();
t2.start();
t3.start();
}
public void run() {

first();
}
public void first(){
for (int i = 0; i < 100; i++) {
System.out.println("Thread First "+i );
}
}
}/* end of class 1 */

/* Class 2 */
class arun implements Runnable{
public void run() {
second();
}
public void second(){
for (int i = 0; i < 100; i++) {
System.out.println("Thread Second "+i);
}
}
}/* End of class 2 */

Java Server /Client Chat program

/* This is an Client to Server One way comm. program
i.e client (writes) send data ,server keep on (read )listen and recv.

For two way communication between server and client we should go for thread.
How can be acheived by thread ?
In both server and client two threads should be created and one for read() and another for write().since read is blocking call.
For thread reference see my next post "Java Thread Simple program ".

Server.Java */

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
ServerSocket serverSocket=null;
Socket socket=null;
InputStream in=null;
OutputStream out=null;

Server() throws IOException{
serverSocket=new ServerSocket(500);
System.out.println("Server Started");
/* server will blocked here till client connects */
socket=serverSocket.accept();
System.out.println("Connected.........");
/* Any in coming dada we stored in this stream */
in=socket.getInputStream();
out=socket.getOutputStream();
}

void read() throws IOException{
int c=0;
/* printing the incoming message from input stream obj */
while((c=in.read())!=-1){
System.out.print((char)c);
}
in.close();
out.close();
socket.close();
}


public static void main(String[] args) throws IOException {
Server ser=new Server();
ser.read();
/*
Test code for string to byte conversion
String str="arun kumar";
Here we reading array string so we used byte array stream
ByteArrayInputStream by=new ByteArrayInputStream(str.getBytes());
int c=0;
while((c=by.read())!=-1){
System.out.println((char)c);
*/
}
}

/********* End of server *****************/

/*Client.Java */

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.io.DataInputStream;
public class Client {

Socket socket=null;
InputStream in=null;
OutputStream out=null;

Client() throws UnknownHostException, IOException{
socket=new Socket("localhost",500);
in=socket.getInputStream();
out=socket.getOutputStream();
}

void write() throws IOException{
/* Buffered input Stream will blocked till Enter key pressed. System.in is used get input from console (kbd) */
BufferedInputStream input=new BufferedInputStream(System.in);
while(true){
/* but here we converting buffer data to stream of bytes since buffer stream will store a block of characters*/
int c=input.read();
System.out.print((char)c);
out.write(c);

}
}
public static void main(String[] args) {
try {
Client client=new Client();
client.write();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

}

}

/********** End of Client *******************/

Monday, December 10, 2007

CreateGUI and Click Event Handler in Java

/* AddressBookDemo.java
Website: java-swing-tutorial.html
Topic: A basic Java Address Book
Conventions Used in Source code
---------------------------------
1. All JLabel components start with jlb*

2. All JPanel components start with jpl*

3. All JMenu components start with jmenu*

4. All JMenuItem components start with jmenuItem*

5. All JDialog components start with jdlg*

6. All JButton components start with jbn*

*/
import java.awt.Container;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;

public class AddressBookDemo implements ActionListener {

ArrayList personsList;
//PersonDAO pDAO;
JFrame appFrame;
JLabel jlbName, jlbAddress, jlbPhone, jlbEmail;
JTextField jtfName, jtfAddress, jtfPhone, jtfEmail;
JButton jbbSave, jbnDelete, jbnUpdate,
jbnBack, jbnSearch, jbnForward,
jbnClear, jbnExit;
String name, address, email;
int phone;
int recordNumber; // used to naviagate using >> and buttons
Container cPane;
public static void main(String args[]) {
new AddressBookDemo();
}
public AddressBookDemo() {
name = "";
address = "";
email = "";
phone = -1; //Stores 0 to indicate no Phone Number
recordNumber = -1;
createGUI();
//personsList = new ArrayList();
// creating PersonDAO object
//pDAO = new PersonDAO();
}
public void createGUI(){

/*Create a frame, get its contentpane and set layout*/
appFrame = new JFrame("Address Book");
cPane = appFrame.getContentPane();
cPane.setLayout(new GridBagLayout());
//Arrange components on contentPane and set Action Listeners to each JButton

arrangeComponents();
appFrame.setSize(260,300);
appFrame.setResizable(false);
appFrame.setVisible(true);

}
public void arrangeComponents() {
jlbName = new JLabel("Name");
jlbAddress = new JLabel("Address");
jlbPhone = new JLabel("Phone");
jlbEmail = new JLabel("Email");
jtfName = new JTextField(20);
jtfAddress = new JTextField(20);
jtfPhone = new JTextField(20);
jtfEmail = new JTextField(20);
jbbSave = new JButton("Save");
jbnDelete = new JButton("Delete");
jbnClear = new JButton("Clear");
jbnUpdate = new JButton("Update");
jbnSearch = new JButton("Search");
jbnForward = new JButton(">>");
jbnBack = new JButton("<<");
jbnExit = new JButton("Exit");

/*add all initialized components to the container*/
/* Name field */
GridBagConstraints gridBagConstraintsx01 = new GridBagConstraints();
gridBagConstraintsx01.gridx = 0;
gridBagConstraintsx01.gridy = 0;
gridBagConstraintsx01.insets = new Insets(5, 5, 5, 5);
cPane.add(jlbName, gridBagConstraintsx01);
GridBagConstraints gridBagConstraintsx02 = new GridBagConstraints();
gridBagConstraintsx02.gridx = 1;
gridBagConstraintsx02.insets = new Insets(5, 5, 5, 5);
gridBagConstraintsx02.gridy = 0;
gridBagConstraintsx02.gridwidth = 2;
gridBagConstraintsx02.fill = GridBagConstraints.BOTH;
cPane.add(jtfName, gridBagConstraintsx02);

/* Address field */
GridBagConstraints gridBagConstraintsx03 = new GridBagConstraints();
gridBagConstraintsx03.gridx = 0;
gridBagConstraintsx03.insets = new Insets(5, 5, 5, 5);
gridBagConstraintsx03.gridy = 1;
cPane.add(jlbAddress, gridBagConstraintsx03);
GridBagConstraints gridBagConstraintsx04 = new GridBagConstraints();
gridBagConstraintsx04.gridx = 1;
gridBagConstraintsx04.insets = new Insets(5, 5, 5, 5);
gridBagConstraintsx04.gridy = 1;
gridBagConstraintsx04.gridwidth = 2;
gridBagConstraintsx04.fill = GridBagConstraints.BOTH;
cPane.add(jtfAddress, gridBagConstraintsx04);

/* Phone Feild */
GridBagConstraints gridBagConstraintsx05 = new GridBagConstraints();
gridBagConstraintsx05.gridx = 0;
gridBagConstraintsx05.insets = new Insets(5, 5, 5, 5);
gridBagConstraintsx05.gridy = 2;
cPane.add(jlbPhone, gridBagConstraintsx05);
GridBagConstraints gridBagConstraintsx06 = new GridBagConstraints();
gridBagConstraintsx06.gridx = 1;
gridBagConstraintsx06.gridy = 2;
gridBagConstraintsx06.insets = new Insets(5, 5, 5, 5);
gridBagConstraintsx06.gridwidth = 2;
gridBagConstraintsx06.fill = GridBagConstraints.BOTH;
cPane.add(jtfPhone, gridBagConstraintsx06);

/* Email field */
GridBagConstraints gridBagConstraintsx07 = new GridBagConstraints();
gridBagConstraintsx07.gridx = 0;
gridBagConstraintsx07.insets = new Insets(5, 5, 5, 5);
gridBagConstraintsx07.gridy = 3;
cPane.add(jlbEmail, gridBagConstraintsx07);
GridBagConstraints gridBagConstraintsx08 = new GridBagConstraints();
gridBagConstraintsx08.gridx = 1;
gridBagConstraintsx08.gridy = 3;
gridBagConstraintsx08.gridwidth = 2;
gridBagConstraintsx08.insets = new Insets(5, 5, 5, 5);
gridBagConstraintsx08.fill = GridBagConstraints.BOTH;
cPane.add(jtfEmail, gridBagConstraintsx08);

/* Save - Delete - Update */
GridBagConstraints gridBagConstraintsx09 = new GridBagConstraints();
gridBagConstraintsx09.gridx = 0;
gridBagConstraintsx09.gridy = 4;
gridBagConstraintsx09.insets = new Insets(5, 5, 5, 5);
cPane.add(jbbSave, gridBagConstraintsx09);
GridBagConstraints gridBagConstraintsx10 = new GridBagConstraints();
gridBagConstraintsx10.gridx = 1;
gridBagConstraintsx10.gridy = 4;
gridBagConstraintsx10.insets = new Insets(5, 5, 5, 5);
cPane.add(jbnDelete, gridBagConstraintsx10);
GridBagConstraints gridBagConstraintsx11 = new GridBagConstraints();
gridBagConstraintsx11.gridx = 2;
gridBagConstraintsx11.gridy = 4;
gridBagConstraintsx11.insets = new Insets(5, 5, 5, 5);
cPane.add(jbnUpdate, gridBagConstraintsx11);

/* << - Search - >> */
GridBagConstraints gridBagConstraintsx12 = new GridBagConstraints();
gridBagConstraintsx12.gridx = 0;
gridBagConstraintsx12.gridy = 5;
gridBagConstraintsx12.insets = new Insets(5, 5, 5, 5);
cPane.add(jbnBack, gridBagConstraintsx12);
GridBagConstraints gridBagConstraintsx13 = new GridBagConstraints();
gridBagConstraintsx13.gridx = 1;
gridBagConstraintsx13.gridy = 5;
gridBagConstraintsx13.insets = new Insets(5, 5, 5, 5);
cPane.add(jbnSearch, gridBagConstraintsx13);
GridBagConstraints gridBagConstraintsx14 = new GridBagConstraints();
gridBagConstraintsx14.gridx = 2;
gridBagConstraintsx14.gridy = 5;
gridBagConstraintsx14.insets = new Insets(5, 5, 5, 5);
cPane.add(jbnForward, gridBagConstraintsx14);

/* - - Clear - Exit */
GridBagConstraints gridBagConstraintsx15 = new GridBagConstraints();
gridBagConstraintsx15.gridx = 1;
gridBagConstraintsx15.insets = new Insets(5, 5, 5, 5);
gridBagConstraintsx15.gridy = 6;
cPane.add(jbnClear, gridBagConstraintsx15);
GridBagConstraints gridBagConstraintsx16 = new GridBagConstraints();
gridBagConstraintsx16.gridx = 2;
gridBagConstraintsx16.gridy = 6;
gridBagConstraintsx16.insets = new Insets(5, 5, 5, 5);
cPane.add(jbnExit, gridBagConstraintsx16);

/* Listen Action */
jbbSave.addActionListener(this);
jbnDelete.addActionListener(this);
jbnClear.addActionListener(this);
jbnUpdate.addActionListener(this);
jbnSearch.addActionListener(this);
jbnForward.addActionListener(this);
jbnBack.addActionListener(this);
jbnExit.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == jbbSave) {
//savePerson();
System.out.println(" Save");
clear();
} else if (e.getSource() == jbnDelete) {
//deletePerson();
clear();
} else if (e.getSource() == jbnUpdate) {
//updatePerson();
clear();
} else if (e.getSource() == jbnSearch) {
//searchPerson();
} else if (e.getSource() == jbnForward) {
//displayNextRecord();
} else if (e.getSource() == jbnBack) {
//displayPreviousRecord();
} else if (e.getSource() == jbnClear) {
System.out.println(" Clear");
clear();
} else if (e.getSource() == jbnExit) {
System.exit(0);
}
}

public void clear() {
jtfName.setText("");
jtfAddress.setText("");
jtfPhone.setText("");
jtfEmail.setText("");
/*clear contents of arraylist*/
/* recordNumber = -1; */
//personsList.clear();
jbnForward.setEnabled(true);
jbnBack.setEnabled(true);
}
}

Wednesday, December 5, 2007

Simple Swing in java

/* First.java */

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

public class First {

public static void main(String args[])
{
new First();
/* Opening Frame */
JFrame frame = new JFrame("Hello");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 150);
/* This resize to components inside the frame */
//frame.pack();
Container content = frame.getContentPane();
content.setBackground(Color.white);
content.setLayout(new FlowLayout());
content.add(new JTextArea("Welcome to My Java World !"));
content.add(new JTextField("Enetr text "));
content.add(new JButton("Click"));
//frame.addWindowListener(new ExitListener());
frame.setVisible(true);

}
//Constructor
public void First()
{
System.out.println(" Constructor hello ");
}
}

/*compile */
javac First.java && java First

/* creating exec jar.
copy con mainClass.txt
"Main-Class: First
*/
jar cmfv mainClass.txt FistSwing.jar *.class *.java

/* execute jar */
java -jar FirstSwing.jar

/* Excute using Browser by adding below code in body*/
LessThan applet code="First" archive="FirstSwing.jar" GreaterThan
Lessthan Slash applet GreaterThan



http://www.apl.jhu.edu/~hall/java/Swing-Tutorial/Swing-Tutorial-JFrame.html
http://www.javabeginner.com/java-addressbook.htm
http://www.beginner-java-tutorial.com/jtextarea.html

How to Use va_args in C

#include stdio.h>
#include stdarg.h>
void LogMsg(int lvl, char *fmt,...)
{
va_list vList ;
char msg[256] ;
char debugmsg[500] ;
printf(" Size %d\n",sizeof(debugmsg));
if(lvl ==1)
{
va_start(vList,fmt) ;
vsnprintf(msg, 256, fmt, vList) ;
sprintf(debugmsg, " %s\n", msg) ;
printf("debugmsg : %s msg : %s\n", debugmsg, msg) ;
va_end(vList);
}
}

int main()
{

printf(" \n");
LogMsg(1,"%s %d Test Message \n",__func__,__LINE__);
return 0;
}
~

Monday, December 3, 2007

How to use mmap

#include sys/mman.h
#include stdio.h
#include sys/types.h
#include sys/stat.h
#include fcntl.h
#include unistd.h

int fd_wd;
void *wd_addr = NULL;
unsigned char *temp;
volatile unsigned int *addr;

#define BASE 0xF0010000

int main (int argc, char *argv[])
{
char dat[4096] = "12345678";
unsigned int i, base_addr, read;
unsigned int store;
unsigned int value;
unsigned short page_size;

page_size = getpagesize ();
if(argc == 1)
{
printf ("Usage : ./mapper [options] \n");
printf (" Options 1 - to mmap local array \n");
printf (" 2 - to map fixed addr 0xF0010000 \n");
printf (" 3 - to map new address and new file eg: ./mapper 3 /dev/mem\n");
return 1;
}
if (atoi(argv[1]) != 1)
{
if(argc == 3)
{
printf("Openning file %s \n",argv[2]);
fd_wd = open (argv[2], O_RDWR | O_SYNC);
if (fd_wd == -1)
{
perror("Open ");
return 1;
}

}
else
{
fd_wd = open ("/dev/mem", O_RDWR | O_SYNC);
printf (" Opening file /dev/mem file \n");
if (fd_wd == -1)
{
perror("While Open ");
return 1;
}
}
if(atoi(argv[1]) == 3 )
{
printf(" Enter 32bit addr eg 0xF0010000 \n Hex 0x");
scanf("%X",&base_addr);
}
else
{
base_addr = BASE;

}
/* mmap() will read only page by page , so BASE should be multiple of Page Size */
if ((base_addr % page_size) != 0)
{
printf (" Base address is not multiple of pagesize ");
return 1;
}
/*page_size will length ,since 0-(lenght-1) = length eg: if size 4096 ...start 0-4095 */
wd_addr = mmap (0, (page_size - 1), PROT_READ | PROT_WRITE, MAP_SHARED, fd_wd, base_addr);
perror (" Memory mapping ");
if (wd_addr == (void *) -1)
{
printf ("Unable to map mem file \n");
perror (" Failed: ");
close (fd_wd);
return 1;
}
}
else
{
printf (" Local mapping to Array \n");
wd_addr = dat;
}

/* Printing the Address */
printf (" wd_addr = %X ", wd_addr);

/*Reading Byte by Byte */
temp = (unsigned char *) wd_addr;
printf ("\n\n Enter Offset [0-%d] : ", (page_size - 1));
scanf ("%d", &read);
/* Moving the pointer to Entered offset */
store = *(temp);
temp = temp + read;
printf (" Reading 4 bytes : \n");
for (i = 0; i < 4; i++)
{
printf (" Addr[%02d] : %X = %02X \n", i, temp, *(temp));
temp++;
}

/*Reading Word by Word */
addr = (unsigned int *) wd_addr;
value = *(addr);
value = *(addr);
printf ("\n Base Addr: %X by Word 0x%08X \n", addr, value);
printf ("\n Enter offset [0-4095] to read word : ");
scanf ("%x", &read);

addr = addr + ((unsigned int) read / 4); /* Asuming 4byte == one word length
it is an 32 it processor */
printf (" Enter no. of words to Read:");
scanf ("%d", &read);
/*In big endian format first readed byte is will not match with truncated byte from Word */
if (store != (unsigned char) value)
printf ("\n Big-endian platform Lsb....Msb \n");
else
printf ("\n Little-endian plat Msb....Lsb \n");
for (i = 0; i < read; i++)
{
value = 0;
value = *(addr);
printf (" Addr[%d] : %X 0x%08X \n", i, addr, value);
addr++;
}
printf ("\n");

if (atoi(argv[1]) != 1)
printf (" Munmap : %d\n", munmap (wd_addr, page_size));
return 0;
}

Function pointer in C

#include stdio.h


void func (int);
void one (int, float);
void two (int, float);
void three (int, float);
void four (int, float);
void five (int, float);

int main ()
{
char findex;

/* Function pointer Declaration */
void (*fp) (int); /* single argum,ent */
void (*fptr) (int, float); /* two argument */

/* Function array pointer Declaration */
void (*fparr[]) (int, float) =
{
one, two, three, four, five}; /* initializers */

printf (" Ordinary function calling five(1,3.4)\n");
five (1, 3.4);

printf (" Calling by function pointer fptr(1,3.4); \n");
fptr = five;
fptr (1, 3.4);

printf (" Calling by fun. array ptr (*fparr[findex]) (1, 3.4) \n");
findex = 4; /* To call five(arg1,arg2) fun. index is 4 */
(*fparr[findex]) (1, 3.4); /* passing argument 1, 3.4 */

printf (" Calling func by single argument function pointer \n");
fp = func;
(*fp) (2); /* Mtd 1 */
fp (2); /* Mtd 2 */

exit (EXIT_SUCCESS);
}

void func (int arg)
{
printf ("func arg: %d\n", arg);
}

void one (int arg, float arg2)
{
printf ("Four %f\n", arg2);
printf (" %d\n", arg);
}

/* Similerly define of thwo three...four*/

void five (int arg, float arg2)
{
printf ("Five %f\n", arg2);
printf (" %d\n", arg);
}

Indent for C Program in linux

/*indent with 3 space */
alias in3='indent -bls -bli0 -cli3 -cbi3 -i3 -di5 -bad -nut -l120 -npsl -sob -sai -saf '

/*Indent With 4 space */
alias in4='indent -bls -bli0 -cli4 -cbi4 -i4 -di5 -bad -nut -l120 -npsl -sob -sai -saf '

see man indent above