Monday, March 29, 2010

Flag Arguments & Clean Code

Flag arguments are ugly. Passing a boolean into a function is a truly terrible practice. It immediately complicates the signature of the method, loudly proclaiming that this function does more than one thing. It does one thing if the flag is true and another if the flag is false!


--Clean Code by Robert C. Martin

Concurrency Tips

Concurrency Tips Blog

Thursday, March 25, 2010

xml2Java java2xml

XStream

Tuesday, March 23, 2010

Class.forName (cslName) VS Thread.currentThread ().getContextClassLoader ().loadClass (clsname)

-- The thing to know here is that the context class loader is loading the class. All apps default, when first started, to the JVM application classloader as being the currentThread context loader. Often code like xerces, ejb based client code, etc will set a different classloader on the context thread. The main purpose is to allow higher up loaders in the hierarchy of a chain to "see" classes lower than it. Normall, any class loaded by a classloader can use any other class loaded by it or any of its parent (with regards to package names, visibility, and other java rules). But a parent loader can't "see" any child loaders classes. By using the thread context loader, a parent loader can be passed a reference to a child classloader of its own or any other classloader and ask that classloader to load classes for it, thus delegating in an unusual manner. It does, however, allow code loaded by the boot loader (rt.jar) to use your own code loaded by the app loader such that things like EJB calls are possible by rt.jar boot loaded classes. You may have to set the loader to your custom loader if you use custom loaders, otherwise its set to the application loader and by default any class loaded by the boot loader or extension loader can access the application loader ref through the context loader, allowing any code there to "see" any classes loaded by the app loader. This is how rt.jar EJB/rmi code can use your classes and reflection, even though they are loaded by a higher parent loader.

-- Sun Java Forum

Monday, March 22, 2010

Recursive Deletion on linux filesysem

find . -type d -name "CVS" -exec rm -rf {} \;

-- deletes all CVS directories starting from current dir.

Saturday, March 20, 2010

Interfaces and Implementations

Suppose that you are building an
ABSTRACT FACTORY for the creation of shapes. This factory will be an interface and will be implemented by a concrete class. What should you name them? IShapeFactory and ShapeFactory? I prefer to leave interfaces unadorned. The preceding I, so common in today’s legacy wads, is a distraction at best and too much information at worst. I don’t want my users knowing that I’m handing them an interface. I just want them to know that it’s a ShapeFactory. So if I must encode either the interface or the implementation, I choose the implementation. Calling it shapeFactoryImp, or even the hideous CShapeFactory, is preferable to encoding the interface.


In general programmers are pretty smart people. Smart people sometimes like to show off their smarts by demonstrating their mental juggling abilities. After all, if you can reliably remember that r is the lower-cased version of the url with the host and scheme removed, then you must clearly be very smart.
One difference between a smart programmer and a professional programmer is that the professional understands that clarity is king. Professionals use their powers for good and write code that others can understand.

   --Clean Code by Robert C. Martin

Wednesday, March 17, 2010

Atomically incremented counters

    private final static int startIndex = 1;
    private final static int pageSize = 5000;

    private AtomicInteger pageNo = new AtomicInteger(startIndex);

    private int getNextPage (){
        return pageNo.getAndIncrement();
    }

insteadOf**


    int pageNo = 0;

    private synchronized int getNextPage (){
        pageNo++;
        return pageNo;
    }



#####################################
#                                          More on it
#####################################



import java.util.concurrent.atomic.AtomicInteger;

public class AtomicIntegerUsage {
    private final static int startIndex = 1;
    private final static int pageSize = 5000;

    private AtomicInteger pageNo = new AtomicInteger(startIndex);
    private AtomicInteger anotherPageNo = new AtomicInteger(startIndex);

    private int getNextPage_getAndIncrement (){
        return pageNo.getAndIncrement();
    }
    private int getNextPage_incrementAndGet (){
        return anotherPageNo.incrementAndGet();
    }

    public AtomicIntegerUsage () {
    }

    public static void main (String[] args) {
        AtomicIntegerUsage t = new AtomicIntegerUsage ();
        System.out.println (" First page is page with getNextPage_getAndIncrement :"+t.getNextPage_getAndIncrement());
        System.out.println (" First page is page with getNextPage_incrementAndGet:"+t.getNextPage_incrementAndGet());
    }
}


 First page is page with getNextPage_getAndIncrement :1
 First page is page with getNextPage_incrementAndGet:2






Java Thread Local Usage

    private ThreadLocal tl = new ThreadLocal(){
        protected synchronized Session initialValue() {
            return sessionForBatchLoading;
        }    
    };
    
    private Session sessionForBatchLoading = null;

    private void initializeSession () throws Exception {
        session = SessionFactory.getSession ();
        sessionForBatchLoading = factory.getSession ();
        tl.set(sessionForBatchLoading);
    }

    private void getOrder (int orderId) throws Exception {
        Session tlSession = tl.get ();
        tlSession.getItemFromDBWithId (orderId);
    }

*Session is not thread safe .


    private void startThreads (int threadCount) throws Exception {
        ExecutorService executor = Executors.newFixedThreadPool(threadCount);

        for (int i = 0; i < threadCount; i++) {
            FetchTask task =  new FetchTask ();
            executor.submit (task);
        }

         executor.shutdown ();
    }

Tuesday, March 16, 2010

Too many open files error / opened file checker

#!/bin/bash
COUNTER=0
HOW_MANY=0
MAX=0
# do not take care about COUNTER - just flag, shown should we continue or not
while [ $COUNTER -lt 10 ]; do
    #run until process with passed pid alive
    if [ -r "/proc/$1" ]; then
        # count, how many files we have
        HOW_MANY=`/usr/sbin/lsof -p $1 | wc -l`
        #output for live monitoring
        echo `date +%H:%M:%S` $HOW_MANY
        # uncomment, if you want to save statistics
        #/usr/sbin/lsof -p $1 > ~/autocount/config_lsof_`echo $HOW_MANY`_`date +%H_%M_%S`.txt

        # look for max value
        if [ $MAX -lt $HOW_MANY ]; then
                let MAX=$HOW_MANY
                echo new max is $MAX
        fi
        # test every second. if you don`t need so frequenlty test - increase this value
        sleep 1
    else
        echo max count is $MAX
        echo Process was finished
        let COUNTER=11
    fi
done

Which type of java exception should be used ?

Unchecked exceptions :
  • represent defects in the program (bugs) - often invalid arguments passed to a non-private method. To quote from The Java Programming Language, by Gosling, Arnold, and Holmes : "Unchecked runtime exceptions represent conditions that, generally speaking, reflect errors in your program's logic and cannot be reasonably recovered from at run time."
  • are subclasses of RuntimeException, and are usually implemented using IllegalArgumentExceptionNullPointerException, or IllegalStateException
  • a method is not obliged to establish a policy for the unchecked exceptions thrown by its implementation (and they almost always do not do so)
Checked exceptions :
  • represent invalid conditions in areas outside the immediate control of the program (invalid user input, database problems, network outages, absent files)
  • are subclasses of Exception
  • a method is obliged to establish a policy for all checked exceptions thrown by its implementation (either pass the checked exception further up the stack, or handle it somehow)
It is somewhat confusing, but note as well that RuntimeException (unchecked) is itself a subclass of Exception (checked).



JMX Sample

public class MessageHolder implements MessageHolderMBean{
public static void main(String[] args) {

}
private String message;
@Override
public void setMessage(String message) {
this.message = message;
}

@Override
public String getMessage() {
return this.message; //To change body of implemented methods use File | Settings | File Templates.
}

@Override
public void sayHello() {
System.out.println("Messsage:"+message);
}
}


public class JmxAgent {

private MBeanServer mbs = null;

public JmxAgent() {

// Get the platform MBeanServer
mbs = ManagementFactory.getPlatformMBeanServer();

// Unique identification of MBeans
MessageHolder helloBean = new MessageHolder();
ObjectName helloName = null;

try {
// Uniquely identify the MBeans and register them with the platform MBeanServer
helloName = new ObjectName("SimpleAgent:name=ManageYourProgram");
mbs.registerMBean(helloBean, helloName);
} catch(Exception e) {
e.printStackTrace();
}
}

// Utility method: so that the application continues to run
private static void waitForEnterPressed() {
try {
System.out.println("Press to continue...");
System.in.read();
} catch (Exception e) {
e.printStackTrace();
}
}

public static void main(String argv[]) {
JmxAgent agent = new JmxAgent();
System.out.println("SimpleAgent is running...");
JmxAgent.waitForEnterPressed();
}
}


public interface MessageHolderMBean
{

public void setMessage(String message);

public String getMessage();

public void sayHello();
}

Friday, March 12, 2010

Some Groovy on Soapui tests :)

Write some entry in a file like below.

[serkans@serkanslnx ~] cat /home/serkans/phoneNumbersOnly.txt
9001234560
9001234561
9001234562
9001234563
9001234564
9001234565
9001234566
9001234567
9001234562
9001234568
9001234562
9001234569

Create a test step , right click on it , Select add new Step , Select Groovy Script.Enter the following lines to it.Play Run button on the window to execute it.Do some customization to run it.File path etc..



// read the file as a properties file, but it is not :)we will get only keys from it
def properties = new java.util.Properties();
properties.load( new java.io.FileInputStream("/home/serkans/phoneNumbersOnly.txt" ));
//get a random index acc. file's line size
Random r = new Random();
def randomIndex  = r.nextInt(properties.size());
            def valueFromFile = (String) properties.entrySet().toArray()[randomIndex].toString();
            valueFromFile = valueFromFile.toString().replaceAll("=","");
log.info(valueFromFile);
return valueFromFile;


After than you need to transfer this value by using another type of Steps in soapui.
Select add new Step , Select "Property Transfer" ,Select GroovyScript as Source and select result as Property to transfer on it,Select your "Test Request" as destination and select Request as Destination.And write "//par1[@*]" to the target window.
     Look at the picture for better understanding.That is why i prefer to watch rather than reading generally:)

It will provide you Random values from file.You can use in your load tests.Enjoy!


Visit soapui page for more.

How to get SystemInfo in HP servers

[root@hpserver ~]# hpasmcli
HP management CLI for Linux (v1.0)
Copyright 2004 Hewlett-Packard Development Group, L.P.

--------------------------------------------------------------------------
NOTE: Some hpasmcli commands may not be supported on all Proliant servers.
Type 'help' to get a list of all top level commands.
--------------------------------------------------------------------------
hpasmcli> show server
System : ProLiant DL380 G5
Serial No. : CZC82758BX
ROM version : P56 01/24/2008
iLo present : Yes
Embedded NICs : 2
NIC1 MAC: 00:1X:29:e8:2c:9a
NIC2 MAC: 00:1X:29:e8:2c:98

Processor: 0
Name : Intel Xeon
Stepping : 6
Speed : 3000 MHz
Bus : 1333 MHz
Core : 4
Thread : 4
Socket : 1
Level2 Cache : 12288 KBytes
Status : Ok

Processor: 1
Name : Intel Xeon
Stepping : 6
Speed : 3000 MHz
Bus : 1333 MHz
Core : 4
Thread : 4
Socket : 2
Level2 Cache : 12288 KBytes
Status : Ok

Processor total : 2

Memory installed : 8192 MBytes
ECC supported : Yes
hpasmcli> exit
[root@hpserver ~]#

AXIS2 Web Service Level Parameters

in the services.xml you need to define your parameters like below

<parameter locked="false" name="MY_PARAMETER_NAME">MY_PARAMETER_VALUE

In your Skel class you can get the value like that:

String paramValue = (String) MessageContext.getCurrentMessageContext().getParameter ("MY_PARAMETER_NAME");

Wednesday, March 3, 2010

How to get opends record count

Following command will give you the exact record count under the given dn: {ou=subscribers,dc=mycompany,dc=com}
Script is using the virtual attribute called {numsubordinates}

sh /space/opends/OpenDS-2.2.0/bin/ldapsearch -h localhost -p 389 -D cn='Directory Manager' -w mycpassword -b "ou=subscribers,dc=mycompany,dc=com" -s base "objectclass=*" numsubordinates| grep "numsubordinates:"| cut -c "18-" > /space/.subscriberCount

Note: Output will be saved under /space/.subscriberCount file.Please customize it for yourself

opends export scheduled to work at midnight

The following crontab entry will get the export of the given branch {ou=subscriptions,dc=mycompany,dc=com} .4444 is the admin port of ldap server.

00 00 * * * sh /space/opends/OpenDS-2.2.0/bin/export-ldif -h localhost -p 4444 -D "cn=Directory Manager" -w mypassword -X --includeBranch "ou=subscriptions,dc=mycompany,dc=com" --backendID userRoot --ldifFile /space/opendsExport.ldif &

Opends replication

[root@dual1 bin]# ./dsreplication enable --host1 192.168.241.179 --port1 4444 --bindDN1 "cn=Directory Manager" --bindPassword1 mypassword --replicationPort1 8989 --host2 192.168.241.195 --port2 4444 --bindDN2 "cn=Directory Manager" --bindPassword2 tneu34 --replicationPort2 8990 --adminUID admin --adminPassword mypassword --baseDN "dc=mycompany,dc=com" -X -n





[root@dual1 bin]# ./dsreplication initialize --baseDN "dc=mycompany,dc=com" --adminUID admin --adminPassword mypassword --hostSource 192.168.241.179 --portSource 4444 --hostDestination 192.168.241.195 --portDestination 4444 -X –n

After executing dsreplication initialize all entries under the given base db {dc=mycompany,dc=com} will be replicated to secondary ldap server.for 1.2G records it takes a few minutes {~3-5 min}

Commands are needed to be executed only primary ldap server.

Tuesday, March 2, 2010

Find null attribute and modify on Ldap Server


Language null search


ldapsearch -x -h localhost -p 389 -D cn=root,dc=mycompany,dc=com -w secret -b ou=subscribers,dc=mycompany,dc=com "(!(tnaLanguage=*))" dn | grep dn:

This script gives us the subscribers without having tnaLanguage attribute.
Modify entries having null language

dn: tnaId=2108840497330132510,ou=subscribers,dc=mycompany,dc=com

dn: tnaId=2806900514076119703,ou=subscribers,dc=mycompany,dc=com

dn: tnaId=3602194238187496434,ou=subscribers,dc=mycompany,dc=com

dn: tnaId=2806900514076119725,ou=subscribers,dc=mycompany,dc=com

Compose modifyLanguage.ldif like below

dn: tnaId=807889406294118443,ou=subscribers,dc=mycompany,dc=com

changetype:modify

add: tnaLanguage

tnaLanguage: english


Execute ldif file like below
ldapmodify -x -h localhost -p 389 -D cn=root,dc=mycompany,dc=com -w secret -f modifyLanguage.ldif

Note: You need use cshell for the use of " ! " sign before search operation

Monday, March 1, 2010

Auto Copy a file to destination host

[root@tas5 astelit]# cat /root/scripts/cleanupcopy.sh
#!/usr/bin/expect -f
# connect via scp
spawn scp /space/cleanupOpendsExport.ldif root@10.1.11.1:/space/
#######################
expect {
-re ".*es.*o.*" {
exp_send "yes\r"
exp_continue
}
-re ".*sword.*" {
exp_send "myPassword\r"
}
}
interact
[root@tas5 astelit]# ENJOY WITH IT :-)
NOTE: This script is copying the local file {/space/cleanupOpendsExport.ldif} to the destination host with IP {10.1.11.1} without entering password.Destination host username is {root} and its password is {myPassword}, destination folder is /space