Ejemplo Flex/JSP: Subir video usando la Media API de Brightcove

Este ejemplo muestra como cargar video a Brightcove usando la Media Write API en una aplicación Flex.

Incluye elementos del cliente y del servidor:

  • En el lado del cliente, VideoUploader.mxml es un aplicacion Flex que ofrece al usuario una interfaz (UI) para navegar hacia y seleccionar un archivo para subir, muestra el progreso del proceso de carga, y llama al script proxy en el servidor. A su vez, lee el video Id si la llamada a la Media API es correcta, o un mensaje de error en el caso que la carga falle.
  • En el lado del servidor, use un script proxy, en este caso una pagina JSP (Uploader.jsp) que recibe la multipart/form-data del cliente Flex, incluyendo el nombre del video, y un la descripción corta y larga, y si anuncios están permitidos o no. Este JSP desglosa la petición y es el que al final llama  create_video Media API.  Los resultados de la API, incluyendo el id del video recién cargado, se envían al cliente de Flex.

La aplicación Flex hace uso de las clase  FileReference para manejar todo lo relacionado a seleccionar el archivo de video, y pasarlo junto con los atributos del video a la pagina JSP.  Si no están familiarizados con esta clase, es posible que quieran leer primero la ayuda de Flex. Antes de usar este ejemplo, asegúrense de tener todos los componentes estén instalados. Todos los archivos que necesitan están incluidos en FlexVideoUploaderExample.zip:

  1. Flex app. Extraigan  VideoUploader.zip e importenlo en Flex Builder. Opción Import > Existing Project Into Workspace > Select archive file > VideoUploader.zipVideoUploader.mxml contiene la aplicación principal.
  2. UploaderVideo.jsp. Extraigan uploader.war y copienlo a un servidor web que soporte Java. En Tomcat por ejemplo, solo necesitan copiar el archivo war bajo el directorio  webapps y es automáticamente reconocido.  Despues de eso, deben tener un proyecto web llamado uploader. Revisen los archivos en el proyecto. La pagina JSP se llama  UploaderVideo.jsp. Este JSP usa ClientHTTPRequest para manipular el multipart/form-data enviado a la Media API. El JSP también necesita los JARs Apache Commons commons-iocommons-fileupload , también incluidos en el archivo war. No necesitan cambiar la utileria ClientHTTPRequest ,  a menos que quieran usar otra utileria HTTP que pueda manipular el envio multiparte. Tambien antes de ejecutar este ejemplo, asegurense de añadir su propio token de escritura de la Media API en UploaderVideo.jsp.  Busquen por la variable WRITE_API_TOKEN y asignen su token ahi. Si no cuentan con un token, por favor contacten al servicio al cliente de Brightcove ( en Ingles)

La aplicación Flex

Sin han usado FileReference antes, notaran que este ejemplo basicamente usa los tres pasos principales para cargar un archivo a un servidor:

  1. Navegar hacia y seleccionar un archivo.
  2. Llamar a un script en el servidor después de que el usuario ha seleccionado un archivo, y
  3. Manejar el resultado de la carga.

Navegando hacia el archivo

Esta acción es empezada cuando el usuario presiona el botón 'Upload' en la forma  uploadForm de la aplicación. La información acerca del video tiene que ser llenada. Noten que dado que solo queremos subir archivos de video, un filtro (FileFilter) con las extensiones comunes para video es usado. Este es también el lugar donde se ponen los metodos que procesan los eventos cuando el archivo es seleccionado (Event.SELECT) y cuando la carga se completa (DataEvent.UPLOAD_COMPLETE_DATA

 /**
   * Abre un mensaje de dialogo para que el usuario seleccione un archivo de vídeo
   * y agrega los métodos para procesar errores y cuando el video ha sido cargado al servidor
   */
    private function fileBrowse():void {
        fileRef = new FileReference();
        fileRef.addEventListener(Event.SELECT,selectHandler);
        fileRef.addEventListener(Event.COMPLETE,onComplete);
        // Procesar cuando el archivo de video ha sido cargado.
        fileRef.addEventListener(DataEvent.UPLOAD_COMPLETE_DATA ,onUploadCompleteData);
        fileRef.addEventListener(IOErrorEvent.IO_ERROR,onError);            

        var videoFilter:FileFilter =
            new FileFilter ("Video (*.flv,*.mov,*.avi,*.mp4,*.wmv,*.mpeg)",
                                     "*.flv;*.mov;*.avi;*.mp4;*.wmv;*.mpeg");
        // Queremos subir solo archivos de video
        fileRef.browse([videoFilter]);
    }

Llamando al JSP despues de que el usuario ha seleccionado un archivo.

Usamos el método fileReference.upload() para llamar al JSP  y enviamos los meta datos del vídeo desde la forma (nombre, descripción, soporta anuncios , etc) como parametros. El JSP es donde en verdad se hace la llamada al metodo create_video de la Media API. Aqui seria donde agregarian mas meta datos como tags, cue points o ids de referencia.

private function selectHandler(event:Event): void {
 // Contruye una URL para llamar al script proxy en el servidor
 var request:URLRequest = new URLRequest(UPLOAD_VIDEO_URL);
 fileName.text = FileReference(event.target).name;

 // Enviar los atributos del video entrados por el usuario. La API de video
 // create_video soporta varios parametros. En este ejemplo son limitados a
 // shortDescription, longDescription, adEnabled, y name.
 // Cada atributo de 'createVideoParams'
 // debe pertenecer a uno de create_video
 // Para una lista completa de los atributos de create_video ver:
 // http://docs.brightcove.com/en/media/#Video_Write

 var createVideoParams:URLVariables = new URLVariables();
 createVideoParams.name=videoName.text;
 createVideoParams.shortDescription=shortDescription.text;
 createVideoParams.longDescription =longDescription.text;
 // Los videos que se cargan a Brightcove soportan anuncios de entrada
 // este ejemplo muestra como subir videos que no permitan anuncios, usando un
// parametro de create_video
 createVideoParams.adEnabled = adEnabledCheckBox.selected?"AD_SUPPORTED":"FREE";

 var parametersObject:Object = new Object();
 request.method = URLRequestMethod.POST;
 request.data = createVideoParams;
 fileRef.upload(request);
 fileUploadProgressBar.visible= true;
}

Procesando el resultado de la transferencia del archivo de vídeo

En onUploadCompleteData, verificamos que la llamada a  create_video en el JSP haya sido exitosa y el vídeo haya sido agregado. Si la llamada falla, un mensaje de error es regresado.  Si reciben un vídeo id, significa que el archivo ha sido agregado al sistema y esta siendo procesado. Pueden verificar el resultado de la transferencia usando la API  get_upload_status de la Media API o en el Media Module.

    /**
     * Se llama cuando UploadVideo.jsp termina de procesar la carga.
     * Si la llamada es exitosa, se puede leer el video id
     * de contenido de JSONResponse.result
     * Si falla, el mensaje de error con los detalles
     * puede leerse de JSONResponse.error.message
     */
    private function onUploadCompleteData(event:DataEvent):void {
     trace("onUploadCompleteData");
     var JSONResponse:Object = (JSON.decode(event.data));

        if(JSONResponse.error != null && JSONResponse.error != ""){
            videoResult.text = "Error : " + JSONResponse.error.message;
         }else {
            // Una llamada exitosa regresa el siguiente contenido JSON
            // {"result": 34414648001, "error";: null, "id": null}
            // Obtener el video id de la propiedad  'result'
            videoResult.text = " Video ID : " + JSONResponse.result;
        }
    }

El lado del Servidor

Entre el paso 2 y 3, la pagina JSP es llamada. El JSP analiza la información enviada por fileReference.upload() y prepara la llamada al método create_video. Este JSP es otra version del java servlet usado en un ejemplo previo "Java Example: Video Uploader", el cual usa HTML en vez de Flex. Una buena explicación del código puede encontrarse ahí. Una diferencia sin embargo, es la adición del parámetro 'anuncios' al subir los videos, para permitir o no anuncios de entrada, y es aqui donde se pueden agregar otros parametros que corresponden al video.  Así mismo, usando un script del lado del servidor protege su token de escritura para API.

Que sigue

Aunque este ejemplo demuestra la idea básica de usar Flex para subir vídeos a su cuenta en el sistema de Brightcove, puede ser expandido para incluir mas funcionalidad. Aquí un par de ideas que ustedes pueden implementar :

  • Agregar suporte para subir vídeos usando etiquetas para su clasificacion (tags).
  • Cambiar este ejemplo a una aplicación de Adobe AIR donde se pueda navegar al vídeo y verlo antes de subirlo.
  • Agregar suporte para cue points.
  • Obtener el estado de la carga del vídeo al sistema Brightcove. Tip: Llamar el método get_upload_status de la Media API

Espero escuchar pronto de lo que han desarrollado!

Flex/JSP Example: Upload video using the Brightcove Media API

If you are looking for an example of using FileReference and a server side script to upload videos to a server, this article that I wrote for the Brightcove developer center might help you.

Flex/JSP Example: Upload video using the Brightcove Media API

Of course, if you in addition use Brightcove, you will find it even more useful!

Printing and Creating Reports in Flex?

Lately people have been asking in the Flex forum in Spanish about what the best way is to generate a report from Flex and print it. It looks like when the Datagrids are sophisticated ( itemRenderes, a lot of fields, etc) things get complicated when printing them using the mechanisms that Flex provides.

I have not tried printing such complicated screens myself so I am asking, how do you generate reports from Flex to be printed? People have mentioned using some sort of mechanism to convert the screen to PDFs or using JasperReports, on your experience what is the best approach?

My guess is that people want to print invoices, schedules or things like that.

Flex Camp Mexico City

Dado el auge que Flex esta teniendo internacionalmente, me preguntaba que tanto interes hay en la Cd de Mexico por un Flex Camp Mexico City?

Adobe auspicia este tipo de eventos pero como minimo requieren que 150 personas atiendan.

Para los que no sepan, Flex Camps han sido organizados alrededor de los Estados Unidos principalmente, donde durante un dia ponentes expertos en Flex y AIR, muestran algun proyecto en el que esten trabajano, tecnicas que utilizaron, demos, etc. Es una excelente oportunidad para conocer a otros desarrolladores al mismo tiempo. El costo normalmente fluctua, pero la cuota para los ultimos Flex Camps ha sido de entre $40.00 y $50.00 dolares, que en realidad es un costo de recuperacion.

He platicado con un par de figuras del ambito Flex en los Estados Unidos, que estarian muy interesados en ir a Mexico a un posible Flex Camp Mexico City. 

Ustedes que opinan?  Dejen un comentario para saber si personalmente estarian interesados.  Si hay suficiente interes, abrire un evento en el grupo de Facebook, para que la gente se vaya pre-registrando. Para hacerlo formal a como dije, si hay sufiente fervor!

Nota: Esto lo he pensado para la Cd. de Mexico de donde soy originario. Pero si ustedes son de otra ciudad de habla hispana y creen que hay suficiente interes por un Flex Camp, lo mismo cuenta para ustedes. Estoy seguro que varios Flex experts de los que conozco estarian encantados de asistir a Argentia, Chile, Brasil o España por ejemplo.

Slides and source code from my talk at Flex Camp Boston

It was great to see everyone at Flex Camp Boston last Friday! As promised, here are the slides and source code from my presentation about Building Mashups with Flex. You will need to get your own APi keys for the NYT, Google, Ribbit APIs before you try it out

Source Code Download

Flex SDK 3.2 and Flash 10

If you like me want to try Flash 10 features in Flex or AIR 1.5 in Flex Builder, I would recommend installing the Flex Builder 3.0.2 update using the update mechanism in Flex Builder (Help>Search for Flex Builder updates) and get the Flex SDK 3.2 installed that way. When I followed the instructions for the manual installation, I realized that dataVisualization.swc was not included in the download. So my projects with Charts were not compiling.
For targeting Flash 10, you still have to remove the default playerGlobal.swc and re-add the one that targets Flash 10 as explained in the instructions. But at least you do not have to manually add (actually borrow from Flex SDK 3.1 ) the dataVisualization.swc. Again, you only need this if you are using Charts or the Advanced Datagrid in your project.

Also make sure to also regenerate your HTML template folder after changing the require Flash Player version to 10.0.0 ( Project>Properties>Flex Compiler>Require Flash Player). That includes the correct version detection scripts for Flash 10.

I did not see the bugs that some people are reporting about missing code hinting for the some Flash APIs ( Graphics and Bitmap). These were bugs that according to Adobe were fixed for the Flex 3.0.2 release, and the fixes are working for me in FB 3.0.2. I guess, you just need to make sure that you have upgraded to Flex Builder 3.0.2, have replaced the playerGlobal.swc that targets Flash 10 and have regenerated your HTML template folder.

Speaking at Flex Camp Boston 2008 - Dec 12th

I will be speaking about Building Mashups with Adobe Flex and AIR at Flex Camp Boston this December 12th at Bentley University.  A Flex camp is a great opportunity to advance your Adobe Flex and AIR skills and network with other fellow Flex developers. Last year, we had a blast and this year looks really promising as well.  Speakers include members of the Adobe Flex Team as well as experts from several companies.

Take a look at the complete agenda here: http://www.flexcampboston.com/page.cfm/agenda

And you register here: http://www.flexcampboston.com/page.cfm/register  Note that there is an early if you register before Dec 1st

See you there!

New blog about Flex by Allen Manning

Allen Manning is a colleague at Brightcove and a talented Adobe Flex developer. He has a great insight about best development practices and is now writing about them in his blog  

http://www.allenmanning.com/

Enjoy!

Adobe Certified Flex 3 Developer Exam

Well, that's it, if you were waiting for this certification to become available, it is now.

Adobe® Flex 3 with AIR
Exam # 9A0-082

http://partners.adobe.com/public/en/ace/ACE_Exam_Guide_FlexAIR.pdf

The “Magic Wall” and Rich Internet Applications.

The Presidential election in the U.S. is today and millions of Americans are making this a historic moment. For the first time an African-American runs for president, a woman is nominated to run for Vice-President and earlier in the primaries a woman was head to head to the presidential nomination in the Democratic party. For many, this is a life time opportunity to write history.

This is also a presidential election where technology has played a role like never before. Four years ago there was no YouTube, no Facebook, no Twitter and there were not thousands of influential blogs. Opinion has been created and spread faster than ever, and people have held their own political debates in this cloud of Web 2.0 artifacts. The Internet has been fundamental in mobilizing volunteers and raising funds.

Something else that is also new in the scene are "Rich Experiences". Not only in the Internet as Rich Internet Applications but also other forms. I am taking specifically about a technology that caught my attention early in the primaries: The "Magic Wall", an electronic multi-touch board that CNN introduced early this year that displays an electoral map and that "magically" changes views as John King clicks, drags and drops, and zooms in and out sections of screen with a touch of his fingers. I immediately started thinking about the parallels between the "Magic Wall" and the RIA apps that we build with Adobe Flex and other technologies.

On the one hand, the input is the same for both, data which changes continuously, and on the other hand, the challenge is the same, this information needs to be organized and presented to the user with the detail to be understood. The latter one, a main and mandatory feature of RIA applications. That is, it is not enough to use shiny components or effects, they must align with the nature of the information. For example, the Magic Wall uses a map metaphor to present electoral results and from there with a touch of a finger or fingers you can zoom in a specific geographical area. The audience can actually analyze the results on the screen even before John King can explain it.

For me the Magic Wall has accomplished things that RIA apps should do as well:

  • Provide competitive advantage. I believe CNN has accomplished that. They have not only accomplished a "Wow" effect, but their competitors are still showing static screens. Everyone's attention is set in the general election, not only in the US but internationally, and it is a good time for News organizations who compete for audiences eager for information. RIA apps should facilitate user's interaction with data and apply information architecture best practices to find and understand data as clear as possible. This can make a big difference between one RIA application and another.
  • Organizes and presents information faster and in different dimensions (geographical and time) in the same screen real state. RIA applications should move from the page and pop-up dialogs paradigms and re-use screen real state dynamically following the direction of what the user is looking for.
  • Places this technology in the path to mainstream and raises expectations from users. CNN has provided the Magic Wall with huge visibility and people are noticing it. Since RIA is still an emerging technology, RIA apps should strive for setting a new standard and raising user's expectations.

I think the Magic Wall is providing a collateral benefit for RIA developers. People who are watching this technology on TV will be looking for the same rich experience in the Internet from now on. The challenge for us, RIA developers, is to provide that same magic in our applications.

Video: