Java and Flex

Document Sample
Java and Flex Powered By Docstoc
					Java and Flex
    Mysql-java-flex with a flex server
•   You’ll need a flex server:
•   Fds-tomcat has been pre-configured to run flex apps.
•   Regular tomcat can run flex too
•   JRun can be downloaded preconfigured with LCDS (Flex
    life-cycle data services express edition)
•   You’ll also need Hibernate, mysql & java
•   Hibernate is open source and comes as a jar file that
    needs to be in the classpath.
•   This tutorial was relatively easy to do using JRun.
 Install LDS (adobe livecycle data
 services) with integrated JRun4..
• This contains the same LCDS as the fds-
  tomcat and has a similar bunch of
• JRun comes preconfigured.
• This is the version I used although the
  next screen shot is of the fancier version
JRun4 – the full-blown version shown below
  - needs to be configured for LCDS but
  allows you to add servers as needed.
  This tutorial (approximately the
           next 14 slides)
• You’ll need to comment out the java.home
  definition in the jvm.config.xml file or
  you’ll get a version error between your
  compiler and the jvm packaged with the
• The main.mxml works fine but you’ll need
  to do some work to get the popup window
  Create a mysql database and a table in it
 named employee…use this script if you like
   USE SampleDB;
   CREATE TABLE `employee` (
     `employeeid` int(10) unsigned NOT NULL auto_increment,
     `firstname` varchar(255) default NULL,
     `lastname` varchar(255) default NULL,
     PRIMARY KEY (`employeeid`)
INSERT INTO `employee` (`employeeid`,`firstname`,`lastname`) VALUES
package EmployeeManagement;
       public class Employee {
      private int id;
            private String firstname;
            private String lastname;
           public void setId(int id)        {   = id;       }
            public int getId()       {          return;          }
                 public void setFirstname(String firstname)
                this.firstname = firstname;
             public String getFirstname()
                  return firstname;
             public void setLastname(String lastname)
                 this.lastname = lastname;
             public String getLastname()
                return lastname;
             }      }
• Save it in c:\fds\jrun4\servers\default\flex\WEB-
• Create directories as needed
• Compile it and save the .class file in
           Hibernate mapping file
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
             "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
   3.0.dtd">       <hibernate-mapping>
           <class name="EmployeeManagement.Employee" table="employee">
                  <id name="id" column="employeeid">
                  <generator class="native"/>
                  <property name="firstname"/>
                  <property name="lastname"/>
        <!-- This is a named query that we will use later -->
        <query name="all.employees">From Employee</query>

•   Save this file as Employee.hbm.xml in the same folder where we just
    placed our persistent (java) class
                    Creating the Hibernate
                      configuration file
•      This file contains the configuration settings that will enable Hibernate to connect to the database that we would
     like to access. The following Hibernate configuration contains the minimal settings required for this tutorial to work:
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
            "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
     <!-- Database connection settings -->
            <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
            <property name="connection.url">jdbc:mysql://localhost/SampleDB</property>
            <property name="connection.username">root</property>
            <property name="connection.password"></property>
     <!-- JDBC connection pool (use the built-in) -->
            <property name="connection.pool_size">1</property>
     <!-- SQL dialect -->
            <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
     <!-- Enable Hibernate's automatic session context management -->
            <property name="current_session_context_class">thread</property>
     <!-- Disable the second-level cache -->
            <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>                       <!--
     Echo all executed SQL to stdout -->
            <property name="show_sql">true</property>
     <!-- Load the database table mapping file -->
            <mapping resource="EmployeeManagement/Employee.hbm.xml"/>
•    This file must be named hibernate.cfg.xml and must be in the application's classpath. Therefore, we will save this
     file in the following location: C:\fds2\jrun4\servers\default\flex\WEB-INF\classes
          edit the data-management-config.xml file located in
<?xml version="1.0" encoding="UTF-8"?>
          <service id="data-service"
               messageTypes="">               <adapters>
                    <adapter-definition id="actionscript" class="" default="true"/>
               <adapter-definition id="java-dao" class=""/>
                    <channel ref="my-rtmp"/>
 <destination id="employee.hibernate">
          <adapter ref="java-dao" />
          <!--This is the unique identifier from the hibernate-entity bean -->
                <identity property="id"/>
                <paging enabled="false" pageSize="10" />
                <throttle-inbound policy="ERROR" max-frequency="500"/>
                <throttle-outbound policy="REPLACE" max-frequency="500"/>
     Adding dependent jars
• copy the mysql-connector-java-3.0.15-ga-
  bin.jar to
• From the Flex Data Services, navigate to
  the resources/hibernate folder, copy all of
  the jars from that folder to the same
  location as the MySQL driver you just
  copied. an actionscript file
package EmployeeManagement
         public class Employee
             public function Employee() {}
               public var id:int;
               public var firstname:String="";
               public var lastname:String="";

•   Save this file as in :
•   C:\fds2\jrun4\servers\default\flex\EmployeeManager\EmployeeManagement
                                        The flex application
