Archive for the ‘Web Development’ Category




Introduction

Few days back I was trying to port my Android Game Development Kit (GDK) into HTML5 (JavaScript based GDK), for that I got a chance to explore Classes (object oriented) in JavaScriptPlease note that I am not an expert of JavaScript, and in this tutorial I have tried to cover all the searches and efforts that I put to get my JavaScript code running in Object Oriented (Classes).

To Keep this tutorial simple I will use very simple example instead of complex game related domain ideas. and will not discuss what OOP is and how and where classes are used in greater or expert level details. I will assume that readers have the knowledge of object oriented programming (using classes in code).

In real life we see different animals. All the animals have few characteristics, habits and actions, and whenever we have to handle such an information for more than one (repeatedly) we think in terms of a Class in computer software programming. Similarly there is another thing which drive us to use class and that is grouping the similar actions and characteristics in one place, again OOP Class is our best shot.

We know that most of the animals have names(Puppy, ScubyDuby), type(Cat, Dog, Lion, Elephant, Tiger etc), color, age etc. so we will group all these information into one Class (Class is basic template or blueprint for some thing)

Animal{
    name
    type
    color
    age
}

Now for each different animal we will create an object (Instantiation of object of the blueprint/template (i.e. Class)). An object of type Animal(Class). and then we will populate the attributes with the required information.
examples are as follows.

Animal
{
    name: "Tango"
    type: "Lion"
    color: "Yellow"
    age: "2 years"
}
Animal
{
    name: "Suzi"
    type: "Elephant"
    color: "Black"
    age: "4 years"
}

We can see that we have grouped and encapsulated relevant information of a particular real life object(the one we see in real world). and now we can store and manipulate this information easily.

before jumping to actual class, lets compare ordinary way and using classes.

	//populating variables
    var animal_1_name = "Tango";
    var animal_1_type = "Lion";
    var animal_1_color = "Yellow";
    var animal_1_age = "2 years";

    var animal_2_name = "Suzi";
    var animal_2_type = "Elephant";
    var animal_2_color = "Black";
    var animal_2_age = "5 years";

    //printing this information
    var str = "** Here is detail of first animal **\n";
    str += "Name: "+ animal_1_name +"\n";
    str += "Type: "+ animal_1_type +"\n";
    str += "Color: "+ animal_1_color +"\n";
    str += "Age: "+ animal_1_age +"\n";

    str += "** Here is detail of Second animal **\n";
    str += "Name: "+ animal_2_name +"\n";
    str += "Type: "+ animal_2_type +"\n";
    str += "Color: "+ animal_2_color +"\n";
    str += "Age: "+ animal_2_age +"\n";

    alert(str);

We can see that there is no such boundary or nothing the code is pretty much messed up and more lines of code. which makes it less manageable ( Consider an example in which we require the information of 10 different animals)

Similarly OOP based code

   var animal_1 = new Animal("Tango", "Lion", "Yellow", "2 Years");
   var animal_2 = new Animal("Suzi", "Elephant", "Black", "5 Years");
   alert(animal_1.getDetail());
   alert(animal_2.getDetail());

We can see our code is very nice and clean and we only concentrate on our logic in main script instead of handling different variables or related information. Similarly we are reusing functionality. likegetDetail() will format string as we want. moreover if in the future we want to change some formatting or want to add an extra field, we don’t have to change code for 10 different animals and resolving the code changes. We will only make a change in relevant class that will be shared(depicted) everywhere, our main script code will be almost intact.

That’s it, I will not go in further object oriented details

Now lets get straight to JavaScript class.

2. JavaScript Class

Every function in JavaScript can behave as a class, and that’s how we define classes in JavaScript.

//class declaration + constructor of class
function Animal( name , age ){
	this.name = name; 
  	this.age = age;
}

//class attributes definitions
Animal.prototype.name = "Animal";
Animal.prototype.age = 0;

//class functions declaration and body
Animal.prototype.getDetail = function(){
	return "Name: " + this.name + "\n"
		  +"Age: "+this.age + "\n";
}

In example above we have defined a class(Animal) that have only 2 attributes (name and age) and only one method/function (getDetail())

2.1 Implementation

var a = new Animal("Kitty", 2);
//alert complete detail
alert(a.getDetail());

//access an attribute of a class (you can also write getter and setter function)
a.name = "Mimi";

//alert complete detail
alert(a.getDetail());

2.2 Access Modifier in JavaScript

2.2.1 Public

In our Animal class we have created 2 variables name and age. both are public variable as we have defined them with following line of code.

Animal.prototype.name = "Animal";
Animal.prototype.age = 0;

//these are accessible with this with in the class methods
this.name

//and can be accessed out of the class by using its instantiated object
objAnimal.name

In simple terms where ever we use this operator with a variable it mean its a public variable.

this.name = name; 
this.age = age;

  return "Name: " + this.name + "\n"
		  +"Age: "+this.age + "\n";

2.2.2 Private

In order to have private variables we have to trick JavaScript in following way.

function Human() {

    //public
    this.name = "Mazhar Hassan";

    //private
    var _age = 5;

    //Getter/Setter to access private variables
    //Please note these getter setter themselves will be public
    this.getAge = function(){
        return _age;
    };
    this.setAge = function(age){
        _age = age;
    };
}
Human.prototype.name = "";
Human.prototype.getName = function() {
	return this.name;
}

//Now we can access this private variable
var h = new Human();
alert(h.getAge());
h.setAge(23);
alert(h.getAge());

2.3 Static variable in JavaScript

Again there is no reserve word for creating static variables, its the way how we access that variable. These are private variables we defined in previous example, only difference is getter and setter methods.

function Human() {

    //public
    this.name = "Mazhar Hassan";

    //private
    var _age = 5;

    //Getter/Setter to access private variables
    //Please note these getter setter themselves will be public
    this.getAge = function(){
        return _age;
    };
    this.setAge = function(age){
        _age = age;
    };

    //private static variable
    var _password = "";

    //public getter/setter for static variable
    Human.prototype.setPassword = function( password ) {
    	_password = password;
    }
    Human.prototype.getPassword = function() {
    	return _password;
    }

}
Human.prototype.name = "";
Human.prototype.getName = function() {
	return this.name;
}

//IMPLEMENTATION --------------------------------------------------
var h1 = new Human();
var h2 = new Human();

h1.setPassword("xyz");
h2.setPassword("abc");

alert(h1.getPassword()+" = "+h2.getPassword()); //will print "abc = abc"

3. Inheritance in JavaScript

Concept of inheritance in JavaScript is same like few other languages. As we already know in order to create a class in JavaScript we have to define a function that can behave as a class. lets define a Dogclass, that will inherit Animal class.

//Dog class inherits Animal Class
Dog.prototype = new Animal();

//Dog Class + constructor
function Dog( name , age){
	this.name = name;
	this.age = age
}

//speak function of Dog
Dog.prototype.Speak = function(){
	alert("waoo waoo");
}

3.1 Implementation

The implementation is pretty much same we are still able to access function and attributes of parent class(Animal) using child class(Dog).

var d = new Dog("Skubby", 2);
alert(d.getDetail());

The Dog class we previously created is inheriting Animal class and have introduced a new function called speak hence we can add more functions and attributes when ever we need to extend any functionality.

3.2 Calling Parent Constructor

In the constructor of child class we can make a call to parent constructor. our previous constructor of child class looks like as follows.

function Dog( name , age){
	this.name = name;
	this.age = age
}

We simply replace it by calling parent constructor.

function Dog( name , age){
	Animal.call(this,  name, age);
}

and following code will return the same result as were before.

var d = new Dog("Skubby", 2);
alert(d.getDetail());

3.3 Overriding a method/function of parent class (Method Overriding)

Now we will override method of a parent class in child class.

//Dog class inherits Animal Class
Dog.prototype = new Animal();

//Dog Class + constructor
function Dog( name , age){
	Animal.call(this, name, age);
}

//speak function of Dog
Dog.prototype.Speek = function(){
	alert("waoo waoo");
}
//Overriding method
Dog.prototype.getDetail = function() {
	return "--- This is a DOG object ---\n";
}

3.4 Calling function of parent class

Syntax

<parent-class-name>.prototype.<method-name>.call(this <,method-arguments>);
Example: Animal.prototype.getDetail.call( this ); 

//Dog class inherits Animal Class
Dog.prototype = new Animal();

//Dog Class + constructor
function Dog( name , age){
	Animal.call(this, name, age);
}

//speak function of Dog
Dog.prototype.Speek = function(){
	alert("waoo waoo");
}
//Overriding method
Dog.prototype.getDetail = function() {
	return "--- This a DOG object ---\n"
		  + Animal.prototype.getDetail.call( this );
}

3.5 Multiple Inherence in JavaScript

Simple answer to multiple inheritance is, JavaScript does not support multiple inheritance just like Java programming language. We know that in order to inherit a class we use following code

Dog.prototype = new Animal();

If you think by Inheriting another class in similar way will work, then you are wrong it will actually replace the inheritance

//Dog is inheriting Animal class
Dog.prototype = new Animal();

//Dog is NOW inheriting Bird class
Dog.prototype = new Bird(); //Previous declaration is overwritten

However there are few workarounds to get the feel of multiple inheritance but that is not actually real inheritance. you can using cloning technique to clone the functions of any other parent class to your child class. however that is not in the scope of this tutorial.
Here are few links that have provided few ways to achive mulitiple inheritence in different ways.
1 -Multiple Inheritance in Javascript
2 -Experimenting With Multiple Class Inheritance In Javascript
3 -Implementing Multiple Inheritance in Javascript
4 -Multiple inheritance in javascript : StackOverflow : Read the last comment by MooGoo, The simplest way to understanding the trick of multiple inheritence.
5 -Classical Inheritance in JavaScript : I have strong recommendation to read this link, it explain different types/styles of Inheritance as well defining class in JavaScript





Here I would like to share an example on how to inject javascript into browser, to fill any of the text field value in a form.

<form name="frm1" action="somelink.php" method="get">
<input id='txt1' type="text" value="muhammad mazhar hassan" />
</form>

What you have to do is,write a javaScript code in browser URL box and press enter (but remember the above page must be loaded before you do this step.

first I will access my target page (get loaded in browser)

url: http://localhost/inject/testpage.html

now I can see a text box in browser with a value in it

muhammad mazhar hassan

In order to replace above value, I will paste following code, in browser’s URL(replace existing url link)

javascript:void(document.frm1.txt1.value = 'papai chullo')

after you press enter you will see that the value of text box has been changed.

papai chullo

Cheers! G-o-Jutta





In previous two tutorials we have discussed JAAS as authentication module, now i will provide source code for authorization using JAAS

for more detail please have a look on previous tutorials

JAAS – Authentication with JBOSS, FORM-BASED tutorial PART1

JAAS – Authentication with JBOSS BASIC MODE tutorial PART2

Authentication : is a process in which valid of a user is checked, if he is valid or not by simply checking his username and password that he entered from some interface

Authorization : is a process in which user authorized against the task he can perform. like mazhar is valid user and he came on site by typing correct username and password but there are few methods/task/areas that he can not access. think it as role, different users have different roles, admin, QA etc.

Strategy: In this tutorial we will create 2 projects, 1st an EJB project which exposes 3 methods by remote interface, one for super user, another for admin user and one is available for every one.

Second project is a web project, that will have few JSP pages,  in admin and super folder, and those folders are secured by JAAS authetication + authorization.

which means authorization is also done on folders/contents.

EJB Project

AuthorizationEJBs
	+ejbModule
		+com.maz.news
			-StatelessNewsEJB.java
			-StatelessNewsEJBRemote.java
			-StatelessNewsEJBLocal.java
	+META-INF
		jboss.xml

StatelessNewsEJB.java

package com.maz.news;

import javax.annotation.security.PermitAll;
import javax.annotation.security.RolesAllowed;
import javax.ejb.Stateless;

/**
 * Session Bean implementation class StatelessNewsEJB
 */
@Stateless
public class StatelessNewsEJB implements
StatelessNewsEJBRemote, StatelessNewsEJBLocal {
    public StatelessNewsEJB() {

    }
	@RolesAllowed({"admin"})
    @Override
	public String getAdminNews() {

		return "Here is news for Admin";
	}
	@PermitAll
	@Override
	public String getNews() {
		return "Herer is news for everyone";
	}
	@RolesAllowed({"superuser"})
	@Override
	public String getSuperUserNews() {

		return "Here is news for super users";
	}

}

StatelessNewsEJBLocal.java

package com.maz.news;
import javax.ejb.Local;

@Local
public interface StatelessNewsEJBLocal {

}

StatelessNewsEJBRemote.java

package com.maz.news;
import javax.ejb.Remote;

@Remote
public interface StatelessNewsEJBRemote {
	public String getNews();
	public String getGuestNews();
	public String getSuperUserNews();
}

and finally an xml file jboss.xml is required in META-INF folder of our EJB project.

jboss.xml

package com.maz.news;
<?xml version="1.0" encoding="UTF-8"?>
<jboss>
  <security-domain>mazhar_policy</security-domain>
  <unauthenticated-principal>unknowUser</unauthenticated-principal>
</jboss>

If you have read previous 2 tutorials as mentioned above you must be aware of this policy (mazhar_policy)which is configured at JBOSS in X:\work-folder\jboss-4.2.3.GA\server\default\conf\login-config.xml, if you do not want to go back to those tutorials, here is the content that u need to paste in above file.

<application-policy name = "mazhar_policy">
<authentication>
  <login-module code = "org.jboss.security.auth.spi.DatabaseServerLoginModule"
flag = "required">
     <module-option name = "unauthenticatedIdentity">guest</module-option>
     <module-option name = "dsJndiName">java:/mazhards</module-option>
     <module-option name = "principalsQuery">
SELECT password FROM myuser WHERE username=?</module-option>
     <module-option name = "rolesQuery">
SELECT role, 'Roles' FROM myuser_role WHERE username=?</module-option>
  </login-module>
</authentication>
</application-policy>

mazhards in above xml is jndi name used for our data source that is an xml file mazhar-ds.xml deployed in jboss/…/deploy folder.

WEB Project

AuthorizationWEB
	+WebContent
		index.jsp
		logout.jsp
		+admin
			admin.jsp
		+super
			super.jsp
		+WEB-INF
			jboss-web.xml
			login.jsp
			loginfail.jsp
			web.xml

index.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>JAAS Authorization</title>
</head>
<body>
<a href="admin/admin.jsp">Admin contents</a> |
<a href="super/super.jsp">Super contents</a> |
<a href="logout.jsp">Logout</a>
</body>
</html>

logout.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<%
      ((HttpSession) request.getSession()).invalidate ();
      SecurityAssociation.clear ();
%>

<%@page import="org.jboss.security.SecurityAssociation"%><html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Logout</title>
</head>
<body>
Log out successfully. :)
</body>
</html>

admin.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%!
  private StatelessNewsEJBRemote ejb = null;

  public String getMyNews () {
    try {
      InitialContext ctx = new InitialContext();
      ejb = (StatelessNewsEJBRemote) ctx.lookup("StatelessNewsEJB/remote");
      return ejb.getAdminNews();
    } catch (Exception e) {
      e.printStackTrace ();
      return e.getMessage();
    }

  }
%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<%@page import="com.maz.news.StatelessNewsEJBRemote"%>
<%@page import="javax.naming.InitialContext"%><html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title></title>
</head>
<body>
<h1>Admin</h1>
<%= getMyNews() %>
</body>
</html>

super.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%!
  private StatelessNewsEJBRemote ejb = null;

  public String getMyNews () {
    try {
      InitialContext ctx = new InitialContext();
      ejb = (StatelessNewsEJBRemote) ctx.lookup("StatelessNewsEJB/remote");
      return ejb.getSuperUserNews();
    } catch (Exception e) {
      e.printStackTrace ();
      return e.getMessage();
    }

  }
%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<%@page import="com.maz.news.StatelessNewsEJBRemote"%>
<%@page import="javax.naming.InitialContext"%><html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title></title>
</head>
<body>
<h1>Superuser</h1>
<%= getMyNews() %>
</body>
</html>

jboss-web.xml

<?xml version="1.0" encoding="UTF-8"?>
<jboss-web>
    <security-domain>java:/jaas/mazhar_policy</security-domain>
</jboss-web>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
  <display-name>AuthorizationWEB</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>

  <security-constraint>
    <web-resource-collection>
        <web-resource-name>Admin Pages</web-resource-name>
        <url-pattern>/admin/*</url-pattern>
        <http-method>POST</http-method>   
        <http-method>GET</http-method>   
    </web-resource-collection>
    <auth-constraint>
        <description>Only allow users from following roles</description>
        <role-name>admin</role-name>
        <role-name>superuser</role-name>
    </auth-constraint>
</security-constraint>

<security-constraint>
    <web-resource-collection>
        <web-resource-name>Admin Pages</web-resource-name>
        <url-pattern>/super/*</url-pattern>
        <http-method>POST</http-method>   
        <http-method>GET</http-method>   
    </web-resource-collection>
    <auth-constraint>
        <description>Only allow users from following roles</description>
        <role-name>superuser</role-name>
    </auth-constraint>
</security-constraint>

<login-config>
    <auth-method>FORM</auth-method>
    <form-login-config>
        <form-login-page>/WEB-INF/login.jsp</form-login-page>
        <form-error-page>/WEB-INF/loginfail.jsp</form-error-page>
    </form-login-config>
</login-config>

</web-app>

login.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Login</title>
</head>
<body>
<form method="post" action="j_security_check">
    <input type="text" name="j_username" /><br/>
    <input type="password" name="j_password" /><br/>
    <input type="submit" value="Login" />
</form>
</body>
</html>

loginfail.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h1>Login failed</h1>
</body>
</html>

Project referencing

We have pretty much configured every thing that is required,in super.jsp and admin.jsp you may see an error StatelessNewsEJBRemote can not be resolved to a type.
for that right click on web project (i am using eclipse) select “Build path” ->”configure build path”,  select project tab, click add button and select ejb project that we have created in 1st step “AuthorizationEJBs”

now you can export web project as war file and ejb project as jar file, copy both files into jboss deploy folder

X:\work-folder\jboss-4.2.3.GA\server\default\deploy

you have successfully deployed your project.

Now you can access your web project using http://localhost:8080/AuthorizationWEB/

this will show index.php page with links, click on super link , as this is secure page, JAAS will present a login form, for username/password input.

login with a user who’s role is “superuser”, you will be redirected to super.jsp page, and it will show you the news, now go back to index.jsp page and this time click on admin link,

as you might remember admin.jsp is in admin folder which is also secure, and its authorization says(web.xml) admin and superuser can access this folder’s content, admin.jsp will be loaded successfully (keeping in mind that your role is superuser but it will not show you news string because this page is calling getAdminNews() which is only permitted to admin user not superuser, so you will see “Authorization failed” message.

@RolesAllowed({"admin"})
    @Override
	public String getAdminNews() {

		return "Here is news for Admin";
	}

mazhar-ds.xml

This file needs to be placed in jboss deploy folder
X:\work-folder\jboss-4.2.3.GA\server\default\deploy

<?xml version="1.0" encoding="UTF-8"?>
<datasources>
  <local-tx-datasource>
    <jndi-name>mazhards</jndi-name>
    <connection-url>
jdbc:mysql://localhost:3306/mazhar_db?useUnicode=true&amp;characterEncoding=UTF-8
</connection-url>
    <driver-class>com.mysql.jdbc.Driver</driver-class>
    <user-name>mazhar</user-name>
    <password>hassan</password>
    <exception-sorter-class-name>
org.jboss.resource.adapter.jdbc.vendor.MySQLExceptionSorter
</exception-sorter-class-name>
    <!-- should only be used on drivers after 3.22.1 with "ping" support-->
    <valid-connection-checker-class-name>
org.jboss.resource.adapter.jdbc.vendor.MySQLValidConnectionChecker
</valid-connection-checker-class-name>
    <!---->
    <!-- sql to call when connection is created
    <new-connection-sql>some arbitrary sql</new-connection-sql>
      -->

    <!-- corresponding type-mapping in the standardjbosscmp-jdbc.xml (optional) -->     <metadata>        <type-mapping>mySQL</type-mapping>     </metadata>   </local-tx-datasource> </datasources>

Database Structure

Can be taken from previous tutorials

Reffrences

Current tutorial is greatly influenced by following tutorial
Using Jaas
and there are others as well for more detail you can refer them

http://en.wikipedia.org/wiki/Authorization

http://download.oracle.com/javase/1.4.2/docs/guide/security/jgss/tutorials/AcnAndAzn.html

http://download.oracle.com/javase/1.4.2/docs/guide/security/jaas/tutorials/GeneralAcnAndAzn.html

http://www.mooreds.com/jaas.html


JAAS, Basic Authentication

Some basic points are discussed in following tutorial.
JAAS Authentication, FORM based Authentication

current tutorial is same as above, except the username and password input is taken differently, in Basic Authentication  popup window is displayed to user to take input. as show in image below.

on success will display secure contents that was accessed


A simple and very easy JBOSS JAAS authentication and authorization tutorial.
Here is directory struture of my project
	[SimpleAuthJASS] (my web project)
		+- [WebContent]
			+- [admin] (this is our secure folder)
				  + index.jsp 

			+- [WEB-INF]
				+- jboss-web.xml
				+- web.xml

			+-index.jsp

1) First we need to define application authetication policy at jboss

D:\jboss-4.2.3.GA\server\mmazharhassan.com\conf\login-config.xml

Here we define application policy named as "mazhar_policy"
and jndi name as "mazhards" which will correspond to "jboss/.../deploy/mazhar-ds.xml"

<application-policy name = "mazhar_policy">
       <authentication>
          <login-module code = "org.jboss.security.auth.spi.DatabaseServerLoginModule" flag = "required">
             <module-option name = "unauthenticatedIdentity">guest</module-option>
			 <module-option name = "dsJndiName">java:/mazhards</module-option>
             <module-option name = "principalsQuery">SELECT password FROM myuser WHERE username=?</module-option>
             <module-option name = "rolesQuery">SELECT role, 'Roles' FROM myuser_roles WHERE username=?</module-option>
          </login-module>
       </authentication>
    </application-policy>

2nd) Create Security Domain

create jboss-web.xml file in you WEB-INF directory of your web application

<?xml version="1.0" encoding="UTF-8"?>
<jboss-web>
	<security-domain>java:/jaas/mazhar_policy</security-domain>
</jboss-web>

3rd) Secure the Application

modify web.xml in WEB-INF directory
and add following configuration

3.1 web.xml

<security-constraint>
	<web-resource-collection>
		<web-resource-name>Admin Pages</web-resource-name>
		<url-pattern>/admin/*</url-pattern>
		<http-method>POST</http-method>
		<http-method>GET</http-method>
	</web-resource-collection>
	<auth-constraint>
		<description>Only allow users from following roles</description>
		<role-name>administrator</role-name>
		<role-name>superuser</role-name>
	</auth-constraint>
</security-constraint>
<login-config>
    <auth-method>BASIC</auth-method>
    <realm-name>My Secure Content Authentication</realm-name>
 </login-config>
4th) Datasource at jboss
D:\jboss-4.2.3.GA\server\mmazharhassan.com\deploy\
mazhar-ds.xml

<?xml version="1.0" encoding="UTF-8"?>
<datasources>
  <local-tx-datasource>
    <jndi-name>mazhards</jndi-name>
    <connection-url>jdbc:mysql://localhost:3306/mazhar_db?useUnicode=true&amp;characterEncoding=UTF-8</connection-url>
    <driver-class>com.mysql.jdbc.Driver</driver-class>
    <user-name>umazhar</user-name>
    <password>mazhar</password>
    <exception-sorter-class-name>org.jboss.resource.adapter.jdbc.vendor.MySQLExceptionSorter</exception-sorter-class-name>
    <valid-connection-checker-class-name>org.jboss.resource.adapter.jdbc.vendor.MySQLValidConnectionChecker</valid-connection-checker-class-name>
    <new-connection-sql>some arbitrary sql</new-connection-sql>
    <check-valid-connection-sql>some arbitrary sql</check-valid-connection-sql>
    <metadata>
       <type-mapping>mySQL</type-mapping>
    </metadata>
  </local-tx-datasource>
</datasources>

5th) Database structure
Table1 : myuser
iduser username password
1	mazhar	123
2	fahad	123
Table2 : myuser_roles
role username
superuser mazhar guest fahad 


6th) Who is authenticated by JAAS Most of my friend ask this question, how our application will know that who is get authenticated by JAAS, so for that i am
presenting a sample index.jsp file that is used in admin folder.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@page import="java.security.AccessController"%>
<%@page import="javax.security.auth.Subject"%><html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Admin Panel</title>
</head>
<body>
%>
<h1>Admin panel</h1>

<pre>
User authenticated by JAAS is [ <%= request.getRemoteUser() %> ]  <br>
<%
    if (request.isUserInRole("superuser")) {
        out.println("and is a Super user");
    } else {
        out.println("and is an other user");
    }
%> 

</pre>
</body>
</html>

More information can be found about displaying information on jSP page as follows
Using JAAS with Tomcat


This tutorial explain how to draw line using JavaScript,  A function is declared that take 4 parameters as input, x,y of first point and second point, and will draw line between these two points.

function is really simple stated as follows

function line(x0, y0, x1, y1)
{
	var dx = x1 - x0;
	var dy = y1 - y0;
	putpixel(x0, y0);
	if (Math.abs(dx) > Math.abs(dy))
	{
		// slope < 1
		var m =  dy /  dx;      // compute slope
		var b = y0 - m*x0;
		dx = (dx < 0) ? -1 : 1;
		while (x0 != x1)
		{
		x0 += dx;
		putpixel(x0, Math.round(m*x0 + b));
		}
}  	else if (dy != 0)  	{                               		// slope >= 1
		var m = dx / dy;      // compute slope
		var b = x0 - m*y0;
		dy = (dy < 0) ? -1 : 1;

		while (y0 != y1)
		{
			y0 += dy;
			putpixel(Math.round(m*y0 + b), y0);
		}
	}
}

function putpixel(x,y)
{

	var img = document.createElement("span");
	img.style.position = "absolute";
	img.style.left = x + "px";
	img.style.width = "1px";
	img.style.height = "1px";
	img.style.border = "1px solid #000000";
	img.style.top = y + "px";
	bdy = document.getElementById("div_1");
	bdy.insertBefore(img, null);
}

now we will require a div that will hold all newly plotted pixels(spans)

<span id="div_1" style="position:absolute; left:0;top:0;width:800px;height;800px; z-index:45"></span>

Java Authentication and Authorization Service, Form based Authentication

JAAS helps in authentication and authorization of a person, system or an automated process. It decreases the concerns for individuals about security, as this will be the first layer user has to go through before going to interact with actual method, interface or a page.
JAAS enables security to be plug able into you project, and it can be replaced by any criteria of security while your main application remain intact.

user/system/process —–>| JAAS ->| Application

JAAS also enables you to configure multiple login module for different section of you project.
How it works.

when user try to access secure content, JAAS get activated and ask for username and password depending upon the “login configuration” (Authentication method Form based or simple)

Form based security will show a user defined form to take inputs, simple will popup a window for username and password. in this tutorial we will concentrate on FORM based authetication.(Please note authorization is not included in this tutorial)

for more detail on JAAS please read following links
JavaRanch.com
Java Authentication and Authorization Service

A simple and very easy JBOSS JAAS authentication and authorization tutorial.
Here is directory struture of my project
	[mazhar] (my web project)
		+- [WebContent]
			+- [admin] (this is our secure folder)
				  + salary.jsp 

			+- [WEB-INF]
				+- jboss-web.xml
				+- web.xml

			+- login.jsp
			+- loginfail.jsp

1) First we need to define application authetication policy at jboss

D:\jboss-4.2.3.GA\server\mmazharhassan.com\conf\login-config.xml

Here we define application policy named as "mazhar_policy"
and jndi name as "mazhards" which will correspond to "jboss/.../deploy/mazhar-ds.xml"

<application-policy name = "mazhar_policy">
       <authentication>
          <login-module code = "org.jboss.security.auth.spi.DatabaseServerLoginModule" flag = "required">
             <module-option name = "unauthenticatedIdentity">guest</module-option>
			 <module-option name = "dsJndiName">java:/mazhards</module-option>
             <module-option name = "principalsQuery">SELECT password FROM myuser WHERE username=?</module-option>
             <module-option name = "rolesQuery">SELECT role, 'Roles' FROM myuser_roles WHERE username=?</module-option>
          </login-module>
       </authentication>
    </application-policy>

2nd) Create Security Domain

create jboss-web.xml file in you WEB-INF directory of your web application

<?xml version="1.0" encoding="UTF-8"?>
<jboss-web>
	<security-domain>java:/jaas/mazhar_policy</security-domain>
</jboss-web>

3rd) Secure the Application

modify web.xml in WEB-INF directory
and add following configuration

3.1 web.xml

<security-constraint>
	<web-resource-collection>
		<web-resource-name>Admin Pages</web-resource-name>
		<url-pattern>/admin/*</url-pattern>
		<http-method>POST</http-method>
		<http-method>GET</http-method>
	</web-resource-collection>
	<auth-constraint>
		<description>Only allow users from following roles</description>
		<role-name>administrator</role-name>
		<role-name>superuser</role-name>
	</auth-constraint>
</security-constraint>
<login-config>
	<auth-method>FORM</auth-method>
	<form-login-config>
		<form-login-page>/login.jsp</form-login-page>
		<form-error-page>/loginfail.jsp</form-error-page>
	</form-login-config>
</login-config>

3.2
carate login.jsp in "webContent"
<form method="post" action="j_security_check">
	<input type="text" name="j_username" /><br/>
	<input type="password" name="j_password" /><br/>
	<input type="submit" value="Login" />
</form>

4th) Datasource at jboss
D:\jboss-4.2.3.GA\server\mmazharhassan.com\deploy\
mazhar-ds.xml

<?xml version="1.0" encoding="UTF-8"?>
<datasources>
  <local-tx-datasource>
    <jndi-name>mazhards</jndi-name>
    <connection-url>jdbc:mysql://localhost:3306/mazhar_db?useUnicode=true&amp;characterEncoding=UTF-8</connection-url>
    <driver-class>com.mysql.jdbc.Driver</driver-class>
    <user-name>umazhar</user-name>
    <password>mazhar</password>
    <exception-sorter-class-name>org.jboss.resource.adapter.jdbc.vendor.MySQLExceptionSorter</exception-sorter-class-name>
    <valid-connection-checker-class-name>org.jboss.resource.adapter.jdbc.vendor.MySQLValidConnectionChecker</valid-connection-checker-class-name>
    <new-connection-sql>some arbitrary sql</new-connection-sql>
    <check-valid-connection-sql>some arbitrary sql</check-valid-connection-sql>
    <metadata>
       <type-mapping>mySQL</type-mapping>
    </metadata>
  </local-tx-datasource>
</datasources>

5th) Database structure
Table1 : myuser
iduser username password
1	mazhar	123
2	fahad	123
Table2 : myuser_roles
role username
superuser mazhar guest fahad 
 

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationComplete="init()">
<mx:Script>
	<![CDATA[
		import mx.controls.Label;
		import mx.containers.Canvas;
		import mx.controls.Alert;
		import mx.controls.Button;
		import mx.core.IUIComponent;
		import mx.managers.DragManager;
		import mx.core.DragSource;
		import mx.events.DragEvent;
		import com.maz.tree.NodeData;
		import mx.collections.ArrayCollection;
		 	[Embed("assets/contact216.png")]
            public var iconUser:Class;

            [Embed("assets/group16.png")]
            public var iconGroup:Class;

            [Embed("assets/group.gif")]
            public var gp:Class;

		public function getTreeItems():ArrayCollection{
			var treeNodes:ArrayCollection = new ArrayCollection();

			treeNodes.addItem(new NodeData("Login",new ArrayCollection([new NodeData("M.Mazhar Hassan"), new NodeData("Hassan")]),"group"));
			treeNodes.addItem(new NodeData("Admin",new ArrayCollection([new NodeData("Mohsin"), new NodeData("Zahoor")]),"group"));
			return treeNodes;
		}
		private function init():void{
			contactTree.dataProvider = getTreeItems();
		}
		private function getIconForNode(item:Object ):Class{
			var cIcon:Class;
			switch(item.icon){
				case "user":
					cIcon = iconUser;
				break;
				case "group":
					cIcon = iconGroup;
				break;
			}
			return cIcon;
		}
		private function getCustomDragImage(caption:String, icon:Class ):IUIComponent{
			 var button:Button = new Button();
            button.label = caption;
            if (icon != null) {
            	button.setStyle("icon",icon);
            }
            button.setStyle("PADDING_LEFT", 10);
            button.setStyle("PADDING_RIGHT", 10);
            button.setStyle("PADDING_TOP", 7);
            button.setStyle("PADDING_BOTTOM", 7);
            button.x = 0;
            button.y=0;

            return IUIComponent(button);
		}
		private function onTreeDragEnter(event:DragEvent):void
		{

			var dragInitiator:Tree = Tree(event.currentTarget); 

			if (dragInitiator.selectedIndices.length > 0){
				var objContact:NodeData = NodeData (dragInitiator.selectedItem); 
				var ds:DragSource = new DragSource();
				 if (objContact.icon == "user")
            	 {
					ds.addData(objContact,"ITEM_CONTACT");
					DragManager.doDrag(dragInitiator, 
					ds, 
					event,
					getCustomDragImage(objContact.chrNode,iconUser),-event.localX+10, -event.localY + 10, 0.8);
            	 }
            	 else{
					ds.addData(objContact,"ITEM_NOT_ALLOWED");
					DragManager.doDrag(dragInitiator, 
					ds, 
					event,
					getCustomDragImage("not Allowed",null),-event.localX+10, -event.localY + 10, 0.8);
            	 }
			}
		}
		 private function onDragEnter(ev:DragEvent, itemType:String):void{
			if (ev.dragSource.hasFormat(itemType)) {
				DragManager.acceptDragDrop(IUIComponent(ev.target));
			}
		}
		private function onDrop(ev:DragEvent, itemType:String):void{
			var myData:NodeData;
			myData =  ev.dragSource.dataForFormat(itemType) as NodeData;
			ev.target.text =myData.chrNode;
		}
	]]>
</mx:Script>
	<mx:Tree 
			alternatingItemColors="[#FFFFFF,#EEEEEE]" 
			id="contactTree" 
			iconFunction="getIconForNode"
			labelField="chrNode" 
			showRoot="true"
			width="250"
			height="615"
			dragEnabled="true"
			dropEnabled="false"
			dragStart="onTreeDragEnter(event)"

		 ></mx:Tree>
		 <mx:TextInput  
		 		id="txtResponisble" 
		 		dragEnter="onDragEnter(event,'ITEM_CONTACT')" 
		 		dragDrop="onDrop(event,'ITEM_CONTACT')" 
		 		x="258" 
		 		y="10" 
		 		borderColor="#0096FF"
		 	/>
</mx:Application>

setup data provider for tree control in such a way that it support nodes to be displayed in nested order.

<?xml version=”1.0″ encoding=”utf-8″?>

<mx:Application xmlns:mx=”http://www.adobe.com/2006/mxml&#8221; layout=”absolute” creationComplete=”init()”>

<mx:Script>

<![CDATA[

import com.maz.tree.NodeData;

import mx.collections.ArrayCollection;

[Embed("assets/contact216.png")]

public var iconUser:Class;

[Embed("assets/group16.png")]

public var iconGroup:Class;

[Embed("assets/group.gif")]

public var gp:Class;

public function getTreeItems():ArrayCollection{

var treeNodes:ArrayCollection = new ArrayCollection();

treeNodes.addItem(new NodeData(“Login”,new ArrayCollection([new NodeData("M.Mazhar Hassan"), new NodeData("Hassan")]),”group”));

treeNodes.addItem(new NodeData(“Admin”,new ArrayCollection([new NodeData("Mohsin"), new NodeData("Zahoor")]),”group”));

return treeNodes;

}

private function init():void{

contactTree.dataProvider = getTreeItems();

}

private function getIconForNode(item:Object ):Class{

var cIcon:Class;

switch(item.icon){

case “user”:

cIcon = iconUser;

break;

case “group”:

cIcon = iconGroup;

break;

}

return cIcon;

}

]]>

</mx:Script>

<mx:Tree

alternatingItemColors=”[#FFFFFF,#EEEEEE]“

id=”contactTree”

iconfunction=”getIconForNode”

labelField=”chrNode”

showRoot=”true”

width=”250″

></mx:Tree>

</mx:Application>

package com.maz.tree
{
	import mx.collections.ArrayCollection;

	public class NodeData
	{
		public var idNode:int;
		public var chrNode:String;
		public var icon:String;
        public var children:ArrayCollection;
        public static var IDGenrator:int = 1;
		public function NodeData(_name:String,children:ArrayCollection = null,icon:String = null)
		{
			this.chrNode = _name;
            this.children = children;
            this.idNode = ++NodeData.IDGenrator;
            if (icon == null){
            	this.icon = "user";
            }
            else {
            	this.icon = icon;
            }
		}
		public function toString():String{
        	return this.chrNode + " ,"+ this.icon;
        }
	}
}
Trick: save child nodes in "children" attribute, any other name may not result in nesting.




This tutorial explain how a
(1) Java script function can be called from Flex
(2) and Flex function from Java script

Flex Side

<?xml version=”1.0″ encoding=”utf-8″?>

<mx:Application xmlns:mx=”http://www.adobe.com/2006/mxml&#8221; layout=”absolute” creationComplete=”init()” height=”143″ width=”378″>

<mx:Script>

<![CDATA[

import mx.controls.Alert;

private function jsCall():void{

//here we are calling javascript function named as "jsAlert"

ExternalInterface.call("jsAlert","sent from flex: " + txt1.text );

}

private function init():void{

//register call back function, that will be called from javascript

ExternalInterface.addCallback("flexAlert",myFlexAlert);

}

public function myFlexAlert(msg:String):void{

Alert.show(msg);

}

]]>

</mx:Script>

<mx:TextInput x=”24″ y=”19″ text=”Mazhar” id=”txt1″/>

<mx:Button x=”201″ y=”19″ label=”Javascript function” click=”jsCall()”/>

</mx:Application>

JAVA Script Side

<script language=”JavaScript” type=”text/javascript”>

function jsAlert(msg){

alert(msg);

}

function callFlex()

{

objEmbedID.flexAlert(“This text came from Javascript”);

}

</script>

<input type=”button” value=”Call Flex function” onClick=”callFlex()” />



Flex connectivity with Java using BlazeDS

[Flex Code and Configuration] A) Create Value Object Classes A.1 – voReminder Class create “Action Script Class” voReminder.as in package com.maz.vo This class will be used to send data object from Flex to JAVA the code look as follows

package com.maz.vo
{
	[RemoteClass(alias="com.maz.vo.voReminder")]
	public class voReminder
	{
		public var _idContact:int;
		public var _chrContact:String;
		public var _idReminder:int;
		public var _chrTitle:String;
		public var _chrDesc:String;
		public function voReminder()
		{
		}
	}
}

A.2 – voReminderResult Class

create “Action Script Class” voReminderResult.as in package com.maz.vo
This class will be used to recive data from JAVA into Flex
the code look as follows

package com.maz.vo
{
	[RemoteClass(alias="com.maz.vo.voReminderResult")]
	public class voReminderResult
	{
		public var _intResult:int;
		public var _chrResult:String;
		public function voReminderResult()
		{
		}
	}
}

Note: [RemoteClass(alias="com.maz.vo.voReminderResult")]
This actualy map the flex class with java class

B) create main project setup
B.1 Create mainApp.mxml file
B.1.1 create a remote object inorder to call java

<mx:RemoteObject 
result="result(event)" 
fault="fault(event)" 
id="objRm" 
destination="reminder"  
endpoint="http://localhost:8080/myReminders/messagebroker/amf"/>

fault here we specify a function that will be called if any error happens
result here we specify a function that will be called automatically if communication is successfull
id id of this remote object tag
destination class we are going to call(Actually in java this name is refference to actual java class)
endpoint url of the our java code, in this myReminders is my java project name, messagebroker/amf is used for
url mapping in java project, means any url having this string will be handled specilly using blazeDS
B.1.2 Create a button and attach an event that will be called

<mx:Button label=”Set Reminder” click=”btnClick()”/>

B.1.3

Now we will define all require function in script tag
B.1.3.1 in case of error this function will be called

public function fault(faultEvent:FaultEvent):void
{
	Alert.show("error occured during login " + faultEvent.toString());
}

B.1.3.2 in case result this function will be called

public function result(resultEvent:ResultEvent):void
{
	if (resultEvent.result)
	{
		var javaResult:voReminderResult = voReminderResult (resultEvent.result);
		Alert.show("["+ javaResult._intResult + "] "+javaResult._chrResult);
	}
	else {
		Alert.show ("Some thing wrong");  
	}
}

B.1.3.3 when button is clicked this function will be called which will actually try to connect with java

private function btnClick():void{
	var voR:voReminder 	= new voReminder();
	voR._idContact 		= 1;
	voR._chrContact 	= "Muhammad Mazhar Hassan";
	voR._idReminder		= 1;
	voR._chrTitle 		= "Urgent Meeting";
	voR._chrDesc 		= "There is an urgen meeting how to use BlazeDS";

	objRm.setReminder(voR);
}

in above function first we have create an object that will be passed to java, and in last line we have called a java function(indirectly)
and have passed the value object to this function.
Remeber objRm we have declared as remote object tag see B.1.1 for detail

thats it we are done with Flex code

[Java Code and Configuration]

C – download BlazeDS

It might be some war file, rename it to .zip and extract files
in lib folder u will find some jar files that need to be included in out project
D – JAVA Project

D 1.1 Create java web project name it “myReminders”
D 1.2 Add BlazeDS jar files

Right Click on project, select “Build Path”->”Configure Build Path”
Click on “Add External JARs…” Button
go to lib folder where we have extracted BlazeDS jars, select all, click open, they are all included into your project

It is good to also copy these jar files into your WEB-INF/lib folder

    backport-util-concurrent.jar
    cfgatewayadapter.jar
    commons-codec-1.3.jar
    commons-httpclient-3.0.1.jar
    commons-logging.jar
    concurrent.jar
    flex-messaging-common.jar
    flex-messaging-core.jar
    flex-messaging-opt.jar
    flex-messaging-proxy.jar
    flex-messaging-remoting.jar
    xalan.jar

D 1.3 web.xml

Open this file and copy paste following code into it

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" 
	xmlns="http://java.sun.com/xml/ns/j2ee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
	http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>

  <!-- MessageBroker Servlet -->
    <servlet>
        <servlet-name>MessageBrokerServlet</servlet-name>
        <servlet-class>flex.messaging.MessageBrokerServlet</servlet-class>
        <init-param>
            <param-name>services.configuration.file</param-name>
            <param-value>/WEB-INF/config/services-config.xml</param-value>
       </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>MessageBrokerServlet</servlet-name>
        <url-pattern>/messagebroker/*</url-pattern>
    </servlet-mapping>
</web-app>

D 1.4 BlazeDS Configuration

Create a folder named “config” in “WEB-INF” folder
create 2 xml files in it
D 1.4.1 WEB-INF/config/services-config.xml

copy paste following xml into it

<?xml version="1.0" encoding="UTF-8"?>
<services-config>
    <services>
        <service-include file-path="remoting-config.xml" />
    </services>
     <channels>
        <channel-definition id="my-amf" class="mx.messaging.channels.AMFChannel">
            <endpoint url="http://{server.name}:{server.port}/{context.root}/messagebroker/amf" class="flex.messaging.endpoints.AMFEndpoint"/>
        </channel-definition>
     </channels>
</services-config>

D 1.4.2 WEB-INF/config/remoting-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<service id="remoting-service" class="flex.messaging.services.RemotingService">
    <adapters>
        <adapter-definition id="java-object" class="flex.messaging.services.remoting.adapters.JavaAdapter" default="true"/>
    </adapters>
    <default-channels>
        <channel ref="my-amf"/>
    </default-channels>
	<destination id="reminder">
		<properties>
			<source>com.maz.controller.ReminderControler</source> 
		</properties>
		<adapter ref="java-object"/>
	</destination>
</service>

D 1.5 Define classes

D 1.5.1 Define a class “ReminderController” that will handle request, we have create an id as “reminder” in above configuration file, it is also defined in flex as destination See destination
Create ReminderController.java in src/com.maz.controller
code is as follows

package com.maz.controller;
import com.maz.vo.voReminder;
import com.maz.vo.voReminderResult;
public class ReminderControler {
	public voReminderResult setReminder2(voReminder rm)	
	{
		return new voReminderResult(101,"Successfully recived object for contact : "+rm._chrContact);
	}
}

D 1.5.2 Define value object classes
2.1 voReminder.java in src/com.maz.vo

package com.maz.vo;
public class voReminder {
	public int _idContact;
	public String _chrContact;
	public int _idReminder;
	public String _chrTitle;
	public String _chrDesc;
	public boolean isValid(){
		System.out.println("**********************************************************************");
		System.out.println(_idContact);
		return (_idContact > 0);
	}
}

2.2 voReminderResult.java in src/com.maz.vo

package com.maz.vo;
public class voReminderResult {
	public int _intResult;
	public String _chrResult;
	public voReminderResult(){

	}
	public voReminderResult(int intResult, String chrResult){
		_intResult = intResult;
		_chrResult = chrResult;
	}
}

Deploy this project using jboss, in Eclips Right Click project , select “Run on Server” from there select jboss
now go back to flex project run it and press button