Menu

Wednesday, July 27, 2011

JQuery - Accordion


1. Include the necessary JQuery's scripts and css in the head tag.
    For Accordion, the jquery-ui must include accordian and widgets related scripts.
    You can download it from here.
<script type="text/javascript" src="scripts/jquery-1.5.1.min.js"></script>
<script type="text/javascript" src="scripts/jquery-ui-1.8.14.custom.min.js"></script>
<link href="css/jquery-ui-1.8.14.custom.css" rel="stylesheet"></script>

2. Include this script in the head tag
<script type="text/javascript">
$(function() {
$('#section').accordion();
});
</script>

3. Include this html in the body
<div id="section"> 
  <h3><a href="#">Section 1</a></h3>
  <div> This is section1.</div>

  <h3><a href="#">Section 2</a></h3>
  <div>This is section2.</div>

  <h3><a href="#">Section 3</a></h3>
  <div>This is section3.</div>

  <h3><a href="#">Section 4</a></h3>
  <div>This is section4.</div>

  <h3><a href="#">Section 5</a></h3>
  <div>This is section5.</div>
</div>

View the complete code here.  This example output

JQuery - UI Tab

Download the necessary js and css file from here. I have downloaded these files with smoothness theme.

<html>
<head>
    <script type="text/javascript" src="scripts/jquery-1.5.1.min.js"></script>
    <script type="text/javascript" src="scripts/jquery-ui-1.8.14.custom.min.js"></script>
    <link href="css/jquery-ui-1.8.14.custom.css" rel="stylesheet"></script>

    <style>
    #tabs{
      width: 300px;
      font-size: 12px;
    }
    </style>
    <script type="text/javascript">
       $(function() {
           $('#tabs').tabs();
           //Tab on mouse over
           //$('#tabs').tabs({event: "mouseover"});
       });
    </script>
</head>

<body>
  <div id="tabs">
    <ul>
      <li><a href="#book">Tab 1</a></li>
      <li><a href="#tab2">Tab 2</a></li>
      <li><a href="#tab3">Tab 3</a></li>
    </ul>
  <div id="book">
      <p>A combination of economic factors resulted in Indian expats waking up this morning to find that the rupee had strengthened considerably – directly hitting their savings.</p>
  </div>
  <div id="tab2">
      <p>Norwegian police said they mistakenly released an alert on Wednesday saying they were searching for a man who identified with mass killer Anders Behring Breivik.</p>
  </div>
  <div id="tab3">
      Content of the tab 3
  </div>
</div>
</body>

</html> 

The tabs will be like this



Tuesday, July 26, 2011

MySql - User related commands

  • 1. How to create user?
    • CREATE USER username@host IDENTIFIED BY password
    • Ex: CREATE USER 'akila'@'localhost' IDENTIFIED BY 'akila';
  • 2. How to set password for the user?
    • # SET PASSWORD FOR username=PASSWORD(password);
    • Example: # SET PASSWORD FOR 'akila' = PASSWORD ('akila');
    • # UPDATE mysql.user SET Password=PASSWORD ('AKILA') WHERE user='akila' AND host='localhost';
  • 3. How to grant permission?
    • GRANT ALL PRIVILEGES ON database TO 'akila'@'localhost' IDENTIFIED BY 'akila';
  • 4. How to switch to another user?
    • # mysql -u user –p
    • Enter Password:
  • 5. How to show users in the database?
    • SELECT * FROM mysql.user

Sunday, July 24, 2011

Install tomcat in windows

  1. Download Tomcat from the below site. http://tomcat.apache.org/
  2. Set the following environment variables in the User or System variables.  See this article to set environment variables. How to set environment variables in windows?
    • JAVA_HOME = location of the JDK
    • CATALINA_HOME = Location of the Tomcat server
    • PATH = Add CATALINA_HOME\bin directory in the path variable
  3. Go to CATALINA_HOME\bin directory in the command prompt and run the startup.bat file.
  4. Run this http://localhost:8080/ URL in the browser to verify tomcat installation. By default tomcat will run on 8080 port.

     Related Articles:

     How to add Tomcat as a service in windows?
     How to change the Tomcat's default port no?

How to set enviroment variables in windows

Right click on the Computer --> Click Advanced system settings --> Click Environment Variables


Javascript - Load XML string

