<?xml version="1.0" encoding="utf-8"?>
<s:WindowedApplication xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx" applicationComplete="init();" initialize="initializeHandler(event)">
<fx:Script>
<![CDATA[
import mx.collections.ArrayCollection;
import mx.events.FlexEvent;
import sandacreative.sqlite.events.StatementSuccessEvent;
import sandacreative.sqlite.SQLiteManager;
private var database:SQLiteManager = SQLiteManager.getInstance();
protected function initializeHandler(event:FlexEvent):void
{ trace("inside initializehandler");
database.start("Users.db", "Users", "CREATE TABLE Users(UserId VARCHAR(150) PRIMARY KEY, UserName VARCHAR(150))");
database.addEventListener(SQLiteManager.COMMAND_EXEC_SUCCESSFULLY, onSelectResult);
database.addEventListener(SQLiteManager.COMMAND_EXEC_FAILED, function():void {
trace("fail!");
});
readEntries();
}
private function insertEntry():void
{
var sql:String = "INSERT INTO Users VALUES('"+nameField.text+"');";
database.executeCustomCommand(sql);
}
// SQLite Ends Here*/
import flash.media.Camera;
import sandacreative.WebCam;
import sandacreative.Base64;
import mx.core.UIComponent;
import mx.graphics.codec.JPEGEncoder;
private var webCam:WebCam;
private function init():void {
webCam = new WebCam(160, 120);
var ref:UIComponent = new UIComponent();
preview.removeAllChildren();
preview.addChild(ref);
ref.addChild(webCam);
}
</fx:Script>
<mx:Panel width="180" height="160" id="preview" title="Snapshotr" x="158" y="343"/>
<mx:Button label="Save" id="submit" x="280" y="521" width="100" enabled="true" click="insertEntry();"/>
init() initiates a cam and that works properly .. while initiliseHandler() creates a sqlite table. But the table is not created and when i try to save it shows the error
Error: Error #3104: A SQLConnection must be open to perform this operation.
at Error$/throwError()
at flash.data::SQLStatement/checkAllowed()
at flash.data::SQLStatement/checkReady()
at flash.data::SQLStatement/execute()
at sandacreative.sqlite::SQLiteManager/executeCustomCommand()[C:\Documents and Settings\sujith\My Documents\Visitrac1\src\sandacreative\sqlite\SQLiteManager.as:238]
at sandacreative::Main/insertEntry()[C:\Documents and Settings\sujith\My Documents\Visitrac1\src\sandacreative\Main.mxml:34]
at sandacreative::Main/__submit_click()[C:\Documents and Settings\sujith\My Documents\Visitrac1\src\sandacreative\Main.mxml:153]
SQLiteManager.as
package sandacreative.sqlite
{
import sandacreative.sqlite.events.StatementSuccessEvent;
import flash.data.SQLConnection;
import flash.data.SQLStatement;
import flash.errors.SQLError;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.SQLErrorEvent;
import flash.events.SQLEvent;
import flash.filesystem.File;
public class SQLiteManager extends EventDispatcher implements ISQLiteManager
{
/**
* Database file name and extension
*/
public var dbFullFileName:String;
/**
* Database Name
*/
public var tableName:String;
/**
* SQL command to create the database
*/
public var createDbStatement:String;
// datsbase apis instances
protected var connection:SQLConnection;
protected var statement:SQLStatement;
protected var sqlFile:File;
// repeated sql command
protected var repeateFailCallBack:Function;
protected var repeateCallBack:Function;
protected var repeateSqlCommand:String = "";
// events strings
public static var COMMAND_EXEC_SUCCESSFULLY:String = "commandExecSuccesfully";
public static var DATABASE_CONNECTED_SUCCESSFULLY:String = "databaseConnectedSuccessfully";
public static var COMMAND_EXEC_FAILED:String = "commandExecFailed";
public static var DATABASE_READY:String = "databaseReady";
// Singleton instance.
protected static var instance:SQLiteManager;
/**
* Enforce singleton design pattern.
*
* #param enforcer
*
*/
public function SQLiteManager(enforcer:AccessRestriction)
{
if (enforcer == null)
throw new Error("Error enforcer input param is undefined" );
}
/**
* Opens a database connection.
*
* #param dbFullFileName the database file name for instance: Users.sql
* #param tableName holds the database name, for instance: Users
* #param createTableStatement holds the create database statment for instance: CREATE TABLE Users(userId VARCHAR(150) PRIMARY KEY, UserName VARCHAR(150))
*
*/
public function start(dbFullFileName:String, tableName:String, createTableStatement:String):void
{
this.dbFullFileName = dbFullFileName;
this.tableName = tableName;
this.createDbStatement = createTableStatement;
connection = new SQLConnection();
sqlFile = File.applicationStorageDirectory.resolvePath(dbFullFileName);
try
{
connection.open(sqlFile);
this.dispatchEvent(new Event(DATABASE_CONNECTED_SUCCESSFULLY));
}
catch (error:SQLError)
{
trace("Error message:", error.message);
trace("Details:", error.details);
fail();
}
}
/**
* Close connection
*
*/
public function close():void
{
connection.close();
}
/**
* Test the table to ensure it exists. Sends a fail call back function to create the table if
* it doesn't exists.
*
*/
public function testTableExists():void
{
var sql:String = "SELECT * FROM "+tableName+" LIMIT 1;";
executeCustomCommand(sql, this.onDatabaseReady, this.createTable );
}
/**
* Method to create the database table.
*
*/
private function createTable():void
{
statement = new SQLStatement();
statement.sqlConnection = connection;
statement.text = createDbStatement;
statement.execute();
statement.addEventListener(SQLEvent.RESULT, onDatabaseReady);
}
/**
* Common sql command: select all entries in database
*
* #param callback
* #param failCallback
*
*/
public function executeSelectAllCommand(callback:Function=null, failCallback:Function=null):void
{
var sql:String = "SELECT * FROM "+tableName+";";
executeCustomCommand(sql, callback, failCallback);
}
/**
* Common sql command: delete all entries in database
*
* #param callback
*
*/
public function executeDeleteAllCommand(callback:Function=null):void
{
var sql:String = "DELETE * FROM "+tableName+";";
executeCustomCommand(sql, callback);
}
/**
* Method to execute a SQL command
*
* #param sql SQL command string
* #param callback success call back function to impliment if necessery
* #param failCallBack fail call back function to impliment if necessery
*
*/
public function executeCustomCommand(sql:String, callBack:Function=null, failCallBack:Function=null):void
{
statement = new SQLStatement();
statement.sqlConnection = connection;
statement.text = sql;
if (callBack!=null)
{
statement.addEventListener(SQLEvent.RESULT, callBack);
}
else
{
statement.addEventListener(SQLEvent.RESULT, onStatementSuccess);
}
statement.addEventListener(SQLErrorEvent.ERROR, function():void {
fail();
});
try
{
statement.execute();
}
catch (error:SQLError)
{
this.handleErrors(error, sql, callBack, failCallBack);
}
}
/**
* Utility method to clean bad characters that can break SQL commands
*
* #param str
* #return
*
*/
public static function removeBadCharacters(str:String):String
{
var retVal:String = str.split("'").join("’’");
return retVal;
}
// ------------------------------HANDLERS----------------------------
/**
* Method to handle SQL command that create the dataabase.
* If the method was created due to a fail SQL command method checks if need to repeate any SQL command.
*
* #param event
*
*/
private function onDatabaseReady(event:Event=null):void
{
var evt:Event = new Event(DATABASE_READY);
this.dispatchEvent(evt);
if (repeateSqlCommand != "")
{
this.executeCustomCommand(repeateSqlCommand, repeateCallBack, repeateFailCallBack);
repeateSqlCommand = "";
repeateFailCallBack = null;
repeateCallBack = null;
}
}
/**
* Handle successful calls
* #param event
*
*/
private function onStatementSuccess(event:SQLEvent):void
{
var results:Object = statement.getResult();
var evt:StatementSuccessEvent = new StatementSuccessEvent(COMMAND_EXEC_SUCCESSFULLY, results);
this.dispatchEvent(evt);
}
/**
* Error handler
*
* #param error
* #param sql
* #param callBack
* #param failCallBack
*
*/
private function handleErrors(error:SQLError, sql:String, callBack:Function, failCallBack:Function):void
{
trace("Error message:", error.message);
trace("Details:", error.details);
if (error.details == "no such table: '"+tableName+"'")
{
repeateSqlCommand = sql;
repeateFailCallBack = failCallBack;
repeateCallBack = callBack;
createTable();
}
else
{
if (failCallBack != null)
{
failCallBack();
}
else
{
fail();
}
}
}
/**
* Handler for fail calls
*
* #param event
*
*/
private function fail(event:Event=null):void
{
var evt:Event = new Event(COMMAND_EXEC_FAILED);
this.dispatchEvent(evt);
close();
}
/**
* Method function to retrieve instance of the class
*
* #return The same instance of the class
*
*/
public static function getInstance():SQLiteManager
{
if( instance == null )
instance = new SQLiteManager(new AccessRestriction());
return instance;
}
}
}
class AccessRestriction {} // can this happen ?
ISQLiteManager.as
package sandacreative.sqlite
{
/**
* Describes the contract for Objects that serve as a central point to access SQLite database.
*
* #author Elad Elrom
*
*/
public interface ISQLiteManager
{
function start(dbFullFileName:String, tableName:String, createTableStatement:String):void
function close():void
}
}
StatementSucessEvent.as
package sandacreative.sqlite.events
{
import flash.events.Event;
public class StatementSuccessEvent extends Event
{
/**
* Holds the event string name
*/
public static var COMMAND_EXEC_SUCCESSFULLY:String = "command_exec_succesfully";
/**
* Holds results object
*/
public var results:Object;
/**
* Default constructor
*
* #param type event name
* #param videoList video list collection
*
*/
public function StatementSuccessEvent(type:String, results:Object)
{
super(type);
this.results = results;
}
}
}
I took this code from Elad Elrom
Is that because i used both applicationComplete and Initilize together ? Please help
The error is kind of obvious. Your database hasn't been created/connected yet before your button is pressed. Also, the createTable function is never called because you never keep state on your connection property.
Before any statement is executed, you should always check that the DB is connected. For all you know, the connection failed.
And thirdly (and probably most important), you are doing a synchronous execution because you used connection.open. For this to work, you need to do connection.begin() before executing any statements and finish with connection.commit(). I think the better way for you to go here is to use connection.openAsync instead to create an asynchronous execution which is easier to manage and probably what you wanted to do. Only use synchronous if the order of the statements are important (like in a transaction or if one statement is dependent on another).
Related
This is my Cest class:
<?php
namespace App\Tests\functional;
use App\Entity\AssetsRecord;
use App\Entity\Provider;
use App\Entity\User;
use App\Tests\FunctionalTester;
use App\Tests\Page\Functional\AssetsRecordIndexPage;
class AssetsRecordIndexCest
{
const FIRST_PROVIDER_NAME = "Provider 1";
const SECOND_PROVIDER_NAME = "Provider 2";
const THIRD_PROVIDER_NAME = "Provider 3";
const FIRST_ASSETS_RECORD_VALUE = 1000;
const SECOND_ASSETS_RECORD_VALUE = 2000;
const THIRD_ASSETS_RECORD_VALUE = 3000;
private array $providers;
/**
* #var array <AssetsRecord>
*/
private array $assetsRecords = [];
private User $singleProviderOperator;
private User $doubleProviderOperator;
public function _before(FunctionalTester $I)
{
$this->buildProviders($I);
$I->haveProvidersInDB($this->providers);
$this->buildAssetsRecords($I);
$I->haveAssetsRecordsInDB($this->assetsRecords);
$this->buildOperators($I);
$I->haveInRepository($this->singleProviderOperator);
$I->haveInRepository($this->doubleProviderOperator);
}
// tests
public function shouldNotShowAssetRecordsForNotEnabledProviders(FunctionalTester $I, AssetsRecordIndexPage $page)
{
$I->amLoggedInAs($this->singleProviderOperator);
$page->doesntShow(...$this->getAssetsRecordsIn($this->providers[self::SECOND_PROVIDER_NAME]));
$page->doesntShow(...$this->getAssetsRecordsIn($this->providers[self::THIRD_PROVIDER_NAME]));
$I->amLoggedInAs($this->doubleProviderOperator);
$page->doesntShow(...$this->getAssetsRecordsIn($this->providers[self::FIRST_PROVIDER_NAME]));
}
public function shouldShowAllAssetsRecordsForEnabledProviders(FunctionalTester $I, AssetsRecordIndexPage $page)
{
$I->amLoggedInAs($this->singleProviderOperator);
$page->shows(...$this->getAssetsRecordsIn($this->providers[self::FIRST_PROVIDER_NAME]));
$I->amLoggedInAs($this->doubleProviderOperator);
$page->shows(...$this->getAssetsRecordsIn($this->providers[self::SECOND_PROVIDER_NAME]));
$page->shows(...$this->getAssetsRecordsIn($this->providers[self::THIRD_PROVIDER_NAME]));
}
/**
* #param Provider $provider
* #return array
*/
private function getAssetsRecordsIn(Provider $provider): array
{
return array_filter($this->assetsRecords, fn(AssetsRecord $assetsRecord) => $assetsRecord->getProvider() === $provider);
}
/**
* #param FunctionalTester $I
* #return void
*/
private function buildAssetsRecords(FunctionalTester $I): void
{
$this->assetsRecords[] = $I->buildAssetsRecord($this->providers[self::FIRST_PROVIDER_NAME], self::FIRST_ASSETS_RECORD_VALUE);
$this->assetsRecords[] = $I->buildAssetsRecord($this->providers[self::SECOND_PROVIDER_NAME], self::SECOND_ASSETS_RECORD_VALUE);
$this->assetsRecords[] = $I->buildAssetsRecord($this->providers[self::THIRD_PROVIDER_NAME], self::THIRD_ASSETS_RECORD_VALUE);
}
/**
* #param FunctionalTester $I
* #return void
*/
private function buildProviders(FunctionalTester $I): void
{
$this->providers[self::FIRST_PROVIDER_NAME] = $I->buildProvider(self::FIRST_PROVIDER_NAME);
$this->providers[self::SECOND_PROVIDER_NAME] = $I->buildProvider(self::SECOND_PROVIDER_NAME);
$this->providers[self::THIRD_PROVIDER_NAME] = $I->buildProvider(self::THIRD_PROVIDER_NAME);
}
/**
* #param FunctionalTester $I
* #return void
*/
private function buildOperators(FunctionalTester $I): void
{
$this->singleProviderOperator = $I->buildOperatorUserWithProvidersEnabled(
$this->providers[self::FIRST_PROVIDER_NAME]
);
$this->doubleProviderOperator = $I->buildOperatorUserWithProvidersEnabled(
$this->providers[self::SECOND_PROVIDER_NAME],
$this->providers[self::THIRD_PROVIDER_NAME]
);
}
}
When I run the whole class I get this error:
A new entity was found through the relationship 'App\Entity\AssetsRecord#provider' that was not configured to cascade persist operations for entity: Provider 1. To solve this issue: Either explicitly call EntityManager#persist() on this unknown entity or configure cascade persist this association in the mapping for example #ManyToOne(..,cascade={"persist"}).
But if I run each test separetely it works ok and the tests are succesful...
Any idea why this is happening? Thanks!
When executing this command from my ../war directory (from https://developers.google.com/appengine/docs/java/endpoints/endpoints_tool#generating_a_discovery_doc):
D:\programs\eclipse-kepler\plugins\com.google.appengine.eclipse.sdkbundle_1.9.4\appengine-java-sdk-1.9.4\bin\endpoints.cmd get-discovery-doc --format=rpc com.smartinteractive.blackwoods.entity.BranchEndpoint com.smartinteractive.blackwoods.PropertyEndpoint
this is the result:
V 08, 2014 9:31:11 AM com.google.apphosting.utils.config.AppEngineWebXmlReader readAppEngineWebXml
INFO: Successfully processed ./war\WEB-INF/appengine-web.xml
Error: com.smartinteractive.blackwoods.entity.BranchEndpoint
I don't have a clue what kind of error this could be. I read in this topic (App engine RPC discovery doc) that
In the Endpoint methods, the return value type cannot be simple type
such as String or int. The return value needs to be a POJO, an array
or a Collection
What else could be the problem.
BranchEndpoint:
package com.smartinteractive.blackwoods.entity;
import com.smartinteractive.blackwoods.dao.service.BranchDataService;
import com.smartinteractive.blackwoods.persistence.EMF;
import com.google.api.server.spi.config.Api;
import com.google.api.server.spi.config.ApiMethod;
import com.google.api.server.spi.config.ApiNamespace;
import com.google.api.server.spi.response.CollectionResponse;
import java.util.List;
import javax.annotation.Nullable;
import javax.inject.Named;
import javax.persistence.EntityExistsException;
import javax.persistence.EntityNotFoundException;
import javax.persistence.EntityManager;
#Api(name = "branchendpoint", namespace = #ApiNamespace(ownerDomain = "smartinteractive.com", ownerName = "smartinteractive.com", packagePath = "blackwoods.entity"))
public class BranchEndpoint {
/**
* This method lists all the entities inserted in datastore.
* It uses HTTP GET method and paging support.
*
* #return A CollectionResponse class containing the list of all entities
* persisted
*/
#SuppressWarnings("unchecked")
#ApiMethod(name = "listBranch")
public CollectionResponse<Branch> listBranch(#Nullable #Named("first") Integer first, #Nullable #Named("last") Integer last) {
EntityManager mgr = getEntityManager();
List<Branch> execute = null;
try {
if(first == null || last == null) {
execute = new BranchDataService().findWithNamedQuery(Branch.ALL);
}
else {
execute = (List<Branch>)new BranchDataService().findAllBranches(mgr, first, last, null, null, null);
}
} finally {
mgr.close();
}
return CollectionResponse.<Branch> builder().setItems(execute).build();
}
/**
* This method gets the entity having primary key id. It uses HTTP GET method.
*
* #param id the primary key of the java bean.
* #return The entity with primary key id.
*/
#ApiMethod(name = "getBranch")
public Branch getBranch(#Named("id") Integer id) {
EntityManager mgr = getEntityManager();
Branch branch = null;
try {
branch = mgr.find(Branch.class, id);
} finally {
mgr.close();
}
return branch;
}
/**
* This inserts a new entity into App Engine datastore. If the entity already
* exists in the datastore, an exception is thrown.
* It uses HTTP POST method.
*
* #param branch the entity to be inserted.
* #return The inserted entity.
*/
#ApiMethod(name = "insertBranch")
public Branch insertBranch(Branch branch) {
EntityManager mgr = getEntityManager();
try {
if (containsBranch(branch)) {
throw new EntityExistsException("Object already exists");
}
mgr.persist(branch);
} finally {
mgr.close();
}
return branch;
}
/**
* This method is used for updating an existing entity. If the entity does not
* exist in the datastore, an exception is thrown.
* It uses HTTP PUT method.
*
* #param branch the entity to be updated.
* #return The updated entity.
*/
#ApiMethod(name = "updateBranch")
public Branch updateBranch(Branch branch) {
EntityManager mgr = getEntityManager();
try {
if (!containsBranch(branch)) {
throw new EntityNotFoundException("Object does not exist");
}
mgr.persist(branch);
} finally {
mgr.close();
}
return branch;
}
private boolean containsBranch(Branch branch) {
EntityManager mgr = getEntityManager();
boolean contains = true;
try {
Branch item = mgr.find(Branch.class, branch.getId());
if (item == null) {
contains = false;
}
} finally {
mgr.close();
}
return contains;
}
private static EntityManager getEntityManager() {
return EMF.get().createEntityManager();
}
}
I am trying to show the page displayed using StageWebView as a bitmap. As per the documentation we need to use DrawViewPortToBitMapData. While displaying the bitmap in a
UIComponent, the image is getting stretched. How can I prevent that?
bitmapData = new BitmapData(webView.viewPort.width, webView.viewPort.height, false,
0x000000 );
webView.drawViewPortToBitmapData(bitmapData);
webViewBmp = new Bitmap(bitmapData);
webView.stage = null;
uiComponent = new UIComponent;
uiComponent.width=webView.viewPort.width;
uiComponent.height=webView.viewPort.height;
uiComponent.addChild(webViewBmp);
I dont think you need to apply width/height to the uicomponent. it should be ok just by adding the bitmap to it. What you seem to be doing is stretching the uicomponent even though you have already added the bitmap at its correct size.
You should set scale to 1 on uiComponet. If you set applicationDPI (let's say to 160dpi), Flex is automatically scalling uiComponent according to the device DPI, setting scaleX and scaleY to runtimeDPI/160.
Try something like this:
uiComponent.scaleX=160/parentApplication.runtimeDPI;
uiComponent.scaleY=160/parentApplication.runtimeDPI;
so scaleX and scaleY ends with:
runtimeDPI/160 (done by flex) * 160/runtimeDPI = 1 :)
I know this is old, but this worked for me:
var r:Rectangle = wView.viewPort;
var bd:BitmapData = new BitmapData(r.width, r.height);
wView.drawViewPortToBitmapData(bd);
var bmp:Bitmap = new Bitmap(bd);
bmp.width = bd.width * (Capabilities.screenResolutionX / 320);
bmp.height = bd.height * (Capabilities.screenResolutionY / 480);
Hope it helps!
Use uiComponent.unscaledWidth & unscaledHeight. This is my working component, altered flexcapacitor code - original here: http://flexcapacitor.googlecode.com/svn-history/r5/trunk/mobilelibrary/src/com/flexcapacitor/controls/WebView.as
look at takeSnapshot:
snapshotBitmapData = new BitmapData(_webView.viewPort.width, _webView.viewPort.height);
webView.drawViewPortToBitmapData(snapshotBitmapData);
webViewBitmap = new Bitmap(snapshotBitmapData);
webViewBitmap.width = unscaledWidth;
webViewBitmap.height = unscaledHeight;
addChild(webViewBitmap);
hideWebView();
full code:
package ctrls {
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.events.ErrorEvent;
import flash.events.Event;
import flash.events.FocusEvent;
import flash.events.KeyboardEvent;
import flash.events.LocationChangeEvent;
import flash.geom.Point;
import flash.geom.Rectangle;
import flash.media.StageWebView;
import flash.ui.Keyboard;
import mx.core.FlexGlobals;
import mx.core.UIComponent;
/** #copy flash.media.StageWebView#ErrorEvent.ERROR */
[Event(name="error", type="flash.events.ErrorEvent")]
/** #copy flash.media.StageWebView#Event.COMPLETE */
[Event(name="complete", type="flash.events.Event")]
/** #copy flash.media.StageWebView#LocationChangeEvent.LOCATION_CHANGING */
[Event(name="locationChanging", type="flash.events.LocationChangeEvent")]
/** #copy flash.media.StageWebView#LocationChangeEvent.LOCATION_CHANGE */
[Event(name="locationChange", type="flash.events.LocationChangeEvent")]
/**
* This class wraps the standard StageWebView with a UIComponent.
* This allows it to be sized and positioned in the same way
* any UIComponent would. <br/><br/>
*
* The StageWebView class documentation follows:<br/>
* #copy flash.media.StageWebView
* */
public class WebView extends UIComponent {
//==================================================================================================
protected var _webView:StageWebView;
private var _source:String;
private var _visibleChanged:Boolean;
private var _sourceChanged:Boolean;
/** #copy flash.media.StageWebView#viewPort */
public function get viewPort():Rectangle { return _webView ? _webView.viewPort : null; }
/** #copy flash.media.StageWebView#dispose() */
public function dispose():void { hideWebView(true); }
/** #copy flash.media.StageWebView#assignFocus() */
public function assignFocus(direction:String = "none"):void { webView.assignFocus(direction); }
/** #copy flash.media.StageWebView#drawViewPortToBitmapData() */
public function drawViewPortToBitmapData(bitmap:BitmapData):void { webView.drawViewPortToBitmapData(bitmap); }
/** #copy flash.media.StageWebView#title */
public function get title():String { return _webView ? _webView.title : null; }
/** #copy flash.media.StageWebView#isHistoryBackEnabled() */
public function get isHistoryBackEnabled():Boolean { return _webView ? _webView.isHistoryBackEnabled : false; }
/** #copy flash.media.StageWebView#isHistoryForwardEnabled() */
public function get isHistoryForwardEnabled():Boolean { return _webView ? _webView.isHistoryForwardEnabled : false; }
/** #copy flash.media.StageWebView#historyBack() */
public function historyBack():void { if(_webView) _webView.historyBack(); }
/** #copy flash.media.StageWebView#historyForward() */
public function historyForward():void { if(_webView) _webView.historyForward(); }
/** #copy flash.media.StageWebView#reload() */
public function reload():void { webView.reload(); }
/** #copy flash.media.StageWebView#stop() */
public function stop():void { if(_webView) webView.stop(); }
/** Load the URL passed in or load the URL specified in the source property
* #see flash.media.StageWebView#loadURL() */
public function load(url:String = null):void { webView.loadURL(url ? _source = url : source); }
override public function set visible(value:Boolean):void {
super.visible = value;
_visibleChanged = true;
invalidateProperties();
invalidateSize();
}
/** #private */
public function get source():String { return _source; }
/**
* Source URL for stage web view.
* #see flash.media.StageWebView#loadURL()
* */
[Bindable]
public function set source(value:String):void {
_source = value;
_sourceChanged = true;
invalidateProperties();
invalidateSize();
}
//==================================================================================================
/**
* Wrapper for StageWebView
*
* #copy flash.media.StageWebView
*/
public function WebView() {
addEventListener(Event.ADDED_TO_STAGE, addedToStage);
addEventListener(Event.REMOVED_FROM_STAGE, removedFromStage);
focusEnabled = false;
}
/** #private */
public function get webView():StageWebView {
if(!_webView) webView = new StageWebView();
return _webView; }
/** #copy flash.media.StageWebView */
public function set webView(value:StageWebView):void {
if(_webView == value) return;
if(_webView) {
_webView.removeEventListener(Event.COMPLETE, completeHandler);
_webView.removeEventListener(ErrorEvent.ERROR, errorHandler);
_webView.removeEventListener(FocusEvent.FOCUS_IN, focusInViewHandler);
_webView.removeEventListener(FocusEvent.FOCUS_OUT, focusOutViewHandler);
_webView.removeEventListener(LocationChangeEvent.LOCATION_CHANGING, locationChangingHandler);
_webView.removeEventListener(LocationChangeEvent.LOCATION_CHANGE, locationChangeHandler); }
_webView = value;
_webView.addEventListener(Event.COMPLETE, completeHandler);
_webView.addEventListener(ErrorEvent.ERROR, errorHandler);
_webView.addEventListener(FocusEvent.FOCUS_IN, focusInViewHandler);
_webView.addEventListener(FocusEvent.FOCUS_OUT, focusOutViewHandler);
_webView.addEventListener(LocationChangeEvent.LOCATION_CHANGING, locationChangingHandler);
_webView.addEventListener(LocationChangeEvent.LOCATION_CHANGE, locationChangeHandler);
_webView.stage = visible ? stage : null;
_visibleChanged = false;
if(source) _webView.loadURL(_source);
_sourceChanged = false;
invalidateDisplayList();
}
/** Hides the web view #see flash.media.StageWebView#stage */
public function hideWebView(destroy:Boolean = false):void {
if(_webView == null) return;
_webView.stage = null;
if(!destroy) return;
_webView.viewPort = null;
_webView.dispose();
_webView = null;
}
/** Displays the web view #see flash.media.StageWebView#stage */
public function showWebView():void {
if(_webView != null) {
webView.stage = stage;
return; }
_visibleChanged = true;
invalidateProperties();
invalidateSize();
invalidateDisplayList(); }
/** #copy mx.core.UIComponent#commitProperties() */
override protected function commitProperties():void {
super.commitProperties();
if(_visibleChanged) {
webView.stage = visible ? stage : null;
_visibleChanged = false; }
if(_sourceChanged) {
webView.loadURL(source);
_sourceChanged = false; }}
//==================================================================================================
/** Flag indicating if a snapshot is being shown */
[Bindable]
public var isSnapshotVisible:Boolean;
/**
* When calling takeSnapshot or setting snapshotMode to true this
* property will contain the bitmap data of the view port.
* */
public var snapshotBitmapData:BitmapData;
/**
* When calling takeSnapshot or setting snapshotMode a snapshot of
* the Stage Web View is taken and added to the stage. This is a
* reference to the displayed bitmap.
* */
public var webViewBitmap:Bitmap;
/**
* #private
* */
public function get snapshotMode():Boolean {
return isSnapshotVisible;
}
/**
* When set to true hides the stage web view and displays a non-interactive
* snapshot of the Stage Web View when the property was set to true.
* */
public function set snapshotMode(value:Boolean):void {
value ? takeSnapshot() : removeSnapshot();
}
/**
* Creates a snapshot of the Stage Web View at the point of this call
* and displays that instead of the actual Stage Web View.
* Use removeSnapshot to dispose of the snapshot and show the web contents again.
*
* #see isSnapshotVisible
* #see flash.media.StageWebView#drawViewPortToBitmapData()
* */
public function takeSnapshot():BitmapData {
destroySnapshot();
snapshotBitmapData = new BitmapData(_webView.viewPort.width, _webView.viewPort.height);
webView.drawViewPortToBitmapData(snapshotBitmapData);
webViewBitmap = new Bitmap(snapshotBitmapData);
webViewBitmap.width = unscaledWidth;
webViewBitmap.height = unscaledHeight;
addChild(webViewBitmap);
hideWebView();
isSnapshotVisible = true;
return snapshotBitmapData;
}
/**
* Removes the bitmap snapshot of the Stage Web View from the display list
* and displays the actual Stage Web View.
* #copy flash.media.StageWebView#drawViewPortToBitmapData()
* */
public function removeSnapshot():void {
destroySnapshot();
showWebView();
}
/**
* Removes the web view snapshot from the display list and disposes of the
* bitmap data
* */
private function destroySnapshot():void {
if (webViewBitmap) {
if (webViewBitmap.parent) removeChild(webViewBitmap);
if (webViewBitmap.bitmapData) webViewBitmap.bitmapData.dispose();
webViewBitmap = null;
}
if (snapshotBitmapData) {
snapshotBitmapData.dispose();
snapshotBitmapData = null;
}
isSnapshotVisible = false;
}
//==================================================================================================
/**
* If enabled adds support for the back and search keys.
* Back key navigates back in web view history and search navigates forward.
* */
public var navigationSupport:Boolean;
/**
* If enabled adds a keyboard listener to the stage.
* This handles when the component does not have focus
* */
public var addKeyHandlerToStage:Boolean;
/**
* KeyCode to use when navigation support is enabled.
* Default is Keyboard.BACK
* */
public var backKeyCode:int = Keyboard.BACK;
/**
* KeyCode to use when navigation support is enabled.
* Default is Keyboard.SEARCH
* */
public var forwardKeyCode:int = Keyboard.SEARCH;
/**
* #copy mx.core.UIComponent#measure()
* */
override protected function measure():void {
super.measure();
measuredWidth=480;
measuredMinWidth=120;
measuredHeight=320;
measuredMinHeight=160;
}
/**
* #copy mx.core.UIComponent#updateDisplayList()
* */
override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void {
// NOTE: IF THE WEBVIEW IS NOT BEING SIZED CORRECTLY
// check if focusEnabled is true. If it is then the soft keyboard may not be dispatching the
// deactivate event because the webview has focus when it is dispatched. set to false
// position according to the container rather than the stage
var runtimeDPI:int = FlexGlobals.topLevelApplication.runtimeDPI;
var applicationDPI:int = FlexGlobals.topLevelApplication.applicationDPI;
var point:Point = localToGlobal(new Point());
var scaleFactor:Number = runtimeDPI / applicationDPI;
var scaledWidth:int = width * scaleFactor;
var scaledHeight:int = height * scaleFactor;
webView.viewPort = new Rectangle(point.x, point.y, scaledWidth, scaledHeight);
}
//--------------------------------------------------------------------------
//
// Event handlers
//
//--------------------------------------------------------------------------
/** When the stage property is available add it to the web view */
public function addedToStage(event:Event):void {
// adds support for keyboard events when not in focus
if (navigationSupport && addKeyHandlerToStage)
stage.addEventListener( KeyboardEvent.KEY_DOWN, keyDownHandler);
_visibleChanged = true;
invalidateProperties();
invalidateDisplayList();
}
/** When removed from the stage remove the web view */
protected function removedFromStage(event:Event):void {
hideWebView();
// removes support for keyboard events when not in focus
if (navigationSupport && addKeyHandlerToStage)
stage.removeEventListener( KeyboardEvent.KEY_DOWN, keyDownHandler );
}
/** Dispatches a focus in event when the web view gains focus. */
protected function focusInViewHandler(event:FocusEvent):void {
//webView.assignFocus();
if (hasEventListener(event.type))
dispatchEvent(event);
}
/** Dispatches a focus out event when the web view gains focus. */
protected function focusOutViewHandler(event:FocusEvent):void {
//webView.assignFocus(FocusDirection.TOP);
if (hasEventListener(event.type))
dispatchEvent(event);
}
/** Dispatches a focus in event when the web view gains focus. */
override protected function keyDownHandler(event:KeyboardEvent):void {
if (navigationSupport) {
if (event.keyCode == backKeyCode && webView.isHistoryBackEnabled ) {
webView.historyBack();
event.preventDefault();
}
if (navigationSupport && event.keyCode == forwardKeyCode && webView.isHistoryForwardEnabled ) {
webView.historyForward();
}
}
super.keyDownHandler(event);
}
/** Dispatched when the page or web content has been fully loaded */
protected function completeHandler(event:Event):void {
if(hasEventListener(event.type)) dispatchEvent(event); }
/** Dispatched when the location is about to change */
protected function locationChangingHandler(event:Event):void {
if(hasEventListener(event.type)) dispatchEvent(event); }
/** Dispatched when the location has changed */
protected function locationChangeHandler(event:Event):void {
if(hasEventListener(event.type)) dispatchEvent(event); }
/** Dispatched when an error occurs */
protected function errorHandler(event:ErrorEvent):void {
if(hasEventListener(event.type)) dispatchEvent(event); }
}}
I am new to Flex and needed some help setting up Web service client.
I have a web service of method:
public String printEchoStr(String str);
I am facing problem while creating action script to call this service. I am getting error:
1067: Implicit coercion of a value of type String to an unrelated type
generated.webservices:PrintEcho.
I am not sure if this is the correct way.
Thanks,
-H
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"
xmlns:srv="generated.webservices.*"
creationComplete="initFunc()">
<mx:Script>
<![CDATA[
import generated.webservices.EchoService;
import generated.webservices.PrintEchoStrResultEvent;
import generated.webservices.PrintEchoResultEvent;
import mx.rpc.events.ResultEvent;
import mx.rpc.events.FaultEvent;
import mx.controls.Alert;
import generated.webservices.PrintEchoStr;
import generated.webservices.PrintEcho;
public var myService:EchoService = new EchoService();
private function initFunc():void{
myService.addprintEchoStrEventListener(argPrintEchoStr);
/*--------------
1067: Implicit coercion of a value of type String to an unrelated type
generated.webservices:PrintEcho. at line below
----------------*/
myService.printEchoStr(textAreaPrintEchoStr.text);
myService.addEventListener(FaultEvent.FAULT,myServices_faultHandler);
}
public function argPrintEchoStr(event:PrintEchoStrResultEvent):void{
trace(event.result);
}
private function myServices_faultHandler(event:FaultEvent):void {
Alert.show(event.fault.faultString,"error with WebServices");
}
]]>
</mx:Script>
<mx:TextArea id ="textAreaPrintEchoStr"
x="81" y="125"/>
</mx:Application>
Generated source of EchoService.as
EchoService.as
package generated.webservices
{
import mx.rpc.AsyncToken;
import flash.events.EventDispatcher;
import mx.rpc.events.ResultEvent;
import mx.rpc.events.FaultEvent;
import flash.utils.ByteArray;
import mx.rpc.soap.types.*;
/**
* Dispatches when a call to the operation printEcho completes with success
* and returns some data
* #eventType PrintEchoResultEvent
*/
[Event(name="PrintEcho_result", type="generated.webservices.PrintEchoResultEvent")]
/**
* Dispatches when a call to the operation printEchoStr completes with success
* and returns some data
* #eventType PrintEchoStrResultEvent
*/
[Event(name="PrintEchoStr_result", type="generated.webservices.PrintEchoStrResultEvent")]
/**
* Dispatches when the operation that has been called fails. The fault event is common for all operations
* of the WSDL
* #eventType mx.rpc.events.FaultEvent
*/
[Event(name="fault", type="mx.rpc.events.FaultEvent")]
public class EchoService extends EventDispatcher implements IEchoService
{
private var _baseService:BaseEchoService;
/**
* Constructor for the facade; sets the destination and create a baseService instance
* #param The LCDS destination (if any) associated with the imported WSDL
*/
public function EchoService(destination:String=null,rootURL:String=null)
{
_baseService = new BaseEchoService(destination,rootURL);
}
//stub functions for the printEcho operation
/**
* #see IEchoService#printEcho()
*/
public function printEcho(printEcho:PrintEcho):AsyncToken
{
var _internal_token:AsyncToken = _baseService.printEcho(printEcho);
_internal_token.addEventListener("result",_printEcho_populate_results);
_internal_token.addEventListener("fault",throwFault);
return _internal_token;
}
/**
* #see IEchoService#printEcho_send()
*/
public function printEcho_send():AsyncToken
{
return printEcho(_printEcho_request.printEcho);
}
/**
* Internal representation of the request wrapper for the operation
* #private
*/
private var _printEcho_request:PrintEcho_request;
/**
* #see IEchoService#printEcho_request_var
*/
[Bindable]
public function get printEcho_request_var():PrintEcho_request
{
return _printEcho_request;
}
/**
* #private
*/
public function set printEcho_request_var(request:PrintEcho_request):void
{
_printEcho_request = request;
}
/**
* Internal variable to store the operation's lastResult
* #private
*/
private var _printEcho_lastResult:PrintEchoResponse;
[Bindable]
/**
* #see IEchoService#printEcho_lastResult
*/
public function get printEcho_lastResult():PrintEchoResponse
{
return _printEcho_lastResult;
}
/**
* #private
*/
public function set printEcho_lastResult(lastResult:PrintEchoResponse):void
{
_printEcho_lastResult = lastResult;
}
/**
* #see IEchoService#addprintEcho()
*/
public function addprintEchoEventListener(listener:Function):void
{
addEventListener(PrintEchoResultEvent.PrintEcho_RESULT,listener);
}
/**
* #private
*/
private function _printEcho_populate_results(event:ResultEvent):void
{
var e:PrintEchoResultEvent = new PrintEchoResultEvent();
e.result = event.result as PrintEchoResponse;
e.headers = event.headers;
printEcho_lastResult = e.result;
dispatchEvent(e);
}
//stub functions for the printEchoStr operation
/**
* #see IEchoService#printEchoStr()
*/
public function printEchoStr(printEchoStr:PrintEchoStr):AsyncToken
{
var _internal_token:AsyncToken = _baseService.printEchoStr(printEchoStr);
_internal_token.addEventListener("result",_printEchoStr_populate_results);
_internal_token.addEventListener("fault",throwFault);
return _internal_token;
}
/**
* #see IEchoService#printEchoStr_send()
*/
public function printEchoStr_send():AsyncToken
{
return printEchoStr(_printEchoStr_request.printEchoStr);
}
/**
* Internal representation of the request wrapper for the operation
* #private
*/
private var _printEchoStr_request:PrintEchoStr_request;
/**
* #see IEchoService#printEchoStr_request_var
*/
[Bindable]
public function get printEchoStr_request_var():PrintEchoStr_request
{
return _printEchoStr_request;
}
/**
* #private
*/
public function set printEchoStr_request_var(request:PrintEchoStr_request):void
{
_printEchoStr_request = request;
}
/**
* Internal variable to store the operation's lastResult
* #private
*/
private var _printEchoStr_lastResult:PrintEchoStrResponse;
[Bindable]
/**
* #see IEchoService#printEchoStr_lastResult
*/
public function get printEchoStr_lastResult():PrintEchoStrResponse
{
return _printEchoStr_lastResult;
}
/**
* #private
*/
public function set printEchoStr_lastResult(lastResult:PrintEchoStrResponse):void
{
_printEchoStr_lastResult = lastResult;
}
/**
* #see IEchoService#addprintEchoStr()
*/
public function addprintEchoStrEventListener(listener:Function):void
{
addEventListener(PrintEchoStrResultEvent.PrintEchoStr_RESULT,listener);
}
/**
* #private
*/
private function _printEchoStr_populate_results(event:ResultEvent):void
{
var e:PrintEchoStrResultEvent = new PrintEchoStrResultEvent();
e.result = event.result as PrintEchoStrResponse;
e.headers = event.headers;
printEchoStr_lastResult = e.result;
dispatchEvent(e);
}
//service-wide functions
/**
* #see IEchoService#getWebService()
*/
public function getWebService():BaseEchoService
{
return _baseService;
}
/**
* Set the event listener for the fault event which can be triggered by each of the operations defined by the facade
*/
public function addEchoServiceFaultEventListener(listener:Function):void
{
addEventListener("fault",listener);
}
/**
* Internal function to re-dispatch the fault event passed on by the base service implementation
* #private
*/
private function throwFault(event:FaultEvent):void
{
dispatchEvent(event);
}
}
}
myService.printEchoStr(textAreaPrintEchoStr.text);
printEchoStr method of EchoService class expects a PrintEcho object, but you're passing textAreaPrintEchoStr.text, which is a String
When attempting to use Joshua Bloch's "Builder Pattern" [Item 2 in Effective Java Second Edition] with reflection [object = constructors[index].newInstance(constructorParameterValues);] the following exception occurs:
java.lang.IllegalAccessException: Class info.soaj.core.util.SjUtilReflection can not access a member of class info.soaj.core.attribute.SjAttributesForThrowable with modifiers "private"
Note: This has been resolved. The accessible (private) constructor was being discarded and a non-accessible (override = false) was being attempted. Bottom Line: Programmer Error
An example Builder Class follows:
package info.soaj.core.attribute;
import info.soaj.core.attribute.internal.SjAttributesForStronglyTypedWrappers;
import info.soaj.core.internal.string.SjPopulatedClassName;
import info.soaj.core.internal.string.SjPopulatedMethodName;
import info.soaj.core.util.internal.SjUtilThrowable;
import java.io.Serializable;
/**
* <p>
* The "Builder" pattern as documented by Joshua Bloch ("Effective Java" -
* Second Edition) is utilized to handle the variable number of required and
* optional parameters.
* </p>
*
* <p style="font-family:Verdana; font-size:10px; font-style:italic"> Copyright
* (c) 2006 - 2008 by Global Technology Consulting Group, Inc. at <a
* href="http://gtcGroup.com">gtcGroup.com </a>. </p>
*
* #author MarvinToll#gtcGroup.com
* #since v. 1.0
*/
public class SjAttributesExample implements Serializable {
/** UID */
private static final long serialVersionUID = 1L;
/** The name of class throwing the exception. */
protected final SjPopulatedClassName classname;
/** The name of method throwing the exception. */
protected final SjPopulatedMethodName methodname;
/**
* Suppresses logging; default is <code>false</code>.
*/
protected final boolean suppressLoggingOnly;
/**
* Constructor - private
*
* #param builderThrowable
*/
private SjAttributesExample(final BuilderThrowable builderThrowable) {
this.classname = builderThrowable.classname;
this.methodname = builderThrowable.methodname;
this.suppressLoggingOnly = builderThrowable.suppressLoggingOnly;
}
/**
* This static member immutable class is used to implement the builder
* pattern.
*
* #author MarvinToll#gtcGroup.com
* #since v. 1.0
*/
public static class BuilderThrowable {
/** Class name. */
private static final String CLASS_NAME = BuilderThrowable.class
.getName();
// Required attributes.
/** The name of class throwing the exception. */
protected final SjPopulatedClassName classname;
/** The name of method throwing the exception. */
protected final SjPopulatedMethodName methodname;
// Optional attributes.
/** Prevents action from occurring. Default is false. */
protected boolean suppressLoggingOnly = false;
/**
* Constructor
*
* #param classname
* #param methodname
*/
public BuilderThrowable(final String classname, final String methodname) {
super();
final String Method_Name = "BuilderThrowable";
// What happens when handling an exception throws an exception?
try {
this.classname = new SjPopulatedClassName(classname,
new SjAttributesForStronglyTypedWrappers(CLASS_NAME,
Method_Name));
this.methodname = new SjPopulatedMethodName(methodname,
new SjAttributesForStronglyTypedWrappers(CLASS_NAME,
Method_Name));
} catch (final RuntimeException e) {
// Log the contextual details.
SjUtilThrowable.logExceptionOccuredWhileThrowingException(
CLASS_NAME, Method_Name, e);
throw e;
}
return;
}
/**
* This method sets a flag to suppress logging.
*
* #param isLoggingSuppressed
* #return BuilderThrowable
*/
public BuilderThrowable suppressLoggingOnly(
final boolean isLoggingSuppressed) {
this.suppressLoggingOnly = isLoggingSuppressed;
return this;
}
/**
* This method is used for instantiating this class.
*
* #return SjAttributesForThrowable
*/
#SuppressWarnings("synthetic-access")
public SjAttributesExample build() {
return new SjAttributesExample(this);
}
}
/**
* This method returns an attribute.
*
* #return String - Returns the <code>classname</code> attribute.
*/
public String getClassname() {
return this.classname.getString();
}
/**
* This method returns an attribute.
*
* #return String - Returns the <code>methodname</code> attribute.
*/
public String getMethodname() {
return this.methodname.getString();
}
/**
* This method returns an attribute.
*
* #return boolean - Returns the <code>suppressLoggingOnly</code> attribute.
*/
public boolean isLoggingSuppressed() {
return this.suppressLoggingOnly;
}
}
Note: This has been resolved. The accessible (private) constructor was being discarded and a non-accessible (override = false) was being attempted. Bottom Line: Programmer Error