Monday 30 May 2011

Reading an XML document using JDOM

ReadingxmlusingJdom.java
/*
 * @Program to read an XML document using JDOM?
 * ReadingxmlusingJdom.java
 * Author:-RoseIndia Team
 * Date:-10-Jun-2008
 */
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import java.io.ByteArrayInputStream;
import java.util.List;
public class ReadingxmlusingJdom {
  public static void main(String[] args) throws Exception {
  String data =
  "<root>" +
  "<Companyname>" +
  "<Employee name=\"Girish\" Age=\"25\">Developer</Employee>" +
  "</Companyname>" +
  "<Companyname>" +
  "<Employee name=\"Komal\" Age=\"25\">Administrator</Employee>" +
  "</Companyname>" +
  "</root>";
  SAXBuilder builder = new SAXBuilder();
  Document document = builder.build(
  new ByteArrayInputStream(data.getBytes()));
  Element root = document.getRootElement();
  List row = root.getChildren("Companyname");
  for (int i = 0; i < row.size(); i++) {
  Element Companyname = (Element) row.get(i);

  List column = Companyname.getChildren("Employee");
  for (int j = 0; j < column.size(); j++) {
 Element Employee = (Element) column.get(j);
 String name = Employee.getAttribute("name").getValue();
 String value = Employee.getText();
 int length = Employee.getAttribute("Age").getIntValue();
 System.out.println("Name = " + name);
 System.out.println("Profile = " + value);
 System.out.println("Age = " + length);
  }
  }
  }
}

Output of the program:-
Name = Girish
Profile = Developer
Age = 25
Name = Komal
Profile = Administrator
Age = 25

Storing xml data into the database


I have to store this file into database

<?xml version="1.0" encoding="ISO-8859-1"?>
<?xml-stylesheet type="text/xsl" href="cdcatalog.xsl"?>
<entertainment category="video">
<movie genre="hollywood">
<title>Ironman2</title>

<artist >
<male>Robert Downing Junior</male>
<female>gwyneth paltrow</female>
</artist>

<country>USA</country>
<company>Columbia pictures</company>
<cost>1000 million</cost>
<release>2010 7 may</release>
</movie>
<movie genre="bollywood">
<title>Kites</title>
<artist >
<male>Hrithik Roshan</male>
<female>barbara mori</female>
</artist>
<country>India</country>
<company>FilmKraft India</company>
<cost>500 million</cost>
<release>2010 17 may</release>
</movie>


</entertainment>

import javax.xml.parsers.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;
import java.sql.*;

public class xml{
public static void main(String[] args) {
try{
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/register";, "root", "root");
Statement st=connection.createStatement();
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse("movie.xml");
NodeList n1= doc.getElementsByTagName("title");
NodeList n2= doc.getElementsByTagName("male");
NodeList n3= doc.getElementsByTagName("female");
NodeList n4= doc.getElementsByTagName("country");
NodeList n5= doc.getElementsByTagName("company");
NodeList n6= doc.getElementsByTagName("cost");
NodeList n7= doc.getElementsByTagName("release");
for(int i=0;i<n1.getLength();i++){
String st1= n1.item(i).getFirstChild().getNodeValue();
String st2= n2.item(i).getFirstChild().getNodeValue();
String st3= n3.item(i).getFirstChild().getNodeValue();
String st4= n4.item(i).getFirstChild().getNodeValue();
String st5= n5.item(i).getFirstChild().getNodeValue();
String st6= n6.item(i).getFirstChild().getNodeValue();
String st7= n7.item(i).getFirstChild().getNodeValue();
System.out.println(st1+" "+st2+" "+st3+" "+st4+" "+st5+" "+st6+" "+st7);
st.executeUpdate("insert into movie(title,male,female,country,company,cost,movierelease) values('"+st1+"','"+st2+"','"+st3+"','"+st4+"','"+st5+"','"+st6+"','"+st7+"')");
}
}
catch(Exception e){
e.printStackTrace();
}
}
}

For the above code, we have created following database table:

CREATE TABLE `movie` (
`id` bigint(255) NOT NULL auto_increment,
`title` varchar(255) default NULL,
`male` varchar(255) default NULL,
`female` varchar(255) default NULL,
`country` varchar(255) default NULL,
`company` varchar(255) default NULL,
`cost` varchar(255) default NULL,
`movierelease` varchar(255) default NULL,
PRIMARY KEY (`id`)
)

Code To check the Range of Ip Address

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class IpRange {
 /**
  * @param args
  * @throws IOException
  */
 public static void main(String[] args) throws IOException {
  // TODO Auto-generated method stub
  String str1="192.168.1.101";
  String str2="192.168.1.199";
  int[] p1 = new int[4];
  int[] p2 = new int[4];
 
  int[] p3 = new int[4];
  System.out.println("Enter valid ip address");
  BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
  String str3=br.readLine();
  String[] s1 =str1.toString().split("\\.");
  String[] s2 =str2.toString().split("\\.");
  String[] s3 =str3.toString().split("\\.");
 
//  p1[0] = Integer.parseInt(s1[0]);
//
//  p1[1] = Integer.parseInt(s1[1]);
  p1[2] = Integer.parseInt(s1[2]);
  p1[3] = Integer.parseInt(s1[3]);
//  p2[0] = Integer.parseInt(s2[0]);
//
//  p2[1] = Integer.parseInt(s2[1]);
  p2[2] = Integer.parseInt(s2[2]);
  p2[3] = Integer.parseInt(s2[3]);
 
//  p3[0] = Integer.parseInt(s3[0]);
// 
//  p3[1] = Integer.parseInt(s3[1]);
  p3[2] = Integer.parseInt(s3[2]);
  p3[3] = Integer.parseInt(s3[3]);
 
  if ((p1[2] < p3[2] && p2[2] > p3[2])&&(p1[3] < p3[3] && p2[3] > p3[3]) )
  {
   System.out.println("valid ip address");
  }
  else
  {
   System.out.println("invalid ip address");
  }
 
 }
}