The below javascript example explains how to load XML string into Dom object.


 
Books
Bind a callback function after Dom is ready.
$(document).ready(function(){
    //Code here
});

or

(function($){
    $(function(){
          //Code here
    });
})(jQuery);

Windows commands

  • 1. Get the help of a command
    • Syntax
    • # command ?/
    • Example:
    • # taskkill ?/
    • Displays the usage of the taskkill command.
  • 2. List all the process running on the windows system.
    • Syntax
    • # tasklist
    • # tasklist /FI "IMAGENAME eq java.exe" - This command list all the process where the image name is java.exe
  • 3. Kill specific process in the command prompt?
    • Example:
    • # taskkill /PID process_id
    • # taskkill /PID 8760
    • This command kills the process whose id is 8760.
  • 4. Kill all java process running on the system.
    • Example:
    • taskkill /F /IM java.exe
    • /F – Delete java.exe process forcefully.
    • /IM – Image name of the process
  • 5. List out all TCP/IP connections.
    • Syntax
    • # netstat
    • Example:
    • # netstat –aon
    • a – List all TCP/IP connections and listening ports.
    • o – Display process id associated with each connection.
    • n – Display addresses and port numbers in Numerical format.
  • 6. Find out a process running on specific port.
    • Syntax
    • # netstat
    • Example:
    • # netstat –aon | findstr 0.0.8080
    • Consider that Tomcat is running on the 8080 port. The output of the above command is


Wednesday, July 20, 2011

Ajax call using jquery

<html>
  <head>
    <title></title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <script src="http://code.jquery.com/jquery-1.6.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(document).ready(function(){
            $('#btn').click (function(){
                $.ajax({
                    type: "GET",
                    url: "test.html",
                    dataType: "html",
                    async: true,
                    success: function (html){
                        alert(html);
                    },
                    error: function (xhr, status, error) {
                        alert(status);
                    }
                });
            });
        });
        
    </script>
  </head>
  <body>
    <button id="btn" >Click Me</button>
  </body>
</html>

Ajax call using java script

<html>
  <head>    
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <script type="text/javascript">
    function callAjaxFn(){
        var http;
        if (window.XMLHttpRequest){
                http = new XMLHttpRequest();
        } else {
                http = ActiveXObject ("Microsoft.XMLHTTP");
        }
        http.open("GET", "test.html", true);
        http.send();
        http.onreadystatechange=function(){
            if (http.readyState == 4 && http.status == 200) {
                alert(http.responseText);
            }
        }
    }
    </script>
  </head>
  <body>    
      <button onclick="callAjaxFn();" >Click Me</button>      
  </body>
</html>



Tuesday, July 19, 2011

SSH without password

This tutorial explains on how to SSH to the server without providing password. This will helpful when there is necessary to do automation process or to keep on logging to the server regularly.

Step 1. Generate the authentication keys in the client system. These keys can be generated using the RSA or DSA algorithm. RSA algorithm is much faster than DSA where as the DSA is more secure.
    
     # ssh-keygen -t rsa

     By default, the key generated by the above command will be in /root/.ssh/id_rsa if you login with root directory. When you generate the key, don’t enter password.

     
     The above command will generate one private and one public key as shown in the below picture.



Step 2.  In the server system, create .ssh directory if it doesn’t exists and then create an authorized_keys file.

# ssh username@server
# mkdir –p .ssh
# touch authorized_keys
# exit

Step 3.  Now append the public key (id_rsa.pub) which is created on the client system in the authorized_keys. and change mode of the .ssh directory and authorized_keys file.

# scp /root/.ssh/id_rsa.pub user@server:/tmp
(copy the id_rsa.pub key to temp directory in the server)
# cat /tmp/id_rsa.pub >> /.ssh/authorized_keys

# chmod 700 .ssh
# chmod 600 .ssh/authorized_keys

Step 4.  Once you complete everything, log into the server from client system. It will not prompt for password.

# ssh user@server 

Sunday, July 17, 2011

How to create xml file in java

Simple example to create a xml file in Java

package com.xml;

import java.io.File;
import java.io.StringWriter;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class Main {
    public static void main (String[] args) {
        try {
            //Create Document
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document document = builder.newDocument();

            //Books Tag - Root Tag
            Element books = document.createElement("books");
            document.appendChild(books);

            //Book Tag - Child Tag
            Element book1 = document.createElement("book");
            books.appendChild(book1);

            Element name = document.createElement("name");
            name.setTextContent("Head First EJB");
            book1.appendChild(name);

            Element author = document.createElement("author");
            author.setTextContent("Kathy Seira");
            book1.appendChild(author);

            //Transform Document Object
            TransformerFactory tfactory = TransformerFactory.newInstance();
            Transformer transformer = tfactory.newTransformer();
            transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            
            DOMSource source = new DOMSource(document);

            //To write the dom object into a file
            StreamResult result = new StreamResult(new File("books.xml"));
            transformer.transform(source, result);

            //To write the dom object content into string
            StringWriter writer = new StringWriter();
            StreamResult result1 = new StreamResult(writer);
            transformer.transform(source, result1);

            //System.out.println (writer.toString());
            
        }catch (ParserConfigurationException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }catch (TransformerConfigurationException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }  catch (TransformerException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        } 
        
    }
}

The output of the program



Head First EJB
Kathy Seira


Monday, July 11, 2011

Rsync in linux


What is rysnc?
rsync is a utility software in Linux/Unix used to transfer files between two destination whereas the destination can be remote or local system. As it transfers only difference of the file if the destination already has that file, it is very fast.

Rsync syntax
rsync [option] [src] [destination]

Example:
rsync    --verbose \
--recursive \
 /etc  backup@backupserver:/opt/backup/frontserver1
The above command syncs the contents of the etc folder to frontserver1 in the backupserver.

Sunday, July 10, 2011

Regular Expression in Java

  • What is regular Expression?
    Regular expression is a sequence of characters called as pattern which is used in search operations.
  • Characters used in Regular Expression.
    • .Matches any character
    • ?Matches zero occurrence or only one time.
      Ex: ab? . It matches (a – Zero occurrence of ‘b’) ( ab – One occurrence of ‘b’)
    • *Matches zero or many times.
      Ex: ab*. It matches a, ab, abb, abb
    • +Matches at least one or many times.
      Ex: ab+. It matches ab, abb, abbb
    • X{n,}Matches the character(s) at least n times.
      Ex: a{2}. It matches aa, aaa, aaa
    • X{n,m}Matches the character(s) at least n times and not more that m times.
    • [ ]Matches single character with in the bracket.
      Ex: [ab] matches a or b or c
    • [^ ]Opposite to [ ]. It matches a character which is not in the bracket.
      Ex: [^ab] matches any character other than a and b.
    • ^Beginning of the line
    • $End of the line
  • Character classes used in Regular Expression.
    • [a-z]Matches lowercase alphabets a to z
    • [A-Z]Matches Uppercase alphabets A to Z
    • [a-zA-Z]Matches alphabets
    • [a-zA-Z0-9]Matches Alphanumeric
    • \wAlphanumeric with underscore character [a-zA-Z0-9_]
    • \WNegation of \w. Non word characters. [^\w]
    • [0-9]Digits 0 to 9
    • \dDigits
    • \DNon Digits. [^0-9]
    • \sWhite Space

Validate Alphabets
Example: Simple program to validate alphabets using regular expression.


Validate Digits
Example: Simple program to validate digits using regular expression.


Validate Alpha Numeric
Example: Simple program to validate alpha numeric using regular expression.


Validate Phone no
Example: Simple program to validate phone no using regular expression.


Validate Email Id
Example: Simple program to validate email id using regular expression.

Regular Expression - Validate email id

Here is a simple program to validate email id.


private static void validateEmailId () {

    String str1 = "test.email@domain.com";

    String expression = "^[\\w\\.-]+@[\\w\\.]+\\.[a-z]{2,3}$";
    Pattern pattern = Pattern.compile(expression);

    Matcher matcher = pattern.matcher(str1);

    boolean found = false;
    if (matcher.find()) {
        System.out.println (str1 + " - is a valid email id.");
        System.out.println (matcher.group(0));
        found = true;
    }
    if(!found){
        System.out.println(str1 + " - is not a valid email id.");
    }
}


Regular Expression - Validate phone no

Here is a simple program to validate phone no with nnn-nnn-nnnn/nnnnnnnnnn format

private static void validatePhone () {
   //Validate phone no.
    String expression = "^\\d{3}-?\\d{3}-?\\d{4}$";
    String str1 = "1233456789"; //It will match.
    String str2 = "2dF1"; //It wont match.
    String str3 = "a33345345"; //It wont match.
    Pattern pattern = Pattern.compile(expression);

    Matcher matcher = pattern.matcher(str1);

    boolean found = false;
    if (matcher.find()) {
        System.out.println (str1 + " - is valid phone no.");
        found = true;
    }
    if(!found){
        System.out.println(str1 + " - is not a valid phone no.");
    }
}


Regular Expression - Validate only alpha numeric letters

Here is the simple program to validate the alpha numeric letters

private static void onlyAlphaNumeric () {
   //Only Alpha numeric letters
    String expression = "^[a-zA-Z0-9]+$";
    String str1 = "33345a345"; //It will match.
    String str2 = "2dF#1"; //It wont match.
    String str3 = "a333@45345"; //It wont match.
    Pattern pattern = Pattern.compile(expression);

    Matcher matcher = pattern.matcher(str1);

    boolean found = false;
    if (matcher.find()) {
        System.out.println (str1 + " - is a alpha numeric");
        String[] items = pattern.split(str1);
        for (String s: items)
        {
            System.out.println (s);
        }
        found = true;
    }
    if(!found){
        System.out.println(str1 + " - is not a alpha numeric");
    }
}

Regular Expression - Validate only digits

Here is the simple program to validate the digits

private static void onlyDigits () {
   //Only Digits
    String expression = "^[0-9]+$";
    String str1 = "123"; //It will match.
    String str2 = "2dF1"; //It wont match.
    String str3 = "a33345345"; //It wont match.
    Pattern pattern = Pattern.compile(expression);

    Matcher matcher = pattern.matcher(str1);

    boolean found = false;
    if (matcher.find()) {
        System.out.println (str1 + "  - is a number");
        found = true;
    }
    if(!found){
        System.out.println(str1 + " - is not a number");
    }
}

Regular Expression - Validate only alphabets

Here is the simple program to validate the digits

private static void onlyAlphabets () {
    //Only Alphabets
    String expression = "^[a-zA-Z]+$";
    String str1 = "It is a string"; //It will match.
    String str2 = "2dF1"; //It wont match.
    String str3 = "a33345345"; //It wont match.
    Pattern pattern = Pattern.compile(expression);

    Matcher matcher = pattern.matcher(str1);

    boolean found = false;
    if (matcher.find()) {
        System.out.println (str1 + " - contains only alphabets");
        found = true;
    }
    if(!found){
        System.out.println(str1 + " - contains other than alphabets");
    }
}

Read Excel file in java

Apache's POI is very useful to read or write an excel file.
You can download the jar file from here. http://poi.apache.org/

Here is the simple java code to read Excel file.
       Include these jar files in the classpath.
  • 01.poi-3.7-20101029.jar
  • 02.poi-ooxml-3.7-20101029.jar
  • 03.poi-ooxml-schemas-3.7-20101029.jar
  • 04.xbean.jar
  • 05.dom4j-1.6.1.jar
package com.excel;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Iterator;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;

import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;

public class ReadExcel {
    public static void main (String[] args) throws Exception {
        InputStream is = new FileInputStream("C:/workbook.xlsx");
        Workbook wb = WorkbookFactory.create(is);
        Sheet sheet = wb.getSheetAt(0);
        Iterator rowIterator = sheet.rowIterator();

        while (rowIterator.hasNext()) {
            Row row = rowIterator.next();
            Iterator cellIterator = row.cellIterator();

            while (cellIterator.hasNext()) {
                Cell cell = cellIterator.next();
                System.out.print(cell.getStringCellValue());
                System.out.print(" : ");
            }
            System.out.println();
        }
    }
}

Input Excel file.


Output of the program.

Crontab


  • 1. What is cron?
    • Cron is utility software in Linux/Unix system used to run a set of tasks automatically in the background without any user interference. This is mainly used to automate the process similar to batch file in windows.
    • The tasks i.e. commands should be specified in the crontab file. By default the crontab file will be in /var/spool/cron and the log file of the crontab in /var/log/cron
  • 2. Crontab commands
    • Syntax
    • # crontab -l        - List all the tasks entered in the crontab file.
    • # crontab -e       - Edit the crontab file.
    • # crontab -r        - Remove the crontab file.
  • 3. Crontab syntax 
    • *    *   *   *   * (command to execute/sh file to execute list of commands) 
  • 4. Examples
    • */2 * * * * backup.sh        - Run the backup.sh file for every two minutes.
    • * */12 * * * bakcup.sh      - Run the backup.sh file for every 12 hours.
    • * * 1,15 * * backup.sh      - Run backup.sh file 1st and 15th of every month.
    • * * * 1,6 * backup.sh        - Run backup.sh file on January and June.
    • * * * * 0 backup.sh           - Run backup.sh file every Sunday.


Saturday, July 9, 2011

How to add tomcat as a service in the windows OS?

1.       Go to the tomcat bin folder in the command prompt.
2.       Type service.bat install which will install tomcat as a service in the windows platform. The tomcat service name will be your tomcat version. Suppose if you installed tomcat 5.5.17 version, the service name would be tomcat5. Basically it will be taken from the service.bat file.



3.       To check tomcat service on Windows go to Control panel – Administrative Tools – Services



4.       Once you installed the service, you can run the tomcat by simply using the service name



How to change the Tomcat default port?

Hope you have installed the tomcat on your system.
The folder structure of the tomcat server is

1.       By default the tomcat server port is 8080.
2.       To change the port, edit the server.xml file in the conf folder.
3.       Search for “8080” and change it to the port number that you wish.

4.       Restart the tomcat server.
5.       To verify the changes, just type http://localhost:xxxx on your web browser where xxxx stands for the port no.

Thursday, July 7, 2011

Log4j - Daily Rolling File Appender

Daily Rolling File Appender in log4j.properties

  • 01.log4j.appender.daily=org.apache.log4j.DailyRollingFileAppender
  • 02.log4j.appender.daily.File=C:/daily.log
  • 03.log4j.appender.daily.DatePattern='.'yyyy-MM-dd-a
  • 04.log4j.appender.rolling.MaxFileSize=5KB
  • 05.log4j.appender.rolling.MaxBackupIndex=1
  • 06.log4j.appender.daily.layout=org.apache.log4j.PatternLayout
  • 07.log4j.appender.daily.layout.ConversionPattern=%d [%t] %-2p %c -%m%n

Daily Rolling File Appender in log4j.xml
  • 01. <?xml version="1.0" encoding="UTF-8" ?>
  • 02. <!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
  • 03. 
  • 04. <log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
  • 05.        <!-- File Appender -->
  • 06.         <appender name="daily"
  • 07.             class="org.apache.log4j.DailyRollingFileAppender">
  • 08.         <param name="File" value="log/daily.log"/>
  • 09.         <param name="DatePattern" value="'.'yyyy-MM-dd"/>
  • 10.         <param name="Append" value="true"/>
  • 11.         <layout class="org.apache.log4j.PatternLayout">
  • 12.             <param name="ConversionPattern" value="%-5p%c{1}-%m%n"/>
  • 13.         </layout>
  • 14.     </appender>
  • 15. 
  • 16.    <root>
  • 17.         <priority value ="debug" />
  • 18.         <appender-ref ref="daily" />
  • 19.     </root>
  • 20. 
  • 21. </log4j:configuration>

Log4j - Rolling File Appender

Rolling File Appender in log4j.properties
  • 01.log4j.appender.rolling=org.apache.log4j.RollingFileAppender
  • 02.log4j.appender.rolling.File=C://rolling.log
  • 03.log4j.appender.rolling.MaxFileSize=5KB
  • 04.log4j.appender.rolling.MaxBackupIndex=1
  • 05.log4j.appender.rolling.layout=org.apache.log4j.PatternLayout
  • 06.log4j.appender.rolling.layout.ConversionPattern=%d [%t] %-2p %c -%m%n

Rolling File Appender in log4j.xml


  • 01. <?xml version="1.0" encoding="UTF-8" ?>
  • 02. <!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
  • 03. 
  • 04. <log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
  • 05.        <!-- File Appender -->
  • 06.     <appender name="rolling" class="org.apache.log4j.RollingFileAppender">
  • 07.         <param name="File" value="log/rolling.log"/>
  • 08.         <param name="MaxFileSize" value="1kb"/>
  • 09.         <param name="MaxBackupIndex" value="1"/>
  • 10.         <param name="Append" value="true"/>
  • 11.         <layout class="org.apache.log4j.PatternLayout">
  • 12.             <param name="ConversionPattern" value="%-5p%c{1}-%m%n"/>
  • 13.         </layout>
  • 14.     </appender>
  • 15. 
  • 16.    <root>
  • 17.         <priority value ="debug"/>
  • 18.         <appender-ref ref="rolling"/>
  • 19.     </root>
  • 20. </log4j:configuration>

Log4j - File Appender

File Appender configuration in log4j.properties

  • 01.log4j.appender.file=org.apache.log4j.FileAppender
  • 02.log4j.appender.file.File=C:/logfile.log
  • 03.log4j.appender.file.layout=org.apache.log4j.PatternLayout
  • 04.log4j.appender.file.layout.ConversionPattern=%d %c [%t] %-2p %c -%m%n

File Appender configuration in log4j.xml
  • 01. <?xml version="1.0" encoding="UTF-8" ?>
  • 02. <!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
  • 03. 
  • 04. <log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
  • 05.        <!-- File Appender -->
  • 06.     <appender name="file" class="org.apache.log4j.FileAppender">
  • 07.         <param name="File" value="log/file.log"/>
  • 08.         <param name="Append" value="true"/>
  • 09.         <layout class="org.apache.log4j.PatternLayout">
  • 10.             <param name="ConversionPattern" value="%-5p%c{1}-%m%n"/>
  • 11.         </layout>
  • 12.     </appender>
  • 13. 
  • 14.    <root>
  • 15.         <priority value ="debug"/>
  • 16.         <appender-ref ref="file"/>
  • 17.     </root>
  • 18. </log4j:configuration>

Wednesday, July 6, 2011

Find no of days between two dates in java

  • 01. import java.util.Calendar;
  • 02. 
  • 03. public class DaysBWDates {
  • 04.     public static void main (String[] args) {
  • 05.         Calendar cal1 = Calendar.getInstance();
  • 06.         Calendar cal2 = Calendar.getInstance();
  • 07.         cal2.add(Calendar.DATE, -3);
  • 08.
  • 09.       long noOfDays = (cal1.getTimeInMillis()
  •                             - cal2.getTimeInMillis())/(1000*60*60*24);
  • 10. 
  • 11.         System.out.println("Date1: " + cal1.getTime());
  • 12.         System.out.println("Date2: " + cal2.getTime());
  • 13.         System.out.println ("No of days between two dates: " + noOfDays);
  • 14.     }
  • 15. }

Log4j - Console Appender

Console Appender configuration in log4j.properties

  • 01.log4j.rootLogger=DEBUG, stdout, file, rolling, daily
  • 02.log4j.appender.stdout=org.apache.log4j.ConsoleAppender
  • 03.log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
  • 04.log4j.appender.stdout.layout.ConversionPattern=%d{ISO8601} [%t] %-2p %c - %m%n

Console Appender configuration in log4j.xml

  • 01. <?xml version="1.0" encoding="UTF-8" ?>
  • 02. <!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
  • 03. 
  • 04. <log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
  • 05.    <!-- Console Appender -->
  • 06.     <appender name="console" class="org.apache.log4j.ConsoleAppender">
  • 07.         <param name="Target" value="System.out"/>
  • 08.         <layout class="org.apache.log4j.PatternLayout">
  • 09.             <param name="ConversionPattern" value="%-5p%c{1}-%m%n"/>
  • 10.         </layout>
  • 11.     </appender>
  • 12. 
  • 13.    <root>
  • 14.         <priority value ="debug"/>
  • 15.         <appender-ref ref="console"/>
  • 16.     </root>
  • 17. </log4j:configuration>

Monday, July 4, 2011

Vi Editor Commands


  • 1. What are the different editors in Linux to edit files?
    • 1. ed
    • 2. vi
    • 3. vim
    • 4. pico
  • 2. How to open a file in vi editor?
    • Syntax
    • # vi file-name
    • Example:
    • # vi names.txt
  • 3. How to quit a file?
    • Example:
    • Vi names.txt – Open a file in vi editor.
    • :q! – If you are in insert mode press escape before you type :q! to quit the editor without saving.
    • :wq – Quit vi editor with saving.
  • 4. Save commands in vi editor
    • q Quit
    • :q! Quit without saving
    • :qa Quit all fiels opened
    • :w Save changes
    • :wq Save and quit
    • zz Save and quit

List Commands

  • List command Syntax.
  • # ls [option] [file]
  • # ll [option] [file]
  • Frequently Asked Questions in Remove Command
  • 1. How to list all the files including hidden files?
    • Syntax
    • # ls –a
    • The above command list all the files including hidden files in the current directory.
    • # ll –a
    • The above command list all the files including hidden files in the current directory with lot more information.


File related commands

  • 1. How to create an empty file?
    • Syntax
    • # touch file-name
    • Example:
    • # touch tmp
    • The above command creates an empty file.
  • 2. How to copy files and directories?
    • Syntax
    • # cp file1 file2
    • Example:
    • # cp names.txt emp.txt
    • The above command copies content of names.txt to emp.txt if you agree for overwrite.
    • # cp -r /opt/dev/project1 /opt/dev/project2
    • The above command copies all the contents of project1 directory to project2 directory recursively.
  • 3. How to read a file?
    • Syntax
    • # more file-name
    • Example:
    • # more /etc/passwd
    • The above command reads passwd file
  • 4. How to concatenate files?
    • Syntax
    • # cat file1 file2
    • Example:
    • # cat /tmp/user-list1.txt /tmp/user-list2.txt > users.txt
    • The above command concatenates both users list file and writes into a "users.txt" file.
  • 5. How to create a directory?
    • Syntax
    • # mkdir directory-name
    • Example:
    • # mkdir downloads
    • The above command creates directory named as "downloads"
    • # mkdir –p /usr/softwares/downloads
    • The above command creates a directory with parent as needed if parent doesn't exist.
  • 6. How to change the current directory?
    • Syntax
    • # cd
    • Example:
    • # cd /opt/dev/project
    • The above command change the current directory to /opt/dev/project
    • # cd ../
    • Go one level up from the current folder
  • 7. How to get current directory path?
    • Syntax
    • # pwd
    • The above command prints the current directory path.
  • 8. How to rename a file?
    • Syntax
    • # mv file1 file2
    • Example:
    • mv names-list.txt emp-list.txt
    • The above command moves the content of "names-list.txt" to emp-list.txt. As Linux doesn't support rename, move command is used.


User and password commands in linux

  • Remove command Syntax.
  • # rm [option] file
  • # rmdir [option] directory
  • Frequently Asked Questions in Remove Command
  • 1. How to check who currently logged into the system?
    • # whoami
    • The above command tells who logged into the system.
  • 2. How do I know what are the users created in linux?
    • # cat /etc/passwd
    • All the created users will be in passwd file
  • 3. How to create new user account in linux?
    • Syntax:
    • # useradd username
    • Example:
    • # useradd -p A18jio guest
    • The above command creates a user called "guest" with password "A18jio".
  • 4. How to change the password of currently logged in user?
    • Syntax:
    • # passwd enter-password
    • Example:
    • # passwd y3d3#uj
    • The above command changes the currently logged in user password.

Remove command in linux

  • Remove command Syntax.
  • # rm [option] file
  • # rmdir [option] directory
  • Frequently Asked Questions in Remove Command
  • 1. How to remove a file?
    • Syntax
    • # rm [option] file
    • Example:
    • # rm tmp.txt
    • The above command will delete the "tmp.txt". Before that it will ask you to confirm for deletion.
    • # rm -f tmp.txt
    • The above command will forcely delete the "tmp.txt" file
  • 2. How to remove a directory?
    • Syntax
    • # rmdir [option] directory
    • Example:
    • # rmdir /temp/test
    • The above command will delete the "test" directory if there is no content in it.
    • If there is any content in this directory, it will throw error: "rmdir: /temp/test: Directory not empty".
    • # rmdir -p /temp/test
    • The above command removes directory and its ancestors.
  • 3. How to remove a directory including its subdirectories?
    • Example:
    • # rm -r /temp/test
    • The above command will delete the "test" directory and its sub subdirectories and files.
    • # rm -rf /temp/test
    • The above command deletes all the files and subdirectories without asking confirmation. If you run this command by mistake, thats all. So very carefull when you execute this command.