Menu

Tuesday, June 28, 2011

MD5

What is MD5?

Message Digest Algorithm is a command line utility used to check the data integrity of a file where it is downloaded from network.

How to install MD5?

Step 1: Download md5sum.exe file from this site http://etree.org/cgi-bin/counter.cgi/software/md5sum.exe

Step 2: Set the location of this exe file in the Path variable.

Right Click on Computer ---> Properties ---> Advanced System Settings ---> Environment Variables ---> Edit Path Variable ---> Add the location (Ex. C:\softwares\md5 – Location of the md5sum.exe).

Step 3: Go to the command prompt and type md5sum –version. Now the md5 utility is successfully installed.




What does md5checksum will do?
        This utility will generate 128 bit hash value which will be used to check the file corruption.

How to verify the downloaded file is not corrupted in windows?

Step 1: Download a file with its corresponding checksum file (extension with md5) or checksum value.
         Ex: I downloaded commons-io-2.0.1-bin.zip file from http://commons.apache.org/io/download_io.cgi




Step 2: Note down the MD5 value - 32a46d8f3c22ecf2be8217f19bb81282

Step 3: Go to the command prompt and type the following command
            > md5sum file-name
      Ex: > md5sum commons-io-2.0.1-bin.zip

This command generated some value. Check this value with the MD5 value that noted previously. Both values are same so that the file is downloaded without any corruption.


Tuesday, June 21, 2011

Learn Maven


What is Maven?
How to install Maven in Windows?
Maven project directory structure
How to create a simple Project using maven?
How to package a Project using Maven?
How to add dependency jar file?
How to include resources in the jar file?

                Maven is a project management tool which is used to build and package the project.

How to install Maven in Windows?
  
1.       Download Maven from the below site.
http://maven.apache.org/download.html - The latest version that I downloaded was apache-maven-3.0.3-bin.zip

2.       Extract the downloaded file. Consider that I have extracted it into the below directory
                  C:\Softwares\Apache Products\Maven\apache-maven-3.0.3

3.       Set the necessary environment variables.
M2_HOME=C:\Softwares\Apache Products\Maven\apache-maven-3.0.3 – Home directory
M2= %M2_HOME%\bin                                                 – Bin directory of the Maven
MAVEN_OPTS= -Xms256m -Xmx512m                        – This is optional
PATH=%M2%                                                                 – Maven bin directory in the path variable

4.       Check the status of the Maven in the command line.
> mvn --version
The output will be like this.
             

                Now the Maven has been installed successfully in the windows system.


Maven project directory structure

src                      - Source code will be here.
target                  - When you do package, maven package the project and will keep  it here.
pom.xml              - Maven Project configuration file.

src/main/java                                - Source code
src/main/resources                        - Resources folder (properties files location)
src/main/filters                              - Resource filter files
src/main/assembly                         - Assembly descriptors
src/main/config                             - Configuration files location
src/main/webapp                          - Web application resource folder
src/test/java                                  - Test Source code
src/test/resources                          - Test Resources folder (properties files location)
src/test/filters                                 - Test filters folder
src/site                                          - Site

All the information to build the project should be entered into the pom.xml file which is a project configuration file in Maven.

Structure of the pom.xml file



How to create a simple Project using maven?

In Maven each task will be considered as a goal. The below goal (archetype:generate) is to create a project called maven-app
> mvn archetype:generate -DgroupId=com.mycompany.app  
-DartifactId=maven-app
-DarchetypeArtifactId=maven-archetype-quickstart
-DinteractiveMode=false

How to package a Project using Maven?
> mvn package

How to add dependency jar file?
Consider you have used classes from the log4j and commons-lang in your application, and then those dependency jar files should be entered in the pom.xml file as shown. If it is not included, it will throw error when you package the application.
<project . . . >
. . .

<dependencies>
      <dependency>
            <groupId>commons-lang</groupId>
            <artifactId>commons-lang</artifactId>
            <version>2.6</version>
            <scope>compile</scope>
      </dependency>    
      <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.12</version>
            <scope>compile</scope>
      </dependency>
</dependencies>

<build>
<plugins>
<plugin>
            <artifactId>maven-dependency-plugin</artifactId>
            <executions>
                  <execution>
                        <id>${project.artifactId}-fetch-deps</id>
                        <phase>generate-sources</phase>
                        <goals>
                              <goal>unpack-dependencies</goal>
                        </goals>
                        <configuration>
                              <outputDirectory>
${project.build.outputDirectory}
</outputDirectory>
                              <stripVersion>true</stripVersion>
                              <excludeTransitive>true</excludeTransitive>
                              <excludeArtifactIds>junit</excludeArtifactIds>
                        </configuration>
                  </execution>
            </executions>
      </plugin>
</plugins>
</build>
. . .
</project>

How to include resources in the jar file?
Consider all the properties file are in the src/main/resources folder
<project …>
      . . .
<build>
            <resources>
                  <resource>
                        <directory>src/main/resources</directory>
                  </resource>
            </resources>
</build>
. . .
</project>

How to read property file in java?

public class ReadProps {
    public static void main (String[] args) {
        ReadProps readProps = new ReadProps();
        readProps.readFile("test.properties");
    }

    private void readFile (String fileName) {
        try {
            InputStream is = getClass().getResourceAsStream(fileName);
            Properties props = new Properties();
            props.load(is);
        } catch (IOException ex) {
           ex.printStackTrace();
        }
    }
}

How to package a java application as a jar file in Eclipse?



1.       Create a simple java project as shown in the screenshot below.
a.       File --> New --> Project --> Java Project

b.      Enter name of the project.

 
2.       Create a class.


3.       Export the project.
a.       Right click on the project --> Click on the Export --> Expand Java --> Select Jar file


  
b.      Enter jar file name and click next.

 
c.       Customize the manifest file as show in the screenshot.

          d.       Click finish. Now the project is packaged as a jar file successfully.


Sunday, June 5, 2011

Parse a html file using HTMLParser

HTMLParser API is one of the powerful parser.   Download the HTML Parser from the site below

Autocad Designer RAMTESA United Arab Emirates 31-May-2011
OIL AND GAS DOWNSTREAM SALES ENGINE RAMTESA United Arab Emirates 31-May-2011


Here is the java class which parses above html.

public class HtmlParserMain {
    public static void main (String[] args) throws Exception{
        FileInputStream fis =
                new FileInputStream (new File("C:/Akila/test.html"));
        //Create parser
        Parser parser = new Parser(new Lexer(new Page(fis, "UTF-8")));

        //Get specific node: Here I want only the tr nodes
        NodeFilter filter =
                    new AndFilter(
                        new TagNameFilter("tr"),
                        new HasAttributeFilter("class"));

        //Parse the html
        NodeList list = parser.parse(filter);

        //Get the iterator
        SimpleNodeIterator iterator = list.elements();

        //Iterate Table rows
        while (iterator.hasMoreNodes()) {
            //Get the TR node
            TagNode node = (TagNode)iterator.nextNode();
            NodeList tdList = new NodeList ();
            //Get the TD nodes
            node.collectInto(tdList, new TagNameFilter("td"));

            System.out.print(tdList.elementAt(0).toPlainTextString() + " : ");
            System.out.print(tdList.elementAt(1).toPlainTextString() + " : ");
            System.out.print(tdList.elementAt(2).toPlainTextString() + " : ");
            System.out.println(tdList.elementAt(3).toPlainTextString());
        }
               
        //If you want to parse the html directly from the web
        //Parser parse = new Parser ("http://www.google.com");
    }
}

Thursday, June 2, 2011

Configure My SQL in GlassFish and Jboss Server


Create database in My SQL Server
1.       Create database in My SQL server.
CREATE DATABASE database_name;
CREATE DATABASE project;
2.       Create username and password to access the database.
CREATE USER ‘user_name’@’host_name’ IDENTIFIED BY ‘password’;
CREATE USER 'kamal'@'localhost' IDENTIFIED BY ‘kamal';
3.       Grant permission for the user.
GRANT ALL PRIVILEGES ON database_name.* TO username@hostname IDENTIFIED BY password;
GRANT ALL PRIVILEGES ON project.* TO kamal@localhost IDENTIFIED BY 'kamal;
4.       Create necessary tables.
CREATE TABLE table_name (col1 type, ….);

Configure My SQL in Glassfish Server
1.       Install the Glassfish server.
2.       Copy the mysql-connector-java-5.1.16-bin.jar file in the Glassfish\lib directory.
3.       Restart the server.
4.       Access the admin console of the Glassfish server and click on the Resources --> JDBC resources
5.       Create JDBC connection pool
a.       Click on the connection pools.
b.      Enter the name of the pool, resource type and database vendor as shown in the picture.


c.       Click next.
d.      Now add additional properties as below.

e.      Click on the connection pool that you created and click the ping button to verify whether the configuration is correct.
6.       Create JDBC resources.
a.       Enter the JNDI name and select the pool that you have created.



Access the My SQL data source which is configured in the glassfish server from servlet.
The below code is used to lookup the MySQL data source configured in the server.
 //Create Initial Context
 InitialContext ctx = new InitialContext ();                   

 //Lookup the data source
                DataSource dataSource = (DataSource) ctx.lookup ("jdbc/mysql");

                //Create connection and statement
                Connection connection = dataSource.getConnection();
                Statement st = connection.createStatement();

Configure My SQL in JBOSS Server
1.       Install the JBOSS server.
2.       Copy the mysql-connector-java-5.1.16-bin.jar file in the default\lib directory.
3.       In the deploy directory, create a xml file which should be ends with ‘-ds.xml’.  Add the below code in that file.

<?xml version="1.0" encoding="UTF-8"?>
<datasources>
  <local-tx-datasource>
        <jndi-name>mysqlds</jndi-name>
<!--<use-java-context>false</use-java-context>-->
        <connection-url>jdbc:mysql://localhost:3306/project </connection-url>
        <driver-class>com.mysql.jdbc.Driver</driver-class>
        <user-name>username</user-name>
        <password>password</password>
        <exception-sorter-class-name>
          com.mysql.jdbc.integration.jboss.ExtendedMysqlExceptionSorter
        </exception-sorter-class-name>
        <valid-connection-checker-class-name>
          com.mysql.jdbc.integration.jboss.MysqlValidConnectionChecker
        </valid-connection-checker-class-name>
        <min-pool-size>5</min-pool-size>
        <max-pool-size>50</max-pool-size>
        <idle-timeout-minutes>5</idle-timeout-minutes>
  </local-tx-datasource>
</datasources>


4.       Restart the server.


Access My SQL data source which is configured in the glassfish server from servlet.
//Create Initial Context
 InitialContext ctx = new InitialContext ();                   

 //Lookup the data source
                DataSource dataSource = (DataSource) ctx.lookup ("java:/mysqlds");

                //Create connection and statement
                Connection connection = dataSource.getConnection();
                Statement st = connection.createStatement();

Note: If you use set use-java-context property to false, the lookup should be
                DataSource dataSource = (DataSource) ctx.lookup ("mysqlds");