Tuesday, February 26, 2008

Drag and Drop Grid of Panels

I needed a grid of panels in which I could exchange the places held by panels by dragging and dropping. I should be able to toggle the visibility of the panel and re-arrange the panels as need be. The grid should be scalable. This would be something like the igoogle panel and is available in most AJAX frameworks like zkoss and yui. Keeping this in mind I have written this code for a 3x3 grid. You can adapt it to any size and any container.

The grids would look something like this:



You can check out the code at: http://docs.google.com/Doc?id=ddhf5h22_69w36cmdh

Any queries/problems /suggestions are welcome :)

Cheers!

Tuesday, February 19, 2008

Datagrid Fix

Was grappling with some Datagrid issues only to discover later that it is a known bug. For a list of datagrid bugs and fix provided by adobe:
Datagrid Bugs Hotfix at Adobe

Thursday, February 7, 2008

Mapping AS objects to Server-Side Java Objects

Such mappings can be useful when you are using a value object ie an object containing values.

AS class:
/*we mark a class we want to map with RemoteClass tag. alias is the exact location of the class*/
package valueObjects
{
[RemoteClass(alias="valueObjects.SampleVo")]
public class SampleVo{
public var val1:String = "val1";
public var num1:int = 1;

public function getServerVal(obj:SampleVo):SampleVo{
return new SampleVo();
}
}
}

Java class (you will have to configure it as a remote object):
package valueObjects;

public class SampleVo {
public String val1 = "val2";
public int num1 = 2;

public SampleVo getServerVal(SampleVo obj){
return new SampleVo();
}
}

If you have this, you can do this in flex while handling result on calling getServerVal function:
var vo:SampleVo = event.result as SampleVo;
resultTxt.text = vo.val1+vo.num1;

Wednesday, February 6, 2008

Implementing Singleton in Flex

Your singleton class should look somewhat like this

package managers {
  /*A singleton class which enforces only a single object is created for each key. To access the specific instance, use getInstance(key:String) */

  public class MySingleton{
    private static var instanceMap:Object = new Object();

    public function MySingleton(pri:PrivateClass){}

    public static function getInstance(key:String):MySingleton{
      if(MySingleton.instanceMap[key] == null){
        MySingleton.instanceMap[key] = new MySingleton(new PrivateClass());
      }
      return MySingleton.instanceMap[key];
    }
  }
}

/* PrivateClass is used to make constructor private (to implement Singleton)*/
class PrivateClass{ public function PrivateClass(){}}

Tuesday, February 5, 2008

Uploading File From Flex to Tomcat

To upload file from Flex to Java utilize the fileUpload utility provided by Apache. Go to http://commons.apache.org/fileupload/ to download the lib files and see documentation. This utility in turn depends on commons-io utitlity that you can get at http://commons.apache.org/io/ . Copy the jar files from these two utilities to WEB-INF/lib of your application.

In Flex use FileReference object to get the file to upload:

private var fileRef:FileReference;

private function fileBrowse():void{
   this.fileRef = new FileReference();
   fileRef.addEventListener(Event.SELECT,selectHandler);
   fileRef.browse();
}


private function selectHandler(event:Event):void{
   var request:URLRequest = new URLRequest("http://localhost:8080/FlexJava1/fileLoader.jsp");
   /*Map this to the servlet or jsp you wish to use to handle your file writing request*/
   fileRef.upload(request);
}




The jsp will be like this (O yes this should be done in a servlet but lazy me doing it in a jsp. But you be good and make a nice servlet :p):


<%@page import="org.apache.commons.fileupload.FileItemFactory"%>
<%@page import="org.apache.commons.fileupload.disk.DiskFileItemFactory"%>
<%@page import="org.apache.commons.fileupload.servlet.ServletFileUpload"%>
<%@page import="org.apache.commons.fileupload.FileItem"%>
<%@page import="java.util.List"%>
<%@page import="java.util.Iterator"%>
<%@page import="java.io.File"%>
<%@page import="java.io.FileOutputStream"%>
<%@page import="java.io.InputStream"%>

<%
// Create a factory for disk-based file items
FileItemFactory factory = new DiskFileItemFactory();
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// Parse the request
List /* FileItem */ items = upload.parseRequest(request);


// Process the uploaded items
Iterator iter = items.iterator();

while (iter.hasNext()) {
   FileItem item = (FileItem) iter.next();
   //handling a normal form-field
   if (item.isFormField()) {
      System.out.println("Got a form field");
      String name = item.getFieldName();
      String value = item.getString();
      System.out.println("Name:"+name+",Value:"+value);
   } else {//handling file loads
      System.out.println("Not form field");
      String fieldName = item.getFieldName();
      String fileName = item.getName();
      String contentType = item.getContentType();
      boolean isInMemory = item.isInMemory();
      long sizeInBytes = item.getSize();
      System.out.println("Field Name:"+fieldName+",File Name:"+fileName);
      System.out.println("Content Type:"+contentType+",Is In Memory:"+isInMemory+",Size:"+sizeInBytes);

      byte[] data = item.get();
      FileOutputStream fileOutSt = new FileOutputStream("outagain.jpg");
      fileOutSt.write(data);
      fileOutSt.close();
   }
}
%>


You will find your file written under the Tomcat root installation folder

Monday, February 4, 2008

Using Remote Objects

Using remote object can be tedious and confusing if you want to do it from the scratch and want to understand everything at once. A better approach is to have something that works and build on it, understand it bit by bit. I used this approach for Tomcat but this should work well for any J2EE container like Websphere or JBoss. I am not focussing on Remote Object basics or RMI here, just how you can make it work for yourself for Java.


Download Adobe LiveCycle Data Services ES from:

http://www.adobe.com/products/livecycle/dataservices/

Install it for J2EE and not for integrated JRun. We will be using the express version. Alternatively you could use BlazeDS. To see the differences between the two visit this link:

Differences between Flex Data Services Express and BlazeDS

Please remember that using either means that you will have to buy it at some stage for commercial applications. See the respective licence for details. That being said these services are extremely useful and without them Flex looses a lot of utility.


  • The installation folder contains many things that you will be using as you understand flex more. For time being our interest lies in a file by name flex.war
  • Take flex.war and unzip the contents into a folder. Name it apporpriately. This folder will be your template for a blank flex application that you may want to develop on your server.
  • Take this skeleton folder and copy in the webapps directory of your Tomcat.
  • Browse to WEB-INF/flex folder. Open a file named license.properties and add license keys (ie if you have one) for flex builder, flex charting and flex data services.
  • In the same folder open file services-config.xml and see the security tag. Uncomment the line for tomcat server and comment the rest.
  • Open Flex builder. Go to File->New->Flex Project. Choose Flex Data Services for data access and compile application on the server when the page is viewed. Click Next. Browse to the folder in tomcat webapps where you are hosting the skeleton app. Validate location and name the root URL and context root appropriately. Click Next. Give an appropriate name to your project and click Finish.
  • You have set up the stage to use Remote Object.

    Now, copy the java class you intend to use in the appropriate directory under WEB-INF/classes. Lets say we have a class file from your compiled java file called MyRemoteObj.class made from this file:

    package app;

    public class MyRemoteObj{

    public String getMessage(){ return "hello"; }

    }

    Browse to WEB-INF/flex and open remoting-config.xml. Make sure it looks something like this:

    <?xml version="1.0" encoding="UTF-8"?>

    <service id="remoting-service" class="flex.messaging.services.RemotingService">

    <adapters> <adapter-definition id="java-object" class="flex.messaging.services.remoting.adapters.JavaAdapter" default="true"/>
    </adapters>

    <default-channels>
    <channel ref="my-amf"/>
    </default-channels>

    <destination id="responder">
    <properties>
    <source>app.MyRemoteObj</source>
    <scope>application</scope>
    </properties>
    </destination>

    </service>

    Remember this xml file is just one of the files uploaded by services-config.xml. It just helps in breaking our config xml into usable parts. <adapters> define the backend object. <channels> are defined in service-config. Here we just specify the channel we intend to use. destination is the part that helps flex use the remote object. id is ised to refer to it. source is its location under the WEB-INF/classes directory.

    Declare your remoter object in the MXML as

    <mx:RemoteObject id="remoteObjRef" destination="responder" fault="handleFault(event)" result="handelResult(event)"/>

    Use the id in AS to call the methods directly on the object: remoteObjRef.getMessage();