Speaking at Adobe Devsummit Chennai and Hyderabad

After an amazing event in Bangalore, Adobe DevSummit is now coming to Chennai and Hyderabad. To register or to know about the venues and dates click here.  I would strongly urge any new Flex developers to attend the talks on Adobe Flash Catalyst and Data centric development.

I will be taking the tutorial session on how to connect to the backend (Learn by doing – Part 2: Integrate with server) together with fellow  technical evangelist, Sujit. This session talks about how to access data from a database through Flash builder. It will cover in detail how to connect to multiple backends from flex. Any developer thinking of starting with flex are encouraged to attend the tutorial sessions.

Hoping to see you there….

PS: All Platinum delegates will get Flex Builder 3 Professional Licence for free !!

Advertisements

Exposing Java project as Web Service to Flash Builder 4 using Data Centric Development (DCD)

The definition of a Web Service as given by W3C is a software system designed to support interoperable machine-to-machine interaction over a network. It has an interface described in a machine-processable format (specifically WSDL). Other systems interact with the Web service in a manner prescribed by its description using SOAP-messages, typically conveyed using HTTP with an XML serialization in conjunction with other Web-related standard.

Web services are often used to provide an Application programming interface to clients systems which use the Server methods running on a remote system.

In this post I will talk about how to expose a java service as a web service. For accessing this service(or any other web service),  user requires a WSDL descriptor file. WSDL stands for Web Services Description Language. How to generate this WSDL will also be explained in this post.

I split this post in the following sections:
•    Creating database and Backend
•    Generating the WSDL
•    Connect to service using DCD in Flash Builder
•    Displaying data fetched by the service

Creating database and Backend

I will not go into the details of how to create the backend.
I am assuming user has a working Java project which can produce the data required by the client. In my opinion the implementation should be hidden to expose only an interface to the required methods. In any case, the user will have a class or an interface file containing declarations of needed methods. I will call this file BackendService.

Generating the WSDL

There are multilple tools available for generating the the WSDL. I have used Apache’s XFIRE. An upgrade of this tool with the name CFX is also available now. I would recommend using the older XFIRE for its simplicity. It can be downloaded from here .
User also needs to have a J2EE web server up and running. I recommend Tomcat but any other server will also do. On your server go to the directory where you would deploy your web applications(Web-apps) and create a directory with the name of your project. Here create another directory with the name WEB-INF. Open WEB-INF and now create the following subdirectories and files inside WEB-INF:

Classes

This directory should contain all the compiled Java classes with their package structure intact.  Also create a subdirectory with the name META-INF. Inside META-INF create another subdirectory with the name “xfire”. Create a new file “services.xml” in “xfire”.
Paste this xml code in Services.xml:
xml1
Change the name of the service to the name of your own service. Accordingly change the serviceClass tag to contain the path of the class from the “classes” directory. The namespace tag should contain your desired namespace.

LIB

In this directory copy all the libraries required by xfire. You can get the list of dependencies and their download links from here. Before downloading any check the libraries that you got from the Xfire download. Most of the dependencies will already be there.

web.xml

Now that you have created and populated the directories, create a new file in the WEB-INF directory with the name web.xml. In this file copy the following content:xml2

Now check out this URL:

http://localhost:8400/ProjectName/services/dataService?wsdl

In the above URL replace “ProjectName” with your actual project name. Replace dataService with the name of your dataService. Change the port if required and try accessing it from a browser.

You should now be able to view the generated WSDL . I will call this URL WSDL-URL. The next step is to access it from Flash builder.

Connect to service using DCD in Flash Builder

Open Flash builder and create a new project by going to file -> New -> Flex project. In the window that follows give an appropriate name to the project. I called it InvokeWSProject. Click Next->Finish to complete project completion.

1

Next step is to connect to the Java service. For this, Click on the Data/Services tab in the bottom frame of the screen.

2

In the screen that follows select Web service and click on next.

3

Enter WSDL-URL. Flash builder populates the Service details.

4

Click on next to see a screen like this. Here select the functions you want to import. All functions are selected by default.

5

When you click finish, you see all functions that you wished to import are now available to you in the Data/Services tab.

