Friday, January 28, 2011

Cannot find the tag library descriptor for "http://java.sun.com/jsp/jstl/core--Jstl Error in eclipse

If jstl error 
Download from http://jakarta.apache.org/site/downloads/downloads_taglibs-standard-1.0.cgi
and include standard.jar and jstl.jar in build path and lib folder

Steps to Install Mysql on Windows

Download 
mysql-5.0.22-win32.exe and Install as standard.
mysql-administrator-1.1.9-win

http://dev.mysql.com/downloads/mysql/
http://techtracer.com/2008/06/09/3-easy-steps-to-install-mysql-on-windows-xp/
start mysql client from desktop>Start> program files>mysql


mysql>
 create database employees;
 show databases;
 USE employees;
CREATE TABLE employee_data
(
emp_id int unsigned not null auto_increment primary key,

f_name varchar(20),
l_name varchar(20),
title varchar(30),
age int,
yos int,
salary int,
perks int,
email varchar(60)
);

Also can use mysql Administrator to check the creation of table and database.

Ajax Mysql Php Example

<html>
<head>
   
<script src=
"http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"
type="text/javascript">
</script>

    <script type="text/javascript">
      function register(){
    //    window.open("/welcome.html",'welcome','width=300,height=200,menubar=yes,status=yes,location=yes,toolbar=yes,scrollbars=yes');

        $.ajax({
            type: "POST",
            url: "/ReturnData.php",
            data:     "username=" + document.getElementById("username").value + 
                    "&email=" + document.getElementById("email").value,
            success: function(html){
                $("#response").html(html);
            }
        });
        }
    </script>
  </head>



<body>
    <form action="" method="post">
            <p>
                <label for="name">Name:</label><br />
                <input type="text" name="username" id="username" size="25" />
            </p>
            <p>
                <label for="email">Email:</label><br />
                <input type="text" name="email" id="email" size="25" />
            </p>
            <p>
                <input type="button" name="submit" id="submit" value="Subscribe" onclick="register()"/>
            </p>
            <ul id="mylist">
                <li><a rel="3" href="/#dave">Dave's email address</a></li>
                <li><a rel="4" href="/#erik">Erik's email address</a></li>
            </ul>

<p id="info">&nbsp;</p> 
    <div id="response">

    </div>
</form>
</body>
</html>


<?php
                $db_host = 'localhost';
                $db_user = 'root';
                $db_pass = 'root';
                $db_name = 'db';

        $Username = $_POST['username'];
        $Email    = $_POST['email'];
      
        $connect = mysql_connect( $db_host, $db_user, $db_pass ) or die( mysql_error());
        $connection = $connect;

        mysql_select_db( $db_name, $connect ) or die( mysql_error() );

         echo $Username;
        $qInsertUser = mysql_query(" INSERT INTO test
                                     VALUES ('$Username','$Email')
                                  ");
        $qGetDetails = mysql_query("SELECT * FROM test");
    
    
         $num=mysql_numrows($qGetDetails);
         echo $num;
         echo "hi";
        $i=0;
        while ($row=mysql_fetch_array($qGetDetails)) {
        echo "<br>".$row['name'];
        }
    ?>

Ajax Json Php Example

Ajax Json Php example
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
<script type="text/javascript">
$('document').ready(function() 
{ 
    $('#mylist a').click(function ()
    {
        var id = $(this).attr('rel');

        $.getJSON('/return.php', {'id' : id}, parseInfo);
    });
});

function parseInfo(data)
{
    $('#info').html(data.name +', '+ data.email);
}
</script> 
</head>
<body>
<ul id="mylist">
   <li><a rel="3" href="#">Dave's email address</a></li>
    <li><a rel="4" href="#">Erik's email address</a></li> 
</ul>

<p id="info">&nbsp;</p> 
</body>
</html>

 
<?php

// see if we have a GET variable 'id' set
$id = (isset($_GET['id']) && !empty($_GET['id'])) ? $_GET['id'] : 0;

// pretend this is a query to a database to fetch the wanted users.
$users[3] = array('name' => 'Dave', 'email' => 'dave@adeepersilence.be');
$users[4] = array('name' => 'Erik', 'email' => 'erik@bauffman.be');

// only if an ID was given and the key exists in the array, we continue
if(!empty($id) && key_exists($id, $users))
{
    // echo (not return) the wanted record from the users array
    echo json_encode($users[$id]);
}

?>

Php Ajax Mysql Example

<html>
<head>
   
<script src=
"http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"
type="text/javascript">
</script>

    <script type="text/javascript">
      function register(){
        alert("hi" +document.getElementById("username").value); 
        $.ajax({
            type: "POST",
            url: "/submit_data.php",
            data:     "username=" + document.getElementById("username").value + 
                    "&email=" + document.getElementById("email").value,
            success: function(html){
                $("#response").html(html);
            }
        });
    
        }
    </script>
  </head>



<body>
    <form action="" method="post">
            <p>
                <label for="name">Name:</label><br />
                <input type="text" name="username" id="username" size="25" />
            </p>
            <p>
                <label for="email">Email:</label><br />
                <input type="text" name="email" id="email" size="25" />
            </p>
            <p>
                <input type="button" name="submit" id="submit" value="Subscribe" onclick="register()"/>
            </p>
<div id="response">
        <!-- Our message will be echoed out here -->
    </div>
</form>
</body>
</html>


<?php
                $db_host = 'localhost';
                $db_user = 'root';
                $db_pass = 'root';
                $db_name = 'db';

        $Username = $_POST['username'];
        $Email    = $_POST['email'];
      
        $connect = mysql_connect( $db_host, $db_user, $db_pass ) or die( mysql_error());
        $connection = $connect;

        mysql_select_db( $db_name, $connect ) or die( mysql_error() );

     
        $qInsertUser = mysql_query(" INSERT INTO test
                                     VALUES ('$Username','$Email')
                                  ");

       if ($qInsertUser){
           echo "You are now subscribed to our newsletter. Thank you!";
        } else {
            echo "Error!";
        }

    ?>

Good link for php and apache2

Upload file example php

Test.html
<html>
<body>

<form action="upload_file.php" method="post"
enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file" /> 
<br />
<input type="submit" name="submit" value="Submit" />
</form>

</body>
</html>
 
----------------
<?php
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/pjpeg"))
&& ($_FILES["file"]["size"] < 20000))
  {
  if ($_FILES["file"]["error"] > 0)
    {
    echo "Error: " . $_FILES["file"]["error"] . "<br />";
    }
  else
    {
    echo "Upload: " . $_FILES["file"]["name"] . "<br />";
    echo "Type: " . $_FILES["file"]["type"] . "<br />";
    echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
    echo "Stored in: " . $_FILES["file"]["tmp_name"];
    }
  }
else
  {
  echo "Invalid file";
  }
?>
 
Upload.php
<?php
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/pjpeg"))
&& ($_FILES["file"]["size"] < 20000))
  {
  if ($_FILES["file"]["error"] > 0)
    {
    echo "Return Code: " . $_FILES["file"]["error"] . "<br />";

    }
  else
    {
    echo "Upload: " . $_FILES["file"]["name"] . "<br />";
    echo "Type: " . $_FILES["file"]["type"] . "<br />";
    echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
    echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";

    if (file_exists("upload/" . $_FILES["file"]["name"]))
      {
      echo $_FILES["file"]["name"] . " already exists. ";
      }
    else
      {
      move_uploaded_file($_FILES["file"]["tmp_name"],
      "upload/" . $_FILES["file"]["name"]);
      echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
      }
    }
  }
else
  {
  echo "Invalid file";
  }
?>

Change the root directory in apache2 other than htdocs


In htttpd.conf file in Apache installation folder change the below C:/ProgramFiles/Apache2 repoint to the folderr where you want to place files
DocumentRoot "C:/phpfiles/php"
Directory "C:/phpfiles/php"


or under sites-enabled  folder change DocumentRoot and Directory in 000-default

Install Php on Windows


Steps:
1.  http://www.php.net/downloads.php download the zip file unzip at C:/php
Download and install apache2 http://httpd.apache.org/download.cgi
httpd-2.2.17-win32-x86-no_ssl.msi

2 Go C:/Program Files/Apache2. In httpd.conf of Apache Software Foundation/conf add the following code


LoadModule php5_module "c:/php/php5apache2_2.dll"
AddHandler application/x-httpd-php .php
3.
# configure the path to php.ini which is present at location C:/php find
PHPIniDir "C:/php"
4. In C:\Apache Software Foundation\Apache2.2\htdocs place the file
test.php

echo "Hello World";
?>
Now start apache2 by clicking on exe in bin folder.

If you want to change the path to other than htdocs go to sites-enabled folder 000-default  in C:/Program File/Apache2....
and change the DocumentRoot to folder you want.

5. http://localhost:8080/test.php should generate the hello world.
Reference

Install Mysql http://harshal-techapps.blogspot.com/2011/01/steps-to-install-mysql-on-windows.html
To configure with Mysql

1. Uncomment the line extension=php_mysql.dll in php.ini which is present in C:/php
2. Set this path extension_dir = "C:\php\ext" in php.ini
3. To change the upload file location
;upload_tmp_dir =
4. Uncomment session.save_path = "C:\WINDOWS\temp"
5. Copy the php.ini to C:\Windows
6.Next we must add the PHP directory to the Windows PATH. To do this, click: Start > My Computer > Properties > Advanced > Environment Variables. Under the second list (System Variables), there will be a variable called "Path". Select it and click "Edit". Add ";C:\php" to the very end of the string and click "OK".
7. In mysql follow the steps below:
use test;
create table name ()
select * from name;
8. Place the attached file at location : C:\Apache Software Foundation\Apache2.2\htdocs
9. Restart the computer and all the servers.
11. Should display
ID: 1
Name: John
Hello
Links for linux

Java NameSpace with XML


 import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.CharacterData;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;


public class NameSpaceXMLExample {
   
    public static final void main(String[] args) {
       
       String xmlFile="/home/localadmin/test2.xml";
       
        try {
            NameSpaceXMLExample xmlTester = new NameSpaceXMLExample(xmlFile);
        }
        catch (Exception e) {
            System.out.println( e.getClass().getName() +": "+ e.getMessage() );
        }
    }
   
    public NameSpaceXMLExample(String xmlFile) throws ParserConfigurationException, SAXException, IOException {


        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        System.out.println("DocumentBuilderFactory: "+ factory.getClass().getName());
       
        factory.setNamespaceAware(true);
        factory.setValidating(true);
        factory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaLanguage", "http://www.w3.org/2001/XMLSchema");
       
        // Specify our own schema - this overrides the schemaLocation in the xml file
        //factory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaSource", "file:./test.xsd");
       
        DocumentBuilder builder = factory.newDocumentBuilder();
        builder.setErrorHandler( new SimpleErrorHandler() );


        Document document = builder.parse(xmlFile);
        String customerMakeAndModel ="";
        try{
            NodeList nodes = document.getElementsByTagName("ns0:Test");
                Element line = (Element) nodes.item(0);
                                //String data = getCharacterDataFromElement(line);
                                if (getCharacterDataFromElement(line) != null) {
                                    customerMakeAndModel=getCharacterDataFromElement(line);
                                    System.out.println(customerMakeAndModel);
                                } else {
                                    customerMakeAndModel="";
                                }
        }catch(Exception e){
            customerMakeAndModel="";
        }   
       
        Node rootNode  = document.getFirstChild();
   //     System.out.println("Root node: "+ rootNode.getNodeName()  );
    }

public static String getCharacterDataFromElement(Element e) {
    Node child = e.getFirstChild();
    if (child instanceof CharacterData) {
        CharacterData cd = (CharacterData) child;
        return cd.getData();
    }
    return "";
}
}

XML file
 ;ltns0:ABC xmlns:ns0="http://ABC/1.0">
 ;lttns0:Test<ABC;&gt

 ;lt/ns0:ABC>

Java NameSpace with XML


 import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;


public class NameSpaceXMLExample {
  
    public static final void main(String[] args) {
      
       String xmlFile="/home/localadmin/test2.xml";
      
        try {
            NameSpaceXMLExample xmlTester = new NameSpaceXMLExample(xmlFile);
        }
        catch (Exception e) {
            System.out.println( e.getClass().getName() +": "+ e.getMessage() );
        }
    }
  
    public NameSpaceXMLExample(String xmlFile) throws ParserConfigurationException, SAXException, IOException {


        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        System.out.println("DocumentBuilderFactory: "+ factory.getClass().getName());
      
        factory.setNamespaceAware(true);
        factory.setValidating(true);
        factory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaLanguage", "http://www.w3.org/2001/XMLSchema");
      
        // Specify our own schema - this overrides the schemaLocation in the xml file
        //factory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaSource", "file:./test.xsd");
      
        DocumentBuilder builder = factory.newDocumentBuilder();
        builder.setErrorHandler( new SimpleErrorHandler() );


        Document document = builder.parse(xmlFile);
        Node rootNode  = document.getFirstChild();
        System.out.println("Root node: "+ rootNode.getNodeName()  );
    }





  
}

Read from a file in java

    public static String readFile(){
        System.out.println("Reading Dummy file");
        StringBuilder contents = new StringBuilder();
        File aFile = new File("/home/localadmin/test.xml");
        try {
              BufferedReader input =  new BufferedReader(new FileReader(aFile));
              try {
                String line = null;
                while (( line = input.readLine()) != null){
                  contents.append(line);
                  contents.append(System.getProperty("line.separator"));
                }
              }
              finally {
                input.close();
              }
            }
            catch (IOException ex){
              ex.printStackTrace();
            }
           
    return contents.toString();


    }