<?xml version="1.0" encoding="utf-8"?>
     <mx:Application xmlns:mx="" layout="absolute" creationComplete="getEmployees()"> <mx:Script>
                  import mx.controls.Alert;
                  import mx.collections.ArrayCollection;
                  import mx.rpc.AsyncToken;
                  import EmployeeManagement.*;
                  private var employee:Employee;
                  private function getEmployees():void {
                       hibernate.fill(myArray,"all.employees",[]);         }
                  private function handleFault(event:FaultEvent):void {
          </mx:Script>     <mx:DataService id="hibernate" destination="employee.hibernate" fault="handleFault(event)" autoCommit="true" />
          <mx:ArrayCollection id="myArray" />
     <mx:VBox width="783" height="562" y="10" x="10">
     <mx:ApplicationControlBar width="782" borderColor="#408080" fillColors="[#408080, #408080]" fillAlphas="[0.53, 0.53]"
     <mx:Text text="Employee Management Console" fontSize="26" fontWeight="bold" fontStyle="italic" themeColor="#ff8000" alpha="0.52"/>
     <mx:HBox x="10" y="10" width="783" height="455" id="hbox1">
     <mx:Panel id="listEmployeePanel" width="783" height="455" layout="absolute" title="Employee List" cornerRadius="8"
     borderColor="#408080" fontSize="13">
          <mx:DataGrid id="dgrid" dataProvider="{myArray}" editable="false" width="763" height="411" bottom="0" right="0">
                   <mx:DataGridColumn headerText="Employee ID" dataField="id"/>
                   <mx:DataGridColumn headerText="First Name" dataField="firstname"/>
                   <mx:DataGridColumn headerText="Last Name" dataField="lastname"/>
           Pop up window
• In my flex.ppt (and on the adobe help
  page) you can find information on setting
  up a pop up window.
• The code for a pop up window for this
  application to create a new employee is in
  this slide’s notes and accompanies the
  download files.
 The application loads hibernate from mysql
and uses a simple java bean and flex… here
           it is running on JRun4
Pop up window to add new employee
Mysql table shows new employees
          Multiple web apps
• One way to establish multiple web apps
  running on the server is to create multiple
  directories under
• Create a subdirectory employee (or
  something) at this level and copy
  necessary files over, maintaining the
  directory structure.
Note url
      About Java DAO and Flex
• Coenraets’ fds-tomcat contains an entire tomcat
  distribution configured to run flex.
• Download it at: 30 minute test drive
• This “test drive” also contains tutorials and examples
  showing flex use with hibernate, spring and java.
• His pdf on java dao/flex (Flex Data Management
  Services Tutorial link in the index) is a good starting
  point tutorial to get your feet wet.
• Careful, there may be a typo or two. His blog site has
Coenraets fds tutorial
    Hw – complete the Coenraets
• Coenreats uses a hibernate database that
  comes with the fds-tomcat. Be careful to make
  copies of various xml config files which you
• Good idea to save the original zip to restore
  settings if things get goofed up.
• In particular, we will later use mysql to interface
  with flex. This involves changing a properties
  file which will break the Coenreats’ tutorial
        Other details: classpath
• To do your own DAO coding, you’ll need more jar files in
   your class path: spring.jar and flex-messaging.jar
• You can set the classpath as you compile or with a
   separate instruction:
C:> sdkTool -classpath classpath1;classpath2...
C:> set CLASSPATH=classpath1;classpath2...
• It may be easiest to make a batch file or set the class
   path environment variable to include the path settings…
   go to control panel->system->advanced->environment
   variables->edit classpath
• You can find more details by searching online.
        About Java DAO and Flex
  Accessing Spring beans from flex (FDS)

• Lin lin has a pretty good tutorial also for building
  the entire DAO layer by hand and provides a flex
  client interface also.
• Tutorial URL at
• There may be an error in here, too. Certainly, as
  with Coenraets, there are a few omissions.
 Screenshot: a DAO layer interfacing with
MySQL and displayed in Flex, running in the
           fds-tomcat server
                         Spring Configuration

•   1). Download spring.jar and flex-spring-factory.jar to your machine, and put them into your flex
    app’s WEB-INF/lib directory.
    2). Add the following into your flex app’s WEB-INF/web.xml file, inside <web-app> tag.
•   <context-param>
       <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class>
•   3). Add the following into to WEB-INF\flex\services-config.xml inside <services-config> tag:
                <factory id="spring" class="flex.samples.factories.SpringFactory"/>
    4). If you are using JRun as app server, set the following in WEB-INF\jrun-web.xml to avoid parser
               <load-system-classes-first> true</load-system-classes-first>
    Now you are ready to use flex to access Spring beans.
Properties file for mysql connection
• In webapps/root/web-inf/src edit the file Be sure to save
  the old version which shows how to
  connect to hibernate!!!
jdbc.url=jdbc:mysql:test ///your_db_name
                Other errata
• For some reason, I needed to use MyAssembler
  as well as MyAssemblerSpring… I couldn’t find
  where the system was looking for it, but I copied
  both identical class files to my java class
  directory. Because this file accessed
  “MyService” I wound up sticking both MyService
  and MyServiceSpring (identical class files) into
  my java classes directory.
• Besides the properties file, you need to put
  database connection details in
• see next slide
   A piece of Webapps\root\Web-
<bean id="dataSource"
     <property name="driverClassName"
     <property name="url" value="http://localhost:3306/test"/>
     <property name="username" value="root"/>
     <property name="password" value=""/>
   Hw: complete lin lin tutorial
• Complete tutorial.
• Then add reasonable CRUD functionality
  to your web app.
  Automatically generate flex and
            java code
      A flex-jrun app example
  x2_gettingstarted.pdf (a large pdf on
  installing and using Flex Builder)

Shared By: