Tuesday, October 18, 2011

To make the process appear concurrently in Swing java and Flush data to the GUI java

For this you need to us need to use SwingWorker Class which makes the data to be displayed in
Swing Frame as soon as the data is available.

class SwingWorkerDemo extends SwingWorker
//Integer- doInBackground return type and String - publish method Type
String command;

public SwingWorkerDemo(String cmd)

public Integer doInBackground() {
Runtime run = Runtime.getRuntime();
Process pr = null;
try {
pr = run.exec(command);
} catch (IOException ee) {
int line;
try {
while ((line=pr.getInputStream().read())!=-1) {doInBackground
char c=(char)line;
// System.out.println(Character.toString(c));

while ((line=pr.getErrorStream().read())!=-1) {
char c=(char)line;
// System.out.println(Character.toString(c));
publish(Character.toString(c)); /// Publish to the process method to update GUI
catch (IOException error)
return 0;
protected void process(java.util.List chunks) {
for ( String fd: chunks)
area1.append(fd); //GUI appending code

protected void done()
JOptionPane.showMessageDialog(null, "Find command Execution Completed.");


By making use of the SwingWorker class the GUI is updated in the Worker Thread .This makes it
possible for the data to be available in the GUI concurrently when read from the inputStream.

Here the doInBackground process runs the Complex Process and when we publish a data via publish method,the result can be made to be appended to the GUI by the process method.The code in the process methos is executed in the worker Thread so make sure to put the GUI updating code here.

The done method is executed once the process is completed.

Above code is liable to hanging as the process's getErrorStream and getOutputStream is executed in the same thread.So make sure you make the getErrorStream and getOutputStream to be executed in a separate Thread.

Process hangs in java

The correct solution according to my experience is the getErrorStream and getOutputStream
of the Process must be executed concurrently in a separate Thread

When you run a  Process proc

Runtime rt = Runtime.getRuntime();
Process proc = rt.exec(cmd);

You need to empty errorStream and outputStream in a separate Thread concurrently.
In case if you get the outputStream  first and get ErrorStream  afterwards it may lead to the Process hang or vice versa.

To make the  empty the errorStream and outputStream in a separate Thread you can use StreamGobbler as follows:

class StreamGobbler extends Thread
    InputStream is;
    String type;
    String command;
    StreamGobbler(InputStream is, String type)
        this.is = is;
        this.type = type;

   public void run()
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);
            String line=null;
            while ( (line = br.readLine()) != null)
                 System.out.println(type + ">" + line);  //Stream to the STDOUT
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);
            String line=null;
            while ( (line = br.readLine()) != null)
                System.out.println(type + ">" + line);
            } catch (IOException ioe)

     public static void main(String args[])
                    Runtime rt = Runtime.getRuntime();
                    Process proc = rt.exec(command);
                    // error message
                    StreamGobbler errorGobbler = new
                        StreamGobbler(proc.getErrorStream(), "ERROR");          
                    //  output  message
                    StreamGobbler outputGobbler = new
                        StreamGobbler(proc.getInputStream(), "OUTPUT");

                    //Start the ErrorStream and inputStream in separate Threads


ANd in case you are using a GUI for displaying the message you need to
use SwingWorker Thread .This i will cover in another blog.

Monday, October 17, 2011

Wednesday, October 12, 2011

Adding policy to a applet java

To Provide permissions to a applet first you need to write a Policy file.

Policy file can be created using a policytool .By this way a policy file can be created.

And to run the applet with the permissions added in the policyfile you need to run the applet in the following way:

appletviewer -J-Djava.security.policy=policy-file  applet-file

Saturday, October 8, 2011

Making window.find method move to the start of the webpage firefox javascript

To make the window.find method move to the starting of the webpage incase when user clicked clear or he is trying to search for another word.

You need to select a word in the starting of the Page and using that word you need to perform window.find method which makes the cursor to move to the start of the webpage

For example in my case i select a word "linux" which lies in the first line of my webpage

You need to do like this:

sel.removeAllRanges(); // To remove any of the selections previously available in the webpage

found=window.find("linux,"false,false); // To select the word in the first line

sel=window.getSelection(); // To select the word to sel

range=sel.getRangeAt(0); // to add the selection to the range

if (sel.RangeCount > 0 ) sel.removeAllRanges(); // To remove the selection made by "linux" word

sel.addRange(range); // To add the selection to sel using addRange

This will do the trick moving to the first part of the webpage.

Thursday, October 6, 2011

For finding text in webpage javascript

In Internet Explorer 

to copy the content of the webpage use


Now we need to search the desired string using findtext method

  Assume string is the desired string to be searched

1)if txt.findtext(string)
 2)       txt.select() ; //will highlight the searched word
For moving to the next string you have to bookmark the String
we need to move to the end we use

 3)   txt.collapse(false) ;

if we use true in this case it moves to the beginning

And again calling the  above three commands will move to the next word.

If we want to move to the previously searched word we need to follow a technique called BookMarking =

var dd=txt.getBookmark();

Here the  getBookMark saves a opaque string which can be used to move to the previously referrenced
textrange using the

likewise you can save the Bookmark for each searched string and retrieve it back.
To search a word in firefox and other browsers we need to use window.find method

To search forward use

window.find("string to search",false,false);
First argument is string to be searched
Second false signifies no need of case sensitivity
Third false signifies forward search

To search Backward use

window.find("string to search",false,true);
First argument is string to be searched
Second false signifies no need of case sensitivity
Third  true signifies backward search.

To get the selection you can use

This can also be used separately if you want to select the text highlighted by the visitor.

To copy the selection to a variable use:

To add the range to the selection use


To remove the selection  from the webPage  you can use


to hide and make visible the textbox javascript

To hide the textbox use

var gg=document.getElementById("txtbox");

To make visible the textbox use:
var gg=document.getElementById("txtbox");

Tuesday, October 4, 2011

table to have empty cells

The table to have empty cells it must be specified with  &nbsp to how many want based on the cell-size.

it should be specified as:


delete the space between two tables

To delete the space between two tables:

Simply add align="left" attribute in both the tables like below and also add <br/> below the first table to avoid the second table coming to the right of the first table.

<table align="left">    
other html code here

<table align="left">    
other html code here

Thursday, September 22, 2011

getopts in perl

my %options=();
getopts("p:a:r:", \%options);

# test for the existence of the options on the command line.
# in a normal program you'd do more than just print these.
print "-p $options{p}\n" if defined $options{p};
print "-a $options{a}\n" if defined $options{a};
print "-r $options{r}\n" if defined $options{r};

Saturday, September 17, 2011

Find command examples

To exclude  directories while searching using find command
For example i want to prevent the find command from moving into the directories hhh and ggg while searching in my home directory

use this example:

find /home/karthik -name hhh -prune -name ggg -prune -o -type f

This will display all files in  my other directories in my home except moving into my ggg and hhh directories

To grep mutiple pattern in the find command

find /home/karthik -type f  | xargs egrep  "(hello)\|(great)|(awesome)"
In this case i am trying to search multiple word hello,great,awesome in the files searched by the find command.

To serach only in the current directory without moving into the sub-directories use:

find  /home/karthik maxdepth -1 -type f

Here all the files in the current directory is displayed without searching for files in any of the sub-directories
max-depth sets the maximum directory level the search can traverse.

To set the directory levels for searching the files you can use:
maxdepth and mindepth options

mindepth -to set the minimum directory level

maxdepth-to set the maximum directory level

In case if you want to search in sub-directory level 2 to 3
Set it as
set the  mindepth as 2 and maxdepth as 3.

find /home/karthik -mindepth 2 -maxdepth 3 -type f

It will search all the the files  from the second directory level to the third directory level.i.e
for example it searches in /home/karthik/fff/   or /home/karthik/fff/kkkk  and not in /home/karthik

To find only ASCII textfiles in your directory excluding all other binary files  use this:

find /home/karthik -type f |xargs file |grep -i ASCII | cut -d: f1

This uses file command which displays the type of file. And grep only text files from it and by cut command displays the filename from the search.

To find files which belong to a specific user :
Use this

find /home/karthik   -user  divya

In this case the find command searches for all the files which belong to divya in the /home/karthik directory.

To find files which is of specific size:

find /home/karthik  -type f  -size  +100c

Here it will search for all the files above 100 bytes

+100c  here   + - more than
If you want files less than 100 bytes specify it as -100c

If you want files of exact size of 100 bytes keep it as 100c

To find empty files in your directory:
for this use -empty option

find /home/karthik -type f -empty

This will list all the empty files in this directory.

To list all the non-empty files you can simply do:

find /home/karthik -type f   ! -empty

"!" just reverses the meaning of -empty

To find all the files of a provided permission

find /home/karthik -perm 777

It list all the files with the permission 777,
if you provide +444  it lists all the files above this permission.

To search in multiple directories you can use this:

find /home/karthik/ /tmp/ -type f

To search in multiple directory simply put it as said before.This will search in multiple directory /home/karthik/ and /tmp/

To grep pattern in the find list:

find /home/karthik/ -type f | xargs grep "hello"
This "xargs grep hello" command searches for hello across all the files returned by the "find /home/karthik/ -type -f"


Friday, September 16, 2011

find command complex pattern exclusion

For complex expression you need to include the pattern inside the brackets \( and \)

For example:

find /home/karthik  -name "*.pl" -o -name "*.pm" -o ! \( -name "*.*" -o -type d \)

1)include the files ending with .pl and .pm

1)exclude the files ending with any other pattern  than the specified "pl" and "pm".
2) to exclude the directories

Tuesday, September 13, 2011

Automating a telnet to a remote system using expect script and running a application

This program i have written to telnet to a remote system and run a applet in that remote system.And exit from the remote host once the expect script receives "zzz" from the applet.

log_file -a /tmp/expectlog     <---all the interactions in the remote system are saved in this file
set timeout 60
spawn telnet
expect "login:"
send "xxxxx\n"                     <-----username
expect "Password:"         
send "fdfdfdffd\n"                 <-----password                 
expect "xxxxx"                       <---prompt expected after login
send "\n"
send "appletviewer  applet.html\n"
interact -o "zzz" return            <-----to come out of the interact mode once the expect receives "zzz" from the application
send "exit\r"                            <------to exit from the telnet session
expect eof {puts "finished "}    <------expecting eof when the spawn process completes
exit 0                                      <-----ending the expect script

Tuesday, September 6, 2011

Converting lowercase to uppercase and uppercase to lowercase in Shell

Simple use  truncate  in Shell

For converting uppercase to lowercase use  tr '[A-Z]' '[a-z]'
echo $ddd | tr '[A-Z]' '[a-z]'    will convert  uppercase into lowercase

For converting lowercase to uppercase use tr '[a-z]' '[A-Z]'
echo $ddd | tr '[a-z]' '[A-Z]'

Monday, August 29, 2011

calling shell in C and getting output

To execute shell command from C and get the output to C we need to use the

popen command  in C.

include <stdio.h>
3int main(void) {
4    FILE *in;
5    extern FILE *popen();
6    char buff[512];
8    if(!(in = popen("ls -sail""r"))){
9        exit(1);
10    }
12    while(fgets(buff, sizeof(buff), in)!=NULL){
13        printf("%s", buff);
14    }
15    pclose(in);

As stated in the program this can be used to get the output to the command.