Wednesday, March 31, 2010

Text to Speech in Java (Worked well on Ubuntu )

First of all install the following packages :
1) espeak : is a software speech synthesizer for English, and some other languages.
2) libespeak-dev : contains the eSpeak development files needed to build against the espeak
shared library.
3) SWIG : SWIG is a compiler that makes it easy to integrate C and C++ code with other
languages including Perl, PHP, Tcl, Ruby, Python, Java,Guile, Mzscheme, Chicken, OCaml,
and C#.

STEPS

1) create a Speak.c file

#include <string.h>
#include <malloc.h>
#include <espeak/speak_lib.h>
int initFlag = 0 ;
/*
* initFlag == 0 means not initialised and initFlag == 1 means initialised and is ready for
* text to speech conversion
*/

espeak_POSITION_TYPE position_type;
espeak_AUDIO_OUTPUT output;


void* user_data;
t_espeak_callback *SynthCallback;
espeak_PARAMETER Parm;

unsigned int Size,position=0, end_position=0, flags=espeakCHARS_AUTO|espeakENDPAUSE, *unique_identifier;

int setPitch(int value){
if(initFlag == 0 ){
printf("espeak Not initialised\n call initialise() first") ;
return -1 ;
}

if(value > 99) value = 99 ;
else if(value < 0) value = 0 ;

espeak_SetParameter(espeakPITCH,value,0) ;

return 0 ;
}

int setAmplitude(int value){
if(initFlag == 0 ){
printf("espeak Not initialised\n call initialise() first") ;
return -1 ;
}

if(value > 200) value = 200 ;
else if(value < 0) value = 0 ;

espeak_SetParameter(espeakVOLUME,value,0) ;

return 0 ;
}

int setPitchRange(int value){
if(initFlag == 0 ){
printf("espeak Not initialised\n call initialise() first") ;
return -1 ;
}

if(value > 100) value = 100 ;
else if(value < 0) value = 0 ;

espeak_SetParameter(espeakRANGE,value,0) ;

return 0 ;
}

int initialise(){
if(initFlag == 1) return 0 ;

int Buflength = 500, Options=0 ;
char *path=NULL;
char Voice[] = {"default"};

output = AUDIO_OUTPUT_PLAYBACK;

if(espeak_Initialize(output, Buflength, path, Options ) == EE_INTERNAL_ERROR){
printf("EE_INTERNAL_ERROR occured inside espeak_Initialize()") ;
return -1 ;
}

if(espeak_SetVoiceByName(Voice) != EE_OK ){
printf("\nEE_BUFFER_FULL | EE_INTERNAL_ERROR occured inside espeak_SetVoiceByName() in initialise()") ;
return -1 ;
}

initFlag = 1 ;

return 0 ;
}

int espeak(const char *arr){
if(initFlag == 0 ){
printf("espeak Not initialised\n call initialise() first") ;
return -1 ;
}

Size = strlen(arr)+1;
printf("Size = %d ; Saying '%s'",Size,arr);

if(espeak_Synth( arr, Size, position, position_type, end_position, flags,unique_identifier, user_data ) != EE_OK){
printf("\nEE_BUFFER_FULL | EE_INTERNAL_ERROR occured inside espeak_Synth() in espeak()") ;
return -1 ;
}

if(espeak_Synchronize( ) != EE_OK){
printf("\nEE_INTERNAL_ERROR occured inside espeak_Synchronize() in espeak()\n syncronisation failed") ;
return -1 ;
}

return 0 ;
}

int cancel(){
if(espeak_Cancel() != EE_OK )
return -1 ;

return 0 ;
}

int isPlaying(){
// Returns 1 if audio is played, 0 otherwise.
return espeak_IsPlaying() ;
}

int terminate(){
if(initFlag == 0 ){
printf("Not initialised\n call initialise() first") ;
return ;
}

printf("\n:Done\n");
if(espeak_Terminate( ) == EE_INTERNAL_ERROR){
printf("EE_INTERNAL_ERROR occured inside espeak_Terminate() in terminate()") ;
return -1 ;
}
printf("\n:Terminated !!!\n");

initFlag = 1 ;

return 0 ;
}




2) create a Speak.i file ( It contains the function prototypes that are to be called from Java and is present in Speak.c file)

/* Speak.i */
%module Speak
%{
/* Put header files here or function declarations like below */
extern int setPitch(int value);
extern int setAmplitude(int value);
extern int setPitchRange(int value);
extern int initialise();
extern int espeak(const char *arr);
extern int cancel() ;
extern int isPlaying();
extern int terminate() ;
%}

extern int setPitch(int value);
extern int setAmplitude(int value);
extern int setPitchRange(int value);
extern int initialise();
extern int espeak(const char *arr);
extern int cancel() ;
extern int isPlaying();
extern int terminate() ;


3) Perform this at the command prompt
$ swig -java Speak.i

This creates the wrapper class for java and also produces a Speak_wrap.c file

4) Compile the Speak.c and Speak_wrap.c files using gcc
$ gcc -fpic -c Speak.c Speak_wrap.c -I $JAVA_HOME/include
-I $JAVA_HOME/include/linux/

Note: $JAVA_HOME is the path to the java installation directory

5) Create a shared library by linking the object codes to espeak's shared library:

$ gcc -shared Speak.o Speak_wrap.o -lespeak -o libjavaSpeak.so

Note: this creates a new shared library named libjavaSpeak.so which we will use in our java
program.

6) Create a java program to test the new library :

public class Main{
public static void main(String[] args){
if(args.length != 1){
System.out.println("USAGE: java -Djava.library.path=. Main ");
return ;
}

if(isContain44greaterNos(args[0])){
//if more than 44 consecutive digits are given then espeak would fail
System.out.println("NOTE: should not contain more than 44 consecutive digits");
return ;
}

System.loadLibrary("javaSpeak");
Speak.initialise() ;

Speak.setPitch(99) ;
Speak.setPitchRange(99) ;

Speak.espeak(args[0]);
Speak.terminate();
}

private static boolean isContain44greaterNos(String numCheck){
return numCheck.matches("\\d{45,}") ;

}
}


7) Compile the main file
$ javac Main.java

8) Run the main file
$ java -Djava.library.path=. Main <text to speak>



NOTE: if we place the libjavaSpeak.so shared library in the $JAVA_HOME/jre/lib/i386/
folder ; the we could run the program as

$ java Main
<text to speak>

Saturday, November 21, 2009

Streaming WAV sound files over network

I've created a simple program that serves sound file to a single client, and it worked well within a LAN . I was able to play the file remotely....
You just try the code :

SoundServer.java

import java.io.*;
import java.net.*;
public class SoundServer{

private InputStream in ;
private OutputStream out ;
private ServerSocket ss ;
private Socket s ;
private String filename ;

public SoundServer(String filename)throws Exception{
this.filename = filename ;
in = new FileInputStream(filename) ;
in = new BufferedInputStream(in) ;

ss = new ServerSocket(2345) ;

}


public class RunWhenShuttingDown extends Thread {
public void run() {
System.out.println("Control-C caught. Shutting down...");
try {
in.close() ;
out.close() ;
ss.close() ;
s.close() ;
}catch(Exception e2){
e2.printStackTrace() ;
}
System.out.println("Shutdown gracefully");
}
}



public void runMain()throws Exception{


Runtime.getRuntime().addShutdownHook(new RunWhenShuttingDown());

s = ss.accept() ;

out = s.getOutputStream() ;
out = new BufferedOutputStream(out) ;


int availSize = 0 ;
byte[] buf = null ;
int noRead = -2 ;

while(noRead!=-1 && noRead!=0 ){
availSize = (in.available())/5 ;
buf = new byte[availSize] ;
noRead = in.read(buf,0,availSize) ;
out.write(buf,0,availSize) ;
System.out.println("Avail Size : "+availSize+" Bytes read : "+noRead+" items");
}

System.out.println("Sound File Served completely");
}

public static void main(String[] args)throws Exception{
if(args.length !=1){
System.out.println("Usage: java SoundServer ");
System.exit(0);
}
new SoundServer(args[0]).runMain() ;
}

}


SoundClient.java

import java.io.*;
import java.net.*;
import javax.sound.sampled.*;

public class SoundClient {
private InetAddress localhost ;
private Socket s ;
private InputStream in ;
private AudioInputStream ais ;
private DataLine.Info info ;
private SourceDataLine srcDataLine ;


public SoundClient(byte[] arr)throws Exception{
// localhost = InetAddress.getByName(name) ;
localhost = InetAddress.getByAddress(arr) ;
s = new Socket(localhost,2345) ;

in = s.getInputStream() ;
in = new BufferedInputStream(in) ;

ais = AudioSystem.getAudioInputStream(in) ;
if(ais==null){
System.out.println("Failure: in getting AudioInputStream ");
System.exit(0);
}

info = new DataLine.Info(SourceDataLine.class,ais.getFormat()) ;
srcDataLine = (SourceDataLine) AudioSystem.getLine(info) ;
srcDataLine.open(ais.getFormat()) ;
srcDataLine.start() ;

int avail = 0 ;
int numBytesRead = 0 ,total = 0;
byte[] myread = null ;
while(true){
avail = ((srcDataLine.getBufferSize())/5);
myread = new byte[avail] ;
numBytesRead = ais.read(myread,0,avail) ;
if(numBytesRead== -1)break;
total += numBytesRead ;
srcDataLine.write(myread,0,numBytesRead) ;
}

srcDataLine.flush() ;

System.out.println("Total Number of bytes read : "+total);

srcDataLine.close() ;
in.close() ;
ais.close();
s.close() ;


System.out.println("Completed Successfully");

}

public static void main(String[] args)throws Exception{
if(args.length!= 4){
System.out.println("Usage: java SoundClient /neg: java SoundClient 192 168 1 1 ");
System.exit(0);
}
byte[] var = new byte[4] ;
var[0] = new Integer(args[0]).byteValue() ;
var[1] = new Integer(args[1]).byteValue() ;
var[2] = new Integer(args[2]).byteValue() ;
var[3] = new Integer(args[3]).byteValue() ;
new SoundClient(var) ;
}
}

BroadCasting Example using UDP

In this example the Server broadcasts messages to all the connected clients.

Server.java


import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.net.*;
import java.util.*;
import java.io.*;
public class Server extends JFrame{
JTextArea jtxt ;
JTextField jfld ;
JPanel jp ;
JScrollPane jsp ;

ArrayList clientDtls ;
DatagramPacket dp ;
DatagramSocket ds ;
ReceiveClients clientThread ;

String message ;

private Runnable runnable = new Runnable(){
public void run() {
clientThread.stop() ;
clientDtls.clear() ;
if(! ds.isClosed()) ds.close() ;
System.out.println("\n\nServer shutdown gracefully.......\n\n") ;
}
};

public Server(){
setServer() ;

clientDtls = new ArrayList() ;
clientDtls.ensureCapacity(20) ;

clientThread = new ReceiveClients(clientDtls,ds) ;

initGUI() ;
}

private void initGUI(){
this.setVisible(true) ;
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) ;
this.setTitle("SERVER>>>>>>") ;
this.setLocation(200,200) ;

jtxt = new JTextArea(30,20) ;
jfld = new JTextField(20) ;
jp = new JPanel(true) ;
jsp = new JScrollPane(jtxt) ;

jfld.addKeyListener(new KeyAdapter(){
public void keyTyped(KeyEvent ke){
if(ke.getKeyChar() == '\n'){
message = jfld.getText() ;

jfld.setText("") ;
jfld.setEditable(false) ;
if(! message.equals(""))
sendPackets() ;
jfld.setEditable(true) ;
jtxt.append(message+"\n") ;
}
}
}
);

jp.setLayout(new BoxLayout(jp,BoxLayout.Y_AXIS)) ;
jp.add(jsp) ;
jp.add(jfld) ;

jtxt.setEditable(false) ;
jtxt.setFocusable(false) ;

this.getContentPane().add(jp) ;
this.pack() ;
}

public void setServer(){
try {
ds = new DatagramSocket(2000) ;
dp = new DatagramPacket(new byte[256],256) ;
} catch (SocketException e) {
e.printStackTrace();
}
Runtime.getRuntime().addShutdownHook(new Thread(runnable)) ;
}

private void sendPackets(){
int size = clientDtls.size() ;
ClientDtls cd ;
int i = 0 ;
while(i cd = clientDtls.get(i) ;

dp.setAddress(cd.getAddress()) ;
dp.setPort(cd.getPort()) ;
dp.setData(message.getBytes()) ;
dp.setLength(message.length()) ;

try {
ds.send(dp) ;
} catch (IOException e) {
e.printStackTrace();
i++ ;
continue ;
}

i++ ;
}
}

public static void main(String[] args){
Server server = new Server() ;
}
}

class ReceiveClients implements Runnable{
private volatile boolean flag ;
private ArrayList clientDtls ;
private DatagramSocket ds ;
private DatagramPacket input ;

public ReceiveClients(ArrayList ref,DatagramSocket ds){
clientDtls = ref ;
this.ds = ds ;
flag = true ;

input = new DatagramPacket(new byte[256],256) ;

Thread t = new Thread(this,"Receive_Clients") ;

t.start() ;
}
public void run() {
while(flag){
try {
ds.receive(input) ;

String request = new String(input.getData(),0,input.getLength(),"ASCII") ;
request = request.trim() ;

InetAddress ia = input.getAddress() ;
int port = input.getPort() ;

ClientDtls cd = new ClientDtls(ia,port) ;


if(request.equals("CONNECT")){
//if(! clientDtls.contains(sa))
clientDtls.add(cd) ;
}
else if(request.equals("RELEASE")){
clientDtls.remove(cd) ;
}
}catch(SocketException se){
System.out.println("Trying to close the server.....") ;
stop() ;
return ;
}
catch (IOException e) {
e.printStackTrace();
continue ;
}
}
}
public void stop(){
flag = false ;
}
}
class ClientDtls{
private InetAddress address ;
private int port ;
public ClientDtls(InetAddress address,int port){
this.address = address ;
this.port = port ;
}
public boolean equals(ClientDtls cd){
if(cd.getAddress().equals(address)){
if(cd.getPort() == port)
return true ;
}
return false ;
}
public int getPort(){
return port ;
}
public InetAddress getAddress(){
return address ;
}
}




Client.java


import javax.swing.* ;

import java.net.*;
import java.io.*;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
public class Client extends JFrame{
JTextArea jtxt ;
JPanel jp ;
JScrollPane jsp ;

DatagramPacket dp ;
DatagramSocket ds ;

private Runnable run = new Runnable(){
public void run() {
if(! ds.isClosed()) ds.close() ;
releaseClient() ;
System.out.println("\nSystem shutdown gracefully......\n\n") ;
}
};
public Client(){
startClient() ;
initGUI() ;
}
private void initGUI(){
this.setVisible(true) ;
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) ;
this.setTitle("CLIENT>>>>>>") ;
this.setLocation(300,200) ;

jtxt = new JTextArea(30,20) ;
jp = new JPanel(true) ;
jsp = new JScrollPane(jtxt) ;


jp.setLayout(new BoxLayout(jp,BoxLayout.Y_AXIS)) ;
jp.add(jsp) ;

jtxt.setEditable(false) ;
jtxt.setFocusable(false) ;

this.getContentPane().add(jp) ;
this.pack() ;
}
private void startClient(){
try {
ds = new DatagramSocket() ;
} catch (SocketException e) {
e.printStackTrace();
}
String connect = "CONNECT" ;

dp = new DatagramPacket(new byte[256],256) ;

dp.setData(connect.getBytes()) ;
dp.setLength(connect.length()) ;

try {
dp.setAddress(InetAddress.getLocalHost()) ;
} catch (UnknownHostException e) {
e.printStackTrace();
}

dp.setPort(2000) ;

try {
ds.send(dp) ;
} catch (IOException e) {
e.printStackTrace();
}

Runtime.getRuntime().addShutdownHook(new Thread(run)) ;

}
private void releaseClient(){
String message = "RELEASE" ;

dp.setData(message.getBytes()) ;
dp.setLength(message.length()) ;

try {
ds.send(dp) ;
} catch (IOException e) {
e.printStackTrace();
}
}
private void writeMessage(){
String message = "" ;
try {
message = new String(dp.getData(),0,dp.getLength(),"ASCII") ;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
jtxt.append(message+"\n") ;
}
public void receiveClient(){
while(true){
dp.setData(new byte[256]) ;
dp.setLength(256) ;

try {
ds.receive(dp) ;
writeMessage() ;
} catch (IOException e) {
e.printStackTrace();
}
}

}

public static void main(String[] args){
Client client = new Client() ;
client.receiveClient() ;
}
}

Mouse Follower



In this program a circle moves along with the movement
of the mouse cursor.













Program

import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import javax.swing.*;
public class MouseMotion {
public static void main(String[] args) {
JFrame f = new JFrame("Aim For the Center");
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
Circle circle = new Circle();
Container panel = circle ;

MouseListen ml = new MouseListen(circle) ;

panel.add(new JLabel("Circle!", SwingConstants.CENTER), BorderLayout.CENTER);
f.getContentPane().add(panel, BorderLayout.CENTER);
f.setSize(500,600) ;
f.addMouseMotionListener(ml);
//f.pack();
f.setVisible(true) ;
}
}
class MouseListen extends MouseMotionAdapter{
Circle circle ;
MouseListen(Circle circle){
this.circle = circle ;
}
public void mouseMoved(MouseEvent me) {
super.mouseMoved(me);
int x = me.getX() ;
int y = me.getY() ;
circle.setPos(x,y) ;
}
}
class Circle extends JPanel{
Shape circle ;
int topX ,topY,width,height ;
public Circle() {
super();
setOpaque(false); // we don't paint all our bits
setLayout(new BorderLayout());
setBorder(BorderFactory.createLineBorder(Color.yellow));
topX = 10 ;//getX() ;
topY = 10 ;//getY() ;
width = 50 ;
height = 50 ;
}

public Dimension getPreferredSize() {
Dimension layoutSize = super.getPreferredSize();
int max = Math.max(layoutSize.width,layoutSize.height);
return new Dimension(max+100,max+100);
}
public void setPos(int xpos,int ypos){
topX = xpos - 30 ;
topY = ypos - 30 ;
repaint() ;
}

public void paintComponent(Graphics g)
{

circle = new Ellipse2D.Float(topX,topY,width,height);
Graphics2D g2d = (Graphics2D) g ;
//initCircle();
g2d.setColor(Color.BLUE) ;
g2d.draw(circle) ;
}

}

File Server using UDP

In this file server example , there is a Client and Server program .
First of all please start the Server then after that start the client.
Note: In this example the client and server need to run from the same machine. You could change this settings and it would take only few steps.

Server.java


import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
public class Server extends JFrame{
JPanel jpTop , jpBottom ;
Container cont ;
JButton browse , start ,stop ,cancel ;
JTextField jtxtFld ;

DatagramSocket ds ;
DatagramPacket dp ;

FileInputStream fileInS ;
File selectedFile ;

InetAddress clientAddress ;
int port ;

String validFileName ;
boolean finalization = false ;

Runnable shutDownThread = new Runnable(){
public void run() {
if(!finalization)
shutDownOperations() ;
}
};

void initGUI(){
this.setTitle("Server") ;
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) ;
this.setVisible(true) ;

cont = this.getContentPane() ;
cont.setLayout(new BoxLayout(cont,BoxLayout.Y_AXIS)) ;

jpTop = new JPanel() ;
jtxtFld = new JTextField(30) ;
jtxtFld.setFont(new Font(Font.SANS_SERIF,Font.PLAIN,20)) ;
jtxtFld.setEditable(false) ;
browse = new JButton("Browse") ;
jpTop.add(jtxtFld) ;
jpTop.add(browse) ;

jpBottom = new JPanel() ;
start = new JButton("Start") ;
start.setEnabled(false) ;
stop = new JButton("Stop") ;
stop.setEnabled(false) ;
cancel = new JButton("Cancel") ;
jpBottom.add(start) ;
jpBottom.add(stop) ;
jpBottom.add(cancel) ;

cont.add(jpTop) ;
cont.add(jpBottom) ;

this.pack() ;
}

void initListeners(){
browse.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
JFileChooser fileChooser = new JFileChooser();
int returnValue = fileChooser.showOpenDialog(null);
if (returnValue == JFileChooser.APPROVE_OPTION) {
selectedFile = fileChooser.getSelectedFile();
validFileName = selectedFile.getName() ;
jtxtFld.setText(selectedFile.getAbsolutePath()) ;
start.setEnabled(true) ;
}
}
});
start.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
start.setEnabled(false) ;
stop.setEnabled(true) ;
browse.setEnabled(false) ;
try{
initServer() ;
}catch(Exception ex){
JOptionPane.showMessageDialog(null,ex.getMessage()) ;
}
}
});
stop.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
stop.setEnabled(false) ;
start.setEnabled(true) ;
browse.setEnabled(true) ;
shutDownOperations() ;
}
}) ;
cancel.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
shutDownOperations() ;
System.exit(0) ;
}
}) ;
}
void initServer()throws Exception{


fileInS = new FileInputStream(selectedFile) ;

long fileSize = selectedFile.length() ;


String msg = validFileName+"\n"+fileSize ;
System.out.println(msg) ;
ds = new DatagramSocket(2000) ;
dp = new DatagramPacket(new byte[8192],8192) ;

//Server waits for the client to make a request
ds.receive(dp) ;

clientAddress = dp.getAddress() ;
port = dp.getPort() ;

dp.setData(new byte[8192]) ;
dp.setLength(8192) ;

//send to the client the Filename and size
dp.setPort(port) ;
dp.setAddress(clientAddress) ;
dp.setData(msg.getBytes()) ;
dp.setLength(msg.length()) ;

ds.send(dp) ;

byte[] data = new byte[8192] ;
int ret = 0 ;
try{
while(true){
ret = fileInS.read(data) ;
if(ret==-1)break ;
dp.setData(data) ;
dp.setLength(data.length) ;
Thread.sleep(100) ;
ds.send(dp);
}
byte val[] = new byte[2] ; val[0] = val[1] = 0 ;
dp.setData(val) ;
dp.setLength(2) ;
// a 2 byte packet denotes end of file
ds.send(dp) ;
}catch(Exception ex){
JOptionPane.showMessageDialog(null,"Error occured during write operation") ;
throw new Exception(ex.getMessage()) ;
}
}
void shutDownOperations(){
try{ds.close() ;}catch(Exception e){e.printStackTrace();}
try {
fileInS.close() ;
} catch (IOException e) {
e.printStackTrace();
}
finalization = true ;
}
public Server(){
initGUI() ;
initListeners() ;
Runtime.getRuntime().addShutdownHook(new Thread(shutDownThread)) ;
}
public static void main(String args[]){
Server server = new Server() ;
}
}





Client.java


import java.lang.reflect.InvocationTargetException;
import java.net.*;
import java.io.*;
import java.awt.*;
import javax.swing.*;

import java.awt.event.*;
public class Client {
DatagramSocket ds ;
DatagramPacket dp ;

JProgressBar jprg ;

FileOutputStream fout ;

String fileName ="" ;
String size ;
String name ;

String destinationFolder ;
volatile boolean flag = true ;

Runnable shutDownHook = new Runnable(){
public void run() {
flag = false ;
shutDownOperations() ;
}
};

Runnable progressMonitor = new Runnable(){
public void run() {
System.out.println("Inside progressmonitor") ;
long originalSize = Long.valueOf(size.trim()) ;
File filevar = new File(name) ;
int percent = 0 ;

jprg = new JProgressBar() ;
jprg.setMinimum(0) ;
jprg.setMaximum(100) ;
jprg.setStringPainted(true) ;

JFrame jf = new JFrame("File Downloading...") ;
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) ;
jf.add(jprg) ;
jf.setVisible(true) ;
jf.pack() ;

while(flag){
try {
Thread.sleep(100) ;
} catch (InterruptedException e) {}

percent = (int) (((filevar.length())/originalSize)*100) ;
jprg.setValue(percent) ;
}
}
};
void initServer()throws Exception{
ds = new DatagramSocket() ;
dp = new DatagramPacket(new byte[8192],8192,InetAddress.getLocalHost(),2000) ;

String msg = "connect request" ;

dp.setData(msg.getBytes()) ;
dp.setLength(msg.length()) ;
// sends connect request to server
ds.send(dp) ;

dp.setData(new byte[8192]) ;
dp.setLength(8192) ;
//collects file information from Server[details are fileName and size]
ds.receive(dp) ;

msg = new String(dp.getData(),0,dp.getLength(),"ASCII") ;
//System.out.println(msg) ;
char ch = 'a' ;
for(int i=0 ; i< msg.length() ; i++){
ch = msg.charAt(i) ;
if(ch=='\n'){
size = msg.substring(i+1) ;
break ;
}
fileName += ch ;
}

}
void selectDestinationFolder(){
JFileChooser fileChooser = new JFileChooser(".");
fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
fileChooser.setDialogTitle("Select Destination to store File") ;
int returnValue = fileChooser.showOpenDialog(null);
if (returnValue == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile() ;
destinationFolder = file.getAbsolutePath() ;
}
else if(returnValue == JFileChooser.CANCEL_OPTION){
System.exit(0) ;
}
}
void fileDownload()throws FileNotFoundException{
name = destinationFolder+File.separatorChar+fileName ;
System.out.println("File name = "+name) ;
System.out.println("File size = "+size) ;
fout = new FileOutputStream(name) ;

System.out.println("Starting downloading file...........") ;

Thread pgbar = new Thread(progressMonitor) ;
pgbar.start() ;


try{
while(true){
dp.setData(new byte[8192]) ;
dp.setLength(8192) ;
ds.receive(dp) ;
if(dp.getLength() == 2)break ;
fout.write(dp.getData()) ;
}
}catch(Exception ex){
ex.printStackTrace() ;
}
System.out.println("\n\n.........Download Complete") ;
}
void shutDownOperations(){
try{
ds.close() ;
fout.close() ;
}catch(Exception ex){
ex.printStackTrace() ;
}
}
public Client(){
selectDestinationFolder() ;
try{
initServer() ;

fileDownload() ;
}catch(Exception ex){
ex.printStackTrace() ;
}

Runtime.getRuntime().addShutdownHook(new Thread(shutDownHook)) ;
}

public static void main(String[] args){
Client client = new Client() ;
}
}


OUTPUT


Server





Client

Arranging numbers inside a Square Matrix in a particular order

Hello my friends ,
The program given below receives a matrix order and prints the matrix in a particular fashion.
For eg : if the program receives 4 as input then it produces a matrix like this given below:

1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7

ie , it produces n square elements arranged in a particular fashion

Program
import java.io.Console ;
public class SquareRoot{
public static void main(String[] args){
Console console = System.console() ;
System.out.print("Enter the order of matrix = ");
String order = console.readLine() ;
int n = Integer.parseInt(order) ;
int arr[][] = new int[n][n] ;
int y , x ,count ;
int x_max , y_max , y_min ,x_min ;
x_max = y_max = n-1 ;
x_min = y_min = 0 ;
int i = 1 ;
int value = n ;
value -= 1 ;
int square = n*n + 1 ;
for(;i!=square;){
x = x_min ;
y = y_min ;
while((y <= y_max)&& i!=square){ arr[x][y] = i ; y++; i++ ; } y -= 1 ; x++ ; while((x <= x_max)&& i!=square){ arr[x][y] = i ; x++; i++ ; } x -= 1 ; y-- ; while((y >= y_min)&& i!=square){
arr[x][y] = i ;
y--; i++ ;
}
y += 1 ; x -= 1;
while((x > x_min)&& i!=square){
arr[x][y] = i ;
x--; i++ ;
}
x += 1 ; y += 1 ;
value -= 1 ;
x_max = y_max = value ;
x_min = x ;
y_min = y ;
}
System.out.println("\nMatrix is :");
for(int l=0;l


OUTPUT


Enter the order of matrix = 7

Matrix is :
1 2 3 4 5 6 7
24 25 26 27 28 29 8
23 40 41 42 43 30 9
22 39 48 49 44 31 10
21 38 47 46 45 32 11
20 37 36 35 34 33 12
19 18 17 16 15 14 13

Linux Master Boot Record display

Hai guys , i would like to show you how to display the MBR contents

Step 1 : Copy the MBR from the boot device ,

$ dd if=/dev/sda of=myMBR.bin bs=512 count=1

Here /dev/sda is my sata hard disk drive file and it would be /dev/hda for IDE drives.

Step 2:
Write the following program:


import java.io.*;
public class MBR {
public static void main(String args[])throws Exception{
if(args.length != 1){
System.out.println("Usage : java MBR ") ;
System.exit(0) ;
}

File file = new File(args[0]) ;

System.out.println("Size of "+args[0]+" = "+file.length());
FileInputStream fin = new FileInputStream(file) ;
byte[] mbr = new byte[512] ;

int size = fin.read(mbr) ;

System.out.println("Size readed = "+size) ;

int j = 0 ;

for(int i=0 ; i j++;
StringBuffer s =
new StringBuffer(Integer.toHexString((mbr[i] >= 0) ? mbr[i] : 256 +mbr[i]));

if(s.length() == 1) s.insert(0,'0');

if(j > 10){
j = 0 ;
System.out.println() ;
}

System.out.print(" "+s.toString()) ;

}

fin.close() ;
}
}




Step 3: Compile the above program , and run it , also pass the file myMBR.bin(which was created in first step).

$ java MBR myMBR.bin

The above command produced the following output when i run it :

OUTPUT

Size of sda = 512
Size readed = 512
eb 48 90 d0 bc 00 7c fb 50 07
50 1f fc be 1b 7c bf 1b 06 50 57
b9 e5 01 f3 a4 cb bd be 07 b1 04
38 6e 00 7c 09 75 13 83 c5 10 e2
f4 cd 18 8b f5 83 c6 10 49 74 19
38 2c 74 f6 a0 b5 07 b4 03 02 ff
00 00 20 01 00 00 00 00 02 fa 90
90 f6 c2 80 75 02 b2 80 ea 59 7c
00 00 31 c0 8e d8 8e d0 bc 00 20
fb a0 40 7c 3c ff 74 02 88 c2 52
be 7f 7d e8 34 01 f6 c2 80 74 54
b4 41 bb aa 55 cd 13 5a 52 72 49
81 fb 55 aa 75 43 a0 41 7c 84 c0
75 05 83 e1 01 74 37 66 8b 4c 10
be 05 7c c6 44 ff 01 66 8b 1e 44
7c c7 04 10 00 c7 44 02 01 00 66
89 5c 08 c7 44 06 00 70 66 31 c0
89 44 04 66 89 44 0c b4 42 cd 13
72 05 bb 00 70 eb 7d b4 08 cd 13
73 0a f6 c2 80 0f 84 ea 00 e9 8d
00 be 05 7c c6 44 ff 00 66 31 c0
88 f0 40 66 89 44 04 31 d2 88 ca
c1 e2 02 88 e8 88 f4 40 89 44 08
31 c0 88 d0 c0 e8 02 66 89 04 66
a1 44 7c 66 31 d2 66 f7 34 88 54
0a 66 31 d2 66 f7 74 04 88 54 0b
89 44 0c 3b 44 08 7d 3c 8a 54 0d
c0 e2 06 8a 4c 0a fe c1 08 d1 8a
6c 0c 5a 8a 74 0b bb 00 70 8e c3
31 db b8 01 02 cd 13 72 2a 8c c3
8e 06 48 7c 60 1e b9 00 01 8e db
31 f6 31 ff fc f3 a5 1f 61 ff 26
42 7c be 85 7d e8 40 00 eb 0e be
8a 7d e8 38 00 eb 06 be 94 7d e8
30 00 be 99 7d e8 2a 00 eb fe 47
52 55 42 20 00 47 65 6f 6d 00 48
61 72 64 20 44 69 73 6b 00 52 65
61 64 00 20 45 72 72 6f 72 00 bb
01 00 b4 0e cd 10 ac 3c 00 75 f4
c3 00 00 00 00 00 00 00 00 00 00
00 56 a8 03 00 00 00 80 01 01 00
83 fe ff b4 3f 00 00 00 36 a1 e8
00 00 00 c1 b5 0f fe ff ff 75 a1
e8 00 4c 43 68 08 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 00 55 aa