Thursday, April 16, 2009

JNI Example

How to use JNI ?? Click here to find out.

NativeAdd.java
public class NativeAdd{
native int addNums(int a, int b);
static{
System.loadLibrary("Add");
}
public static void main(String args[]){
NativeAdd na = new NativeAdd();
System.out.println(""+na.addNums(1,2));
}
}

NativeAdd.h
/* DO NOT EDIT THIS FILE - it is machine generated */
#include
/* Header for class NativeAdd */

#ifndef _Included_NativeAdd
#define _Included_NativeAdd
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: NativeAdd
* Method: addNums
* Signature: (II)I
*/
JNIEXPORT jint JNICALL Java_NativeAdd_addNums
(JNIEnv *, jobject, jint, jint);

#ifdef __cplusplus
}
#endif
#endif

NativeAdd.c
#include "jni.h"
#include "NativeAdd.h"
JNIEXPORT jint JNICALL Java_NativeAdd_addNums
(JNIEnv * jenv, jobject jobj, jint a, jint b){
int sum = 0;
sum = a + b;
return sum;
}

How to use JNI (Java Native Interface) in Linux

Java Native Interface allows you to call functions written in different programming languages from java code. For eg C, C++.
Steps involved:
  1. Create your java class & declare the method to be called using JNI with the native keyword.
  2. Compile the java program (javac FileName.java)
  3. Create the C or C++ header (javah -jni FileName) , FileName.h is generated by the machine.
  4. Write your C or C++ program and include the above generated header file.
  5. Create the shared object file (.so) (gcc -path_where_jdk_is_located/jdk1.6/include -path_where_jdk_is_located/jdk1.6/include/linux FileName.c -shared -o filename.so)
Note : Be sure to specify the same "filename.so" in the java program as well...

How to display HTML code on a web page

This article shows you how to display HTML tags or HTML code on a web page...
For example to display :

<b><i>This text is italic and bold</i></b>

instead of This text is italic and bold

You should replace the "<" and ">" by
"& lt;" and "& gt;" respectively.

Please note that there should be no space between "&" and "lt;" or "&" and "gt;"

How to create effective GUI in JAVA

Steps involved in creating a effective GUI (Graphical User Interfaces) in Java

1. Design the GUI on paper.

2. Get feedback from users.

3. Decide if the class that will display the GUI extends a Container, or has references to a Container.

( This choice will effect to some extend the flexibility of the class. If the purpose of a class is to be a GUI then extend from a Container.)

4. Create references to all components used in the GUI as attributes of the class.

5. Implement a contructor that creates instances of all the components used.

6. Select a layout manager fo each of the containers.

7. Assemble the components in a window or a frame.

8. Set the size of the container.

9. Make the container visible.

How to create a simple applet

Steps in creating an Applet
(An applet is a java program that runs in the web browser)

1. The java.applet package must be included.

2. The class must extend from the Applet class.

3. Writing and compiling the Java code.

4. Writing a HTML code that will run the applet.

A Simple Applet

import java.applet.*;
public class MyApplet extends Applet{}
HTML Code

<html>

<body>
<title>Applet Test Page</title>
<h1>Applet Test Page</h1>
<applet code="MyApplet.class" width=250 height=250 name="MyApplet">
</applet>

</body>
</html>

Life cycle of an applet

Invoking a .exe from Java code

Invoking a .exe file from Java

pass the .exe file path as a command line argument

import java.io.*;
public class InvokeExe
{
public static void main(String[] args) throws IOException
{
if (args.length <= 0)
{
System.err.println("Need command to run");
System.exit(-1);
}
Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec(args);
System.exit(0);
}

}

Using the last_insert_id() function

Using the last_insert_id() function

NOTE

This function does'nt work when used with AIR applications... It always returns zero..

mysql> USE test;
Database changed
mysql> CREATE TABLE t (
-> id INT AUTO_INCREMENT NOT NULL PRIMARY KEY,
-> name VARCHAR(10) NOT NULL
-> );
Query OK, 0 rows affected (0.09 sec)

mysql> INSERT INTO t VALUES (NULL, 'Bob');
Query OK, 1 row affected (0.01 sec)

mysql> SELECT * FROM t;
+----+------+
| id | name |
+----+------+
| 1 | Bob |
+----+------+
1 row in set (0.01 sec)

mysql> SELECT LAST_INSERT_ID();
+------------------+
| LAST_INSERT_ID() |
+------------------+
| 1 |
+------------------+
1 row in set (0.00 sec)

mysql> INSERT INTO t VALUES
-> (NULL, 'Mary'), (NULL, 'Jane'), (NULL, 'Lisa');
Query OK, 3 rows affected (0.00 sec)
Records: 3 Duplicates: 0 Warnings: 0

mysql> SELECT * FROM t;
+----+------+
| id | name |
+----+------+
| 1 | Bob |
| 2 | Mary |
| 3 | Jane |
| 4 | Lisa |
+----+------+
4 rows in set (0.01 sec)

mysql> SELECT LAST_INSERT_ID();
+------------------+
| LAST_INSERT_ID() |
+------------------+
| 2 |
+------------------+
1 row in set (0.00 sec)

Storing user input into a database using PHP

TABLE CREATION

CREATE TABLE `employee` (
`id` int(10) default NULL,
`name` varchar(20) default NULL,
`salary` int(10) default NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

HTML CODE

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style type="text/css">
<!--
.style1 {
font-size: larger;
font-weight: bold;
color: #FF0000;
}
-->
</style>
</head>

<body>
<form action="insert.php" method="post" name="form1" target="_self" id="form1">
<label></label>
<p>
<label></label>
<label></label><label></label>
<span class="style1">Employee Details</span></p>
<table width="323" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="146"><label>ID</label></td>
<td width="171"><input type="text" name="idval" id="idval" /></td>
</tr>
<tr>
<td>Name</td>
<td><input type="text" name="nameval" id="nameval" /></td>
</tr>
<tr>
<td>Salary</td>
<td><input type="text" name="salval" id="salval" /></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" name="submitbutton" id="submitbutton" value="Submit Details" /></td>
</tr>
</table>
</form>
</body>
</html>

PHP CODE (insert.php)

<?php
$con=mysql_connect("localhost","root","");
mysql_select_db("employee",$con);
$idval=$_POST['idval'];
$nameval=$_POST["nameval"];
$salval=$_POST["salval"];
$query="insert into employee values($idval,'$nameval',$salval)";
mysql_query($query);
mysql_close($con);
include ("show.php");
?>

PHP CODE (show.php)

<?php

$con = mysql_connect("localhost", "root","");
mysql_select_db("employee",$con);
$query="select * from employee";
$result=mysql_query($query);
echo '<table border="1" align="center">';
while($row=mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>".$row["id"]."</td>";
echo "<td>".$row["name"]."</td>";
echo "<td>".$row["salary"]."</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($con);

?>

Database insert operation using PHP

TABLE STRUCTURE

Product
id integer primary key auto_increment,name varchar(50),price decimal(10,2),category_id integer,imagepath varchar(100),updateDay date
PHP CODE

<?php
$con=mysql_connect("localhost","root","");
mysql_select_db("phpDB",$con);
$nameVal="DVD";
$priceVal="25";
$imagepathVal="c:/image.jpg";
$updateDayVal="2008-09-10";
$categoryIdVal="156";
$query='insert into product(name,price,imagepath,updateDay,category_id)
values("'.$nameVal.'",'.$priceVal.',"'.
$imagepathVal.'","'.$updateDayVal.'",'
.$categoryIdVal.")";
mysql_query($query);
$query="commit";
mysql_query($query);
mysql_close($con);
?>

Reading table contents into an XML file

TABLE STRUCTURE

Product
id integer primary key auto_increment,name varchar(50),price decimal(10,2),category_id integer,imagepath varchar(100),updateDay date

PHP CODE

<?php
$con=mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
else
{

mysql_select_db("phpDB",$con);
$query="select * from product";
$result=mysql_query($query,$con);
if (!$file=fopen("report.xml","w+"))
{
echo "Cannot open file";
exit;
}
else
{

$toBeWritten=''."\n\n"."<productinfo>"."\n\n";
while($row=mysql_fetch_array($result))
{
$toBeWritten.="\t<product>"."\n\n".
"\t\t<id>".$row["id"]."</id>"."\n\n".
"\t\t<name>".$row["name"]."</name>"."\n\n".
"\t\t<price>".$row["price"]."</price>"."\n\n".
"\t\t<imagepath>".$row["imagepath"]."</imagepath>"."\n\n".
"\t\t<updateday>".$row["updateDay"]."</updateday>"."\n\n".
"\t\t<category_id>".$row["category_id"]."</category_id>"."\n\n".
"\t</product>"."\n\n";
}
$toBeWritten.="</productinfo>"."\n\n";
if (fwrite($file, $toBeWritten) === FALSE)
{
echo "Cannot write to file";
exit;
}

fclose($file);
$query="commit";
mysql_query($query);
mysql_close($con);
}
}

?>

Database delete operation using PHP

TABLE STRUCTURE

Product

id integer primary key auto_increment,name varchar(50),price decimal(10,2),category_id integer,imagepath varchar(100),updateDay date

PHP CODE

<?php
$idStr=$_POST["idStrVal"];
$idVal=strtok($idStr,'|');
$con=mysql_connect("localhost","root","");
mysql_select_db("phpDB",$con);
while($idVal!==FALSE)
{
mysql_query("delete from product where id=".$idVal);
$idVal=strtok("|");
}
mysql_query("commit");
mysql_close($con);
?>

Database select operation using PHP

TABLE STRUCTURE

Product

id integer primary key auto_increment,name varchar(50),price decimal(10,2),category_id integer,imagepath varchar(100),updateDay date

PHP CODE

<?php
$con=mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
else
{

mysql_select_db("phpDB",$con);
$query="select * from product";
$result=mysql_query($query,$con);
while($row=mysql_fetch_array($result))
{
echo $row["id"].$row["name"].$row["price"].$row["imagepath"].$row["updateDay"].$row["category_id"];
}
}
?>

Using Remote Object with LCDS

Download the .class file below and copy it to lcds\jrun4\servers\default\samples\WEB-INF\classes

Add the following lines of code to your source code


<!--Signature of executeSQL(DBname,Query) -->

<mx:RemoteObject id="sqlObj" destination="mysqladmin">
<mx:method name="executeSQL">
</mx:method>
</mx:RemoteObject>

Edit the following files

1. lcds\jrun4\servers\default\samples\WEB-INF\flex\services-config.xml
Add the following entry

<channel-definition id="my-amf" class="mx.messaging.channels.AMFChannel">
<endpoint url="http://static IP:8700/samples/messagebroker/amf" class="flex.messaging.endpoints.AMFEndpoint"/>
<properties>
<polling-enabled>false</polling-enabled>
</properties>
</channel-definition>

2. lcds\jrun4\servers\default\samples\WEB-INF\flex\remoting-config.xml
Add the following entry
<destination id="mysqladmin">
<properties>
<source>MySQLAdmin</source>
</properties>
</destination>

NOTE

1. LCDS server must be running
2. A static IP is required for LCDS to be used with AIR Applications

Using PHP with Flex

TABLE STRUCTURE

Product

id integer primary key auto_increment,name varchar(50),price decimal(10,2),category_id integer,imagepath varchar(100),updateDay date

FLEX CODE

<?xml version="1.0" encoding="utf-8"?>
<mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationComplete="{this.nativeWindow.maximize()}">
<mx:Script source="assets/dbUpdaterscript.as"/>
<mx:Panel width="589" height="610" layout="absolute" title="Product Details" horizontalCenter="3" verticalCenter="15">
<mx:Grid width="506.5" height="376" horizontalCenter="0" verticalCenter="-60">
<mx:GridRow width="100%" height="100%">
<mx:GridItem width="141" height="100%" verticalAlign="middle">
<mx:Label text="Product Name"/>
</mx:GridItem>
<mx:GridItem width="100%" height="100%" verticalAlign="middle" horizontalAlign="left">
<mx:TextInput id="nameTB" width="247"/>
</mx:GridItem>
</mx:GridRow>
<mx:GridRow width="100%" height="100%">
<mx:GridItem width="100%" height="100%" verticalAlign="middle">
<mx:Label text="Product Price"/>
</mx:GridItem>
<mx:GridItem width="100%" height="100%" verticalAlign="middle" horizontalAlign="left">
<mx:TextInput id="priceTB" width="247"/>
</mx:GridItem>
</mx:GridRow>
<mx:GridRow width="100%" height="100%">
<mx:GridItem width="100%" height="100%" verticalAlign="middle">
<mx:Label text="Product Category"/>
</mx:GridItem>
<mx:GridItem width="100%" height="100%" verticalAlign="middle" horizontalAlign="left">
<mx:TextInput id="categoryIdTB" width="247"/>
</mx:GridItem>
</mx:GridRow>
<mx:GridRow width="100%" height="100%">
<mx:GridItem width="100%" height="100%" verticalAlign="middle">
<mx:Label text="Last Updated"/>
</mx:GridItem>
<mx:GridItem width="100%" height="100%" verticalAlign="middle" horizontalAlign="left">
<mx:DateField showToday="true" id="dateSelecter" width="247" formatString="YYYY-MM-DD" change="onDateChange(event)"/>
</mx:GridItem>
</mx:GridRow>
<mx:GridRow width="100%" height="100%">
<mx:GridItem width="100%" height="100%" verticalAlign="middle">
<mx:Label text="Product Image"/>
</mx:GridItem>
<mx:GridItem width="100%" height="100%" verticalAlign="middle">
<mx:TextInput id="imagePathTB" width="165"/>
<mx:Button label="Browse" id="browseButton" click="browseForFile(event)" width="74"/>
</mx:GridItem>
</mx:GridRow>
</mx:Grid>
<mx:Button x="233" y="443" label="SUBMIT INFO" click="submitData(event)"/>
</mx:Panel>
</mx:WindowedApplication>

ACTIONSCRIPT CODE (databaseupdaterscript.as)

// ActionScript file
import flash.events.Event;
import flash.filesystem.File;
import flash.net.FileFilter;

import mx.rpc.http.HTTPService;
private var dayStr:String;
private var monthStr:String;
private var yearStr:String;
[Bindable]
private var dateStr:String;
private var file:File;
private var fileFilter:FileFilter;
private var phpInvoker:HTTPService=new HTTPService();
public function browseForFile(e:Event):void
{
file=new File();
fileFilter=new FileFilter("Image","*.jpg;*.png;*.tiff;*.gif;");
file.browse([fileFilter]);
file.addEventListener(Event.SELECT,fileSelectHandler);
}
private function fileSelectHandler(e:Event):void
{
imagePathTB.text=file.url.substr(8,file.url.length);
}
public function onDateChange(e:Event):void
{
yearStr=e.currentTarget.selectedDate.getFullYear();
dayStr=e.currentTarget.selectedDate.getDate();
monthStr=(e.currentTarget.selectedDate.getMonth()+1);
dateStr=yearStr+"/"+monthStr+"/"+dayStr;
}
public function submitData(e:Event):void
{
var postData:Object={nameVal:nameTB.text,priceVal:priceTB.text,imagepathVal:imagePathTB.text
,updateDayVal:dateStr,categoryIdVal:categoryIdTB.text}
phpInvoker.url="http://localhost/test/dbUpdater.php";
phpInvoker.method="POST";
phpInvoker.send(postData);

}

PHP CODE (dbupdater.php)

<?php
include("../database/db.php");
$nameVal=$_POST["nameVal"];
$categoryVal=$_POST["categoryVal"];
$priceLevel0=$_POST["priceLevel0"];
$priceLevel1=$_POST["priceLevel1"];
$priceLevel2=$_POST["priceLevel2"];
$imagepathVal=$_POST["imagepathVal"];
$descriptionVal=$_POST["descriptionTxt"];
$today=date("Y-m-d");

$query="select category_id from category where category_name='$categoryVal'";
$result=mysql_query($query,$db);
if($row=mysql_fetch_array($result))
{
$categoryVal=$row['category_id'];
}
$query ="insert into product(`product_name`, `category_id`, `price_level0`, `price_level1`, `price_level2`, `product_image`,
`update_date`, `description`) values('$nameVal',$categoryVal,$priceLevel0,$priceLevel1,$priceLevel2,'$imagepathVal','$today','$descriptionVal')";
echo "OK";
mysql_query($query,$db);
$query="commit";
mysql_query($query,$db);
mysql_close($db);
?>

Using HttpService to read the contents of an external file

<?xml version="1.0" encoding="utf-8"?>
<mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationComplete="getMenuData.send()">
<mx:HTTPService id="getMenuData" url="menudata.txt" resultFormat="flashvars"/>
<mx:ComboBox x="269" y="134" dataProvider="{getMenuData.lastResult.currencies.split('|')}"></mx:ComboBox>
</mx:WindowedApplication>


The menudata.txt file

label=currency&currencies=Dollar|Rupee|Dinar|Pound|Sterling

Wednesday, April 15, 2009

Creating a custom context menu

<?xml version="1.0" encoding="utf-8"?>
<mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationComplete="initApp()">
    <mx:DataGrid x="231" y="45" id="sampleGrid" dataProvider="{sampleXML.person}">
        <mx:columns>
            <mx:DataGridColumn headerText="Name" dataField="name"/>
            <mx:DataGridColumn headerText="Age" dataField="age"/>
        </mx:columns>
    </mx:DataGrid>
    <!--This is the XML used as the data provider for the data grid-->
    <mx:XML xmlns="" id="sampleXML" format="e4x">
        <people>
            <person>
                <name>John</name>
                <age>20</age>
            </person>
            <person>
                <name>Sean</name>
                <age>22</age>
            </person>
            <person>
                <name>Max</name>
                <age>25</age>
            </person>
        </people>        
    </mx:XML>
    <!--This is the XML used for the context menu-->
    <mx:XML format="e4x" id="menuData">
        <root>
            <menuitem label="Menu Item 1"/>
            <menuitem label="Menu Item 2"/>
         </root>
    </mx:XML>
    <mx:Script>
        <![CDATA[
            import mx.controls.FlexNativeMenu;
            import mx.events.FlexNativeMenuEvent;
            import mx.controls.Alert;
            private var dgContextMenu:FlexNativeMenu;
            public function initApp():void
            {
                dgContextMenu=new FlexNativeMenu();
                createContextMenu();
            }
            private function createContextMenu():void
            {
                dgContextMenu.dataProvider=menuData;
                dgContextMenu.labelField="@label";
                dgContextMenu.showRoot=false;
                dgContextMenu.setContextMenu(sampleGrid);
                dgContextMenu.addEventListener(FlexNativeMenuEvent.ITEM_CLICK,onItemClick);
            }
            private function onItemClick(e:FlexNativeMenuEvent):void
            {
                switch(e.index)
                {
                    case 0:
                            Alert.show("You clicked Menu Item 1");        
                            break;
                    case 1:
                            Alert.show("You clicked Menu Item 2");        
                            break;    
                }
            }
        ]]>
    </mx:Script>    
</mx:WindowedApplication>

Displaying XML contents in a datagrid

<?xml version="1.0" encoding="utf-8"?>
<mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
<mx:DataGrid x="114" y="92" dataProvider="{sampleXML.product}">
<mx:columns>
<mx:DataGridColumn headerText="NAME" dataField="name"/>
<mx:DataGridColumn headerText="PRICE" dataField="price"/>
<mx:DataGridColumn headerText="AVAILABILITY" dataField="availability"/>
</mx:columns>
</mx:DataGrid>
<mx:XML xmlns="" id="sampleXML" format="e4x">
<items>
<product>
<name>A</name>
<price>1234</price>
<availability>Yes</availability>
</product>
<product>
<name>B</name>
<price>5678</price>
<availability>Yes</availability>
</product>
<product>
<name>C</name>
<price>910</price>
<availability>NO</availability>
</product>
</items>
</mx:XML>
</mx:WindowedApplication>

Deleting Datagrid contents

<?xml version="1.0" encoding="utf-8"?>
<mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
<mx:DataGrid id="studentDetails" x="216" y="41" dataProvider="{listCollection}" itemClick="onItemClick(event)">
<mx:columns>
<mx:DataGridColumn headerText="Name" dataField="name"/>
<mx:DataGridColumn headerText="Age" dataField="age"/>
<mx:DataGridColumn headerText="Sex" dataField="sex"/>
</mx:columns>
</mx:DataGrid>
<mx:Button x="311" y="237" label="Delete Student" click="onClick(event)" id="deleteButton" enabled="false"/>
<mx:XML id="sampleXML" format="e4x" xmlns="">
<students>
<student>
<name>Michael</name>
<age>12</age>
<sex>Male</sex>
</student>
<student>
<name>Jesse</name>
<age>15</age>
<sex>Female</sex>
</student>
<student>
<name>Ben</name>
<age>10</age>
<sex>Male</sex>
</student>
</students>
</mx:XML>
<mx:XMLListCollection id="listCollection" source="{sampleXML.student}"/>
<mx:Script>
<![CDATA[
import mx.events.ListEvent;
import mx.controls.Alert;
public function onItemClick(e:ListEvent):void
{
deleteButtonEnableToggle(true);
}
public function onClick(e:Event):void
{
deleteButtonEnableToggle(false);
listCollection.removeItemAt(studentDetails.selectedIndex);
listCollection.refresh();
}
public function deleteButtonEnableToggle(val:Boolean):void
{
deleteButton.enabled=val;
}
]]>
</mx:Script>
</mx:WindowedApplication>