1 Farata Systems Training. BlazeDS Data Synchronization with CDB, Workshop.

© Farata Systems, L.L.C., 2010 www.faratasystems.com 2

Adobe Flex

Advanced Training

© Farata Systems, L.L.C., 2010 www.faratasystems.com 3 Farata Systems Training. BlazeDS Data Synchronization with CDB, Workshop. PREREQUISITIES:

Java JDK 6 Apache Tomcat 6

Eclipse JEE Ganymede SR-2 Flash Builder 4 Plug-in for Eclipse

Walkthrough 1. Creating Eclipse-embedded Tomcat Instance

In this walkthrough you’ll configure an instance of Tomcat inside Eclipse JEE IDE. This will allow you to create, deploy, and run Flex/J2EE applications without leaving Eclipse

1. Create the instance of Apache Tomcat in Eclipse IDE

a. Create new server in the Servers View of the JEE perspective:

b. In the New Server dialog select Apache Tomcat and click Next.

© Farata Systems, L.L.C., 2010 www.faratasystems.com 4

© Farata Systems, L.L.C., 2010 www.faratasystems.com 5 Farata Systems Training. BlazeDS Data Synchronization with CDB, Workshop. c. Browse to Tomcat installation root and click Choose.

d. Click Finish. Verify that the server entry has been created in the Servers view:

© Farata Systems, L.L.C., 2010 www.faratasystems.com 6

© Farata Systems, L.L.C., 2010 www.faratasystems.com 7 Farata Systems Training. BlazeDS Data Synchronization with CDB, Workshop. a. You may also open a browser and hit URL

http://localhost:8080/SampleFlexWebProject/SampleFlexWebProject. html. In either case you will get a blank white page, since nothing had been added to MXML application.

b. In additionally, open the URL http://localhost:8080/SampleFlexWebProject/messagebroker/amf.

You should be also getting a blank page. This is the best way to verify that BlazeDS MessageBroker, corresponding to your context is alive.

© Farata Systems, L.L.C., 2010 www.faratasystems.com 8

Walkthrough 2. Installation of the Farata Clear Plugin

In this walkthrough you’ll learn how to install Farata Clear assets during runtime.

Farata Clear Plugin automates persistence tasks, whether you code for BlazeDS or LCDS. It turn, it consists of several plugins, in particular – DTO2Fx and Clear Data Builder aka CDB. Together they perform the following functions:

a. DTO2Fx generates matching ActionScript class every time a Java class annotated with the @FXClass annotation is modified

b. CDB automates registration of the remote Java classes with the MessageBroker configuration files.

c. CDB generates Java Assembler files to support push of the changes to all clients subscribed to the result set identified by the same retrieval parameters. d. CDB, optionally, replaces writing of the persistence code via model-driven development, based on a Fiber model XML, JP-QL/HQLi or Java SQL annotationii

1. This step is described for a Windows OS. If you are running Mac OS X 10.6 you should proceed directly to step 2. Otherwise, make appropriate adjustments.

a. Make sure that JDK 1.6 is installed on your computer and system variable JAVA_HOME points to JDK 1.6. Otherwise, download and install JDK 1.6.x:

© Farata Systems, L.L.C., 2010 www.faratasystems.com 9 Farata Systems Training. BlazeDS Data Synchronization with CDB, Workshop.

b. Make sure that default JRE used by Eclipse is JDK 1.6:

2. In Eclipse Ganymede click Help->Software Updates and select Available Software tab. In the dialog, click Add Site and, via Archive… navigate to the site_4.0.0.zip. You will find a copy of the file in the root of the FarataTraining folder. Click OK.

© Farata Systems, L.L.C., 2010 www.faratasystems.com 10

i. These are features of upcoming CDB 4.0

ii. This is a feature of CDB 3.x and it will be preserved in CDB 4.0 with Java annotations replacing Doclets.

© Farata Systems, L.L.C., 2010 www.faratasystems.com 11 Farata Systems Training. BlazeDS Data Synchronization with CDB, Workshop. 3. Back in the Available Software dialog make sure checkbox site_4.0.0.zip is on and then click Install.

4. In the next dialog click Next

5. And in the following dialog click Finish.

© Farata Systems, L.L.C., 2010 www.faratasystems.com 12

6. Click Yes to restart Eclipse, when prompted, after installation. This will restart Eclipse with the new installed version of the Farata Clear Plugin

7. DO NOT DO IT NOW. To upgrade Farata Clear Plugin you would proceed to the Installed Software dialog and click Uninstall

© Farata Systems, L.L.C., 2010 www.faratasystems.com 13 Farata Systems Training. BlazeDS Data Synchronization with CDB, Workshop. After uninstall you would manually delete all com.farata.* jars and folders from Eclipse/plugins and Eclipse/features. Then you would install a new version of the site_4.x.x.zip

© Farata Systems, L.L.C., 2010 www.faratasystems.com 14

Walkthrough 3. Creation of the New CDB Project

CDB Project is similar to Flex Project with Java features. In Eclipse terms, it is also a Dynamic Web Project, which, in addition has Flex Feature and also the CDB Feature.

1. Start creating of the new CDB project with invoking the New->Dynamic Web Project. You may want to navigate to it via Other…:

2. In the dialog below, select the name of the project - ClearFlexJava. Then click Modify to add CDB facets.

© Farata Systems, L.L.C., 2010 www.faratasystems.com 15 Farata Systems Training. BlazeDS Data Synchronization with CDB, Workshop.

© Farata Systems, L.L.C., 2010 www.faratasystems.com 16 3. In the Project Facets dialog, check all Farata Clear facets and then OK.

NOTE: One of the facets that you are selecting populates the project with examples. You do not have to turn it on unless you are in the training mode.

4. Back in the New Dynamic Web Project dialog click Next

© Farata Systems, L.L.C., 2010 www.faratasystems.com 17 Farata Systems Training. BlazeDS Data Synchronization with CDB, Workshop. 5. Confirm the context URL and folder by clicking another Next:

6. Make sure that BlazeDS radiobutton (if you are creating a BlazeDS project) is selected and select the location of the BlazeDS jar. Please use a copy of the BlazeDS 4 from the root of the FarataTraining folder. Click Finish.

7. The automatic build of the CDB will start. CDB is running ANT build script as final part of its job. You will see the following in your console:

© Farata Systems, L.L.C., 2010 www.faratasystems.com 18

This indicates that (examples) Java files of the project have been processed and, in particular, services-generated.jar have been placed in WEB-INF/lib of your Web application.

© Farata Systems, L.L.C., 2010 www.faratasystems.com 19 Farata Systems Training. BlazeDS Data Synchronization with CDB, Workshop. 8. In the Servers View (you can find it in the J2EE Perspective or, alternatively, you have to add it to the Flex perspective via View->ShowView menu) right- mouse click on the embedded instance of the Tomcat server and select Add/Remove Projects. In the popup window select the project to deploy in the Available projects panel, hit Add and then Finish. The name of the deployed project will appear in the Configured project panel:

9. Right-click on the server again and select the Start. This completes the project creation. You can run Flex files from this project as usual.

© Farata Systems, L.L.C., 2010 www.faratasystems.com 20

Walkthrough 4. Running CDB Examples (Java- based)

In the walkthrough you will learn how to run test artifacts generated by CDB per your Java annotated classes. You will also get introduction to Autosync feature of the Clear toolkit, that allows to automatically propagate data changes across browser instances/computers.

1. After each run of the CDB it generates sample Flex examples for each annotated Java file. Locate the FreeFormTest.mxml sample that was generated based on the com.farata.test.basic.Company.java file and copy it to the flex_src folder. Mark it as Default Application and run as Flex Application:

© Farata Systems, L.L.C., 2010 www.faratasystems.com 21 Farata Systems Training. BlazeDS Data Synchronization with CDB, Workshop. 2. Use the following testing sequence:

a. Click on Fill to populate the top DataGrid b. Click on Add to create an empty company record

c. Enter new company name in the Farata DataForm d. Click Commit to persist the change

NOTE. The backing Java example file does not use any database or file, your changes will remain only until the restart of the server.

© Farata Systems, L.L.C., 2010 www.faratasystems.com 22 3. In the flex_src folder locate CompanyEntryDemo.mxml. Set it as Default Application and run as Flex application. Use the following testing sequence:

a. Click on Fill to populate the top DataGrid b. In the top DataGrid click on Add to add a new Company

c. DO NOT modify Id (it will be autoincremented by the backend automatically). Type in the name of the new company.

d. In the bottom DataGrid click on Add to add an associate for the company e. DO NOT modify Id or CompanyId. Type in the name of the new associate.

f. Click Commit g. Bring the second instance of the browser and run the duplicate instance of the application by copying your URL (default: http://localhost:8080/ClearFlexJava/CompanyEntryDemo.html)

h. Resize both windows and place them side by side as shown below i. Click Fill on the second instance. Watch that any commited change to the hierarchical data via either of the instances is reflected on another one. This illustrates that push of the change messages from the BlazeDS to Flex client.

© Farata Systems, L.L.C., 2010 www.faratasystems.com 23 Farata Systems Training. BlazeDS Data Synchronization with CDB, Workshop.

Walkthrough 5. CDB with Existing Java Code: DTO

In this following walkthroughs you will learn how to annotate a regular pair of Java data transfer object (DTO) and Java data access class (DAO) so that you can take full advantage of the Clear components on the Flex and BlazeDS side. 1. Notice that for each AssociateDTO.java and CompanyDTO.java there is a corresponding pair of classes in the flex_src folder:

NOTE: Two files for each annotated Java file reflect “generation-gap” pattern, whereby the low-level class is being regenerated by the tool and the inheriting class is reserved for the developer’s modifications: the tool generates it only in the absence of the existing copy.

© Farata Systems, L.L.C., 2010 www.faratasystems.com 24 2. Open project Properties->JavaCompiler->Annotation Processing and explore the setting that directs the output location of the Flex DTO. You can use absolute or relative the project path here:

3. Open com.farata.test.dto.CompanyDTO.java. Observe the @FxClass annotation. Parameter ignoreSuperClasses allows skip generation of the mathching Flex properties for the superclasses and interfaces of the current class.

@FXClass(ignoreSuperclasses={com.farata.daoflex.IUID.class}) public class CompanyDTO implements Serializable, com.farata.daoflex.IUID {

4. Observe implementation of the company property. FxClass annotation automatically facilitates processing both for public variables and accessors. You could drop getCompany()/setCompany() and it would work with public String company, or likewise you could use private instance variable for company with the public get()/set() pair. The following syntax adheres to JavaBeans convention (has the pair of accessor method ) plus it allows using dot-notation while referencing company property:

public String company;

public String getCompany() { return company; }

public void setCompany(String value) {

© Farata Systems, L.L.C., 2010 www.faratasystems.com 25 Farata Systems Training. BlazeDS Data Synchronization with CDB, Workshop. this.company = value; }

5. Add a public property myProperty and watch that com.farata.test.dto.generated._CompanyDTO.as instantly has this property as well.

public java.lang.String myProperty;

6. Observe implementation of the id property. It is annotated with @Id and @GeneratedValue annotations.

If your database is MySQL, this indicates that this column is “autoincremented” by the DAO layer; in case of ORACLE it means that DAO layer is using a sequence to update it explicitly. Either way, Flex UI has to know about the new value upon insert and @GeneratedValue serves this purpose: generated Assembler code will communicate to the Flex the value changed by the persistent back-end (a bit later on that).

7. Observe implementation of the id property once more. It is annotated with @FxKeyColumn. Properties annotated with @FxKeyColumn make a composite semantic key. If present, this key: d.a) supercedes @Id while finding the record to delete or update in the persistent storage; d.b) supercedes @Id and complements internal uid in process of finding the record during server-to-client push (the match is attempted first on uid and then on the combination of properties contributing to the semantic key)

It this example - along with @Id annotation @FxKeyColumn is redundant, and serves only the reference purposes.

public Long id;

@Id @GeneratedValue @FXKeyColumn public Long getId() { © Farata Systems, L.L.C., 2010 www.faratasystems.com 26 return id; }

public void setId(Long value) { this.id = value; } }

8. Observe implementation of the uid property. This is an internal property very much liked by Flex and BlazeDS. If you do not create it yourself, Flex and BlazeDS create it. However it is highly recommended that you explicitly create your own, precisely as sampled.

NOTE: annotation FxIgnore allows you to skip generation of the particular property. In this case it is done to allow different code generation that is done for “id” and “company” properties.

NOTE: If you leave both accessors and variable public, accessors get preferential treatment. So, if you need to annotate such property with @FxIgnore - do it on the method.

@FXIgnore public String getUid() {

if (uid==null ) { uid = "" +id; if (uid.equals("")) uid = UUIDUtils.createUUID(false); } return uid; }

public void setUid(String uid) { this.uid = uid; }

9. Inspect a “second-tier” generated file – com.farata.test.dto.AssociateDTO. Notice that [RemoteClass] annotates precisely this class and not it’s super - _AccosiateDTO. Flex application code is supposed to use this very class.

[RemoteClass(alias="com.farata.test.dto.AssociateDTO")]

© Farata Systems, L.L.C., 2010 www.faratasystems.com 27 Farata Systems Training. BlazeDS Data Synchronization with CDB, Workshop.

public class AssociateDTO extends com.farata.test.dto.generated._AssociateDTO { …

© Farata Systems, L.L.C., 2010 www.faratasystems.com 28

Walkthrough 6. CDB with Existing Java Code: DAO

In this walkthrough you continue to learn how to use CDB with existing Java code. Once you learned automation of the DTOs you will look at what you need to do with your DAO classes.

1. Open com.farata.test.basic.Company.java. Observe that it “implements” two methods:

public List fill(); public List sync(List list);

Why sync() is returning the list if the changes back to the client? Discuss it with instructor.

2. Notice that Company.java is using Doclet annotation @daoflex:webservice for the entire class. This tells CDB to process this file. Annotation @daoflex:java in front of the fill() method is required as well. Parameter autoSyncEnabled is optional. In this case it tells that generated Assembler code will push incoming changes out to other Flex client consuming the same result set.

/** * @daoflex :webservice */

public class Company implements IJavaDAO {

DataEngine dataEngine = DataEngine.getInstance();

/** * @daoflex :java autoSyncEnabled=true */

public List fill() { List companyList = dataEngine.getCompanyList(); return companyList; }

NOTE CDB 4.0.1 will replace Doclet annotations with Java 5 ones.

3. Open WebContent/WEB-INF/flex/remoting-config.xml and observe line © Farata Systems, L.L.C., 2010 www.faratasystems.com 29 Farata Systems Training. BlazeDS Data Synchronization with CDB, Workshop.

4. Open and explore the corresponding file as well. Notice that it registers the CompanyAssembler class (a bit later), a subclass of the Company.

5. To understand the placement and how you can control the content of these files, open file daoflex.conf/daoflex.properties. Parameter remoting- config.out determines the location:

codegen.dao.template.remoting-config.name=remoting-config.xml codegen.dao.template.remoting-config.src=xsl/remoting-config.xsl codegen.dao.template.remoting-config.out=$ (flexConfigPath)/daoflex/remoting-config/$(packagePath)/$ (baseName).xml codegen.dao.template.remoting-config.override=true

NOTE: All CDB artifacts are created via XSL templates. CDB creates metadata XML files, one per annotated Java class, and then applies XSL templates against them. To peek at metadata files you should run ANT build script located in daoflex.build/build.xml and inspect .daoflex- temp folder.

6. In addition to registering Java Assembler to a remoting destination CDB creates a messaging one for every class annotated with autoSyncEnabled=true. Open WebContent/WEB-INF/flex/messaging-

© Farata Systems, L.L.C., 2010 www.faratasystems.com 30 config.xml and explain why there is no messaging destination for com.farata.test.basic.Associate Java class

7. Locate src/generated folder that contains source of the generated Java classes.

NOTE: Java Build Path->Source excludes compilation of these classes; they are compiled, jared and placed in the WEB-INF/lib by CDB/Ant

8. In the src/generated/com.farata.test.basic compare CompanyAssembler and AssociateAssembler, notice that Company Assembler does the push of the changes and AssociateAssembler is redundantly extending the super.

public final List fill_sync(List items) { List result = super.sync(items);

pushChanges("com.farata.test.basic.Company.fill", result); return result; }

public final List pushChanges(String destination, List items) { if (!items.isEmpty()) { MessageBroker msgBroker = MessageBroker.getMessageBroker(null); AsyncMessage msg = new AsyncMessage(); Message message = LastMessage.getMessage(); if (message!=null) { String autoSyncSubtopic = (String) message.getHeader( LastMessage.AUTOSYNC_SUBTOPIC_HEADER_NAME ); if (autoSyncSubtopic!=null) msg.setHeader( AsyncMessage.SUBTOPIC_HEADER_NAME, autoSyncSubtopic ); }

© Farata Systems, L.L.C., 2010 www.faratasystems.com 31 Farata Systems Training. BlazeDS Data Synchronization with CDB, Workshop. msg.setDestination(destination); msg.setClientId(UUIDUtils.createUUID(true)); msg.setMessageId(UUIDUtils.createUUID(true)); msg.setTimestamp(System.currentTimeMillis()); msg.setBody(items); msgBroker.routeMessageToService(msg, null); }

return items; }

Discuss with instructor the use of the LastMessage. It is a static class keeping the thread-local last remoting message that was sent from Flex.

9. Open WebContent/WEB-INF/flex/remoting-config.xml and observe that instead of the regular Adobe adapter, remoting to Java is done via custom Farata adapter. The sole purpose of that adapter is to keep the message in the thead-local inside the LastMessage.

. . .

10. Open FreeFormText.mxml. Find fill_onClick() fill() method – this is how you invoke the Java fill() method from your class:

collection.method="fill";

where collection is an instance of the Farata clear.collections.DataCollection.

11. Locate the use of the sync() method, which sends all updates to the server: © Farata Systems, L.L.C., 2010 www.faratasystems.com 32

collection.sync();

12. Notice the initialization of the collection in the onCreationComplete():

private function onCreationComplete() : void { collection = new DataCollection(); collection.destination="com.farata.test.basic.Company"; collection.method="fill"; collection.autoSyncEnabled = true; }

This completes the walkthrough: you have went through entire cycle from Java DTO to Flex DTO and from Java DAO to Flex application.

© Farata Systems, L.L.C., 2010 www.faratasystems.com 33 Farata Systems Training. BlazeDS Data Synchronization with CDB, Workshop.

Walkthrough 7. Transactional Update of Hierarchically Related Entities

In this walkthrough you further knowledge of CDB when it comes to transactional update of the server with the data associated hierarchically via “one-to-many” relationships.

1. In the src folder compare com.farata.test.transactional.Company and com.farata.test.basic.Company .

/** * @daoflex :webservice */ public class Company extends com.farata.test.basic.Company implements IJavaDAO,IBatchServiceTransactionSupport {. . .

public final List fill_deleteItems(List items) { . . .} public final List fill_updateItems(List items) { . . .} public final List fill_insertItems(List items) { . . .}

Observe that “transactional” Company feature additional implementation of IBatchServiceTransactionSupport interface. Separate invocation of these methods versus atomic sync() is required to maintain order of inserts and deletes as far as dependent records are concerned:

- delete child

- delete parent - update parent

- update child - insert parent

- insert child

-

© Farata Systems, L.L.C., 2010 www.faratasystems.com 34 This is supported by the ActionsScript BatchService and Java class BatchGateway. Usage of these clasess is automated by the API dataCollection.sync(true), which indicates transactional update of the hierarchy of DataCollections.

2. In the forlder WebContent/WEB-INF/flex open remoting-config.xml and observe destination batchGateway:

In the same folder open daoflex/remoting-config/BatchGateway.xml:

com.farata.remoting.BatchGateway

BatchGateway is a part of the daoflex-runtime.jar

3. Open Java file src/com/farata/test/dto/CompanyDTO.java. Observe that property associates is annotated as @OneToMany. On the Flex side, it will result in creating an ArrayCollection property associates and assigning to it an instance of CompanyAssociateCollection.

@OneToMany( dataCollectionClass="collections.CompanyAssociateCollection", keys="id", syncType=SyncType.BATCH) public List associates;

4. Open Flex file flex_src/com/farata/test/dto/generated/_CompanyDTO.as. Observe that generated Flex property associates of type CompanyAssociateCollection gets “lazy” populated on first read:

/* One to many property "associates" */ private var _associates:collections.CompanyAssociateCollection;

[Transient][Bindable(event="propertyChange")] public function get associates():mx.collections.ArrayCollection { if (_associates==null) { _associates = new collections.CompanyAssociateCollection(); © Farata Systems, L.L.C., 2010 www.faratasystems.com 35 Farata Systems Training. BlazeDS Data Synchronization with CDB, Workshop. . . . . _associates.fill(id); } return _associates; } public function set associates(value:mx.collections.ArrayCollection):void { . . . . }

This collection is a child of the parent collection (the one that holds individual CompanyDTOs). Syncronization of changes to child collections is done automatically as part of the deep sync of the topmost collection in the hierarchy.

5. Open flex_src/views/CompanyEntryToolbar.mxml and locate fill() and sync() method invocations. This is population of the top-level collection and sync of the top-level collection, correspondingly:

NOTE: Bindable property dataCollection.commitRequired is conveniently used to enable/disable Commit button.

6. Often DTOs contain identity property that is autoincremented by the backend database. In the case corresponding property has to be annotated as @Id. In our scenario, both CompanyDTO.java and AssociateDTO.java annotated id property as identity.

© Farata Systems, L.L.C., 2010 www.faratasystems.com 36 In the folder src/generated, containing generated Java files, locate com/farata/test/transactional/CompanyAssembler.java and observe its fill_insertItems() method.

Notice that after insert is done, for every inserted item CompanyAssembler saves the mapping (client identity -> server identity). Client identity is an arbitrary number that you set in the (Flex) application code (you will see an example a bit later). Server identity is a value produced by the backend upon insert. Assemblers keeps unique map per class name (in this case – com.farata.test.dto.CompanyDTO):

IdentityRack.setIdentity( "com.farata.test.dto.CompanyDTO", tempIdentityMap.get(item).longValue(), item.id );

7. Open com/farata/test/transactional/AssociateAssembler.java in the same folder.

Notice that (prior to insert) for every to-be-inserted item AssociateAssembler replaces the client identity with the server identity that was saved by the insert of the parent DTO in the prior step. In this case item.company_id is a key to retrieve that value. This works as long as the Flex application code presets item.company_id with the values 0, -1, -2 matching what was set as “id” in the parental record:

item.company_id= IdentityRack.getIdentity( "com.farata.test.dto.CompanyDTO", item.company_id );

8. Open src/com/farata/test/dto/AssociateDTO.java and observe that company_id is annotated with @ManyToOne annotation:

@ManyToOne(parent="com.farata.test.dto.CompanyDTO") public Long getCompany_id() { return company_id; }

This annotation, combined with the @Id annotation results in the described Assembler code generation.

© Farata Systems, L.L.C., 2010 www.faratasystems.com 37 Farata Systems Training. BlazeDS Data Synchronization with CDB, Workshop.

9. In flex_src/views open CompaniesPanel.mxml and CompanyAssociatesPanel.mxml. Locate and compare use of DataCollectionUtils.getLocalIdentity() API. This is how a Flex client code is supposed to pre-set values that will be replaced by the AUTOINCREMENTed.

private function onAdd(position:int):void { var item:CompanyDTO = new CompanyDTO(); // For the purpose of PK-FK linking in batch transaction // you should initialize new autoincrement values with //"locally" unique values: 0, -1, -2, etc. item.id = DataCollectionUtils.getLocalIdentity( companies,"id" ); companies.addItemAt(item, position); dg.selectedIndex = position; }

10. Summary

Code of the Farata Clear components: DataCollection and BatchService ensures that a serialized descriptor of “to-be-made” remote calls is sent to the BatchGateway, including destination names, method names and parameters.

For each data collection there are three calls instead of one sync(). These “calls” are sorted so the hierarchically “deeper” collections run their deletes prior to the parents and, vise versa, inserts of the parents always go before inserts of the kids.

The actual calls are done by the BatchGateway via reflection and Flex/BlazeDS API. The whole sequence of calls is done under JTA UserTransaction.

This completes the series of walkthroughs on CDB-Java usage © Farata Systems, L.L.C., 2010 www.faratasystems.com 38

© Farata Systems, L.L.C., 2010 www.faratasystems.com 39 Farata Systems Training. BlazeDS Data Synchronization with CDB, Workshop.

Walkthrough 8. Using CDB In the Model-Driven Way (SQL, JPQL, Fiber)

CDB 4 allows to automatically generate all Java code given you know the SQL of the datasource that needs to be synchronized with the client. It supports it via Doclet-style SQL annotations of the abstract Java classes that serve as a development model. Release version of CDB 4.0.0, in addition to SQL, will support JPQL/HQL and Fiber XML, however, it will use Java5 annotations in place of Doclets.

1. As a pre-requisite you need to install MySQL 5 and restore the database using back up file farata_test_MySQLWindows.sql. This file can be found in the root of the FarataTraining folder.

You should also create the database user: dba. Password: sql.

This user has to have all rights to the “test” catalog.

2. Start creation of the FlexSQLJava project by creating a new Dynamic Web Project:

© Farata Systems, L.L.C., 2010 www.faratasystems.com 40

© Farata Systems, L.L.C., 2010 www.faratasystems.com 41 Farata Systems Training. BlazeDS Data Synchronization with CDB, Workshop. 3. Add Farata Clear facets and click OK

4. Back in the dialog, click Next:

© Farata Systems, L.L.C., 2010 www.faratasystems.com 42 5. Select BlazeDS radiobutton, located BlazeDs.war and click Next:

6. In the following dialog, select: Database Driver – MySql 5,

Pool Name (JNDI Datasource name) – jdbc/test, database URL – jdbc:mysql://localhost:3306/test

User – dba Password - sql

Click Test Connection, then Finish.

© Farata Systems, L.L.C., 2010 www.faratasystems.com 43 Farata Systems Training. BlazeDS Data Synchronization with CDB, Workshop.

7. The automatic build of the CDB will start. CDB is running ANT build script as final part of its job. You will see in your console the output similar to the one in Step 7 of the Walkthrough 3, indicating that ANT build script ran by the CDB is successful.

8. Navigate to test/rpc/com/farata/test/Employee/getEmployees and copy generated test file FreeFormTest.mxml to the flex_src.

© Farata Systems, L.L.C., 2010 www.faratasystems.com 44

© Farata Systems, L.L.C., 2010 www.faratasystems.com 45 Farata Systems Training. BlazeDS Data Synchronization with CDB, Workshop. 9. Set the application as Default and Run it as Flex application. You will see and will be able to edit and persist the database data:

10. Observe the correspondence between methods of Employee class and generated tests. Notice that there is more then one annotated method per class.

© Farata Systems, L.L.C., 2010 www.faratasystems.com 46

11. In the folder src/com/farata/test open Employee.java and discuss it with your instructor.

Notice that you can indicate pool (datasource) on the class or on the method level. Annotation parameter sql allows CDB to query result set metadata in the design time, during code generation, while parameter transferType tells CDB the name of the Java DTO class.

If JavaDTO does not exist – in the dto subfolder relative to the class directory, it will be created with the properties derived from the result set metadata.

The Flex DTO will then, automatically, be created by CDB, based on Java DTO

Parameter autoSyncEnabled will tell CDB to push changes to connected clients of the same result set.

© Farata Systems, L.L.C., 2010 www.faratasystems.com 47 Farata Systems Training. BlazeDS Data Synchronization with CDB, Workshop. Parameter updateTable is required to generate getEmployee_sync() as well as getEmployees()_insertItems()/_deleteItems/_updateItems().

Parameter keyColumns determines how incoming records should be matched with ones existing in the database.

/** * @daoflex :webservice * pool=jdbc/test */ public abstract class Employee { /** * @daoflex :sql * pool=jdbc/test * sql=:: select * from employee * :: * transferType=EmployeeDTO[] * keyColumns=emp_id * updateTable=employee * autoSyncEnabled=true */ public abstract List getEmployees(); . . .

© Farata Systems, L.L.C., 2010 www.faratasystems.com 48 12. In the same folder open Company.java and observe two annotated methods: getCompanies() and getCompanyAssociates(). They correspond to Company.java and Associate.java that were “hand-written” in Walkthroughs 3-7. However, all that is handwritten here is how the classes should look like, because this is abstract class.

Observe parameters identity and mappedByColumns. The latter indicates that column_id of the CompanyAssociateDTO is “many-to-one” to identity column of the parental record in the company table.

/** * @daoflex :webservice * pool=jdbc/test */ public abstract class Company { /** * @daoflex :sql * sql=:: select id,company * from company * :: * transferType=CompanyDTO[] * keyColumns=id * identity=id * updateTable=company * autoSyncEnabled=true */ public abstract List getCompanies();

/** * @daoflex :sql * sql=select * from company_associate WHERE company_id=:companyId * transferType=CompanyAssociateDTO[] * updateTable=company_associate * keyColumns=id * identity=id * mappedColumns=company_id:company * autoSyncEnabled=true * transferCase=upper * transformCase=upper */ public abstract List getCompanyAssociates(String companyId); }

NOTE. There are few other Doclet annotations in CDB, all of them are sampled in the CDB project, unless you check off the Example facet during the project creation. © Farata Systems, L.L.C., 2010 www.faratasystems.com 49 Farata Systems Training. BlazeDS Data Synchronization with CDB, Workshop. 13. Examine the generated code in the folder src/generated and discuss it with your instructor. As in case with the manually created Java, the code is produced based on the XSL templates located in the daoflex.conf/xsl folder.

14. In the flex_src folder locate CompanyEntryDemo.mxml. Set it as Default Application and run as Flex application. Use the following testing sequence:

a. Click on Fill to populate the top DataGrid b. In the top DataGrid click on Add to add a new Company

c. DO NOT modify Id (it will be autoincremented by the backend automatically). Type in the name of the new company.

d. In the bottom DataGrid click on Add to add an associate for the company e. DO NOT modify Id or CompanyId. Type in the name of the new associate.

f. Click Commit g. Bring the second instance of the browser and run the duplicate instance of the application by copying your URL (default: http://localhost:8080/ClearFlexJava/CompanyEntryDemo.html)

© Farata Systems, L.L.C., 2010 www.faratasystems.com 50 h. Resize both windows and place them side by side as shown below i. Click Fill on the second instance. Watch that any commited change to the hierarchical data via either of the instances is reflected on another one. This illustrates that push of the change messages from the BlazeDS to Flex client.

© Farata Systems, L.L.C., 2010 www.faratasystems.com