Mapping Action Script objects to Java objects

Invoking Java classes on a server is a very useful feature provided by the BlazeDS. When a method from a Java class is invoked from a Flex application on the client, Blaze DS converts automatically converts the Java data types to suitable Action Script (AS) data types

For Java objects that BlazeDS does not handle implicitly, values found in public bean properties with get/set methods and public variables are sent to the client as properties on an Object. Private properties, constants, static properties, and read-only properties, and so on, are not serialized. For ActionScript objects, public properties defined with the get/set accessors and public variables are sent to the server.

BlazeDS uses the standard Java class, java.beans.Introspector, to get property descriptors for a Java bean class. It also uses reflection to gather public fields on a class. It uses bean properties in preference to fields. The Java and Action-Script property names should match. Native Flash Player code determines how ActionScript classes are introspected on the client.

We can map an Action Script class to a Java class on the server. Once mapped the objects are casted to respective types on the client and the server. We use [RemoteClass] metadata tag to map Action Script class to the Java class.

For this we will create a Person.java class and an Person.as class and map both. Once mapped we will invoke a method from a Java class which will return a object of the type Person.java on the server using RemoteObject component. Once the object is returned, we will use the returned object as object of the type Person.as

We need BlazeDS setup and running to execute this sample. Please follow the steps in https://sujitreddyg.wordpress.com/2008/01/14/invoking-java-methods-from-adobe-flex/ to set up the BlazeDS and setting up a Flex application, which is mapped to BlazeDS root directory. Use the same link to configure a destination on BlazeDS to map to a Java Class.

Creating Java classes

RemoteServicehandler.java

This class will be invoked from the Flex application. Once the getPerson() method is invoked, we will return the Person object.

package com.adobe.remoteobjects;

import java.util.Date;

import com.adobe.objects.Person;

public class RemoteServiceHandler {

public RemoteServiceHandler()

{

}

public Person getPerson()

{

Person person = new Person();

person.id = 1;

person.dateOfBirth = new Date();

person.name = “Sujit”;

person.company = “Adobe”;

return person;

}

}

Person.java

package com.adobe.objects;

import java.util.Date;

public class Person {

public int id;

public String name;

public Date dateOfBirth;

public String company;

}

Under the folder where the Blaze DS zip file was extracted, navigate to tomcat/webapps/blazeds/WEB-INF/classes and then copy the Java class in appropriate directory structure.

Creating Flex application

RPC.mxml

Please do have a reference to the Person.as in your mxml file, otherwise Person.as will not be linked to the SWF file created and will not be available on run time.

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

<mx:Application xmlns:mx=”http://www.adobe.com/2006/mxml&#8221; layout=”vertical”>

<mx:Script>

<![CDATA[

import objects.Person;

import mx.rpc.events.ResultEvent;

import mx.controls.Alert;

private function displayPersonDetails(event:ResultEvent):void

{

var person:Person = Person(event.result);

Alert.show(person.name + “, ” + person.dateOfBirth.toDateString() + “, ” + person.id);

}

]]>

</mx:Script>

<mx:RemoteObject id=”remObj”

destination=”CreatingRpc”

result=”displayPersonDetails(event)”

fault=”Alert.show(event.fault.faultString);”

/>

<mx:Button label=”Get Person” click=”remObj.getPerson();” />

</mx:Application>

Person.as

Please observe the [RemoteObject] metadata tag. Using this tag we map this class to the Java class on the remote location. The Java class should be in the classpath, recognizable by the BlazeDS. The name should be the fully qualified name.

package objects

{

[RemoteClass(alias=”com.adobe.objects.Person”)]

public class Person

{

public var id:int;

public var name:String;

public var dateOfBirth:Date;

}

}

That is all we need to do.🙂

114 Responses to Mapping Action Script objects to Java objects

  1. ann says:

    Hi Sujit,

    Your posts are great!
    I was also wondering if you know whether arrays of objects can be passed the same way as described in your post?

    For example, if you have a datagrid of people and allow users to update their info. Can you send the list from flex back to your RemoteServiceHandler as java objects to receive them like this:

    public void update(List newInfoList){
    //update database here…
    }

    I tried something similar but I can only receive a List of AS objects on the java side…😦

    I’ll really appreciate any input or thoughts you have on the matter! Thanks!!

  2. Sujit Reddy G says:

    Hi,

    You can definitely send array of objects. I cannot understand, what you meant when you said that you are getting List of AS objects.😦 I can suggest you to try casting the objects in the Java method or try Generics like update(List <Person> newInfoList). Please let me know if you are still facing problem implementing this.🙂

  3. ann says:

    Hi Sujit,
    This might be kind of a dumb question… Is there any way to set the class path within Flex 3 builder? I haven’t found an option for it or any reference on the internet.
    Also, when you said “recognizable by the BlazeDS” is there anything special besides setting the environment variable classpath?

    Thanks!

  4. ann says:

    Sorry, please disregard my previous post… Your code works like a charm!

    I found the issue I was previously experiencing. I was only displaying a few of the data fields of the action class in the datagrid. For example, I only want users to edit their name but not their id so I only displayed the name column. However, when I pass the datagrid dataProvider back to the RemoteServiceHandler it didn’t match the Person class anymore and gave a class cast exception. I suspect it’s because dataProvider only contains the name field so does not match the Person class. I will try to find a solution around this. If you have any thoughts around this I’ll appreciate it, too.

    Thanks so much for your help!

  5. Sujit Reddy G says:

    Check out the description provided for the dataProvider property of the DataGrid in the Flex language reference. That might help you solve all problems you are facing🙂
    http://livedocs.adobe.com/labs/flex3/langref/

  6. Paul Bohnenkamp says:

    Hi Sujit,

    One issue I forsee with this implementation is that the Java instance variables are public and in turn the reflected ActionScript object then has public instance variables as well which I would like to know if there is a way to ensure they remain private?

    My very limited understanding is that the reflection happens on the getters, so for instance,

    Java > Person.getName = ActionScript Person.name??

    Is that correct?

    Do you know if below would achieve my objective for the instance variables to remain private?

    package {

    [RemoteClass(alias=”com.adobe.objects.Person”)]
    public class Person {
    private var _name:String;

    public function Person() {}

    public function set name (name) { this._name = name; }

    public function get name () { return this._name }

    }
    }

    Also, would this work at both ends of the wire? ie, not just Java to AS, but then back AS to Java?

    Regards,
    Paul

  7. Sujit Reddy G says:

    Hi Paul,

    Your understanding regarding reflection is correct🙂 You can have your variables as private and just expose the getters and setters in both AS and Java classes. Just let me know if you have problem implementing this🙂

  8. […] Action Script objects to Java objects This entry was written by Sujit Reddy G. Bookmark the permalink. Follow any comments here with the RSS feed for this post.Content related […]

  9. Eric says:

    Hi Sujit,

    Before I start, great great articles. It is a great resource. I have been doing Flex/ActionScript and BlazeDS for about 30 hours or so…. very very newbie and your articles really helped me along.

    I am writing a chat application (very basic but good way to learn) and am trying to populate a list of all online users (J2EE backend) into a mx:DataGrid.

    I am starting with this article to learn how to move data from Java to J2EE but the issue I am having is the person name is blank… and i am quite sure the Java code is right.

    Have you or anyone experience this

    many thanks
    Eric

  10. Shankar says:

    Hi Sujit. Your tutorials are very easy to follow. But I ran into a problem when I tried this. When I make the remote call, I get a null result back. The connectivity is working though, because I did write another public function in remoteservicehandler that returned string and it worked. Seems like a propblem only while returning data type Person. Any ideas?

  11. Sujit Reddy G says:

    Hi Eric,

    Where exactly is the person name blank? is it in the datagrid? If it is in the datagrid, please make sure if the dataField property is set as required. If you can explain your problem with the code snippets, it will be easier to help you out🙂 If you don’t want to post your code in my blog .. Please feel free to mail me🙂 my mail id is sujitreddy.g@gmail.com

  12. Sujit Reddy G says:

    Hi Shankar,

    It should be working when you return the person object also … can you please explain share the code snippets, where you are accessing the person object on the client.

  13. Shankar says:

    Sujit,

    Thanks much for your prompt response. I took your surety for granted, combed my code, and it didnt take too long to be ‘enlightened’ that all my public variables in the Java class were static. That will do it, isnt it?

    Thanks again. Now I know where to seek if I am stuck.

  14. Sujit Reddy G says:

    Hi Shankar,
    Good to know that you got things working🙂 You can definitely get back to me if you are stuck.🙂 I will try to solve the problem by myself or by taking help from the our experts here🙂

  15. SriJ says:

    I would like to know if the Person object had a nested object say Address, would that get serialized while being sent back to flash?

    class Person {
    Address address;
    String name;
    Date birthDate;
    …..
    }

  16. SriJ says:

    on the same token
    can we have Address as a static inner class of Person and would that be serialized properly?

  17. Sujit Reddy G says:

    Hi SriJ,

    yes, the Address object will also be serialized. Any variable which is public will be serialized. If you have mapped the Address class also to some class in the AS, you will be accessing the Address object as object of the type of mapped class; Otherwise you will be accessing the Address as the object of the type Object in the Flex application.
    Hope this helps.🙂

  18. Joanne says:

    How about mapping Spring AOP proxy beans? How could they be mapped to AS objects? When modifying RemoteClass alias to an interface the mapping does not work. Is mapping to an interface (that includes the setter and getter methods) possible?

  19. Joanne says:

    I also meant to say thank you so much for your posts. I have found them extremely helpful in getting up to speed on flex development.

  20. Paul W says:

    Sujit,

    Do you know is there any open source utility out there that automate conversion of Java classes to Actionscript classes?

  21. Sujit Reddy G says:

    Hi Joanne,

    I haven’t tried mapping to Spring AOP proxy beans. Mapping to an Interface is something which is possible. I tried this and it works. If you can provide more details on what problem u r facing, we can help you out.

  22. Sujit Reddy G says:

    Hi Paul,

    Try out the URLs below. Looks like they have created application for converting Java classes to AS classes.
    http://www.physicsdev.com/blog/?p=8
    http://www.mindtheflex.com/?p=61

    Hope this helps

  23. Ted C says:

    Sujit,

    The code provided in the above example gives me the following error in FlexBuilder 3 when trying to print out either company or dateOfBirth:
    (example)
    1119: Access of possibly undefined property company through a reference with static type Person.
    Any idea why the Builder cannot resolve either of these attributes, but name and id resolve fine?

    Thanks,

    Ted

  24. Sujit Reddy G says:

    Hi Ted,

    Person.as code, which i provided doesn’t have the variable named company declared. Please add that to your Person.as file and then try accessing. dateOfBirth should be accessible, please try to clean your project or share the code, so that we can figure out if we are missing something🙂

    Hope this helps.

  25. Shawn says:

    Thanks for the example. Is there a way to send the Person object from Flex to Java? I’ve tried reversing the code, but when it gets sent, Flex nulls my object. Here is an example:

    DTOTest.as

    package testingonly
    {
    [Bindable]
    [RemoteClass(alias=”testingonly.DTOTest”)]

    public dynamic class DTOTest
    {
    public var firstName:String;
    public var lastName:String;

    public function DTOTest(fname:String,lname:String){
    firstName = fname;
    lastName = lname;
    }
    }
    }

    DOTTest.java:
    package testingonly;
    import java.io.Serializable;

    public class DTOTest implements Serializable {

    private static final long serialVersionUID = 1L;
    public String firstName;
    public String lastName;

    public DTOTest(){

    }

    public DTOTest(String fname, String lname){
    firstName = fname;
    lastName = lname;
    }
    }
    TestingOnly.java:
    package testingonly;

    import java.util.*;
    import testingonly.DTOTest;

    public class TestingOnly {

    static DTOTest[] dtot;// = {

    public DTOTest[] sendTokenList(DTOTest d)
    {
    dtot[0] = d;

    return dtot;
    }

    }
    TestingOnly.mxml:

    Thanks for these great tutorials!

  26. Shawn says:

    Sorry, my last post got cut off.

    TestingOnly.mxml:

  27. Shawn says:

    I think it is the xml reference that is cutting this off. Here’s it with the xml piece removed:

    TestingOnly.mxml:

  28. Shawn says:

    Argh! Okay, only the CDATA section:

    import mx.rpc.events.ResultEvent;
    import testingonly.DTOTest;

    function sendTokenList():void
    {
    var dtot:DTOTest = new DTOTest();
    dtot.firstName = “John”;
    dtot.lastName = “Smith”;

    testCommunication.sendTokenList(dtot);

    }

    function displayResult(event:ResultEvent):void
    {
    var names:Array = event.result as Array;
    var person:DTOTest = DTOTest(names[0]);

    myBtn.label = person.firstName + “” + person.lastName;
    }

  29. Sujit Reddy G says:

    Hi Shawn,

    Yes, you can send objects from Flex to Java. Can you please mail me the source files, so that i can see what is going wrong🙂 my mail id: sujitreddy.g@gmail.com🙂

  30. Sujit Reddy G says:

    Hi Shawn,

    Couple of things went wrong. Firstly the object which are subject to serialization by BlazeDS are expected to have a default no argument constructor. Your DTOTest.class did not have a default no argument constructor. Second thing is the in your
    TestingOnly.class, you were using the array before initializing it, due to this there was an exception thrown. Thirdly, the DTOTest.as didn’t have a default no argument constructor. As AS3 will not allow you to overload constructors, you can make the constructor arguments optional.

  31. Shawn says:

    THANKS! So, just to recap for other readers,

    on the Java side, the class must have a no argument constructor such as:

    // required for BlazeDS
    public myClass(){
    // do nothing
    }

    as well as the constructor that gets values passed to it such as:

    // constructor used
    public myClass( variableType variable)
    {
    // this is where the logic goes
    }

    on the Actionscript side of things it should read such as:

    public function myClass( variableType = null )
    {
    // this is where the logic goes
    }

    By assigning the variables a null value, you are basically creating a constructor that is read both as a no argument constructor (since the values are applied with the default null if none are sent) as well as a constructor that receives a value that is passed to it (so the null value is overwritten by the passed value).

    Finally, to send private values from AS to Java you have to use the get/set methonds as found in http://livedocs.adobe.com/flex/3/html/ascomponents_3.html

    Am I understanding correctly?

    Thanks SO much for this example!

    Shawn

  32. Chandu says:

    Hi Sujith

    I have another question. I have a editable data grid which is filled with values from
    objects (Server object) retrieved from server through BlazeDS and these values are data provider for my dataGrid.

    If one more client logs in and is looking at the same data set and a user modifies the values in the dataGrid, I will modify and send the data to Server Objects for updating, but is there way I can make this happen dynamically i.e if one user edits the dataGrid and clicks update, it will automatically for another user looking at the same dataGrid

    Regards
    -Chandu

  33. Sujit Reddy G says:

    Hi chandu,

    This implementation requires code at the server to push the data to all the clients reading the data. This is something which is provided by the DataManagement service of LCDS. You can try creating a custom adapter of BlazeDS and push the data to all the clients when the data is modified.

    Hope this helps.

  34. Brian says:

    Sujit –

    Great article and very helpful! I got your example working but was wondering if you had a code snippet that uses remoteObject from within an AS class as opposed to in the mxml directly. And, if you could, include how to send the result (maybe via bindable) to an mxml component?

    Thanks so much
    -Brian

  35. Brian says:

    Sujit –

    Great article and very useful! I got your example working but was wondering if you have a code snippet that shows how to use remoteObject in an AS class instead of from the .mxml (for learning purposes)? Also, can you include how best to return the result from the AS class to the mxml component (maybe via bindable).

    Thanks,
    Brian

    PS – Sorry if this double posts.

  36. baji says:

    hey Sujit,

    I have a editable datagrid filled with Array of Objects from the server, am using blaze ds to get data from server through remote service(BlazeDS)..

    when i try to send the updated data back to server, am receiving the following error:

    [BlazeDS] Cannot create class of type ‘CardEconVar’.

    flex.messaging.MessageException: Cannot create class of type ‘CardEconVar’. Type

    ‘CardEconVar’ not found.

    at flex.messaging.util.ClassUtil.createClass(ClassUtil.java:65)

    at flex.messaging.io.AbstractProxy.getClassFromClassName(AbstractProxy.j

    ava:72)

    at flex.messaging.io.amf.Amf3Input.readScriptObject(Amf3Input.java:430)

    at flex.messaging.io.amf.Amf3Input.readObjectValue(Amf3Input.java:153)

    at flex.messaging.io.amf.Amf3Input.readObject(Amf3Input.java:132)

    at flex.messaging.io.amf.Amf3Input.readArray(Amf3Input.java:371)

    at flex.messaging.io.amf.Amf3Input.readObjectValue(Amf3Input.java:157)

    at flex.messaging.io.amf.Amf3Input.readObject(Amf3Input.java:132)

    at flex.messaging.io.ArrayCollection.readExternal(ArrayCollection.java:8

    7)

    at flex.messaging.io.amf.Amf3Input.readExternalizable(Amf3Input.java:528

    )

    at flex.messaging.io.amf.Amf3Input.readScriptObject(Amf3Input.java:455)

    at flex.messaging.io.amf.Amf3Input.readObjectValue(Amf3Input.java:153)

    at flex.messaging.io.amf.Amf3Input.readObject(Amf3Input.java:132)

    at flex.messaging.io.amf.Amf3Input.readArray(Amf3Input.java:371)

    at flex.messaging.io.amf.Amf3Input.readObjectValue(Amf3Input.java:157)

    at flex.messaging.io.amf.Amf3Input.readObject(Amf3Input.java:132)

    at flex.messaging.io.amf.Amf3Input.readScriptObject(Amf3Input.java:473)

    at flex.messaging.io.amf.Amf3Input.readObjectValue(Amf3Input.java:153)

    at flex.messaging.io.amf.Amf3Input.readObject(Amf3Input.java:132)

    at flex.messaging.io.amf.Amf0Input.readObjectValue(Amf0Input.java:132)

    at flex.messaging.io.amf.Amf0Input.readArrayValue(Amf0Input.java:323)

    at flex.messaging.io.amf.Amf0Input.readObjectValue(Amf0Input.java:136)

    at flex.messaging.io.amf.Amf0Input.readObject(Amf0Input.java:92)

    at flex.messaging.io.amf.AmfMessageDeserializer.readObject(AmfMessageDes

    erializer.java:217)

    at flex.messaging.io.amf.AmfMessageDeserializer.readBody(AmfMessageDeser

    ializer.java:196)

    at flex.messaging.io.amf.AmfMessageDeserializer.readMessage(AmfMessageDe

    serializer.java:120)

    at flex.messaging.endpoints.amf.SerializationFilter.invoke(Serialization

    Filter.java:114)

    at flex.messaging.endpoints.BaseHTTPEndpoint.service(BaseHTTPEndpoint.ja

    va:274)

    at flex.messaging.MessageBrokerServlet.service

    your help would be greatly appreciated.

  37. Sujit Reddy G says:

    Hi Brian,

    I was busy with projects this week and so could not reply soon🙂

    RemoteObject code in AS3

    var searchRemoteObject:RemoteObject = new RemoteObject();
    searchRemoteObject.destination = “destinationName”;
    searchRemoteObject.showBusyCursor = true;
    searchRemoteObject.addEventListener(ResultEvent.RESULT, searchEmployeeResultHandler);
    searchRemoteObject.addEventListener(FaultEvent.FAULT, faultHandler);
    searchRemoteObject.searchForEmployees(searchString); //this is method call

    For returning result from the AS class, i would throw a custom event and include the result in the event object. Sample:

    private function searchEmployeeResultHandler(event:ResultEvent):void
    {
    searchRemoteObject.removeEventListener(ResultEvent.RESULT, searchEmployeeResultHandler);
    var employeeConnections:ArrayCollection = event.result as ArrayCollection;

    var helperEvent:ConnectionsHelperEvent =
    new ConnectionsHelperEvent(ConnectionsHelperEvent.SEARCH_EMPLOYEE_EVENT);
    helperEvent.employeeConnections = employeeConnections;
    dispatchEvent(helperEvent);
    }

    Hope this helps.🙂

  38. Meena says:

    Hello Sujit,

    Thanks for the article; I am stuck at one place though. Actually, my java class has one ArrayList of Objects (which is another java class) for example (sorry in advance for long post however I wanted to make it clear) I think I am missing something here however I have no idea about it…please bare with me.
    Java class:
    public class UserAccountDTO{

    private String loginID;
    private String name;
    private ArrayList assignedFunction;
    ………
    ……..

    //getter and setter method
    //no args constructor
    // constructor to set all these values from outside
    public UserAccountDTO(String loginID,String name, ArrayList assignedFunction){
    this.setLoginID(loginID);
    this.setName(name);
    this.setAssignedFunction(assignedFunction);
    }
    }

    public class AssignedFunctionDTO(){
    private int function_id;
    private String function_name;

    //getter and setter methods
    //no args constructor
    //constructor to set all these value from out side
    }

    Then the method which Remote Object service calls
    public loginUtil(){

    //fetches user records from database
    //creates arraylist of AssignedFunctionDTO by
    assignedFunction.add(new AssignedFunctionDTO(functioned,functionName);
    //returns UserAccountDTO object by
    return new UserAccountDTO(loginID,name,assignedFunciton);
    }

    I am using blazeds for remoting and cairngorm for structure and created two DTO classes in flex like this:
    package;
    {
    [RemoteClass(alias=”myPackage.UserAccountDTO”)]
    public class UserAccountDTO{
    Public var loginID:String;
    Public var name:String;
    public var assignedFunctaion:Object //I tried using assignedFunctionDTO/ArrayCollection too
    }
    }

    package;
    {
    [RemoteClass(alias=”myPackage.AssignedFunctionDTO”)]
    public class AssignedFunctionDTO {
    public var function_id:int;
    public var function_name:String;
    }
    }

    In my command class I am not getting value of AssignedFunctionDTO its null
    I am doing : modelLocator.userAccountDTO = event.result;

    This gives me everything other then AssignedFunctionDTO don’t know why, if I pass a simple arraylist I get its value, however I do not get value of ArrayList which contains another object inside it… please help

  39. Sujit Reddy G says:

    Hi Meena,

    Can you please send the Java files and Flex files required to reproduce this issue to my mail id (sujitreddy.g@gmail.com). From the code you pasted in your message, the method loginUtil() does not have a return type declared. It will be easy to track down the issue if you can share the files, so that i can deploy them and reproduce the issue.

    We can definitely send ArrayList with objects of any class type.

  40. Wolman says:

    Hi Sujit,

    We’re having the same problem as Meena. We’d just like to know if there was any conclusion or explanation for that behavior.

    We are successfully sending an ArrayList of DTO objects to the flex client but when we try to send that same ArrayList back to the Java Service we are getting the following exception:

    ClassCastException : flex.messaging.io.amf.ASObject cannot be cast to ourpackage.OurDTO

    Any help much appreciated.
    Chz

  41. Prakash says:

    Hi Sujit,
    I also have the same problem. ArrayList of java objects are null at Flex client using blazeDS. If you have found the solution could you please share it?

  42. pp says:

    Wolman, Prakash

    convert your ArrayList to Array.

    pp

  43. Carlo says:

    Hello,
    how pass an object to an Java class method ? Something like this :

    //AnneSearchVO is an ActionScript class with annotations :
    //[Bindable]
    //[RemoteClass(alias=”net.AnneSearchVO”)]
    //and the class AnagraficaNeonati::getListPatient(AnneSearchVO anneSearchVO)

    var anneSearchVO:AnneSearchVO = new AnneSearchVO();
    var codiceUtente:Number = new Number(20130);
    anneSearchVO.setCodiceUtente(codiceUtente);

    AnagraficaNeonati.getListPatient(anneSearchVO);

    I get this Exception : UndeclaredThrowableException.

    Any help much appreciated.

  44. Sujit Reddy G says:

    Hi Carlo,

    Looks like you are throwing some exception from the Java class which you are invoking. It will be helpful to have a glance at the Java class. Please try to share the Java class code with us.

    Feel free to mail me your code if you are not comfortable posting your code on the blog page🙂

  45. Sujit Reddy G says:

    Hi Wolman,

    Please make sure you are mapping the objects in the ArrayCollection you are passing and the Java objects in the ArrayList which the Java method is expecting.

    Hope this helps.

  46. Don Hook says:

    Sujit –

    I have an app that calls a remote service, gets the objects, and displays them. I then go to another page, then come back to the first page and for some reason the objects do not get cast – they are null. For example, I get an error :

    TypeError: Error #1034: Type Coercion failed: cannot convert com.spinnaker.model::ExchangeVO@537d089 to com.spinnaker.model.ExchangeVO

    Where it looks like the right type of object. Not sure what the @537d089 is that is appended to the first object. Is that the serialized id?

    THanks for you help.

  47. Sujit Reddy G says:

    Hi Don,

    You said you are navigating from one page to another, can you please explain this. Are the objects in scope when you are moving to another screen? As you said the objects are becoming null, please make sure the objects scope is not lost.

    You need not worry about the @53**🙂

    Hope this helps.

  48. Deepa says:

    Hi Sujit,

    Need your help with a problem I am facing while binding Java Class with Flex Class.

    I have DesktopSearch.as model object and a similar DesktopSearch.java. When i try to send my Flex data which is a DesktopSearch object, I get this following error.

    onGetSearchFailure [FaultEvent fault=[RPC Fault faultString=”Cannot invoke method ‘getSearchResults’.” faultCode=”Server.ResourceUnavailable” faultDetail=”The expected argument types are (com.citi.sps.domain.DesktopSearch) but the supplied types were (flex.messaging.io.amf.ASObject) and converted to (null).”] messageId=”FAE91AC4-780D-D913-7FEE-3853FA82A4F7″ type=”fault” bubbles=false cancelable=true eventPhase=2]

    Please let me know what might be the cause for this problem.

    Thanks & Regards,
    Deepa

  49. Sujit Reddy G says:

    Hi Deepa,

    This might be because the DesktopSearch.as is not converted to DesktopSearch.java type when invoking the Java method. This might be because the mapping of the Class is not proper. Can you please make sure the [RemoteClass] tag is there in your DesktopSearch.as and has the Java class name.

    If this is already done and still you are facing the problem, please share the code of DesktopSearch.as and DesktopSearch.java. So that we can find out the problem. Either host the files in some URL and share links or email the source files to sujitreddy.g@gmail.com

    Hope this helps.

  50. Don Hook says:

    Sujit – I am not sure what you mean by scope. When I make the service call, I get a list of objects. Each object also has another object as an attribute. For example, the BackTest Object has a Stock object as an attribute. So on the call, I get a list of BackTest objects. I then get the Stock object from the BackTest object to display some information. The first time I execute the call – it displays fine. Subsequent calls result in the Stock Object being null on the BackTest Object.

    Again – thanks for your input.

  51. Manish says:

    Hi Sujit:
    I am trying to implement flex remoting by having flex instantiate a remote java object but it is complaining that it is not able to create a java remote object.
    I am sorry what I am giving you is a bit long. But I wanted to make the problem I am facing clear.
    I am using live cycle with flex 2.0.1
    —-
    Here are the contents of my remoting-config.xml file:

    pmmcFlex.ServerDetailRO
    request

    ——
    Here is the actionscript code snippet I am using for remote object: At this point, I am just using alert box to give me info on the size of the returned array collection BUT I GET AN ERROR Fault string (also shown on the alert box)
    private function serverGroupsClickHandler(event:ServerGroupsClickEvent):void {
    _serverGroupNameVal = String(event.group);
    _groupCategory = String(event.groupCategory);
    var serverDetailsRO:RemoteObject = new RemoteObject();
    serverDetailsRO.destination = “serverDetail”;
    serverDetailsRO.getServerDetails.addEventListener(“result”, serverDetailsResultHandler);
    serverDetailsRO.addEventListener(“fault”, serverDetailsFaultHandler);
    serverDetailsRO.getServerDetails(_serverGroupNameVal, _groupCategory);

    }

    private function serverDetailsFaultHandler(event:FaultEvent):void {
    //Deal with event.fault.faultString, etc.
    var errors:String = “The following error occurred:\n”;
    errors += “\n Fault code is:\n” + event.fault.faultCode;
    errors += “\n Fault detail is:\n” + event.fault.faultDetail;
    errors += “\n Fault string is:\n” + event.fault.faultString;
    Alert.show(errors, ‘Error’);
    }

    private function serverDetailsResultHandler(event:ResultEvent):void {
    // Process server details list
    var serverDetailsList:Object = event.result;
    _serverGroupDetailArrayCol = serverDetailsList as ArrayCollection;
    Alert.show(“The size of server details list was ” + _serverGroupDetailArrayCol.length);
    }

    ****************
    In the above code snippet, the variables beginning with underscore are declared private. Some are of type String and some of type ArrayCollection
    ****************
    Here is the code snippet of my Java remote object class. The method returns an ArrayList.
    public class ServerDetailRO {
    public ServerDetailRO() {}

    public List getServerDetails(String name, String category) {
    System.out.println(“Message from class ServerDetailRO – method getServerDetailsRO was called”);
    PmmcXmlGenerator pmmcXmlGenerator = new PmmcXmlGenerator();
    String data = pmmcXmlGenerator.getEcnHandlerXml(name);
    ServerDetailDTO serverDetailDTO = null;
    PmmcClientSessionsDTO pmmcClientSessionsDTO = null;

    List serverDetailList = new ArrayList();
    List serverDetailClientSessionsList = new ArrayList();
    Document doc = null;
    DocumentBuilder builder = null;
    XPathFactory xPathFactory = null;
    XPath xpath = null;

    String commandNameAndOrParam = “”;
    .
    .
    .
    ——-
    Here is my ActionScript DTO:
    package {
    [Bindable]
    [RemoteClass(alias=”pmmcFlex.ServerDetailDTO”)]
    public class ServerDetailDTO {
    public var ecnHandler:String;
    public var routingExchange:String;
    public var exchangeStatus:String;
    public var ipAddress:String;
    public var port:String;
    public var senderID:String;
    public var targetID:String;
    public var comments:String;
    public var cloudName:String;
    public var cloudLocation:String;
    public var cmd:String;
    }
    }

    AND here is my corresponding Java DTO:
    package pmmcFlex;

    public class ServerDetailDTO implements java.io.Serializable {
    private static final long serialVersionUID = 5672447577075475118L;
    private String ecnHandler;
    private String routingExchange;
    private String exchangeStatus;
    private String ipAddress;
    private String port;
    private String senderID;
    private String targetID;
    private String comments;
    private String cloudName;
    private String cloudLocation;
    private String cmd;

    public String getEcnHandler() {
    return ecnHandler;
    }
    public void setEcnHandler(String ecnHandler) {
    this.ecnHandler = ecnHandler;
    }

    public String getRoutingExchange() {
    return routingExchange;
    }
    public void setRoutingExchange(String routingExchange) {
    this.routingExchange = routingExchange;
    }

    public String getExchangeStatus() {
    return exchangeStatus;
    }
    public void setExchangeStatus(String exchangeStatus) {
    this.exchangeStatus = exchangeStatus;
    }

    public String getIpAddress() {
    return ipAddress;
    }
    public void setIpAddress(String ipAddress) {
    this.ipAddress = ipAddress;
    }

    public String getPort() {
    return port;
    }
    public void setPort(String port) {
    this.port = port;
    }

    public String getSenderID() {
    return senderID;
    }
    public void setSenderID(String senderID) {
    this.senderID = senderID;
    }

    public String getTargetID() {
    return targetID;
    }
    public void setTargetID(String targetID) {
    this.targetID = targetID;
    }

    public String getComments() {
    return comments;
    }
    public void setComments(String comments) {
    this.comments = comments;
    }

    public String getCloudName() {
    return cloudName;
    }
    public void setCloudName(String cloudName) {
    this.cloudName = cloudName;
    }

    public String getCloudLocation() {
    return cloudLocation;
    }
    public void setCloudLocation(String cloudLocation) {
    this.cloudLocation = cloudLocation;
    }
    public String getCmd() {
    return cmd;
    }
    public void setCmd(String cmd) {
    this.cmd = cmd;
    }
    }

    I really need to resolve this problem. Thanks in advance.
    -Manish

    ______

  52. Manish says:

    Contents of remoting-config.xml file:

    pmmcFlex.ServerDetailRO
    request

  53. Sujit Reddy G says:

    Hi Manish,

    Looks like the configuration XML content got cut. Can you please email the files? Also the details of the error you are getting in the web server log files🙂

    my email id: sujitreddy.g@gmail.com
    🙂

  54. Sujit Reddy G says:

    Hi Don,

    I am sorry, I did not understood the problem properly. can you please Email me the files which I can use to reproduce this?

    My Email id: sujitreddy.g@gmail.com
    🙂

  55. SM says:

    Hi Sujit,

    Just stumbled on this post while searching for a solution.
    Some of the answers on the comment section helped me get thru it.
    Thanks a ton.

  56. Sujit Reddy G says:

    Hi SM,

    Good to know that you got the solution🙂

    Web 2.0 rocks🙂

  57. Gijo says:

    Hi Sujit,
    Great Article !
    I have a doubt, Is it possible to invoke a Java Servlet through Remote Object from Flex ? If so can you please provide me any useful links.
    Thank you for your time in Advance.

  58. Sujit Reddy G says:

    Hi Gijo,

    Try creating channels dynamically and set the end point URL to your servlet. Set this channel to your RemoteObject.
    You can also try changing the end point URL in the services-config.xml, but this might affect all other destinations/services using that channel.

    Please find details on how to create channels dynamically at the URL below.

    https://sujitreddyg.wordpress.com/2008/07/03/creating-blazeds-channels-at-runtime/

    Hope this helps.🙂

  59. Arunkumar K says:

    Hi Sujith,
    It was great to see a thorough support you are offering to Flex developers. Hats off to you. There is a post similar to my problem but I was not able to find the solution for it. Kindly request you to share the same.
    It is related to Post no: 38 written by Meena. The deserialization of a java object that contains an arraylist member inside it is not happening on the actionscript side. It is coming as null.
    Let me know if I need to paste my code in fact it is similar to Meena’s.
    Thanks in advance
    K. Arun

  60. Sujit Reddy G says:

    Hi Arun,

    Please try to send the files to my email id sujitreddy.g@gmail.com. I will try to solve the problem. This should be a minor problem as ArrayList de-serialization is very common and its working fine in my projects🙂

  61. bibin says:

    hi sujit,

    I have an array of objects in an ActionScript class to map to array of objects in the the corresponding java class in the server side.

    I am using flex3 with BlazeDs and cairngorm framework.

    The mapping of array values from java class to actionscript class works smoothly. But when i am sending the populated action script class object to server side, in the corresponding java object in server side ,for some reason the array is set to null.

    But whe i am using the array list in the java side and ArrayCollection in the actionscript side, it works fine

    Any clue?

    Thanks in advance.

  62. Radhika says:

    Hi Sujith,

    Thanks for your support in resolving my problem and enlightening me about the Marshall-Plan of Flex3.
    It helped me a whole lot.

  63. dayakar says:

    Hi sujit,

    can you please send me a sample application of flex with java and hibernate, I have an application, which i need to configure, i tried a lot but i am not configuring properly, when i am trying to compile the xx.mxml file it in browser it showing xx.html file not available.

    Thanks in advance

  64. Sujit Reddy G says:

    Hi Dayakar,

    What exactly are u trying to do? How are u compiling the MXML file?

  65. Tanmoy says:

    Hi Sujit…
    I am working on mapping ActionScript with Java and when my mxml compiles it gives me the following error.
    Reference Error #1056. My declared objects in AS is also declared public. Any idea where could these problems be resolved ?

    Sincerely
    Tanmoy

  66. Tanmoy says:

    Hi Sujit..
    I am having a reference error #1056 when i am trying to map ActionScript objects to Java. Could you let me know where could i be getting wrong.

  67. Sujit Reddy G says:

    Hi Tanmoy,

    Are you getting this error when you compile your application?

  68. Tanmoy says:

    Yes. My application basically tries to work on XML generated from java which i keep as a XML List collection. I planned to use remote objects to access them. I used HTTP service and it worked fine. I however want to know where could i be wrong with Remote Object. Do you think sending the code would be of any help ?

    Sincerely
    Tanmoy

  69. Tanmoy says:

    Also,
    I am actually trying to use trace to access my xml data but am getting this reference error.

    Sincerely
    Tanmoy

  70. Sujit Reddy G says:

    Hi Tanmoy,

    What exactly is your Java method returning? Can you access a simple String returned by Java method on server using RemoteObject on the client? Sharing code sample to replicate this issue will definitely help in solving the problem. You can email the code to sujitreddy.g@gmail.com

  71. Charles says:

    Hi,
    Great Post.

    I have a Problem.

    I when I send a object as a Parameter from FLEX to JAVA, I get the object in JAVA with all the properties in null or 0. Is this a commmon mistake??

    Thanks!!!
    -Charles

  72. veeru says:

    Hi Sujit,
    I am having a problem, I am returning a TO from my server side which holds a list and that customizedTo holds a string,customizedObject1 and list. While making the service call I am getting the string and list but i am not getting the customizedObject1 which is inside the customizedTo. Provided I have replicated all the java classes in the flex side also with the metaTag Remote alias and in the places of list i have added arrayElementType also.But I have not received the particular object inside the list. In the back end i have serialized all the required To’s I am damn confused why the particular object alone is not coming? Please help me out with this.

  73. moiaz says:

    Hi sujit,
    i am new to flex and your blog was a big help for me..
    i have some basic queries.
    i want to create a role based login system. Once the user is logged in successfully different layouts are shown to him depending on different roles..I know it can be done using the concept of states. There are two ways- either i create the states in my mxml files and change it according to role, or i can create it using actionscript at runtime…
    which is the better way to do..
    Regards
    Moiaz Jiwani

  74. Sujit Reddy G says:

    Hi Charles,

    Are your properties public?

  75. Sujit Reddy G says:

    Hi Veeru,
    Please send me files to reproduce this. I will try to find out what’s going wrong.

  76. Das says:

    Hi Sujit,
    Thank you for the informative posts.
    What I have here is Flex-BlazeDS-Spring-J2EE. Getting data (List) from server-side and displaying them (ArrayCollection) in a DataGrid is smooth. Problem is when I try to save these data back.
    I have a remote method which accepts List, and I am passing an ArrayCollection from client side. I am getting a ClassCastException like
    RPC Fault faultString=”java.lang.ClassCastException : flex.messaging.io.amf.ASObject cannot be cast to com.MyDTO” faultCode=”Server.Processing” faultDetail=”null”]
    at mx.rpc::AbstractInvoker/http://www.adobe.com/2006/flex/mx/internal::faultHandler()
    at mx.rpc::Responder/fault()
    at mx.rpc::AsyncRequest/fault()
    at NetConnectionMessageResponder/statusHandler()
    at mx.messaging::MessageResponder/status()

    Have you experienced this while you are working? How do I solve this problem?

    Thanks….

  77. Hi Das,

    Looks like you have class named MyDTO and the class casting is failing. Please make sure you are mapping the object you are sending to MyDTO class.

    Hope this helps.

  78. Karan says:

    Hi,

    I am using Blaze DS for communication between Flex and Java.

    I have an Array in ActionScript, which contains objects of some class (mapped to Java class). I have confirmed the mapping and it looks fine. When sending the data back to Java side, I am receiving a ArrayList, but that ArrayList contains objects of type ASObject and not of the mapped Java Class.

    I am not able to find out the reason behind this behaviour. If I try to send only the mapped Java class (instead of Array), I get the mapped class perfectly on the server side.

    This is highly urgent as I am stuck since last 2 days!! Please reply ASAP.

    Regards,
    Karan

  79. Hi Karan,

    I replied to your email. Hope that solved your problem.

  80. Karan says:

    Hi Sujit,

    Thanks for your reply. Unfortunately it didn’t solve my problem. But anyhow, I moved ahead and did an explicit type casting on the java side from AS Object to the desired server side object.

    Still, thanks for the help!

    Karan

  81. Robert says:

    I’m having issues mapping a class I want to use in a tree.

    as class:

    package com.mycompany.FlexA5Test.utils
    {
    import mx.collections.ArrayCollection;
    import mx.collections.ICollectionView;
    import mx.controls.treeClasses.ITreeDataDescriptor;

    [RemoteClass(alias=”com.mycompany.FlexA5Test.RollupNode”)]
    public class RollupNode implements ITreeDataDescriptor
    {
    public var name:String;
    public var nodes:ArrayCollection=new ArrayCollection();

    public function addChildAt(parent:Object, newChild:Object, index:int, model:Object = null):Boolean{
    return false;
    }
    public function getChildren(node:Object, model:Object = null):ICollectionView{
    return nodes;
    }
    public function hasChildren(node:Object, model:Object = null):Boolean{
    return nodes==null || nodes.length==0;
    }
    public function getData(node:Object, model:Object = null):Object{
    return name;
    }
    public function isBranch(node:Object, model:Object=null):Boolean{
    return nodes==null || nodes.length==0;
    }
    public function removeChildAt(parent:Object,child:Object,index:int,model:Object=null):Boolean{
    return false;
    }
    }
    }

    java:
    package com.mycompany.flexa5test.util;

    import java.util.ArrayList;
    import java.util.List;
    import java.util.Set;

    import com.mycompany.beans.Rollup;

    public class RollupNode {
    String name;
    List nodes = new ArrayList();
    public RollupNode(String name, Set nodes) {
    super();
    this.name = name;
    if(nodes!=null){
    for(Rollup node : nodes){
    this.nodes.add(new RollupNode(node.getNode().getName(),node.getRollups()));
    }}
    }
    }

    function for handling event:
    private function categoryHandler(event:ResultEvent):void{
    var value:RollupNode = RollupNode(event.result);
    tree.dataProvider = value;
    //tree.dataProvider = new RollupNode(“TEST”,new ArrayCollection());

    }

    and the error:
    TypeError: Error #1034: Type Coercion failed: cannot convert mx.utils::ObjectProxy@15825f71 to com.mycompany.FlexA5Test.utils.RollupNode.

  82. David W says:

    Hi Sujit,

    I am looking for a solution for getting images/binary objects thru BlazeDS, and the images are on a server which require basic authentication. I understand HTTPService does not support binary data, so, I assume this rules out using the BlazeDS Http Proxy service (I’ve tried, but, it always returns a Java exception).

    I could use a RemoteObject call (the images/objects can be retrieved thru a database call or URL), but, how should the mapping be, as a byte array from Java, I assume, but
    how to load on the Flex side?

    Also, thanks for the very informative postings!

    David

  83. Hi Robert,

    You AS class has this [RemoteClass(alias=”com.mycompany.FlexA5Test.RollupNode”)] and the Java class is in a different package com.mycompany.flexa5test.util Try correcting this.

    Hope this helps.

  84. Hi David,

    byte Array byte[] in Java is converted to flash.utils.ByteArray on AS.

    Hope this helps.

  85. Sachin Patil says:

    Hi Sujit,

    I just went through the new enhancements for FileReferance class in flash player 10. With load() function we can load the ByteArray to Flex application.

    I want to use this to develop a File Upload component. I want to save/get images to/from server(Java) using remote object.

    I am able to send the file ByteArray to server. However, when i try to get byte[] from java to flex (using remote object) i get null.

    i am getting exception below:
    TypeError: Error #1034: Type Coercion failed: cannot convert to flash.utils.ByteArray

    I am not sure if i can achieve this, should i use upload, download? or i can use load/save and data communication through remoteObject?

    Need your help on this.

    Regards,
    Sachin Patil.

  86. Hi Sachin,

    Please try returning java.lang.Byte[]

    Hope this helps.

  87. Aruna says:

    Hi Sujith,
    I am new to flex and trying some example using yours.
    When I am trying to display object variables, I am getting null. But I am able to display if a string is returned from remote Java class.
    I am having a problem only while displaying an object variables.
    Can you please let me know where I am going wrong.

    In the following function:

    private function nodeResultHandler(evt:ResultEvent):void
    {
    var node1:Node = Node(evt.result);
    Alert.show(evt.message.body.toString());
    Alert.show(node1.nodeId.toString());

    }

    For the first Alert statement I am getting Object Node as my response.
    But for the second Alert, I am getting 0 instead of 11.

    Can you please help.

    Aruna.

  88. Aruna says:

    Hi Sujit,
    I got it resolved. Silly mistake. I had my java class variables as private instead of public.

  89. Gagan says:

    Hi Sujit,

    I am getting a strange error. I am using Flex SDK3.2 and BlazeDS 3. My two remote methods are not working. It comes in the fault handler and show below error message :

    faultCode = “Server.ResourceUnavailable”
    faultDetail = “The expected argument types are (com.common.transferobjects.SearchDataTO) but the supplied types were (flex.messaging.io.amf.ASObject) and converted to (null).”
    faultString = “Cannot invoke method ‘searchData’.”

    Rest of the remote methods are wokring fine. When I compiled the source with Flex SDK3.1, all remote methods are fine but for SDK 3.2 or SDK 3.3, the two methods are not working.

    Please help.

    Thanks,
    Gagan

    Regrads,
    Gagan

  90. Hi Gagan,

    Looks like the mapping is not done properly, pleas make sure you have everything in place.

    Hope this helps.

  91. Jan says:

    Hello,

    For all you people who are having collections of ASObjects on the server side :

    I had the same issue. In my case it seemed to be caused by the fact that when I sent it from server to client, I did not actively use the items in the collection. This meant (I think) that the objects in there were never properly transformed to their flex-side counterpart. When being sent back to the server, this caused them to become (or remain?) ASObjects.

    When I iterated through the collection on the flex-side, casting them to their flex-side types, all worked fine later on when going back to the server:

    for (var i:Number = 0; i < objecta.objectbcollection.length; i++)
    var objectb:Objectb = Objectb(objecta.objectbcollection.getItemAt(i));

    Interested to see if this works for you.

  92. Sandeep Reddy says:

    Hi Sujit,

    I am using RemoteObject calls in flex. When I am returning a custom object (which contains two list properties) to the flex i am getting null as the response at flex side.
    What could be done to resolve the above problem.
    Similer posts i have seen above but i didn’e see any answers for the same.
    Can you replay on the same.
    Thanks in advance.

  93. udaychow says:

    Hi Sujit,

    I had seen your blog very recently and very much impressed with ur blogs.I had seen ur code ,communication between flex and java with remoteobject and Blaze.I tried exactly with ur code by copy pasre, but unable to get the output.Currently im using Flex Builder 3.0 with WTP.Can u just help me out in this regard.My mail id is udayshankar.tummala@gmail.com

  94. Luigi says:

    Hello, I’ve a similar problem mapping java class in flex.
    I’d like to map a java inner class in a flex class as follow:

    package myPack;
    
    public class MyClass {
    
        public String a;
    
        MyClass() {
        }
    
        public Class MySubClass {
            public String b;
    
            MySubClass() {
            }
    
        }
    
    }
    

    And this is the flex class:

    package
    {
        
        [RemoteClass(alias="myPack.MyClass$MySubClass")] 
        public class MySubClass
        {
            public function MySubClass()
            {
            }
    
            public var b:String;
    
        }
    }
    

    But I got this error message:
    2009-07-03 15:33:26,531 INFO [STDOUT] [Flex] 07/03/2009 15:33:26.531 [ERROR] [Endpoint.AMF] Unable to create a new instance of type ‘myPack.MyClass$MySubClass’.
    flex.messaging.MessageException: Unable to create a new instance of type ‘myPack.MyClass$MySubClass’. Types cannot be instantiated without a public, no arguments constructor.
    at flex.messaging.util.ClassUtil.createDefaultInstance(ClassUtil.java:143)
    at flex.messaging.io.AbstractProxy.createInstance(AbstractProxy.java:86)
    at flex.messaging.io.amf.Amf3Input.readScriptObject(Amf3Input.java:409)
    [etc]

    Suggestion? Thanks in advance

  95. manu says:

    I have used blazeds+flex builder in my project where i have to collect around more than 100000 records from the database. Data brought to the client as list of java bean object through remoting where there is an action script object corresponding to java bean as explained in this blog. But the problem is that it takes more than a minute to bring data from the server to the client. Is there anyway to display data in a datagrid as the data is coming from the server.

    With thanks
    Manu

  96. Jesse says:

    Hi, thank you so much for this blog posting. It has been a great help.

    I have got my flex remoting up and running, but I am having a problem with collections. I have data that is more or less in a tree like structure. The class that gets sent from the server to flex has ArrayList’s of other classes.

    These lists have data in them when the server method returns, but on the flex side they have length = 0. The classes in the lists are also mapped to actionscript classes. The List fields themselves are mapped in actionscript as ArrayCollection’s.

    Other’s have posted similar issues, but I have not seen a comment post that explains a resolution. Any help would be greatly appreciated… this blog post has helped me a lot already! Thanks.

  97. Ivan Yiu says:

    I’ve problem on the nested remote object also.

    I want to populate the object in a DataGrid, say:
    Class Person {
    Address address;
    String name;
    }

    The name can be retrieve by using datafield=”name”.

    But when I use datafield=”address.street”, the output is empty, please kindly help…

  98. Hi Jesse,

    Please try sharing your Java and AS3 VO classes.

  99. Hi Ivan,

    You should be writing a labelFunction to handle this case. Please find details at this URL http://livedocs.adobe.com/flex/3/langref/mx/controls/listClasses/ListBase.html#labelFunction

    Hope this helps.

  100. kalondar says:

    Simple solution for below exception when you using List list in your java code:
    (for OurDTOFlex in flex side)

    “ClassCastException : flex.messaging.io.amf.ASObject cannot be cast to ourpackage.OurDTO”

    Just type this whenever in flex side:

    var dummy:OurDTOFlex = new OurDTOFlex ();

    Strange but it works🙂

  101. Hi Kalondar,

    This is because a class definition is not compiled into a swf unless it is being at least once in the code.

  102. Sonu says:

    Hi
    Thanks for the blog.I have a query.I am working on the serialization of amf to java object.I have written a method which is taking amf data in the form of bytearray and then it should be returning after decoding amf databyte array to the Java object in the form bytearray.

    I am not able to resolve this problem as I am getting the below expception while running my class.I have got the solution that I will need to pass the type of class but here whicgh type of class should I pass here.

    Thats my class which have been taking a amf data as bytearray:

    import java.io.ByteArrayInputStream;
    import java.io.ByteArrayOutputStream;
    import java.io.IOException;
    import java.io.InputStream;

    import flex.messaging.io.MessageDeserializer;
    import flex.messaging.io.SerializationContext;
    import flex.messaging.io.amf.ActionContext;
    import flex.messaging.io.amf.ActionMessage;
    import flex.messaging.io.amf.Amf3Output;
    import flex.messaging.io.amf.AmfMessageDeserializer;
    import flex.messaging.io.amf.AmfTrace;
    import flex.messaging.io.ClassAliasRegistry;

    public class AMFConverter {

    public Object fromAmf(final byte[] decodedDataBytesStr) throws IOException, ClassNotFoundException
    {
    SerializationContext context = getSerializationContext();

    ActionContext blazeDSActionContext = new ActionContext();
    InputStream bIn = new ByteArrayInputStream(decodedDataBytesStr);
    int contentLength = decodedDataBytesStr.length;

    blazeDSActionContext.setDeserializedBytes(contentLength);
    ActionMessage requestMessage = new ActionMessage();
    blazeDSActionContext.setRequestMessage(requestMessage);
    String alias = “TestAMF_RI”;
    ClassAliasRegistry.getRegistry().getClassName(alias);

    MessageDeserializer deserializer = new AmfMessageDeserializer();
    deserializer.initialize(context, bIn, new AmfTrace());

    Object y = null;
    try {
    deserializer.readMessage(requestMessage, blazeDSActionContext);
    y = deserializer.readObject();
    } catch (Throwable t) {
    throw new IOException(t);
    }
    return y;
    }

    public byte[] toAmf(final Object source) throws IOException {
    SerializationContext context = getSerializationContext();
    // final StringBuffer buffer = new StringBuffer();
    final ByteArrayOutputStream bout = new ByteArrayOutputStream();
    final Amf3Output amf3Output = new Amf3Output(context);// creating the context instance
    amf3Output.setOutputStream(bout);
    amf3Output.writeObject(source);
    amf3Output.flush();
    amf3Output.close();
    return bout.toByteArray();
    }

    public static SerializationContext getSerializationContext(){
    SerializationContext serializationContext = SerializationContext.getSerializationContext();
    serializationContext.enableSmallMessages = true;
    serializationContext.instantiateTypes = true; //use _remoteClass field
    serializationContext.supportRemoteClass = true;
    //false Legacy Flex 1.5 behavior was to return a java.util.Collection for Array
    //ture New Flex 2+ behavior is to return Object[] for AS3 Array
    serializationContext.legacyCollection = false;
    serializationContext.legacyMap = false;
    //false Legacy flash.xml.XMLDocument Type //true New E4X XML Type
    serializationContext.legacyXMLDocument = false;
    //determines whether the constructed Document is name-space aware
    serializationContext.legacyXMLNamespaces = false;
    serializationContext.legacyThrowable = false;
    serializationContext.legacyBigNumbers = false;
    serializationContext.restoreReferences = false;
    serializationContext.logPropertyErrors = false;
    serializationContext.ignorePropertyErrors = true;
    serializationContext.createASObjectForMissingType=true;
    return serializationContext;

    /* serializationContext.enableSmallMessages = serialization.getPropertyAsBoolean(ENABLE_SMALL_MESSAGES, true); serializationContext.instantiateTypes = serialization.getPropertyAsBoolean(INSTANTIATE_TYPES, true); serializationContext.supportRemoteClass = serialization.getPropertyAsBoolean(SUPPORT_REMOTE_CLASS, false); serializationContext.legacyCollection = serialization.getPropertyAsBoolean(LEGACY_COLLECTION, false); serializationContext.legacyMap = serialization.getPropertyAsBoolean(LEGACY_MAP, false); serializationContext.legacyXMLDocument = serialization.getPropertyAsBoolean(LEGACY_XML, false); serializationContext.legacyXMLNamespaces = serialization.getPropertyAsBoolean(LEGACY_XML_NAMESPACES, false); serializationContext.legacyThrowable = serialization.getPropertyAsBoolean(LEGACY_THROWABLE, false); serializationContext.legacyBigNumbers = serialization.getPropertyAsBoolean(LEGACY_BIG_NUMBERS, false); boolean showStacktraces = serialization.getPropertyAsBoolean(SHOW_STACKTRACES, false); if (showStacktraces && Log.isWarn()) log.warn(“The ” + SHOW_STACKTRACES + ” configuration option is deprecated and non-functional. Please remove this from your configuration file.”); serializationContext.restoreReferences = serialization.getPropertyAsBoolean(RESTORE_REFERENCES, false); serializationContext.logPropertyErrors = serialization.getPropertyAsBoolean(LOG_PROPERTY_ERRORS, false); serializationContext.ignorePropertyErrors = serialization.getPropertyAsBoolean(IGNORE_PROPERTY_ERRORS, true); */
    }

    }

    Exception :

    java.io.IOException: flex.messaging.MessageException: Cannot create class of type ‘DSK’. Type ‘DSK’ not found.
    at AMFConverter.fromAmf(AMFConverter.java:52)
    at TestAMF_RI.interpret(TestAMF_RI.java:40)
    at com.recordingtool.DebugWebScript.executeRequest(Unknown Source)
    at com.recordingtool.DebugWebScript.handleRequest(Unknown Source)
    at com.recordingtool.WebScript.actionOnAgendaView(Unknown Source)
    at com.recordingtool.DebugWebScript.execute(Unknown Source)
    at com.recordingtool.DebugScriptRunner.run(Unknown Source)
    Caused by: flex.messaging.MessageException: Cannot create class of type ‘DSK’. Type ‘DSK’ not found.
    at flex.messaging.util.ClassUtil.createClass(ClassUtil.java:66)
    at flex.messaging.io.AbstractProxy.getClassFromClassName(AbstractProxy.java:103)
    at flex.messaging.io.AbstractProxy.getClassFromClassName(AbstractProxy.java:85)
    at flex.messaging.io.AbstractProxy.createInstanceFromClassName(AbstractProxy.java:125)
    at flex.messaging.io.AbstractProxy.createInstance(AbstractProxy.java:148)
    at flex.messaging.io.amf.Amf3Input.readScriptObject(Amf3Input.java:437)
    at flex.messaging.io.amf.Amf3Input.readObjectValue(Amf3Input.java:153)
    at flex.messaging.io.amf.Amf3Input.readObject(Amf3Input.java:132)
    at flex.messaging.io.amf.Amf0Input.readObjectValue(Amf0Input.java:135)
    at flex.messaging.io.amf.Amf0Input.readObject(Amf0Input.java:95)
    at flex.messaging.io.amf.AmfMessageDeserializer.readObject(AmfMessageDeserializer.java:226)
    at flex.messaging.io.amf.AmfMessageDeserializer.readBody(AmfMessageDeserializer.java:205)
    at flex.messaging.io.amf.AmfMessageDeserializer.readMessage(AmfMessageDeserializer.java:125)
    at AMFConverter.fromAmf(AMFConverter.java:49)
    … 6 more

  103. Sonu says:

    Please reply on the above query.I had tried so many things but it is not working

  104. vijay says:

    Hi Sujit,
    I Like ur posts on blogs.Here I have the requirement like autogeneration of Actionscript classes(Value Objects) from Java classes(DAOs).I tried using graniteDS plugin for eclipse, but it is generating double the classes what we required.Do we have any tool or plugin like that?Please let me know.

  105. yam says:

    Hi Sonu,

    To solve your problem (flex.messaging.MessageException: Cannot create class of type ‘DSK’. Type ‘DSK’ not found.), you need to register the DSK alias to AcknowledgeMessageExt:

    ClassAliasRegistry.getRegistry().registerAlias(“DSK”, “flex.messaging.messages.AcknowledgeMessageExt”);
    ClassAliasRegistry.getRegistry().registerAlias(“DSC”, “flex.messaging.messages.CommandMessageExt”);
    ClassAliasRegistry.getRegistry().registerAlias(“DSA”, “flex.messaging.messages.AsyncMessageExt”);

    Check this default implementation:
    http://opensource.adobe.com/svn/opensource/blazeds/trunk/modules/core/src/flex/messaging/endpoints/AbstractEndpoint.java

  106. Jatin says:

    Hi ,
    I have following classes

    Flex:::::

    package com.mycompany
    {
    import flash.utils.Dictionary;

    [Bindable]
    [RemoteClass(alias=”com.mycompany.bean.MessageBundle”)]

    [Bindable]
    public class MessageBundleVO
    {
    public var messages:Object ;

    public function getMessage(key:String):String{
    return messages.key as String;
    }
    }
    }

    Java::::

    package com.mycompany.bean;

    import java.io.Serializable;
    import java.util.Map;

    public class MessageBundle implements Serializable {
    private static final long serialVersionUID = 1L;
    private Map messages;

    public Map getMessageBundle() {
    return messages;
    }

    public void setMessageBundle(Map messageBundle) {
    this.messages = messageBundle;
    }

    public String toString(){
    return messages.toString();
    }
    }

    The Everything is properly linked and instance for MessageBundleVO is not null but the its attribute messages is coming null.

    Can you please tell me what is the Flex equivalent of Map if we use RemoteClass tag as give in the above code.

    This is comming null on the flex side.
    MessageBundleVO.messages

    The Aodbe
    http://livedocs.adobe.com/flex/3/html/help.html?content=data_access_4.html

    is suggesting
    Array (sparse)—->java.util.Map–>java.util.Map

    Does anybody know how to solve this issue.

    Regards
    Jatin

  107. Anatoliy says:

    Hi Sujit,

    First of all, thank you for this great resource.

    I was trying to test if I can access a nested object in your Person example.

    For this I made the following changes:

    1. Added a variable in the Person.java:
    public Person son;

    2. The same in Person.as:
    public var son:Person;

    3. Changed getPerson() method in RemoteServiceHandler.java:

    public Person getPerson()
    {
    Person person = new Person();
    person.id = 1;
    person.dateOfBirth = new Date();
    person.name = “Sujit”;
    person.company = “Adobe”;

    Person son = new Person();
    son.id = 2;
    son.name = “Amarjeet”;
    person.son = son;
    return person;
    }

    4. Changed displayPersonDetails in RPC.mxml:

    private function displayPersonDetails(event:ResultEvent):void
    {
    var person:Person = Person(event.result);
    var son:Person = person.son;
    Alert.show(person.name + “, ” + person.dateOfBirth.toDateString() + “, ” + person.id);
    Alert.show(“Son: ” + son.name + “, ” + person.id);
    }

    With these changes, I still see only the first alert. The second one is silentlly “ignored”.

    Regards,
    Anatoliy

  108. Hi Anatoliy,

    This will definitely work. Please try moving the window, you should be able to see the other one right behind it.

    Hope this helps.

  109. nirav says:

    HI..
    in my application i have a form to fill person detail,i want to store person detail to database on server side, how can i typecast person.as into person.java at the server side java class.

  110. nirav says:

    I am using this two files, it throws me typecast error at client side.
    whats wrong with this?
    //EmployeeInfoObj.as
    package
    {
    [RemoteClass(alias=”remoteObj.Employee”)]
    /*[RemoteClass(alias=”http://localhost:8400/blazeds/Employee”)]*/
    public class EmployeeInfoObj
    {
    public function EmployeeInfoObj()
    {}

    public var firstName:String;
    public var lastName:String;
    public var city:String
    public var empCode:String
    }
    }
    //Employee.java

    package remoteObj;

    public class Employee
    {
    public String firstName;
    public String lastName;
    public String city;
    public String empCode;
    public Employee(){}
    public Employee(String firstName,String lastName,String city,String empCode)
    {
    this. firstName = firstName;
    this.lastName = lastName;
    this.city = city;
    this.empCode = empCode;
    }
    public String getFirstName()
    {
    return this.firstName;
    }
    public void setFirstName(String firstName)
    {
    this.firstName = firstName;
    }
    public String getLastName()
    {
    return this.lastName;
    }
    public void setLastName(String lastName)
    {
    this.lastName = lastName;
    }
    public String getCity()
    {
    return this.city;
    }
    public void setCity(String city)
    {
    this.city = city;
    }
    public String getEmpCode()
    {
    return this.empCode;
    }
    public void setEmpCode(String empCode)
    {
    this.empCode = empCode;
    }
    }

  111. Hi Nirav,

    As explained in this article adding [RemoteClass(alias=”com.adobe.objects.Person”)] tag to Person.as will do. Once you add this metadata tag, Flash Player will take care of converting Person.as instances to Person.java instances and other way round too.

  112. Hi Nirav,

    Can you please make sure a reference to EmployeeInfoObj.as is compiled to your application. You can check this by intentionally adding a compiler error into EmployeeInfoObj.as and compile your application. If you see a compiler error then the class is getting compiled.

    Hope this helps.

  113. Jeyabalan says:

    Hi Sujit,

    I am Jeyabalan first of all very thanks to you, i am familiar with Flex&PHP but new in Flex with Java, i need simple database program(add, delete, update) using Flex, Java, MySQL Connector, Spring or Hibernate. I humble requeste to you Please send me this program file to my email id (giribala14@gmail.com). please

    Thank you

  114. Dhanalakshmi says:

    Actually I am a beginner.. It was very useful to me..

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: