Skip navigation
nsreekumar
Currently Being Moderated

How to store an image into MySQL db using BlazeDS and Hibernate?

Sep 6, 2012 10:16 AM

Hi!

 

I am using Flash Builder 4.6, BlazeDS, and Hibernate. How to store a webcam snapshot into the MySql Database. I stored Form Items by using RemoteObject into the database. But I failed to store webcam snapshot. I captured that image on Panel component.I converted that image to ByteArray. Now I want to save that image into the database. Please help me in this regard.

 

thanks in advance.

 

Here the Code:

 

VisitorEntryForm.mxml

 

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

<mx:TitleWindow

          xmlns:mx="http://www.adobe.com/2006/mxml"

          xmlns:vo="com.visitor.vo.*"

          width="600"

          height="300"

          defaultButton="{submitButton}"

          showCloseButton="true"

          creationComplete="creationCompleteHandler();"

          close="PopUpManager.removePopUp(this);"

          title="Visitor Entry Form" xmlns:text="flash.text.*">

 

          <mx:RemoteObject id="saveService" destination="visitorService" result="handleSaveResult(event)" fault="handleFault(event)" showBusyCursor="true" />

 

          <vo:Visitor id="visitor"

                                           vType="{vTypeField.text}"

                                           vPurpose="{vPurposeField.text}"

                                           vName="{vNameField.text}"

                                           vAddress="{vAddressField.text}"

                                           cPerson="{cPersonField.text}"

                                           cAddress="{cAddressField.text}"

                                 />

                    <mx:Script>

                    <![CDATA[

 

                    import mx.managers.PopUpManager;

                    import flash.media.Camera;

                    import com.visitor.vo.WebCam;

                    import com.visitor.vo.Base64;

                    import mx.core.UIComponent;

                    import mx.graphics.codec.JPEGEncoder;

                    import mx.controls.Alert;

                    import mx.containers.Canvas;

                    import mx.rpc.events.ResultEvent;

                    import mx.rpc.events.FaultEvent;

                    import mx.events.ValidationResultEvent;

                    import mx.validators.Validator;

 

 

                              [Bindable]

                              private var webCam: com.visitor.vo.WebCam;

 

                              [Bindable]

                              private var message:String;

 

                              [Bindable]

                              private var formIsValid:Boolean = false;

 

                              [Bindable]

                              public var formIsEmpty:Boolean;

 

                              private var focussedFormControl:DisplayObject;

 

                              private function handleSaveResult(ev:ResultEvent):void {

                                        clearFormHandler();

                                        validateForm(ev);

                                        Alert.show("Visitor successfully created/updated.", "Information", Alert.OK, null, null, null, Alert.OK);

 

                                        // Reload the list.

                                        parentApplication.listConsultants.loaderService.getConsultants();

                                        PopUpManager.removePopUp(this);

                              }

                              private function handleFault(ev:FaultEvent):void {

                                        message = "Error: " + ev.fault.faultCode + " \n "

                                                  + "Detail: " + ev.fault.faultDetail + " \n "

                                                  + "Message: " + ev.fault.faultString;

                              }

                              public function saveVisitor():void {

                                        saveService.addUpdateVisitor(visitor);

                              }

                              private function creationCompleteHandler():void {

                                        init();

                                        PopUpManager.centerPopUp(this);

                                        resetFocus();

                              }

 

                              private function resetFocus():void {

                                        focusManager.setFocus(vTypeField);

                              }

                              public function validateForm(event:Event):void  {

                                        focussedFormControl = event.target as DisplayObject;   

                                        formIsValid = true;

 

                                        // Check if form is empty

                                        formIsEmpty = (vTypeField.text == "" && vPurposeField.text == "" && vNameField.text == "" && vAddressField.text == "" && cPersonField.text == "" && cAddressField.text == "");

 

                                        validate(vTypeValidator);               

                                        validate(vPurposeValidator);

                                        validate(vNameValidator);

                                        validate(vAddressValidator);

                                        validate(cPersonValidator);

                                        validate(cAddressValidator);

                              }

                              private function validate(validator:Validator):Boolean {

 

                                        var validatorSource:DisplayObject = validator.source as DisplayObject;

                                        var suppressEvents:Boolean = (validatorSource != focussedFormControl);

                                        var event:ValidationResultEvent = validator.validate(null, suppressEvents);

                                        var currentControlIsValid:Boolean = (event.type == ValidationResultEvent.VALID);

 

                                        formIsValid = formIsValid && currentControlIsValid;

                                        return currentControlIsValid;

                              }

                              private function clearFormHandler():void {

                                        // Clear all input fields.

                                        vTypeField.text = "";

                                        vPurposeField.text = "";

                                        vNameField.text = "";

                                        vAddressField.text = "";

                                        cPersonField.text = "";

                                        cAddressField.text = "";

 

                                        message = "";

 

                                        // Clear validation error messages.

                                        vTypeField.errorString = "";

                                        vPurposeField.errorString = "";

                                        vNameField.errorString = "";

                                        vAddressField.errorString = "";

                                        cPersonField.errorString = "";

                                        cAddressField.errorString = "";

 

                                        formIsEmpty = true;

                                        formIsValid = false;

                                        resetFocus();

                              }

                              private function init():void {

                              webCam = new WebCam(97,97);

                              var ref:UIComponent = new UIComponent();

                              preview.removeAllChildren();

                              preview.addChild(ref);

                              ref.addChild(webCam);

                              }

                              private function takeSnapshot():void {

                              imageViewer.visible = true;

                              imageViewer.width = preview.width;

                              imageViewer.height = preview.height;

                              var uiComponent : UIComponent = new UIComponent();

                              uiComponent.width = webCam.width;

                              uiComponent.height = webCam.height;

                              var photoData:Bitmap = webCam.getSnapshot();

                              var photoBitmap:BitmapData = photoData.bitmapData;

                              uiComponent.addChild(photoData);

                              imageViewer.removeAllChildren();

                              imageViewer.addChild(uiComponent);

                              }

                              private function uploadSnapshot():void

                              {

                                        if (imageViewer.getChildren().length > 0)

                                        {

                                                  var uic:UIComponent = imageViewer.getChildAt(0) as UIComponent;

                                                  var bitmap:Bitmap = uic.getChildAt(0) as Bitmap;

                                                  var jpgEncoder:JPEGEncoder = new JPEGEncoder(75);

                                                  var jpgBytes:ByteArray = jpgEncoder.encode(bitmap.bitmapData);

                                        }

                              }

                              private function deleteSnapshot():void

                              {

                                        imageViewer.removeAllChildren();

                              }

                    ]]>

                    </mx:Script>

 

          <mx:StringValidator id="vTypeValidator"          source="{vTypeField}"          property="text" minLength="2" required="true" />

          <mx:StringValidator id="vPurposeValidator" source="{vPurposeField}"          property="text" minLength="2" required="true" />

          <mx:StringValidator id="vNameValidator"          source="{vNameField}"          property="text" minLength="2" required="true" />

          <mx:StringValidator id="vAddressValidator"          source="{vAddressField}"          property="text" minLength="5" required="true" />

          <mx:StringValidator id="cPersonValidator" source="{cPersonField}"          property="text" minLength="2" required="true" />

          <mx:StringValidator id="cAddressValidator"          source="{cAddressField}"          property="text" minLength="5" required="true" />

 

          <mx:Grid width="575" height="211">

                    <mx:GridRow width="575" height="211">

                              <mx:GridItem width="301" height="235">

                                        <mx:Form width="301" height="208">

                                                  <mx:FormItem label="Visitor's Type">

                                                            <mx:ComboBox id="vTypeField" text="{visitor.vType}" change="validateForm(event);" editable="true">

                                                                      <mx:Array>

                                                                                 <mx:String></mx:String>

                                                                                 <mx:String>Contractor</mx:String>

                                                                                 <mx:String>Supplier</mx:String>

                                                                                 <mx:String>Transporter</mx:String>

                                                                                 <mx:String>Plant</mx:String>

                                                                                 <mx:String>Non-Plant</mx:String>

                                                                      </mx:Array>

                                                            </mx:ComboBox>

                                                  </mx:FormItem>

                                                  <mx:FormItem label="Visit Purpose">

                                                            <mx:ComboBox id="vPurposeField" text="{visitor.vPurpose}" change="validateForm(event);" editable="true">

                                                                      <mx:Array>

                                                                                 <mx:String></mx:String>

                                                                                 <mx:String>Official</mx:String>

                                                                                 <mx:String>Personal</mx:String>

                                                                      </mx:Array>

                                                            </mx:ComboBox>

                                                  </mx:FormItem>

                                                  <mx:FormItem label="Visitor's Name">

                                                            <mx:TextInput id="vNameField"  text="{visitor.vName}" change="validateForm(event);"/>

                                                  </mx:FormItem>

                                                  <mx:FormItem label="Address">

                                                            <mx:TextInput id="vAddressField"   text="{visitor.vAddress}" change="validateForm(event);"/>

                                                  </mx:FormItem>

                                                  <mx:FormItem label="Contact Person">

                                                            <mx:TextInput id="cPersonField"  text="{visitor.cPerson}" change="validateForm(event);"/>

                                                  </mx:FormItem>

                                                  <mx:FormItem label="Address">

                                                            <mx:TextInput id="cAddressField"  text="{visitor.cAddress}" change="validateForm(event);"/>

                                                  </mx:FormItem>

                                                  </mx:Form>

                              </mx:GridItem>

                              <mx:GridItem width="264" height="193">

                                        <mx:Grid width="241" height="206">

                                                  <mx:GridRow width="100%" height="100%">

                                                            <mx:GridItem width="100%" height="100%" horizontalAlign="center" verticalAlign="middle">

                                                                      <mx:Panel width="100" height="132" title="Snap" id="preview" layout="absolute"/>

                                                            </mx:GridItem>

                                                            <mx:GridItem width="100%" height="100%" horizontalAlign="center" verticalAlign="middle">

                                                                      <mx:Panel width="100" height="132" title="Preview" id="imageViewer"  layout="absolute"/>

                                                            </mx:GridItem>

                                                  </mx:GridRow>

                                                  <mx:GridRow width="100%" height="27" >

                                                            <mx:GridItem width="100%" height="100%" horizontalAlign="center">

                                                                      <mx:Button id="snapshot" x="2" width="106" height="27" label="Snap"

                                                                                              click="takeSnapshot();"/>

                                                            </mx:GridItem>

                                                            <mx:GridItem width="100%" height="100%" horizontalAlign="center">

                                                                      <mx:Button id="deleteButton" x="1" width="106" height="27" label="Delete"

                                                                                              click="deleteSnapshot();"/>

                                                            </mx:GridItem>

                                                  </mx:GridRow>

                                        </mx:Grid>

                              </mx:GridItem>

                    </mx:GridRow>

          </mx:Grid>

          <mx:ControlBar height="40" horizontalAlign="center">

                    <mx:Button label="Save Visitor"          id="submitButton" enabled="{formIsValid}" click="saveVisitor();" />

                    <mx:Button label="Clear form" enabled="{!formIsEmpty}"          click="clearFormHandler();" />

                    <mx:Button label="Cancel" click="PopUpManager.removePopUp(this);"/>

                    <mx:Label width="211" id="state"/>

          </mx:ControlBar>

          <mx:Text text="{message}" fontWeight="bold" width="300"/>

</mx:TitleWindow>

 

ListVisitors.mxml

 

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

<mx:Panel

          xmlns:mx="http://www.adobe.com/2006/mxml"

          xmlns:view="com.visitor.view.*"

          width="100%"

          height="100%"

          title="Visitor Management System - Found {visitorRecords} visitors."

          creationComplete="loadVisitors();">

 

          <mx:RemoteObject id="loaderService" destination="visitorService" result="handleLoadResult(event)"          fault="handleFault(event)" showBusyCursor="true" />

          <mx:RemoteObject id="deleteService" destination="visitorService" result="handleDeleteResult(event)"          fault="handleFault(event)" showBusyCursor="true" />

 

          <mx:Script>

                    <![CDATA[

                              import com.visitor.vo.Visitor;

                              import mx.controls.Alert;

                              import mx.managers.PopUpManager;

                              import mx.containers.TitleWindow;

                              import mx.collections.ArrayCollection;

                              import mx.rpc.events.ResultEvent;

                              import mx.rpc.events.FaultEvent;

 

                              [Bindable]

                              private var message:String;

 

                              [Bindable]

                              private var visitors:ArrayCollection = new ArrayCollection();

 

                              [Bindable]

                              private var visitorRecords:int = 0;

 

                              public function loadVisitors():void {

                                        loaderService.getVisitors();

                              }

 

                              private function deleteVisitor():void {

                                        if(dataGrid.selectedItem != null) {

                                                  var selectedItem:Visitor = dataGrid.selectedItem as Visitor;

                                                  deleteService.deleteVisitor(selectedItem.visitorId);

                                        }

                              }

 

                              private function createVisitor():void {

                                        var titleWindow:VisitorEntryForm = VisitorEntryForm(PopUpManager.createPopUp(this, VisitorEntryForm, true));

                                        titleWindow.setStyle("borderAlpha", 0.9);

                                        titleWindow.formIsEmpty = true;

                              }

 

                              private function updateVisitor():void {

                                        var titleWindow:VisitorEntryForm = VisitorEntryForm(PopUpManager.createPopUp(this, VisitorEntryForm, true));

                                        titleWindow.setStyle("borderAlpha", 0.9);

                                        titleWindow.visitor = dataGrid.selectedItem as Visitor;

                                        titleWindow.formIsEmpty = false;

                              }

 

                              private function handleLoadResult(ev:ResultEvent):void {

                                        visitors = ev.result as ArrayCollection;

                                        visitorRecords = visitors.length;

                              }

 

                              private function handleDeleteResult(ev:ResultEvent):void {

                                        Alert.show("The visitor has been deleted.", "Information", Alert.OK, null, null, null, Alert.OK);

                                        loadVisitors();

                              }

 

 

                              private function handleFault(ev:FaultEvent):void {

                                        message = "Error: "

                                                  + ev.fault.faultCode + " - "

                                                  + ev.fault.faultDetail + " - "

                                                  + ev.fault.faultString;

                              }

                    ]]>

          </mx:Script>

 

 

          <mx:VBox width="100%" height="100%">

                    <mx:Label text="{message}" fontWeight="bold" includeInLayout="false" />

                    <mx:DataGrid

                              id="dataGrid"

                              width="100%"

                              height="100%"

                              dataProvider="{visitors}"

                              doubleClickEnabled="true"

                              doubleClick="updateVisitor()" >

                              <mx:columns>

                                        <mx:DataGridColumn dataField="visitorId"          headerText="Visitor ID" width="100"/>

                                        <mx:DataGridColumn dataField="vType"                    headerText="Visitor's Type" />

                                        <mx:DataGridColumn dataField="vPurpose"           headerText="Visit Purpose" />

                                        <mx:DataGridColumn dataField="vName"                     headerText="Visitor's Name" />

                                        <mx:DataGridColumn dataField="vAddress"                    headerText="Visitor's Address" />

                                        <mx:DataGridColumn dataField="cPerson"                     headerText="Contact Person" />

                                        <mx:DataGridColumn dataField="cAddress"                    headerText="Contact Address" />

                                        <mx:DataGridColumn dataField="timeIn"                     headerText="Time-In" />

                                        <mx:DataGridColumn dataField="timeOut"                     headerText="Time-Out" />

                                        <mx:DataGridColumn dataField="vPhoto"                     headerText="Visitor's Photo" />

                              </mx:columns>

                    </mx:DataGrid>

 

                    <mx:ControlBar horizontalAlign="center">

                              <mx:Button label="Create Visitor"          click="createVisitor()"          toolTip="Create a new visitor and store it in the database." />

                              <mx:Button label="Update Visitor"          click="updateVisitor()"           enabled="{dataGrid.selectedItem}" toolTip="Update an existing database visitor." />

                              <mx:Button label="Delete Visitor"          click="deleteVisitor()"          enabled="{dataGrid.selectedItem}" toolTip="Delete the visitor from the database." />

                              <mx:Button label="Reload Data"                    click="loadVisitors()"           toolTip="Reload the visitor list from the database." />

                    </mx:ControlBar>

          </mx:VBox>

</mx:Panel>

 

Visitor.as

 

package com.visitor.vo

{

          import mx.controls.Image;

 

          import spark.primitives.BitmapImage;

 

 

          [Bindable]

          [RemoteClass(alias="com.visitor.Visitor")]

          public class Visitor

          {

                    public function Visitor()

                    {

                    }

 

                    public var visitorId:Number;

                    public var vType:String;

                    public var vPurpose:String;

                    public var vName:String;

                    public var vAddress:String;

                    public var cPerson:String;

                    public var cAddress:String;

                    public var timeIn:Date;

                    public var timeOut:Date;

                   public var vPhoto: Image;

          }

}

 

Visitor.java

package com.visitor;

 

 

import java.sql.Blob;

import java.sql.Timestamp;

 

 

import javax.persistence.Basic;

import javax.persistence.Column;

import javax.persistence.Entity;

import javax.persistence.GeneratedValue;

import javax.persistence.GenerationType;

import javax.persistence.Id;

import javax.persistence.NamedQueries;

import javax.persistence.NamedQuery;

import javax.persistence.Table;

 

 

import org.hibernate.annotations.Index;

 

 

@Entity

@Table(name = "visitors")

@NamedQueries( {

                    @NamedQuery(name = "visitors.findAll", query = "from Visitor"),

                    @NamedQuery(name = "visitors.byId", query = "select v from Visitor v where v.visitorId= :visitorId") })

public class Visitor {

 

 

          @Id

          @GeneratedValue(strategy = GenerationType.AUTO)

          @Column(name = "visitorId", nullable = false)

          private Long visitorId;

 

 

          @Basic

          @Index(name = "vType_idx_1")

          @Column(name = "vType", nullable = true, unique = false)

          private String vType;

 

 

          @Basic

          @Column(name = "vPurpose", nullable = true, unique = false)

          private String vPurpose;

 

 

          @Basic

          @Column(name = "vName", nullable = true, unique = false)

          private String vName;

 

 

          @Basic

          @Column(name = "vAddress", nullable = true, unique = false)

          private String vAddress;

 

          @Basic

          @Column(name = "cPerson", nullable = true, unique = false)

          private String cPerson;

 

          @Basic

          @Column(name = "cAddress", nullable = true, unique = false)

          private String cAddress;

 

          @Basic

          @Column(name = "timeIn", nullable = false, unique = false)

          private Timestamp timeIn;

 

 

          @Basic

          @Column(name = "timeOut", nullable = true, unique = false)

          private Timestamp timeOut;

 

          @Basic

          @Column(name = "vPhoto", nullable = true, unique = false)

          private Blob vPhoto;

 

          public Visitor() {

                    super();

          }

 

 

          public Long getVisitorId() {

                    return visitorId;

          }

 

 

          public void setVisitorId(Long visitorId) {

                    this.visitorId = visitorId;

          }

 

 

          public String getvType() {

                    return vType;

          }

 

 

          public void setvType(String vType) {

                    this.vType = vType;

          }

 

 

          public String getvPurpose() {

                    return vPurpose;

          }

 

 

          public void setvPurpose(String vPurpose) {

                    this.vPurpose = vPurpose;

          }

 

 

          public String getvName() {

                    return vName;

          }

 

 

          public void setvName(String vName) {

                    this.vName = vName;

          }

 

 

          public String getvAddress() {

                    return vAddress;

          }

 

 

          public void setvAddress(String vAddress) {

                    this.vAddress = vAddress;

          }

 

 

          public String getcPerson() {

                    return cPerson;

          }

 

 

          public void setcPerson(String cPerson) {

                    this.cPerson = cPerson;

          }

 

 

          public String getcAddress() {

                    return cAddress;

          }

 

 

          public void setcAddress(String cAddress) {

                    this.cAddress = cAddress;

          }

 

 

          public Timestamp getTimeIn() {

                    return timeIn;

          }

 

 

          public void setTimeIn(Timestamp timeIn) {

                    this.timeIn = timeIn;

          }

 

 

          public Timestamp getTimeOut() {

                    return timeOut;

          }

 

 

          public void setTimeOut(Timestamp timeOut) {

                    this.timeOut = timeOut;

          }

 

 

          public Blob getvPhoto() {

                    return vPhoto;

          }

 

 

          public void setvPhoto(Blob vPhoto) {

                    this.vPhoto = vPhoto;

          }

 

 

}

 

VisitorService.java


package com.visitor;

 

import java.sql.Timestamp;

import java.util.Date;

import java.util.List;

 

 

import javax.persistence.EntityManager;

import javax.persistence.EntityManagerFactory;

import javax.persistence.EntityTransaction;

import javax.persistence.Persistence;

import javax.persistence.Query;

 

 

import org.apache.log4j.Logger;

 

 

public class VisitorService {

 

 

          private static final String PERSISTENCE_UNIT = "visitor_db";

 

 

          private static Logger logger = Logger.getLogger(VisitorService.class);

 

 

          public VisitorService() {

                    super();

          }

 

 

          public List<Visitor> getvisitors() {

                    logger.debug("** getVisitors called...");

 

 

                    EntityManagerFactory entityManagerFactory = Persistence

                                        .createEntityManagerFactory(PERSISTENCE_UNIT);

 

 

                    EntityManager em = entityManagerFactory.createEntityManager();

 

 

                    Query findAllQuery = em.createNamedQuery("visitors.findAll");

                    List<Visitor> visitors = findAllQuery.getResultList();

 

 

                    if (visitors != null)

                              logger.debug("** Found " + visitors.size() + " records:");

 

 

                    return visitors;

          }

 

 

          public void addUpdateVisitor(Visitor visitor) throws Exception {

                    logger.debug("** addUpdateVisitor called...");

 

 

                    EntityManagerFactory emf = Persistence

                                        .createEntityManagerFactory(PERSISTENCE_UNIT);

 

 

                    EntityManager em = emf.createEntityManager();

 

 

                    // When passing Boolean and Number values from the Flash client to a

                    // Java object, Java interprets null values as the default values for

                    // primitive types; for example, 0 for double, float, long, int, short,

                    // byte.

                    if (visitor.getVisitorId() == null          || visitor.getVisitorId() == 0) {

                              // New consultant is created

                              visitor.setVisitorId(null);

                              visitor.setTimeIn(new Timestamp(new Date().getTime()));

                    } else {

 

                              visitor.setTimeOut(new Timestamp(new Date().getTime()));

                              // Existing consultant is updated - do nothing.

                    }

 

 

                    EntityTransaction tx = em.getTransaction();

                    tx.begin();

                    try {

                              em.merge(visitor);

                              tx.commit();

                    } catch (Exception e) {

                              logger.error("** Error: " + e.getMessage());

                              tx.rollback();

                              throw new Exception(e.getMessage());

                    } finally {

                              logger.info("** Closing Entity Manager.");

                              em.close();

                    }

          }

 

 

          public void deleteVisitor(Long visitorId) {

                    logger.debug("** deleteVisitor called...");

 

 

                    EntityManagerFactory emf = Persistence

                                        .createEntityManagerFactory(PERSISTENCE_UNIT);

 

 

                    EntityManager em = emf.createEntityManager();

 

 

                    Query q = em.createNamedQuery("visitors.byId");

                    q.setParameter("visitorId", visitorId);

                    Visitor visitor = (Visitor) q.getSingleResult();

 

 

                    if (visitor != null) {

                              EntityTransaction tx = em.getTransaction();

                              tx.begin();

                              try {

                                        em.remove(visitor);

                                        tx.commit();

                              } catch (Exception e) {

                                        logger.error("** Error: " + e.getMessage());

                                        tx.rollback();

                              } finally {

                                        logger.info("** Closing Entity Manager.");

                                        em.close();

                              }

                    }

          }

}

remoting-config.xml


<?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.JavaA dapter"

                              default="true" />

          </adapters>

          <default-channels>

                    <channel ref="my-amf" />

          </default-channels>

   

          <!-- ADC Demo application -->

          <destination id="visitorService">

                    <properties>

                              <source>com.visitor.VisitorService</source>

                    </properties>

          </destination>

</service>

 


 

More Like This

  • Retrieving data ...

Bookmarked By (0)

Answers + Points = Status

  • 10 points awarded for Correct Answers
  • 5 points awarded for Helpful Answers
  • 10,000+ points
  • 1,001-10,000 points
  • 501-1,000 points
  • 5-500 points