Skip to content

Code Snippets

February 17, 2011

Listing out some code snippets:

1. Short 2 liner code which will give the highest number of an array.
public int guessWhat( int arr[] )
{
for( int i = 0, x= 0; i < arr.length; i++ )
x = x < arr[i] ? arr[i] : x;
return x;
}

2. Find the port occupied by the process or process-id.
pid=SOME_PROCESS_ID
netstat -nlp | grep $pid | awk ‘{print $4}’ | cut -f2 -d:

3. List all the ports occupied in a linux/solaris machine
netstat -nlp | grep tcp | awk {print $4} | cut -f2 -d:

4. jfind utility which will search for class file (s) from jar files in a given directory.
user@sqindia$ sh jfind directory-name class1 class2 ……

jfind.sh

#!/bin/sh
out=”";
c=”0″;
jarDir=$1;
if [ ! -x ${jarDir} ] ; then echo “Directory or File $jarDir does not exit.”; exit 1; fi
shift 1;
cls=$*;
ss=$#;
tf=”`echo “$*” | sed -e ‘s/ /\\\\|/g’`”;
for i in `find $jarDir -name “*.jar” -print`
do
out=`jar -tvf $i | grep -w ${tf}* | awk ‘{print $8}’`;
if [ "$out" != "" ] ; then
c=”1″;
echo;
echo “————————-”;
echo “Jar file: ‘${i}’ “;
out1=`echo $out | sed -e ‘s/ /\\\\n/g’`;
echo -e $out1;
echo “————————-”;
fi
done
if [ "$c" = "0" ]; then
echo “The classname ‘$cls’ cannot be found.”;
fi

Output:

[bala@cepheusvir16 ~]$ jfind $JAVA_HOME/jre/lib BootstrapServer StubEntry BadPaddingException
————————-
Jar file: ‘/usr/local/java/jre/lib/jce.jar’
javax/crypto/BadPaddingException.class
————————-

————————-
Jar file: ‘/usr/local/java/jre/lib/rt.jar’
com/sun/corba/se/impl/util/StubEntry.class
com/sun/corba/se/internal/CosNaming/BootstrapServer.class
————————-

Jfind is a very cool utility which will help in searching for class file(s) from huge jar-file repository.

5. Automate interactive script using expect
#!/usr/local/bin/expect -f #
spawn ssh
expect “password:”
send xxxxx\n
interact
put employees.lst
put student.lst
echo “Transfer complete”
bye

7. On Solaris you can create a read-only version of any directory by adding something like this to /etc/auto_direct:
/var/rot -ro,fstype=lofs :/var/tmp
Then you can go to /var/rot to read what’s in /var/tmp, but you can’t write anything.

Advertisement

From → tech

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.