Sunday, December 16, 2012

Print JEditorPane content using Java with header and footer

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package javatest.pritom;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.MessageFormat;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ScrollPaneConstants;
import javax.swing.SwingUtilities;
import javax.swing.text.Document;
import javax.swing.text.html.HTMLEditorKit;
import javax.swing.text.html.StyleSheet;

/**
 *
 * @author User
 */
public class JavaSimpleBrowser extends JPanel {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                JFrame frame = new JFrame("Print Test");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.getContentPane().add(new JavaSimpleBrowser(), BorderLayout.CENTER);
                frame.setSize(800, 600);
                frame.setLocationByPlatform(true);
                frame.setVisible(true);
            }
        });
    }
   
    private JComponent simpleBrowser;
    private final JEditorPane editorPane;
    private final JScrollPane scrollPane;
    public JavaSimpleBrowser() {
        this.setSize(new Dimension(800, 600));
        this.setPreferredSize(new Dimension(800, 600));
        JPanel pnlM = new JPanel(new BorderLayout());
        this.add(pnlM, BorderLayout.CENTER);
       
        HTMLEditorKit kit = new HTMLEditorKit();
       
        StyleSheet styleSheet = kit.getStyleSheet();
        styleSheet.addRule("body {color:#000; font-family:times; margin: 0px; }");
        styleSheet.addRule("p.line {"
                + "border-width: 3px; border-style: solid; border-color: red;"
                + "font : 10px monaco; padding: 4px; background-color: gray;"
                + "} ");
       
        editorPane = new JEditorPane();
        editorPane.setEditorKit(kit);
        Document doc = kit.createDefaultDocument();
        editorPane.setDocument(doc);
        editorPane.setContentType("text/html");
        editorPane.setText(getHtml());
        editorPane.setEditable(false);
       
        scrollPane = new JScrollPane(editorPane);
        scrollPane.setPreferredSize(new Dimension(780, 500));
        scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
       
        pnlM.add(scrollPane, BorderLayout.CENTER);
       
        JButton button = new JButton("Print");
        pnlM.add(button, BorderLayout.NORTH);
        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                MessageFormat header = new MessageFormat("Order Details History");               
                MessageFormat footer = new MessageFormat(" Page #{0,number,integer}");
                try {
                    editorPane.print(header, footer);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        });
    }
   
    private String getHtml() {
        StringBuffer sb = new StringBuffer();
       
        sb.append("<html>");
        sb.append("<body>");
        for(int index = 0; index < 500; index++) {
            sb.append("<p class='line'>I AM IN LINE: "+index+"</p>");
        }
        sb.append("</body>");
        sb.append("</html>");
       
        return sb.toString();
    }
}

Friday, December 14, 2012

Java: Reading and writing text files

package pritom;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * User: pritom
 * Date: 14/12/12
 * Time: 9:28 AM
 * To change this template use File | Settings | File Templates.
 */
public class ReadWriteTextFileJDK7 {

    public static void main(String... aArgs) throws IOException {
        ReadWriteTextFileJDK7 text = new ReadWriteTextFileJDK7();

        //treat as a small file
        List<String> lines = text.readSmallTextFile(FILE_NAME);
        log(lines);
        lines.add("This is a line added in code.");
        text.writeSmallTextFile(lines, FILE_NAME);

        //treat as a large file - use some buffering
        text.readLargerTextFile(FILE_NAME);
        lines = Arrays.asList("Line added #1", "Line added #2");
        text.writeLargerTextFile(OUTPUT_FILE_NAME, lines);
    }

    final static String FILE_NAME = "C:/tmp/input.txt";
    final static String OUTPUT_FILE_NAME = "C:/tmp/output.txt";
    final static Charset ENCODING = StandardCharsets.UTF_8;

    //For smaller files

    List<String> readSmallTextFile(String aFileName) throws IOException {
        System.out.print("***** readSmallTextFile *****\n");
        Path path = Paths.get(aFileName);
        return Files.readAllLines(path, ENCODING);
    }

    void writeSmallTextFile(List<String> aLines, String aFileName) throws IOException {
        System.out.print("***** writeSmallTextFile *****\n");
        Path path = Paths.get(aFileName);
        Files.write(path, aLines, ENCODING);
    }

