how to access DB at wordpress






$wpconfig = get_site_url().”/wp-config.php”;

foreach (explode(“n”, file_get_contents($wpconfig)) as $line)


if (preg_match(‘/define.+?DB_|table_prefix/’, $line))




if (defined(‘DB_USER’))


$dbh = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);

mysql_select_db(DB_NAME, $dbh);


$sqlq=”select * from wp_cimy_uef_data where user_id='”.$curr_user->id.”‘” ;



$r = mysql_query( $sqlq,$dbh) or die(mysql_error());

while($userdata = mysql_fetch_array($r)){

// print_r($userdata);
















childs with Jquery (select,ul)

jQuery(document).ready(function() {
jQuery(‘#active_booking_formid :nth-child(2)’).attr(‘selected’, ‘selected’);
jQuery(‘>li:nth-child(1) a’).addClass(‘menuItem2’);
jQuery(‘>li:nth-child(1) a span.t’).addClass(‘specialforhome’);
/*jQuery(‘>li:nth-child(3) a’).addClass(‘menuItem2’); // services
jQuery(‘>li:nth-child(5) a’).addClass(‘menuItem2’); //contact us

How do you put a module inside an article in joomla?

To insert a module inside an article, use the {loadposition xx} command, as follows:

  1. Create a module and set its position to any value that doesn’t conflict with an existing template position. You can type in the position value instead of selecting it from the drop-down list. For example, use the position myposition.
  2. Assign the module to the Menu Items that contain the articles that you want the module to show in. You can also just assign the module to all Menu Items.
  3. Edit the articles where you want this module to appear and insert the text {loadposition myposition} in the article at the place where you want the module.

String in java

Java Programming

String is Special

A Brief Summary of String Class

A String contains a sequence of Unicode characters. Unlike C/C++, where string is simply an array of char, Java’s String is an object class in the core package java.lang. Unlike an ordinary class:

  • String is associated with string literal in the form of double-quoted texts such as “Hello, world”. You can assign a String literal directly into a String variable, instead of calling the constructor to create a String instance.
  • The '+' operator is overloaded to concatenate two String operands.
  • String is immutable. That is, its content cannot be modified once it is created. For example, the method toUpperCase() constructs and returns a new String instead of modifying its content.

The commonly-used method in the String class are summarized below:

// Length
int length()       // returns the length of the String
boolean isEmpty()  // same as thisString.length == 0

// Comparison
boolean equals(String another) // CANNOT use '==' or '!=' to compare two Strings
boolean equalsIgnoreCase(String another)
int compareTo(String another)  // return 0 if this string is the same as another; // <0 if lexicographically less than another; or >0
int compareToIgnoreCase(String another)
boolean startsWith(String another)
boolean startsWith(String another, int fromIndex)  // search begins at fromIndex
boolean endsWith(String another)

// Searching & Indexing
int indexOf(String search)
int indexOf(String search, int fromIndex)
int indexOf(int character)
int indexOf(int character, int fromIndex)      // search forward starting at fromIndex
int lastIndexOf(String search)
int lastIndexOf(String search, int fromIndex)  // search backward starting at fromIndex
int lastIndexOf(int character)
int lastIndexOf(int character, int fromIndex)

// Extracting character or part of the String
char charAt(int index)              // index from 0 to String's length - 1
String substring(int fromIndex)
String substring(int fromIndex, int endIndex)  // exclude endIndex

// Creating a new String or char[] from the original (Strings are immutable!)
String toLowerCase()
String toUpperCase()
String trim()          // create a new String removing white spaces from front and back
String replace(char oldChar, char newChar)  // create a new String with oldChar replaced by newChar
String concat(String another)               // same as thisString + another
char[] toCharArray()                        // create a char[] from this string
void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)  // copy into dst char[]

// Static methods for converting primitives to String
static String ValueOf(type arg)  // type can be primitives or char[]

// Static method resulted in a formatted String using format specifiers
static String format(String formattingString, Object... args)   // same as printf()

// Regular Expression (JDK 1.4)
boolean matches(String regexe)
String replaceAll(String regexe, String replacement)
String replaceAll(String regexe, String replacement)
String[] split(String regexe)             // Split the String using regexe as delimiter, // return a String array
String[] split(String regexe, int count)  // for count times only 

String is Really Special

String receives special treatment in Java, because it is used frequently in a program. Hence, efficiency (in terms of computation and storage) is crucial.

The designers of Java decided to retain primitive types in an object-oriented language, instead of making everything an object, so as to improve the performance of the language. Primitives are stored in the call stack, which require less storage spaces and are cheaper to manipulate. On the other hand, objects are stored in the program heap, which require complex memory management and more storage spaces.

For performance reason, Java’s String is designed to be in between a primitive and a class. The special features in String include:

  • The '+' operator, which performs addition on primitives (such as int and double), is extended (or overloaded) to operate on String objects. '+' performs concatenation for two String operands.

    Java does not support operator overloading for software engineering consideration. In a language that supports operator overloading like C++, you can turn a '+' operator to perform a subtraction, resulted in poor codes. The '+' operator is the only operator that is internally overloaded in Java.

  • A Stringcan be constructed by either:
    1. directly assigning a string literal to a String reference – just like a primitive, or
    2. via the “new” operator and constructor, similar to any other classes. (This is not commonly used and is not recommended.)

    For example,

    String str1 = "Java is Hot";           // Implicit construction via string literal
    String str2 = new String("I'm cool");  // Explicit construction via new

    In the first statement, str1 is declared as a String reference and initialized with a String literal "Java is Hot". In the second statement, str2 is declared as a String reference and initialized via the new operator and constructor to contain "I'm cool".

  • String literals are stored in a common pool. This facilitates sharing of storage for strings with the same contents to conserve storage. String objects allocated via new operator are stored in the heap, and there is no sharing of storage for common contents.

String Literal vs. String Object

As mentioned, there are two ways to construct a string: implicit construction by assigning a String literal or explicitly creating a String object via the new operator and constructor. For example,

String s1 = "Hello";              // String literal
String s2 = "Hello";              // String literal
String s3 = s1;                   // same reference
String s4 = new String("Hello");  // String object
String s5 = new String("Hello");  // String object

Java has designed a special mechanism for keeping the String literals – in a so-called string common pool. If two String literals have the same contents, they will share the same storage locations inside the common pool. This approach is adopted to conserve storage for frequently-used strings. On the other hands, String object created via the new operator are kept in the heap. Each String object in the heap has its own storage just like any other object. There is no sharing of storage in heap even if two String objects have the same contents.

You can use the method equals() of the String class to compare the contents of two Strings. You can use the relational equality operator '==' to compare the references (or pointers) of two objects. Study the following codes:

s1 == s1;         // true, same pointer
s1 == s2;         // true, s1 and s1 share storage in common pool
s1 == s3;         // true, s3 is assigned same pointer as s1
s1.equals(s3);    // true, same contents
s1 == s4;         // false, different pointers
s1.equals(s4);    // true, same contents
s4 == s5;         // false, different pointers in heap
s4.equals(s5);    // true, same contents

Important Notes:

  • In the above example, I used relational equality operator '==' to compare the references of two String objects. This is done to demonstrate the differences between String literals sharing storage in the common pool and String objects created in the heap. It is a logical error to use (str1 == str2) in your program for comparing the contents of two Strings.
  • String can be created by directly assigning a String literal which is shared in a common pool. It is uncommon and not recommended to use the new operator to construct a String object in the heap.

[TODO] Explain the method String.intern().

String is Immutable

Since String literals with the same contents share storage in the common pool, Java’s String is immutable. That is, once a String is constructed, its contents cannot be modified. Otherwise, the other String references sharing the same storage location will be affected by the change, which can be unpredictable and therefore is undesirable. Methods such as toUpperCase() might appear to modify the contents of a String object. In fact, a completely new String object is created and returned to the caller. The original String object will be deallocated, once there is no more references, and subsequently garbage-collected.

Because String is immutable, it is not efficient to use String if you need to modify your string frequently (that would create many new Strings occupying new storage areas). For example,

// inefficient codes
String str = "Hello";
for (int i = 1; i < 1000; i++) {
   str = str + i;

If the contents of a String have to be modified frequently, use the StringBuffer or StringBuilder class instead.

StringBuffer and StringBuilder

As explained earlier, Strings are immutable because String literals with same content share the same storage in the string common pool. Modifying the content of one String directly may cause adverse side-effects to other Strings sharing the same storage.

JDK provides two classes to support mutable strings: StringBuffer and StringBuilder (in core package java.lang) . A StringBuffer or StringBuilder object is just like any ordinary object, which are stored in the heap and not shared, and therefore, can be modified without causing adverse side-effect to other objects.

StringBuilder class was introduced in JDK 1.5. It is the same as StringBuffer class, except that StringBuilder is not synchronized for multi-thread operations. However, for single-thread program, StringBuilder, without the synchronization overhead, is more efficient.


Read the JDK API specification for java.lang.StringBuffer.

// Constructors
StringBuffer()             // an initially-empty StringBuffer
StringBuffer(int size)     // with the specified initial size
StringBuffer(String s)     // with the specified initial content

// Length
int length()

// Methods for building up the content
StringBuffer append(type arg)  // type could be primitives, char[], String, StringBuffer, etc
StringBuffer insert(int offset, arg)

// Methods for manipulating the content
StringBuffer delete(int start, int end)
StringBuffer deleteCharAt(int index)
void setLength(int newSize)
void setCharAt(int index, char newChar)
StringBuffer replace(int start, int end, String s)
StringBuffer reverse()

// Methods for extracting whole/part of the content
char charAt(int index)
String substring(int start)
String substring(int start, int end)
String toString()

// Methods for searching
int indexOf(String searchKey)
int indexOf(String searchKey, int fromIndex)
int lastIndexOf(String searchKey)
int lastIndexOf(String searchKey, int fromIndex)

Take note that StringBuffer is an ordinary object. You need to use a constructor to create a StringBuffer (instead of assigning to a String literal). Furthermore, '+' operator does not apply to objects, inclusive of StringBuffer. You need to use a proper method such as append() or insert() to manipulating a StringBuffer.

To create a string from parts, It is more efficient to use StringBuffer (multi-thread) or StringBuilder (single-thread) instead of via String concatenation. For example,

// Create a string of YYYY-MM-DD HH:MM:SS
int year = 2010, month = 10, day = 10;
int hour = 10, minute = 10, second = 10;
String dateStr = new StringBuilder()
      .append(year).append("-").append(month).append("-").append(day).append(" ")

// StringBuilder is more efficient than String concatenation
String anotherDataStr = year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second;

JDK compiler, in fact, uses both String and StringBuffer to handle string concatenation via the '+' operator. For examples,

String msg = "a" + "b" + "c";

will be compiled into the following codes for better efficiency:

String msg = new StringBuffer().append("a").append("b").append("c").toString();

Two objects are created during the process, an intermediate StringBuffer object and the returned String object.

Rule of Thumb: Strings are more efficient if they are not modified (because they are shared in the string common pool). However, if you have to modify the content of a string frequently (such as a status message), you should use the StringBuffer class (or the StringBuilder described below) instead.

StringBuilder Class

Java SE 5 introduced a new StringBuilder class (in package java.lang), which is almost identical to the StringBuffer class, except that it is not synchronized. In other words, if multiple threads are accessing a StringBuilder instance at the same time, its integrity cannot be guaranteed. However, for a single-thread program (most commonly), doing away with the overhead of synchronization makes the StringBuilder slightly faster.

StringBuilder is API-compatible with the StringBuffer class, i.e., having the same set of constructors and methods, but with no guarantee of synchronization. It can be a drop-in replacement for StringBuffer under a single-thread environment.

Benchmarking String/StringBuffer/StringBuilder

The following program compare the times taken to reverse a long String via a String object an a StringBuffer.

// Reversing a long String via a String vs. a StringBuffer
public class StringBufferTest {
   public static void main(String[] args) {
      long beginTime, elapsedTime;

      // Build a long string
      String str = "";
      int size = 2048;    // program hangs for size > 4000??
      char c = 'a';
      beginTime = System.nanoTime();   // Reference time in nanoseconds
      for (int count = 0; count < size; count++) {
         str += c;
         if (c > 'z') {
            c = 'a';
      elapsedTime = System.nanoTime() - beginTime;
      System.out.println("Elapsed Time is " + elapsedTime/1000 + " us");

      // Reverse a String by building another String character-by-character in the reverse order
      String strReverse = "";
      beginTime = System.nanoTime();
      for (int pos = str.length() - 1; pos >= 0 ; pos--) {
         strReverse += str.charAt(pos);   // Concatenate
      elapsedTime = System.nanoTime() - beginTime;
      System.out.println("Elapsed Time is " + elapsedTime/1000 + " us");

      // Reverse a String via an empty StringBuffer by appending characters in the reverse order
      beginTime = System.nanoTime();
      StringBuffer sb = new StringBuffer(size);
      for (int pos = str.length() - 1; pos >= 0 ; pos--) {
         sb.append(str.charAt(pos));    // append
      elapsedTime = System.nanoTime() - beginTime;
      System.out.println("Elapsed Time is " + elapsedTime/1000 + " us");

      // Reverse a String by creating a StringBuffer with the given String and invoke its reverse()
      beginTime = System.nanoTime();
      StringBuffer sb1 = new StringBuffer(str);
      sb1.reverse();     // use reverse() method
      elapsedTime = System.nanoTime() - beginTime;
      System.out.println("Elapsed Time is " + elapsedTime/1000 + " us");
Elapsed Time is 17006 us (Building the String)
Elapsed Time is 9370 us  (Reversing via building another String character-by-character)
Elapsed Time is 535 us   (Reversing via an empty StringBuffer and append character-by-character)
Elapsed Time is 148 us   (Reversing via creating a StringBuffer with the given string, then reverse()

Observe that constructing a StringBuffer and then using the reverse() method is 4 times faster than building a StringBuffer character-by-character; and is 60 times faster than using the String object.

// Comparing StringBuffer and StringBuilder via reversing a long string 
public class StringBuilderTest {
   public static void main(String[] args) {
      long beginTime, elapsedTime;

      // Build a long string
      String str = "";
      int size = 2048;    // program hangs for size > 4000??
      char c = 'a';
      for (int count = 0; count < size; count++) {
         str += c;
         if (c > 'z') {
            c = 'a';

      // Reverse a String via an empty StringBuffer by appending characters in the reverse order
      beginTime = System.nanoTime();
      StringBuffer sBuffer1 = new StringBuffer(size);
      for (int pos = str.length() - 1; pos >= 0 ; pos--) {
      elapsedTime = System.nanoTime() - beginTime;
      System.out.println("Elapsed Time is " + elapsedTime/1000 + " us");

      // Repeat with StringBuilder
      beginTime = System.nanoTime();
      StringBuilder sBuilder1 = new StringBuilder(size);
      for (int pos = str.length() - 1; pos >= 0 ; pos--) {
      elapsedTime = System.nanoTime() - beginTime;
      System.out.println("Elapsed Time is " + elapsedTime/1000 + " us");

      // Reverse a String by creating a StringBuffer with the given String and invoke its reverse()
      beginTime = System.nanoTime();
      StringBuffer sBuffer2 = new StringBuffer(str);
      elapsedTime = System.nanoTime() - beginTime;
      System.out.println("Elapsed Time is " + elapsedTime/1000 + " us");

      // Repeat with StringBuilder
      beginTime = System.nanoTime();
      StringBuffer sBuilder2 = new StringBuffer(str);
      elapsedTime = System.nanoTime() - beginTime;
      System.out.println("Elapsed Time is " + elapsedTime/1000 + " us");
Elapsed Time is 849 us (StringBuffer)
Elapsed Time is 204 us (StringBuilder)
Elapsed Time is 190 us (StringBuffer)
Elapsed Time is 131 us (StringBuilder)

Observer that StringBuilder is always faster than the StringBuilder, although the absolute timing varies from run to run.


Very often, you need to break a line of texts into tokens delimited by white spaces. The StringTokenizer class supports this.

For example, the following program reverses the words in a String.

// Reverse the words in a String using StringTokenizer
import java.util.StringTokenizer;
public class StringTokenizerTest {
   public static void main(String[] args) {
      String str = "Monday Tuesday Wednesday Thursday Friday Saturday Sunday";
      String strReverse;
      StringBuilder sb = new StringBuilder();
      StringTokenizer st = new StringTokenizer(str);

      while (st.hasMoreTokens()) {
         sb.insert(0, st.nextToken());
         if (st.hasMoreTokens()) {
            sb.insert(0, " ");
      strReverse = sb.toString();
// Constructors
StringTokenizer(String s)  // Constructs a StringTokenizer for the given string, // using the default delimiter set of " \t\n\r\f" // (i.e., blank, tab, newline, carriage-return, and form-feed). // Delimiter characters themselves will not be treated as tokens. 
StrintTokenizer(String s, String delimiterSet)  // Use characters in delimiterSet as delimiters.

// Methods
boolean hasNextToken()     // Returns true if next token available
String nextToken()         // Returns the next token

// Code Sample
StringTokenizer tokenizer = new StringTokenizer(aString);
while (tokenizer.hasNextToken()) {
   String token = tokenizer.nextToken();

The JDK documentation stated that “StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code. It is recommended that anyone seeking this functionality use the split() method of String or the java.util.regex package instead.”

For example, the following program uses the split() method of the String class to reverse the words of a String.

 // Reverse the words in a String using split() method of the String class
public class StringSplitTest {
   public static void main(String[] args) {
      String str = "Monday Tuesday Wednesday Thursday Friday Saturday Sunday";
      String[] tokens = str.split("\\s");  // white space '\s' as delimiter
      StringBuilder sb = new StringBuilder();
      for (int i = 0; i < tokens.length; i++) {
         sb.insert(0, tokens[i]);
         if (i < tokens.length - 1) {
            sb.insert(0, " ");
      String strReverse = sb.toString();

Regular Expression (Regexe), Patterns & Matches (JDK 1.4)

Read “Regular Expression in Java“.


  • JDK 1.6 Documentation.
  • [TODO] more

Latest version tested: JDK 1.6

Last modified: October, 2010

How to use ContextLoaderListener,how to make application Listener

publicclass Main extends org.springframework.web.context.ContextLoaderListener {


*@param args


DatabaseListner listener = new DatabaseListner();

publicvoid contextDestroyed(ServletContextEvent event) {



listener = null;

System.out.println(“web app undeployed”);


publicvoid contextInitialized(ServletContextEvent event) {


new Thread(){

publicvoid run() {




System.out.println(“Web app is ready.”);



and add those lines to servlet at web.xml


move directory in Java ,convert file to linux,remove CRLF

privatevoid moveFilesFromSourceToDestination(String sourceFolder,String destinationFolder) throws IOException{ “trying move “+sourceFolder+” to “+destinationFolder );

File sFolder = new File(sourceFolder);

File dFolder = new File(destinationFolder);

for (File file : sFolder.listFiles()){

if (file.isFile()){

File newFile = new File(dFolder.getAbsolutePath() + “/”+file.getName());


}elseif (file.isDirectory()){

File newFile = new File(dFolder.getAbsolutePath() + “/”+file.getName());



File oldFile = new File(sFolder.getAbsolutePath() + “/”+file.getName());



} “move “+sourceFolder+” to “+destinationFolder+” Done succesfully “ );


privatevoid moveFile(File file, File newFile) throws IOException {

FileReader in = new FileReader(file);

FileWriter out = new FileWriter(newFile);

int c;

while ((c = != -1)




//delete old one and convert the new one from dos2linux




privatevoid convertFromDosToLinux(String fileName,String folderName) throws IOException{

//create shell script

FileWriter fstream = new FileWriter(folderName+“/”);

BufferedWriter out = new BufferedWriter(fstream);

out.write(“tr -d ‘\\r’ “+“<“+folderName+“/”+fileName+“> “+folderName+“/temp”);



//delete script and input file and rename the output

File fileTobeDeleted = new File(folderName+“/”+fileName);


File fileTobeRenamed = new File(folderName+“/temp”);


File scriptToBeDeleted = new File(folderName+“/”);



privatevoid runShellScript(String shellScript) throws IOException {

Runtime run=Runtime.getRuntime();

String command = “sh “+shellScript;

Process process=run.exec(command);

InputStream stderr = process.getErrorStream();

InputStreamReader isr = new InputStreamReader(stderr);

BufferedReader br = new BufferedReader(isr);

String line = null;

System.out.println(“start converting …..”);

while ( (line = br.readLine()) != null)


int exitVal;

try {

exitVal = process.waitFor();

if (exitVal == 0){

System.out.println(“—converting done—- “ );“—converting done —- “);



System.out.println(“—converting failure—- “ );“—converting failure —- “);


} catch (InterruptedException e) {




How to Write Good API

 1– methods should do only one operation (only one function per method)

this enable -code reuse


-sample for testing

2– keep method small

if method have to make more than function you can encapsulate them in object

3– defensive Programming check on expected arguments to method

Ex.- If not null

– should be string

– should be array

but not validation on argument it should isolated to another method

4- use design patterns if and only if scenario,logic require that

not use design patterns just for using them

5- All types have to be interfaces

-and if you need to add function for this type you can use wrapper(delegates)

-you can wrap you function in new object (use decorator)

6- keep method name descriptive

7- you have to use factory for creating objects

you have not create object of module into another one use factory for this

8- try to provide all information for client code

9- make logging information as a informative conversation (you can report those information later )

10- Anti-if else

you have not use if else ==>use factory to select between state of object

11- null object

1- avoid return null from method

2-at some cases you should use null object which implement interface and have empty

implementation for all method

Ex: you should not pass null to command ,state machine design pattern

12- Object or Variable

1- every thing could be object as long as has it’s behavior ,attribute ,flow to avoid the god class

2- it could be data object which encapsulate data

13- The definition of Done

mean task well documented,tested