6

What remains now is to get the data fetched by the dataService and display them.

Displaying data fetched by the service

Go to Flash builder Design view. Drag and Drop a DataGrid from Flex component controls.

7

Your data will be shown in this grid. All that remains is to put the data in the grid. You already have the data methods in the Data/Services tab. Select the method whose output you want to see in the grid. Just drag and drop this method on the grid.

8

You see that the grid changes to the return value of the method. In my case it looked like this

9

Only thing remaining is to run the project. Press CTRL+F11 to run it.

10

Reviewing once …

User creates the database, populates it, writes a data service (dataService) to fetch the data. This completes the backend work. User exposes the service as a WSDL descriptor. User creates a flex project and links to the WSDL descriptor to get access to his functions on Client.

PS: User has not written a line of code on the Frontend J

QandA

User: Where can I get to know more about WSDL’s and web services?

Editor: http://en.wikipedia.org/wiki/Web_Services_Description_Language http://en.wikipedia.org/wiki/Web_service

User: I am using Eclipse IDE to code in Java. Is there some way I can generate my WSDL directly?

Editor: The Latest Eclipse build which can be downloaded from here has a feature of generating the WSDL. But the generated WSDL is just a prototype and needs work. Check out eclipse documentation to find out more. You can also download and install the axis plugin for eclipse. This tool directly converts Java to WSDL. Download the plugin from here. For installation instructions read this.

User: Flash Builder beta 2 was recently launched. Where can I download it?

Editor: To download Flash Builder 4 beta2  go here.

User: Any way I can know more about this product and its new features?

Editor:  Tim Buntel has a written an excellent article on what is new in this Beta. Here is the link: http://www.adobe.com/devnet/flex/articles/flashbuilder4_whatsnew.html

An aggregated list of articles on Flash Builder 4 was created by Sujit Reddy. Here is the link: http://sujitreddyg.wordpress.com/flash-builder-4/

How to use Flash Builder 4 DB introspector with PHP

How to use Flash Builder 4 DB introspector with PHP

Content
The second beta of Flash builder 4 is now available on Adobe labs. This new beta comes with the original goodness of the earlier versions and addition of many requested features. To see what’s new with this beta click here. Release notes can be viewed at http://labs.adobe.com/wiki/index.php/Flash_Builder_4:Release_Notes One of the many features introduced in this beta is the Database introspector. It can be a drag sometimes to write basic read and update methods and classes for each and every table in a database. This is where the Database introspector of Flash builder 4 will become very handy. A developer can use this feature to generate a sample code in PHP or ColdFusion for basic CRUD operations simply by pointing to the database from Flash builder project. This post contains details for generating PHP code. Here is a step by step for how to invoke the database introspector

Create the database and tables

I am using the following commands in mysql to create two tables, User, User_profile in the database “testdb”.

DROP TABLE IF EXISTS `testdb`.`user`;
CREATE TABLE `testdb`.`user` (
`ID` int(10) unsigned NOT NULL auto_increment,
`FIRST_NAME` varchar(100) default NULL,
`LAST_NAME` varchar(100) default NULL,
`DISPLAY_NAME` varchar(250) default NULL,
`COMPANY_ID` varchar(100) default NULL,
`LOGIN_ID` varchar(250) NOT NULL default '',
`LOGIN_PASSWORD` varchar(45) NOT NULL default '',
`DEPARTMENT` varchar(100) default NULL,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;


DROP TABLE IF EXISTS `testdb`.`user_profile`;
CREATE TABLE `testdb`.`user_profile` (
`ID` int(10) unsigned NOT NULL auto_increment,
`USER_ID` int(10) unsigned NOT NULL default '0',
`BLOG_URL` varchar(300) default NULL,
`DESCRIPTION` varchar(300) default NULL,
`TWITTER_URL` varchar(300) default NULL,
PRIMARY KEY (`ID`),
CONSTRAINT `FK_COURSE_USAGE_USER` FOREIGN KEY (`USER_ID`) REFERENCES `user` (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=32 DEFAULT CHARSET=utf8;

Execute these commands in Mysql and you will have your tables. The next step obviously is to create client code. You start by creating a flex project.

Create the flex project

Start Flash builder 4. Go to File menu select New and then select Flex Project. A window appears with options to fill up the project details. 1

  • Give an appropriate name to the project (here I gave it the name testIntrospector)
  • Change the application server type to PHP.
  • Let other options keep their default value

2

Click on next and you see options to fill in the server details.

  • Web root: Specify the root folder of your web server (in my case it was C:\Program Files\Apache Software Foundation\Apache2.2\htdocs)
  • Next specify the root URL as appropriate (I entered -> http://localhost:8080)
  • Now click on validate configuration. In case there is an error in accessing the data server, it will be shown. Otherwise Flash builder tells you that the root folder and URL are valid.

The output folder can be changed according to your need. I am kept the default value 3 Click on next -> finish to be done with the project completion. What next? Now you need a PHP service that can read and edit the database

Generate the Service

Click on the Data/Services tab in the bottom frame. 4 This tab shows a link which says “Connect to Data/Service”. Click on this link to see this window 5 Here select PHP as your service type and click on next. The same can be done by going to Data in the tool bar and selecting Connect to PHP. You will be taken to a window where you need to fill in details about the service. The next step is to generate the PHP Code based on our Database Table. 6

Generating PHP Code based on a Database Table

Here is how you do that. Click on the link which says “click here to generate a sample”. 7 It opens a window where you can enter details about the database you want to connect to. You would be required to enter the following details about the database:

  • Username – Enter the username having all privileges over the table you want to generate the service for (I entered root)
  • Password – Enter the password for that user.
  • Host name and port– Give the name of the host where the database is and the port on which it can be accessed(localhost,3306 in my case)
  • Finally enter the name of the database

Click on the “Connect to Database” button. If all details have been correctly entered all tables from the entered database will be now visible in Table comboBox like this.. 8

Select the table (I select the User table from our database testdb ) for which you require the CRUD methods and click on OK. You can also select the location where this sample PHP service is created. I have used the default location. Once you click OK Flash builder might show you a warning that the service generated is intended for a trusted environment. The code generated will allow anyone with network access to your server to be able to select, insert, update or delete information from this table. The code should be reviewed before it’s used for production purposes. If you go ahead and press Ok and finish with the default values of the Service name and Service package, the introspector generates a Sample PHP and opens it for you to view and edit. Here is a code snippet of what was generated for me for the table testdb.User


public function getAllUser()
{
$stmt = mysqli_prepare($this->connection, "SELECT * FROM $this->tablename");
$this->throwExceptionOnError();
mysqli_stmt_execute($stmt);
$this->throwExceptionOnError();
$rows = array();
mysqli_stmt_bind_result($stmt, $row->ID, $row->FIRST_NAME, $row->LAST_NAME, $row->DISPLAY_NAME, $row->COMPANY_ID, $row->LOGIN_ID, $row->LOGIN_PASSWORD, $row->DEPARTMENT);
while (mysqli_stmt_fetch($stmt))
{
$rows[] = $row;
$row = new stdClass();
mysqli_stmt_bind_result($stmt, $row->ID, $row->FIRST_NAME, $row->LAST_NAME, $row->DISPLAY_NAME, $row->COMPANY_ID, $row->LOGIN_ID, $row->LOGIN_PASSWORD, $row->DEPARTMENT);
}
mysqli_stmt_free_result($stmt);
mysqli_close($this->connection);
return $rows;
}

This method gets all users present in the user table. Now that you have your service to get you data from the database, you just need to display it. Go to Flash builder design view and drag and drop a DataGrid on the application. This done you have to decide what to display in this grid. In this case let us say you want this grid to display all users. To get the DataGrid to show all users drag and drop the above method getAllUser from the Data/Services tab on the DataGrid 9 When you drop the method on the grid it the grid adapts to the return value of the function and looks something like this now.10 If you now run the project with data in the database, this is what you see.11 You have created an application which reads from a Mysql database through a PHP service and displays the data on a Flex DataGrid and you have not written one line of code. Feels like magic? It is 🙂 More on Flash Builder 4 can be seen at http://sujitreddyg.wordpress.com/flash-builder-4/