General pagenation code

//function to return the pagination string
function getPaginationString($page = 1, $totalitems, $limit = 15, $adjacents = 1, $targetpage = "/", $pagestring = "?page=")
{       
    //defaults
    if(!$adjacents) $adjacents = 1;
    if(!$limit) $limit = 15;
    if(!$page) $page = 1;
    if(!$targetpage) $targetpage = "/";
   
    //other vars
    $prev = $page - 1;                                    //previous page is page - 1
    $next = $page + 1;                                    //next page is page + 1
    $lastpage = ceil($totalitems / $limit);                //lastpage is = total items / items per page, rounded up.
    $lpm1 = $lastpage - 1;                                //last page minus 1
   
    /*
        Now we apply our rules and draw the pagination object.
        We're actually saving the code to a variable in case we want to draw it more than once.
    */
    $pagination = "";
    if($lastpage > 1)
    {   
        $pagination .= "<div class=\"pagination\"";
        if($margin || $padding)
        {
            $pagination .= " style=\"";
            if($margin)
                $pagination .= "margin: $margin;";
            if($padding)
                $pagination .= "padding: $padding;";
            $pagination .= "\"";
        }
        $pagination .= ">";
        //previous button
        if ($page > 1)
            $pagination .= "<a href=\"$targetpage$pagestring$prev\">« prev</a>";
        else
            $pagination .= "<span class=\"disabled\">« prev</span>";   
       
        //pages   
        if ($lastpage < 7 + ($adjacents * 2))    //not enough pages to bother breaking it up
        {   
            for ($counter = 1; $counter <= $lastpage; $counter++)
            {
                if ($counter == $page)
                    $pagination .= "<span class=\"current\">$counter</span>";
                else
                    $pagination .= "<a href=\"" . $targetpage . $pagestring . $counter . "\">$counter</a>";                   
            }
        }
        elseif($lastpage >= 7 + ($adjacents * 2))    //enough pages to hide some
        {
            //close to beginning; only hide later pages
            if($page < 1 + ($adjacents * 3))       
            {
                for ($counter = 1; $counter < 4 + ($adjacents * 2); $counter++)
                {
                    if ($counter == $page)
                        $pagination .= "<span class=\"current\">$counter</span>";
                    else
                        $pagination .= "<a href=\"" . $targetpage . $pagestring . $counter . "\">$counter</a>";                   
                }
                $pagination .= "...";
                $pagination .= "<a href=\"" . $targetpage . $pagestring . $lpm1 . "\">$lpm1</a>";
                $pagination .= "<a href=\"" . $targetpage . $pagestring . $lastpage . "\">$lastpage</a>";       
            }
            //in middle; hide some front and some back
            elseif($lastpage - ($adjacents * 2) > $page && $page > ($adjacents * 2))
            {
                $pagination .= "<a href=\"" . $targetpage . $pagestring . "1\">1</a>";
                $pagination .= "<a href=\"" . $targetpage . $pagestring . "2\">2</a>";
                $pagination .= "...";
                for ($counter = $page - $adjacents; $counter <= $page + $adjacents; $counter++)
                {
                    if ($counter == $page)
                        $pagination .= "<span class=\"current\">$counter</span>";
                    else
                        $pagination .= "<a href=\"" . $targetpage . $pagestring . $counter . "\">$counter</a>";                   
                }
                $pagination .= "...";
                $pagination .= "<a href=\"" . $targetpage . $pagestring . $lpm1 . "\">$lpm1</a>";
                $pagination .= "<a href=\"" . $targetpage . $pagestring . $lastpage . "\">$lastpage</a>";       
            }
            //close to end; only hide early pages
            else
            {
                $pagination .= "<a href=\"" . $targetpage . $pagestring . "1\">1</a>";
                $pagination .= "<a href=\"" . $targetpage . $pagestring . "2\">2</a>";
                $pagination .= "...";
                for ($counter = $lastpage - (1 + ($adjacents * 3)); $counter <= $lastpage; $counter++)
                {
                    if ($counter == $page)
                        $pagination .= "<span class=\"current\">$counter</span>";
                    else
                        $pagination .= "<a href=\"" . $targetpage . $pagestring . $counter . "\">$counter</a>";                   
                }
            }
        }
       
        //next button
        if ($page < $counter - 1)
            $pagination .= "<a href=\"" . $targetpage . $pagestring . $next . "\">next »</a>";
        else
            $pagination .= "<span class=\"disabled\">next »</span>";
        $pagination .= "</div>\n";
    }
   
    return $pagination;
}