    //For larger files

    void readLargerTextFile(String aFileName) throws IOException {
        System.out.print("***** readLargerTextFile *****\n");
        Path path = Paths.get(aFileName);
        Scanner scanner =  new Scanner(path, ENCODING.name());
        while (scanner.hasNextLine()){
            //process each line in some way
            log(scanner.nextLine());
        }
    }

    void readLargerTextFileAlternate(String aFileName) throws IOException {
        System.out.print("***** readLargerTextFileAlternate *****\n");
        Path path = Paths.get(aFileName);
        BufferedReader reader = Files.newBufferedReader(path, ENCODING);
        String line = null;
        while ((line = reader.readLine()) != null) {
            //process each line in some way
            log(line);
        }
    }

    void writeLargerTextFile(String aFileName, List<String> aLines) throws IOException {
        System.out.print("***** writeLargerTextFile *****\n");
        Path path = Paths.get(aFileName);
        BufferedWriter writer = Files.newBufferedWriter(path, ENCODING);
        for(String line : aLines){
            writer.write(line);
            writer.newLine();
        }
        writer.flush();
    }

    private static void log(Object aMsg){
        System.out.println(String.valueOf(aMsg));
    }

}
http://www.javapractices.com/topic/TopicAction.do?Id=42 

Thursday, December 13, 2012

Finding real body height using jQuery

function getDocumentHeight() {
    if ($.browser.msie) {
        var $temp = $("<div>")
            .css("position", "absolute")
            .css("left", "-10000px")
            .append($("body").html());

        $("body").append($temp);
        var h = $temp.height();
        $temp.remove();
        return h;
    }
    return $("body").height();
}

Java: iterate through HashMap

Map resultMap = new HashMap();

ResultSet resultSetRegion = s.executeQuery(sSql2);
if(resultSetRegion.next()) {
    resultMap.put( "firstName", "" + resultSetRegion.getString("first_name") );
}

Iterator it = resultMap.entrySet().iterator();
while (it.hasNext()) {
    Map.Entry pairs = (Map.Entry) it.next();
    System.out.println("KEY: "+pairs.getKey()+"\tVALUE: "+pairs.getValue());
}

Run Bash Script Using Java And Get Debug And Error Output

String command = "sudo /usr/bin/some_name.sh";
System.out.println("runBashScriptCommand: " + command);
try {
    Runtime runtime = Runtime.getRuntime();
    Process process = runtime.exec(command);
    printBufferedReaderOutputFromProcess(process);
    process.waitFor();
    return "true";
} catch (Exception ex) {
    System.out.println("EX:" + ex.toString());
    return ex.toString();
}

private void printBufferedReaderOutputFromProcess(Process p) {
    try {
        String s = null;
        BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
        BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
        // read the output from the command
        System.out.println("\n\npHere is the standard output of the command:\n");
        while ((s = stdInput.readLine()) != null) {
            System.out.println(s);
        }
        // read any errors from the attempted command
        System.out.println("Here is the standard error of the command (if any):\n");
        while ((s = stdError.readLine()) != null) {
            System.out.println(s);
        }
    } catch (Exception ex) {
        System.out.println("printBufferedReaderOutputFromProcess:" + ex.toString());
    }
}

Wednesday, December 12, 2012

Height of tab (JTabbedPane) in MAC

Code: 
JTabbedPane paneItem = new JTabbedPane();
JLabel iconInTab = new JLabel(new ImageIcon("myImage.png"));
iconInTab.setPreferredSize(new Dimension(100,80)); 
paneItem.addTab(null,new JPanel());
paneItem.setTabComponentAt(0,iconInTab);
 
I've also try this using html but it did not work either:
paneItem.addTab("<html><p><p><p></html>",new ImageIcon("myImage.png"),new JPanel()) 

Solution:
paneItem.setUI(new BasicTabbedPaneUI());
Also with some features:
paneItem.setTabPlacement(JTabbedPane.TOP);
paneItem.setTabLayoutPolicy(JTabbedPane.WRAP_TAB_LAYOUT);
paneItem.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);

Tuesday, December 11, 2012

Move all files except one

File Structure:
/root/tmp/test
[root@dswing test]# ll
total 12
-rw-r--r-- 1 root root    2 Dec 12 13:41 a.txt
-rw-r--r-- 1 root root    4 Dec 12 13:42 b.txt
-rw-r--r-- 1 root root    0 Dec 12 13:43 c.txt
drwxr-xr-x 2 root root 4096 Dec 12 13:50 ks

Command:
find /root/tmp/test/ -maxdepth 1 -mindepth 1 -type f -not -name c.txt | grep -i txt$ | xargs -i cp -af {} /root/tmp/test/ks

Description:
-maxdepth 1 makes it not search recursively.  
-mindepth 1 makes it not include the /root/tmp/test/ path itself into the result.
-type f means search only for file type.
-not -name c.txt means all files except c.txt
grep -i txt$ means files name ends with txt. 

Put a.txt -file to the end of b.txt -file

In a bash script such append.sh file, write the following code: 
#!/bin/bash
A=/root/tmp/test/a.txt
B=/root/tmp/test/b.txt
cat $A >> $B


The >> redirects the output of the cat command (which output file A) to the file B. But instead of overwriting contents of B, it appends to it. If you use a single >, it will instead overwrite any previous content in B.

Check if a program exists from a bash script

$ command -v foo >/dev/null 2>&1 || { 
  echo >&2 "I require foo but it's not installed.  Aborting."; exit 1;  
}
OR 
$ type foo >/dev/null 2>&1 || { 
  echo >&2 "I require foo but it's not installed.  Aborting."; exit 1;  
}
OR 
$ hash foo 2>/dev/null || { 
  echo >&2 "I require foo but it's not installed.  Aborting."; exit 1;  
}

Resize a list of images in line command

for file in *.jpg; do 
  convert -resize 800x600 -- "$file" "${file%%.jpg}-resized.jpg"; 
done
 
OR 
 
ls *.jpg|sed -e 's/\..*//'|xargs -I X convert X.jpg whatever-options X-resized.jpg 
 
 
# .jpg files, 10% size, no rename, it will overwrite the old pictures
#!/bin/bash
for i in *.jpg; do convert $i -resize 10% $(basename $i .jpg).jpg; done

How to output MySQL query results in csv format

SELECT 'Order Id', 'Product Name', 'Quantity'
UNION
(
SELECT order_id,product_name,qty
FROM orders
INTO OUTFILE 'C:\\tmp\\orders.csv'
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n'
)

How to do something with bash when a text line appear to a file

Use command
tail -f file.log | grep --line-buffered "my pattern" | while read line
do
  echo $line
done
The --line-buffered is the key here, otherwise the read will fail.

Delete all but the 4 newest directories

ls -atrd */ | head --lines=-4 | xargs rm -rf

Bash One Liner: copy template_*.txt to foo_*.txt

Say I have three files (template_*.txt):
  • template_x.txt
  • template_y.txt
  • template_z.txt
I want to copy them to three new files (foo_*.txt).
  • foo_x.txt
  • foo_y.txt
  • foo_z.txt
for f in template_*.txt; do cp $f foo_${f#template_}; done
or
for file in template_*.txt ; do 
  cp $file `echo $file | sed 's/template_\(.*\)/foo_\1/'` ;  
done 

Monday, December 10, 2012

Add or remove month from a date using jQuery

var monthsToAdd =  1;
or
var monthsToAdd = -1;
var today = Date.today().addMonths(monthsToAdd);

if today is 10-12-2012 the today after add 1 month to it is: 10-01-2013

/* download and include in your page */
https://www.box.com/s/qwe136z4awrfuad1z9cm

Sunday, December 9, 2012

Linux group and permission and owner

Linux group and permission and owner:
View all group:
    getent group
    getent group | grep apache (apache is a group name and searching)
    getent group 92 (get group details by group id 92)
    groupadd -g200 deploy ( add a group id=200 and name=deploy)
View all user details:
    useradd pritom ( add a user, name=pritom)
    passwd pritom (set user password)
    getent passwd
    getent passwd | grep root (root is a user name and searching)
    getent passwd 91 (get user details by user id 91)
    usermod -G deploy apache ( add existing user to existing group, group=deploy, user=apache)
    useradd -G deploy pritom3 ( add user=pritom3 to group deploy on creating)


Change file owner:
chown -Rv root:deploy  /skel
chown -Rv root  /skel

root=user
deploy=group
skel=folder
-R=recursive
-v option, chown will list what it did (or didn't do) to the file.

chgrp - change the group ownership of a file
chgrp usergroup somefile
chgrp -Rv usergroup somedir

chmod - modify file access rights
su - temporarily become the superuser
chown - change file ownership
chgrp - change a file's group ownership

chmod 600 some_file
777 (rwxrwxrwx) No restrictions on permissions. Anybody may do anything. Generally not a desirable setting.

755 (rwxr-xr-x) The file's owner may read, write, and execute the file.
All others may read and execute the file. This setting is common for programs that are used by all users.

700 (rwx------) The file's owner may read, write, and execute the file.
Nobody else has any rights. This setting is useful for programs that only the owner may use
and must be kept private from others.

666 (rw-rw-rw-) All users may read and write the file.

644 (rw-r--r--) The owner may read and write a file, while all others may only read the file.
A common setting for data files that everybody may read, but only the owner may change.

600 (rw-------) The owner may read and write a file. All others have no rights.
A common setting for data files that the owner wants to keep private.


Directory permissions:
777 (rwxrwxrwx) No restrictions on permissions. Anybody may list files,
create new files in the directory and delete files in the directory. Generally not a good setting.


755 (rwxr-xr-x) The directory owner has full access. All others may list the directory,
but cannot create files nor delete them. This setting is common for directories that
you wish to share with other users.

700 (rwx------) The directory owner has full access. Nobody else has any rights.
This setting is useful for directories that only the owner may use and must
be kept private from others.


Becoming the superuser for a short while
[me@linuxbox me]$ su
Password:
[root@linuxbox me]#


Changing file ownership:
[me@linuxbox me]$ su
Password:
[root@linuxbox me]# chown you some_file
[root@linuxbox me]# exit
[me@linuxbox me]$

Changing group ownership:
[me@linuxbox me]$ chgrp new_group some_file

Edit /etc/sudoers by command
    visudo
    or
    vim /etc/sudoers
Allow apache to run various commands:
apache ALL=/usr/bin/wat_deploy, /usr/bin/wat_destroy

Allow user apache to run commands without any password i.e. as root without authenticating himself:
apache ALL= NOPASSWD: /usr/bin/wat_deploy, /usr/bin/wat_destroy

Run the command:
$ sudo /usr/bin/wat_deploy

Embedding Your SWF in a Web Page

<OBJECT classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0" 
WIDTH="320" 
HEIGHT="240" 
id="Yourfilename" 
ALIGN="">
<PARAM NAME=movie VALUE="Yourfilename.swf"> 

<PARAM NAME=quality VALUE=high> 
<PARAM NAME=bgcolor VALUE=#333399> 
<EMBED 
  src="Yourfilename.swf" 
  quality=high 
  bgcolor=#333399 
  WIDTH="320" 
  HEIGHT="240" 
  NAME="Yourfilename" 
  ALIGN="" 
  TYPE="application/x-shockwave-flash" 
  PLUGINSPAGE="http://www.macromedia.com/go/getflashplayer">
</EMBED> 
</OBJECT>

Thursday, December 6, 2012

How do I escape single quotes in SQL queries?

INVALID:

SELECT * FROM TableName WHERE FieldName = 'QueryString's Value'

VALID:

SELECT * FROM TableName WHERE FieldName = 'QueryString''s Value'

Java rounding off a float to two decimal places

double r = 5.1234;
System.out.println(r); // r is 5.1234

int decimalPlaces = 2;
BigDecimal bd = new BigDecimal(r);

// setScale is immutable
bd = bd.setScale(decimalPlaces, BigDecimal.ROUND_HALF_UP);
r = bd.doubleValue();

System.out.println(r); // r is 5.12
 

int n = 100; 
float f = (float) (Math.round(n*100.0f)/100.0f);

DecimalFormat df2 = new DecimalFormat( "#,###,###,##0.00" );
double dd2dec = new Double(df2.format(f)).doubleValue();

// The value of dd2dec will be 100.00 



int n = 100.203;
float f = (float) (Math.round(n*100.0f)/100.0f);

DecimalFormat df2 = new DecimalFormat( "#,###,###,##0.00" );
double dd2dec = new Double(df2.format(f)).doubleValue();

// The value of dd2dec will be 100.20

Wednesday, December 5, 2012

Php make zip file

$zip = new ZipArchive();
$zipFileDir = "c:/src/";
$zipFileName = "test.zip";
$zip->open($zipFileDir.$zipFileName, ZIPARCHIVE::CREATE);

/* FROM FOLDER c:/files/ */
$zipIncludedFilesDir = "c:/files/";
chdir($zipIncludedFilesDir);
$zip->addFile("a.jpg");
$zip->addFile("b.jpg");
$zip->close();
if(file_exists($zipFileDir.$zipFileName)) {
    header('Content-Type: application/zip');
    header('Content-disposition: attachment; filename='.$zipFileName);
    header('Content-Length: ' . filesize($zipFileDir.$zipFileName));
    readfile($zipFileDir.$zipFileName);
    unlink($zipFileDir.$zipFileName);
}
exit;

Java check if file exists on remote server using its url

import java.net.*;
import java.io.*;

public class URLUtils {

  public static void main(String s[]) {
    System.out.println(URLUtils.exists("http://www.test.com/exists.html"));
    System.out.println(URLUtils.exists("http://www.test.com/no_exists.html"));
    /*
      output :
        true
        false
    */    
  }

  public static boolean exists(String URLName){
    try {
      HttpURLConnection.setFollowRedirects(false);
      // note : you may also need
      //        HttpURLConnection.setInstanceFollowRedirects(false)
      HttpURLConnection con =
         (HttpURLConnection) new URL(URLName).openConnection();
      con.setRequestMethod("HEAD");
      return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
    }
    catch (Exception e) {
       e.printStackTrace();
       return false;
    }
  }
}
 
 
The following is doing the same thing but this time we identify ourself to a proxy.
See also this HowTo.
 
import java.net.*;
import java.io.*;
import java.util.Properties;

public class URLUtils {

  public static void main(String s[]) {
    System.out.println(exists("http://www.your_server.com"));
    System.out.println(exists("http://www.yahoo.com"));
  }


  public static boolean exists(String URLName){
    try {
      Properties systemSettings = System.getProperties();
      systemSettings.put("proxySet", "true");
      systemSettings.put("http.proxyHost","proxy.mycompany.local") ;
      systemSettings.put("http.proxyPort", "80") ;

      URL u = new URL(URLName);
      HttpURLConnection con = (HttpURLConnection) u.openConnection();
      //
      // it's not the greatest idea to use a sun.misc.* class
      // Sun strongly advises not to use them since they can 
      // change or go away in a future release so beware.
      //
      sun.misc.BASE64Encoder encoder = new sun.misc.BASE64Encoder();
      String encodedUserPwd =
         encoder.encode("domain\\username:password".getBytes());
      con.setRequestProperty
         ("Proxy-Authorization", "Basic " + encodedUserPwd);
      con.setRequestMethod("HEAD");
      System.out.println
         (con.getResponseCode() + " : " + con.getResponseMessage());
      return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
    }
    catch (Exception e) {
      e.printStackTrace();
      return false;
    }
  }
}  

http://www.rgagnon.com/javadetails/java-0059.html

Run Multiple Java Thread

bool isFinished = false;
final ProgressDialogue dialogue = new ProgressDialogue("Loading...");
final Thread progressThread = new Thread() {
    public void run() {
        dialogue.setVisible(true);
    }
};
final Thread progressEvent = new Thread() {
    public synchronized void run() {
        /* DO SOME WORK */
        isFinished = true;
    }
};
 final Runnable doFinished = new Runnable() {
     public void run() { saveBackupFile(); }
};
final Thread progressMonitor = new Thread() {
    public void run() {
        while (true) {
            try {
                /* SLEEP SOME TIME 1000 ms */
                Thread.sleep(1000);
            } catch (Exception ex) {

            }
            /* WAIT FOR WORK FINISHED */
            if (isFinished) {
                /* FINISH ALL */
                Thread.currentThread().interrupt();
                break;
            }
        }
         /* CALL DO FINISH METHOD WHEN THIS PROCESS REACH TO END */
         SwingUtilities.invokeLater(doFinished);
    }
};
progressThread.start();
progressEvent.start();
progressMonitor.start();

Tuesday, December 4, 2012

Execute shell commands in PHP

/**
Method to execute a command in the terminal
Uses :

1. system
2. passthru
3. exec
4. shell_exec

 */
function terminal($command)
{
    //system
    if (function_exists('system')) {
        ob_start();
        system($command, $return_var);
        $output = ob_get_contents();
        ob_end_clean();
    } //passthru
    else if (function_exists('passthru')) {
        ob_start();
        passthru($command, $return_var);
        $output = ob_get_contents();
        ob_end_clean();
    } //exec
    else if (function_exists('exec')) {
        exec($command, $output, $return_var);
        $output = implode("\n", $output);
    } //shell_exec
    else if (function_exists('shell_exec')) {
        $output = shell_exec($command);
    } else {
        $output = 'Command execution not possible on this system';
        $return_var = 1;
    }

    return array('output' => $output, 'status' => $return_var);
}

Use as this way:
$o = terminal('ls');
print_r($o);

http://www.binarytides.com/execute-shell-commands-php/

How to know that a string starts/ends with a specific string in jQuery

One option is to use regular expressions:
if (str.match("^Hello")) {
   // ...
}

if (str.match("World$")) {
   // ...
}

How to download and save a file from url using Java

Give a try to Java NIO:

try {
    URL url = new URL("http://portal.com/img/logo-header.gif");
    ReadableByteChannel rbc = Channels.newChannel(url.openStream());
    FileOutputStream fileOutputStream = new FileOutputStream("C:\\src\\a.gif");
    fileOutputStream.getChannel().transferFrom(rbc, 0, 1 << 24);
} catch (Exception ex) {
    ex.printStackTrace();
}

Using transferFrom() is potentially much more efficient than a simple loop that reads from the source channel and writes to this channel. Many operating systems can transfer bytes directly from the source channel into the filesystem cache without actually copying them.
http://docs.oracle.com/javase/6/docs/api/java/nio/channels/FileChannel.html 

Sunday, December 2, 2012

jQuery Tabs Tutorial

See total result in jsFiddle

Html for tab

<ul class='tabs'>
    <li><a href='#tab1'>Tab 1</a></li>
    <li><a href='#tab2'>Tab 2</a></li>
    <li><a href='#tab3'>Tab 3</a></li>
</ul>
<div style='clear: both;'>&nbsp;</div>
<div class='tab_div' id='tab1'>
    <p>Hi, this is the first tab.</p>
</div>
<div class='tab_div' id='tab2'>
    <p>This is the 2nd tab.</p>
</div>
<div class='tab_div' id='tab3'>
    <p>And this is the 3rd tab.</p>
</div>

jQuery code to make tab


$('ul.tabs').each(function(){
    // For each set of tabs, we want to keep track of
    // which tab is active and it's associated content
    var $active, $content, $links = $(this).find('a');

    // If the location.hash matches one of the links, use that as the active tab.
    // If no match is found, use the first link as the initial active tab.
    $active = $($links.filter('[href="'+location.hash+'"]')[0] || $links[0]);
    $active.addClass('active');
    $content = $($active.attr('href'));

    // Hide the remaining content
    $links.not($active).each(function () {
        $($(this).attr('href')).hide();
    });

    // Bind the click event handler
    $(this).on('click', 'a', function(e){
        // Make the old tab inactive.
        $active.closest("ul").find(".active").removeClass('active');
        $content.hide();

        // Update the variables with the new link and content
        $active = $(this);
        $content = $($(this).attr('href'));

        // Make the tab active.
        $active.addClass('active');
        $active.closest("li").addClass("active");
        $content.show();

        // Prevent the anchor's default click action
        e.preventDefault();
    });
});

Css


ul {
    display: inline;
}
ul.tabs li {
    float: left;
    margin: 10px 15px 10px 0;
    list-style-type: none;
    border: 1px solid gray;
}
ul.tabs li a {
    text-decoration: none;
    padding: 5px;
}
ul.tabs li a.active {
    font-weight: bold;
    color: blue;
}
div.tab_div {
    background-color: gray;
    padding: 20px;
}

Output is as following