package {
    import flash.display.Sprite;
    import flash.display.StageScaleMode;
    import flash.display.StageAlign;
    import flash.geom.Point;

    import flash.external.ExternalInterface;

    import flash.display.Bitmap;
    import flash.display.BitmapData;
    import flash.media.Camera;
    import flash.media.Video;
    import flash.utils.ByteArray;
    import mx.graphics.codec.JPEGEncoder;

    import flash.events.Event;
    import flash.events.HTTPStatusEvent;
    import flash.events.IOErrorEvent;
    import flash.events.SecurityErrorEvent;
    import flash.net.URLLoader;
    import flash.net.URLRequest;

    public class CameraMan extends Sprite {

        private var videoface:Video;
        private var cam:Camera;
        private var photo:BitmapData;
        private var sendto:String;
        private var movieSize:Point;

        public function CameraMan() {
            stage.scaleMode = StageScaleMode.NO_SCALE;
            stage.align = StageAlign.TOP_LEFT;

            sendto = stage.loaderInfo.parameters.sendto;
            movieSize = new Point(stage.loaderInfo.width, stage.loaderInfo.height);

            this.initCamera();

            if (ExternalInterface.available) {
                ExternalInterface.addCallback("takePhoto", takePhoto);
                ExternalInterface.addCallback("sendPhoto", sendPhoto);
            }
        }

        public function initCamera() : void {
            videoface = new Video(movieSize.x, movieSize.y);
            this.addChild(this.videoface);
            cam = Camera.getCamera();
            cam.setMode(width, height, 15);
            videoface.attachCamera(cam);
        }

        public function takePhoto() : void {
            // freeze image
            try {
                photo = new BitmapData(videoface.videoWidth, videoface.videoHeight, false);
                photo.draw(videoface);

                // Swap the video for the captured bitmap.
                var bitty:Bitmap = new Bitmap(photo);
                this.addChild(bitty);
                this.removeChild(videoface);
            } catch(err:Error) {
                trace(err.name + " " + err.message);
            }

            if (ExternalInterface.available) {
                ExternalInterface.call('cameraman._tookPhoto');
            }
        }

        public function sendPhoto() : void {
            try {
                // produce image file
                var peggy:JPEGEncoder = new JPEGEncoder(75.0);
                var image:ByteArray = peggy.encode(photo);

                // send image file to server
                var req:URLRequest = new URLRequest();
                req.url = this.sendto;
                req.method = "POST";
                req.contentType = peggy.contentType;
                req.data = image;

                var http:URLLoader = new URLLoader();
                http.addEventListener("complete", sentPhoto);
                http.addEventListener("ioError", sendingIOError);
                http.addEventListener("securityError", sendingSecurityError);
                http.addEventListener("httpStatus", sendingHttpStatus);
                http.load(req);
            } catch(err:Error) {
                trace(err.name + " " + err.message);
            }
        }

        public function sendingHttpStatus(event:HTTPStatusEvent) : void {
            trace("HTTPStatus: " + event.status + " " + event.target);
        }

        public function sendingIOError(event:IOErrorEvent) : void {
            trace("IOError: " + event.type + " " + event.text + " " + event.target + " " + event.target.bytesLoaded);
        }

        public function sendingSecurityError(event:SecurityErrorEvent) : void {
            trace("SecurityError: " + event.text + " " + event.target);
        }

        public function sentPhoto(event:Event) : void {
            var url:String = event.target.data;
            if (ExternalInterface.available)
                ExternalInterface.call('cameraman._sentPhoto', url);
        }

    }
}

Add existing CameraMan source (such as it is)


// Http request example.
// This example demonstrates:
//     - How to use Http request API

#include "Scripts/Utilities/Sample.as"

String message;
Text@ text;
HttpRequest@ httpRequest;

void Start()
{
    // Execute the common startup for samples
    SampleStart();

    // Create the user interface
    CreateUI();

    // Set the mouse mode to use in the sample
    SampleInitMouseMode(MM_FREE);

    // Subscribe to basic events such as update
    SubscribeToEvents();
}

void CreateUI()
{
    // Construct new Text object
    text = Text();

    // Set font and text color
    text.SetFont(cache.GetResource("Font", "Fonts/Anonymous Pro.ttf"), 15);
    text.color = Color(1.0f, 1.0f, 0.0f);

    // Align Text center-screen
    text.horizontalAlignment = HA_CENTER;
    text.verticalAlignment = VA_CENTER;

    // Add Text instance to the UI root element
    ui.root.AddChild(text);
}

void SubscribeToEvents()
{
    // Subscribe HandleUpdate() function for processing HTTP request
    SubscribeToEvent("Update", "HandleUpdate");
}

void HandleUpdate(StringHash eventType, VariantMap& eventData)
{
    // Create HTTP request
    if (httpRequest is null)
        httpRequest = network.MakeHttpRequest("http://httpbin.org/ip", "GET");
    else
    {
        // Initializing HTTP request
        if (httpRequest.state == HTTP_INITIALIZING)
            return;
        // An error has occured
        else if (httpRequest.state == HTTP_ERROR)
        {
            text.text = "An error has occured.";
            UnsubscribeFromEvent("Update");
        }
        // Get message data
        else
        {
            if (httpRequest.availableSize > 0)
                message += httpRequest.ReadLine();
            else
            {
                text.text = "Processing...";

                JSONFile@ json = JSONFile();
                json.FromString(message);

                JSONValue val = json.GetRoot().Get("origin");

                if (val.isNull)
                    text.text = "Invalid string.";
                else
                    text.text =  "Your IP is: " + val.GetString();

                UnsubscribeFromEvent("Update");
            }
        }
    }
}

// Create XML patch instructions for screen joystick layout specific to this sample app
String patchInstructions =
        "<patch>" +
        "    <add sel=\"/element/element[./attribute[@name='Name' and @value='Hat0']]\">" +
        "        <attribute name=\"Is Visible\" value=\"false\" />" +
        "    </add>" +
        "</patch>";

Add AngelScript Http Request demo sample.


package dolly {

import dolly.core.dolly_internal;
import dolly.data.CompositeCopyableClass;

import mx.collections.ArrayCollection;
import mx.collections.ArrayList;

import org.as3commons.reflect.Field;
import org.as3commons.reflect.Type;
import org.flexunit.asserts.assertEquals;
import org.flexunit.asserts.assertNotNull;

use namespace dolly_internal;

public class CopyingOfCompositeCopyableClassTest {

	private var compositeCopyableClass:CompositeCopyableClass;
	private var compositeCopyableClassType:Type;

	[Before]
	public function before():void {
		compositeCopyableClass = new CompositeCopyableClass();
		compositeCopyableClass.array = [1, 2, 3, 4, 5];
		compositeCopyableClass.arrayList = new ArrayList([1, 2, 3, 4, 5]);
		compositeCopyableClass.arrayCollection = new ArrayCollection([1, 2, 3, 4, 5]);

		compositeCopyableClassType = Type.forInstance(compositeCopyableClass);
	}

	[After]
	public function after():void {
		compositeCopyableClass = null;
		compositeCopyableClassType = null;
	}

	[Test]
	public function findingAllWritableFieldsForType():void {
		const writableFields:Vector.<Field> = Copier.findCopyableFieldsForType(compositeCopyableClassType);
		assertNotNull(writableFields);
		assertEquals(4, writableFields.length);
	}
}
}

Add new test class: CopyingOfCompositeCopyableClassTest.


	.file	"crt.as"
	.text
	.global	_start

_start:
	call	$main
	movl    %eax, %edi
	call	$exit

add amd64-linux crt

[crt] add amd64-linux crt


			import flash.events.MouseEvent;
			import com.example.programmingas3.playlist.PlayList;
			import com.example.programmingas3.playlist.Song;
			import com.example.programmingas3.playlist.SortProperty;

			// constants for the different "states" of the song form
			private static const ADD_SONG:uint = 1;
			private static const SONG_DETAIL:uint = 2;

			private var playList:PlayList = new PlayList();

			private function initApp():void
			{
				// set the initial state of the song form, for adding a new song
				setFormState(ADD_SONG);

				// prepopulate the list with a few songs
				playList.addSong(new Song("Nessun Dorma", "Luciano Pavarotti", 1990, "nessundorma.mp3", ["90's", "Opera"]));
				playList.addSong(new Song("Come Undone", "Duran Duran", 1993, "comeundone.mp3", ["90's", "Pop"]));
				playList.addSong(new Song("Think of Me", "Sarah Brightman", 1987, "thinkofme.mp3", ["Showtunes"]));
				playList.addSong(new Song("Unbelievable", "EMF", 1991, "unbelievable.mp3", ["90's", "Pop"]));

				songList.dataProvider = playList.songList;
			}

			private function sortList(sortField:SortProperty):void
			{
				// Make all the sort type buttons enabled.
				// The active one will be grayed-out below
				sortByTitle.selected = false;
				sortByArtist.selected = false;
				sortByYear.selected = false;

				switch (sortField)
				{
					case SortProperty.TITLE:
						sortByTitle.selected = true;
						break;
					case SortProperty.ARTIST:
						sortByArtist.selected = true;
						break;
					case SortProperty.YEAR:
						sortByYear.selected = true;
						break;
				}

				playList.sortList(sortField);

				refreshList();
			}

			private function refreshList():void
			{
				// remember which song was selected
				var selectedSong:Song = Song(songList.selectedItem);

				// re-assign the song list as the dataprovider to get the newly sorted list
				// and force the List control to refresh itself
				songList.dataProvider = playList.songList;

				// reset the song selection
				if (selectedSong != null)
				{
					songList.selectedItem = selectedSong;
				}
			}

			private function songSelectionChange():void
			{
				if (songList.selectedIndex != -1)
				{
					setFormState(SONG_DETAIL);
				}
				else
				{
					setFormState(ADD_SONG);
				}
			}

			private function addNewSong():void
			{
				// gather the values from the form and add the new song
				var title:String = newSongTitle.text;
				var artist:String = newSongArtist.text;
				var year:uint = newSongYear.value;
				var filename:String = newSongFilename.text;
				var genres:Array = newSongGenres.selectedItems;

				playList.addSong(new Song(title, artist, year, filename, genres));

				refreshList();

				// clear out the "add song" form fields
				setFormState(ADD_SONG);
			}

			private function songListLabel(item:Object):String
			{
				return item.toString();
			}

			private function setFormState(state:uint):void
			{
				// set the form title and control state
				switch (state)
				{
					case ADD_SONG:
						formTitle.text = "Add New Song";
						// show the submit button
						submitSongData.visible = true;
						showAddControlsBtn.visible = false;
						// clear the form fields
						newSongTitle.text = "";
						newSongArtist.text = "";
						newSongYear.value = (new Date()).fullYear;
						newSongFilename.text = "";
						newSongGenres.selectedIndex = -1;
						// deselect the currently selected song (if any)
						songList.selectedIndex = -1;
						break;

					case SONG_DETAIL:
						formTitle.text = "Song Details";
						// populate the form with the selected item's data
						var selectedSong:Song = Song(songList.selectedItem);
						newSongTitle.text = selectedSong.title;
						newSongArtist.text = selectedSong.artist;
						newSongYear.value = selectedSong.year;
						newSongFilename.text = selectedSong.filename;
						newSongGenres.selectedItems = selectedSong.genres;
						// hide the submit button
						submitSongData.visible = false;
						showAddControlsBtn.visible = true;
						break;
				}
			}

Add AS3 example.

Add AS3 example.


Add AS3 example.

Add AS3 example.

--HG--
branch : trunk


///////////////////////////////////////////////////////////////////////////
// Copyright (c) 2011 Esri. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
///////////////////////////////////////////////////////////////////////////
package com.esri.viewer.utils
{

import mx.core.FlexGlobals;

import spark.utils.LabelUtil;

public final class LabelUtil
{
    public static function findLongestItemLabel(items:Array,
                                                labelField:String = null,
                                                labelFunction:Function = null):String
    {
        var currentItemWidth:Number;
        var longestItemLabel:String = "";
        var longestItemLabelWidth:Number = 0;
        var currentItemLabel:String;

        for each (var item:Object in items)
        {
            currentItemLabel =
                spark.utils.LabelUtil.itemToLabel(item, labelField, labelFunction);

            currentItemWidth =
                FlexGlobals.topLevelApplication.measureText(currentItemLabel).width;

            if (currentItemWidth > longestItemLabelWidth)
            {
                longestItemLabelWidth = currentItemWidth;
                longestItemLabel = currentItemLabel;
            }
        }

        return longestItemLabel;
    }
}
}

Add LabelUtil.

Add LabelUtil.


package dolly {
import dolly.core.dolly_internal;
import dolly.data.PropertyLevelCopyableSubclass;

import org.as3commons.reflect.Field;
import org.as3commons.reflect.Type;
import org.flexunit.asserts.assertEquals;
import org.flexunit.asserts.assertFalse;
import org.flexunit.asserts.assertNotNull;

use namespace dolly_internal;

public class CopyingOfPropertyLevelCopyableSubclassTest {

	private var propertyLevelCopyableSubclass:PropertyLevelCopyableSubclass;
	private var propertyLevelCopyableSubclassType:Type;

	[Before]
	public function before():void {
		propertyLevelCopyableSubclass = new PropertyLevelCopyableSubclass();
		propertyLevelCopyableSubclass.property1 = "property1 value";
		propertyLevelCopyableSubclass.property2 = "property2 value";
		propertyLevelCopyableSubclass.property3 = "property3 value";
		propertyLevelCopyableSubclass.property4 = "property4 value";
		propertyLevelCopyableSubclass.writableField1 = "writableField1 value";
		propertyLevelCopyableSubclass.writableField2 = "writableField2 value";

		propertyLevelCopyableSubclassType = Type.forInstance(propertyLevelCopyableSubclass);
	}

	[After]
	public function after():void {
		propertyLevelCopyableSubclass = null;
		propertyLevelCopyableSubclassType = null;
	}

	[Test]
	public function findingAllCopyableFieldsForType():void {
		const copyableFields:Vector.<Field> = Copier.findCopyableFieldsForType(propertyLevelCopyableSubclassType);
		assertNotNull(copyableFields);
		assertEquals(4, copyableFields.length);
		assertNotNull(copyableFields[0]);
		assertNotNull(copyableFields[1]);
		assertNotNull(copyableFields[2]);
		assertNotNull(copyableFields[3]);
	}

	[Test]
	public function copyingByCopier():void {
		const copyInstance:PropertyLevelCopyableSubclass = Copier.copy(propertyLevelCopyableSubclass);
		assertNotNull(copyInstance);
		assertNotNull(copyInstance.property1);
		assertEquals(copyInstance.property1, propertyLevelCopyableSubclass.property1);
		assertNotNull(copyInstance.property2);
		assertFalse(copyInstance.property2 == propertyLevelCopyableSubclass.property2);
		assertNotNull(copyInstance.property3);
		assertEquals(copyInstance.property3, propertyLevelCopyableSubclass.property3);
		assertNotNull(copyInstance.property4);
		assertFalse(copyInstance.property4 == propertyLevelCopyableSubclass.property4);
		assertNotNull(copyInstance.writableField1);
		assertEquals(copyInstance.writableField1, propertyLevelCopyableSubclass.writableField1);
		assertNotNull(copyInstance.writableField2);
		assertEquals(copyInstance.writableField2, propertyLevelCopyableSubclass.writableField2);
	}

	[Test]
	public function copyingByCopyFunction():void {
		const copyInstance:PropertyLevelCopyableSubclass = copy(propertyLevelCopyableSubclass);
		assertNotNull(copyInstance);
		assertNotNull(copyInstance.property1);
		assertEquals(copyInstance.property1, propertyLevelCopyableSubclass.property1);
		assertNotNull(copyInstance.property2);
		assertFalse(copyInstance.property2 == propertyLevelCopyableSubclass.property2);
		assertNotNull(copyInstance.property3);
		assertEquals(copyInstance.property3, propertyLevelCopyableSubclass.property3);
		assertNotNull(copyInstance.property4);
		assertFalse(copyInstance.property4 == propertyLevelCopyableSubclass.property4);
		assertNotNull(copyInstance.writableField1);
		assertEquals(copyInstance.writableField1, propertyLevelCopyableSubclass.writableField1);
		assertNotNull(copyInstance.writableField2);
		assertEquals(copyInstance.writableField2, propertyLevelCopyableSubclass.writableField2);
	}
}
}

Create new test class: CopyingOfPropertyLevelCopyableSubclassTest.


package dolly.utils {
import flash.net.registerClassAlias;
import flash.utils.getQualifiedClassName;

public class ClassUtil {

	public static function getFullClassName(clazz:Class):String {
		return getQualifiedClassName(clazz).replace("::", ".");
	}

	public static function registerAliasFor(clazz:Class):void {
		registerClassAlias(
				getFullClassName(clazz),
				clazz
		);
	}
}
}

Create new utility class: ClassUtil.

Create new utility class: ClassUtil.


Add AS3 example.

Add AS3 example.


/*
 * Copyright 2008 Adobe Systems Inc., 2008 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * Contributor(s):
 *   Zwetan Kjukov <zwetan@gmail.com>.
 */

package
{
    import library.ASTUce.Runner;

    import com.google.analytics.AllTests;
    import flash.display.Sprite;

    public class TestRunner extends Sprite
    {
        public function TestRunner()
        {
            Runner.main( com.google.analytics.AllTests.suite( ) );
        }

    }
}

rename to TestRunner

rename to TestRunner


package dolly {

import dolly.core.dolly_internal;
import dolly.data.CopyableCloneableClass;

import org.as3commons.reflect.Field;
import org.as3commons.reflect.Type;
import org.flexunit.asserts.assertEquals;
import org.flexunit.asserts.assertNotNull;

use namespace dolly_internal;

public class CopyingOfCopyableCloneableClassTest {

	private var copyableCloneableClass:CopyableCloneableClass;
	private var copyableCloneableClassType:Type;

	[Before]
	public function before():void {
		copyableCloneableClass = new CopyableCloneableClass();
		copyableCloneableClass.property1 = "property1 value";
		copyableCloneableClass.writableField1 = "writableField1 value";
		copyableCloneableClassType = Type.forInstance(copyableCloneableClass);
	}

	[After]
	public function after():void {
		copyableCloneableClass = null;
		copyableCloneableClassType = null;
	}

	[Test]
	public function findingAllWritableFieldsForType():void {
		const writableFields:Vector.<Field> = Copier.findCopyableFieldsForType(copyableCloneableClassType);
		assertNotNull(writableFields);
		assertEquals(2, writableFields.length);
	}

	[Test]
	public function cloningByCloner():void {
		const clone:CopyableCloneableClass = Copier.copy(copyableCloneableClass);

		assertNotNull(clone);
		assertNotNull(clone.property1);
		assertEquals(clone.property1, copyableCloneableClass.property1);
		assertNotNull(clone.writableField1);
		assertEquals(clone.writableField1, copyableCloneableClass.writableField1);
	}

	[Test]
	public function cloningByCloneFunction():void {
		const cloneInstance:CopyableCloneableClass = copy(copyableCloneableClass);

		assertNotNull(cloneInstance);
		assertNotNull(cloneInstance.property1);
		assertEquals(cloneInstance.property1, copyableCloneableClass.property1);
		assertNotNull(cloneInstance.writableField1);
		assertEquals(cloneInstance.writableField1, copyableCloneableClass.writableField1);
	}
}
}

Create new test class CopyingOfCopyableCloneableClassTest for testing of creation copies for CopyableCloneableClass.


package dolly.data {

public class PropertyLevelCopyableSubclass extends PropertyLevelCopyableClass {

	[Copyable]
	public static var staticProperty3:String = "Value of second-level static property 3.";

	public static var staticProperty4:String = "Value of second-level static property 4.";

	[Copyable]
	private var _writableField2:String = "Value of second-level writable field.";

	[Copyable]
	public var property3:String = "Value of second-level public property 3.";

	public var property4:String = "Value of second-level public property 4.";

	public function PropertyLevelCopyableSubclass() {
	}

	[Copyable]
	public function get writableField2():String {
		return _writableField2;
	}

	public function set writableField2(value:String):void {
		_writableField2 = value;
	}

	[Copyable]
	public function get readOnlyField2():String {
		return "Value of second-level read-only field.";
	}
}
}

Add new test data subclass: PropertyLevelCopyableSubclass.


////////////////////////////////////////////////////////////////////////////////
//
//  Licensed to the Apache Software Foundation (ASF) under one or more
//  contributor license agreements.  See the NOTICE file distributed with
//  this work for additional information regarding copyright ownership.
//  The ASF licenses this file to You under the Apache License, Version 2.0
//  (the "License"); you may not use this file except in compliance with
//  the License.  You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
package org.apache.flex.html.staticControls.beads.controllers
{
	import flash.events.IEventDispatcher;
    import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.utils.clearInterval;
	import flash.utils.clearTimeout;
    import flash.utils.setInterval;
    import flash.utils.setTimeout;

	import org.apache.flex.core.IBead;
	import org.apache.flex.core.IStrand;

    public class ButtonAutoRepeatController implements IBead
	{
		public function ButtonAutoRepeatController()
		{
		}

        private var _strand:IStrand;

        public function get strand():IStrand
        {
            return _strand;
        }

        public function set strand(value:IStrand):void
        {
            _strand = value;
            IEventDispatcher(value).addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler);
        }

        public var delay:int = 250;
        public var interval:int = 100;

        private var timeout:uint;
        private var repeater:uint;

        private function mouseDownHandler(event:MouseEvent):void
        {
            event.target.addEventListener(MouseEvent.MOUSE_OUT, mouseOutHandler);
            event.target.addEventListener(MouseEvent.MOUSE_UP, mouseUpHandler);
            setTimeout(sendFirstRepeat, delay);
        }

        private function mouseOutHandler(event:MouseEvent):void
        {
            event.target.removeEventListener(MouseEvent.MOUSE_OUT, mouseOutHandler);
            event.target.removeEventListener(MouseEvent.MOUSE_UP, mouseUpHandler);
            if (repeater > 0)
                clearInterval(repeater);
            repeater = 0;
            if (timeout > 0)
                clearTimeout(timeout);
            timeout = 0;
        }

        private function mouseUpHandler(event:MouseEvent):void
        {
            event.target.removeEventListener(MouseEvent.MOUSE_OUT, mouseOutHandler);
            event.target.removeEventListener(MouseEvent.MOUSE_UP, mouseUpHandler);
            if (repeater > 0)
                clearInterval(repeater);
            repeater = 0;
            if (timeout > 0)
                clearTimeout(timeout);
            timeout = 0;
        }

        private function sendFirstRepeat():void
        {
            clearTimeout(timeout);
            timeout = 0;
            repeater = setInterval(sendRepeats, interval);
            IEventDispatcher(_strand).dispatchEvent(new Event("buttonRepeat"));
        }

        private function sendRepeats():void
        {
            IEventDispatcher(_strand).dispatchEvent(new Event("buttonRepeat"));
        }
	}
}

Add autorepeat for buttons

Add autorepeat for buttons

git-svn-id: 00225d326fbeb9978ee2ea3564602c0fe18eb5d2@1441561 13f79535-47bb-0310-9956-ffa450edef68


package dolly {
public class CopierTest {

	[Before]
	public function before():void {
	}

	[After]
	public function after():void {
	}

	[Test]
	public function testSmth():void {
	}
}
}

Add empty CopierTest class.

Add empty CopierTest class.


import avmplus.System;
import avmplus.FileSystem;
import C.stdlib.*;

const USAGE:String = <![CDATA[usage: %cmd options file

This script generate SWF chunks of a font, by calling flex-fontkit.jar of Flex SDK.

Supported font file types are TrueType, OpenType, TrueType Collection and Datafork TrueType.

OPTIONS:
   -h	 	   Show this message
   -b	 	   Embeds the fonts bold face.
   -i	 	   Embeds the fonts italic face.
   -u          Ouput uncompressed SWF
   -a alias    Sets the fonts alias. The default is the fonts family name.
   -c length   Sets the number of chars in each SWF chunks. The default is 100.

Require RedTamarin %minversion, available here: http://code.google.com/p/redtamarin/
Require FLEX_HOME environment variable, defining location of Flex SDK folder.]]>;

const INVALID_FILE:uint = 2;
const ARG_ERROR:uint = 10;
const INVALID_API:uint = 20;
const MIN_VERSION:Array = [0, 3, 0];//0.3.0

function usage()
{
	trace(USAGE.replace("%cmd", System.programFilename).replace("%minversion", MIN_VERSION.join(".")));
}

/*
Check RedTamarin version
*/
var redTamarinVersion:Array = System.getRedtamarinVersion().split(".");
if(parseInt(redTamarinVersion[2]) < MIN_VERSION[2]
	&& parseInt(redTamarinVersion[1]) < MIN_VERSION[1]
	&& parseInt(redTamarinVersion[0]) < MIN_VERSION[0])
{
	trace("Require RedTamarin shell equal or greated than %minversion. Current version is %currentversion\n".replace("%minversion", MIN_VERSION.join(".")).replace("%currentversion", redTamarinVersion.join(".")));
	usage();
	System.exit(INVALID_API);
}
/*
Check FLEX_HOME env var
*/
if(getenv("FLEX_HOME") == "" || getenv("FLEX_HOME") == null)
{
	trace("Require environment variable FLEX_HOME. To define it, use this command:\n\tset FLEX_HOME=\"" + FileSystem.normalizePath("path/to/flex") + "\"\n");
	usage();
	System.exit(INVALID_API);
}
/*
TODO check if java and jar of fontSWF are available
*/

var javaCmd:String = "java -Dsun.io.useCanonCaches=false -Xms32m -Xmx512m"
var fontSWFJarCmd:String = " -jar \"%flexhome/lib/flex-fontkit.jar\" -3".replace("%flexhome", getenv("FLEX_HOME"));
var chunkLength:uint = 100;
var alias:String = null;
var bold:Boolean = false, italic:Boolean = false;
var file:String = null;

/*
Parse args
*/
var argv:Array = System.argv;//C argv[0] is not included (start at 0 without path of current exec)
var argc:uint = argv.length;
for(var i:uint = 0; i < argc; i++)
{
	var arg:String = argv[i];
	//Help
	if(arg == "-h" || arg == "-help" || arg == "--help" || arg == "-?")
	{
		usage();
		System.exit();
	}
	//Bold flag
	else if(arg == "-b" || arg == "-bold" || arg == "--bold")
	{
		bold = true;
	}
	//Italic flag
	else if(arg == "-i" || arg == "-italic" || arg == "--italic")
	{
		bold = true;
	}
	//Alias
	else if(arg == "-a" || arg == "-alias" || arg == "--alias")
	{
		if(i < argc - 1)
		{
			alias = argv[++i];
		}
		else
		{
			trace("%arg requires an argument\n".replace("%arg", arg));
			usage();
			System.exit(ARG_ERROR);
		}
	}
	//
	else if(arg == "-c" || arg == "-chunk" || arg == "--chunk")
	{
		if(i < argc - 1)
		{
			chunkLength = argv[++i];
		}
		else
		{
			trace("%arg requires an argument\n".replace("%arg", arg));
			usage();
			System.exit(ARG_ERROR);
		}
	}
	//Uncompressed flag
	/*
	http://opensource.adobe.com/svn/opensource/flex/sdk/trunk/modules/swfutils/src/java/flash/swf/MovieEncoder.java -> http://opensource.adobe.com/svn/opensource/flex/sdk/trunk/modules/swfutils/src/java/flash/swf/Header.java
	http://www.rgagnon.com/javadetails/java-0150.html
	*/
	else if(arg == "-u" || arg == "-uncompressed" || arg == "--uncompressed")
	{
		javaCmd += " -Dflex.swf.uncompressed=\"true\"";
	}
	//No more optional arguments, next is file
	else if(arg == "--")
	{
		if(i == argc - 2)
		{
			file = argv[++i];
		}
		else if(i >= argc - 1)
		{
			trace("file is required.\n");
			usage();
			System.exit(ARG_ERROR);
		}
		else
		{
			trace("Can't handle more than one file at the same time.\n");
			usage();
			System.exit(ARG_ERROR);
		}
	}
	//Other arguments
	else if(arg.charAt() == "-")
	{
		trace("Invalid option: $arg\n".replace("%arg", arg));
		usage();
		System.exit(ARG_ERROR);
	}
	//Assumed as file (only one)
	else
	{
		//Is last argument
		if(i == argc - 1)
		{
			file = argv[i];
		}
		else
		{
			trace("Can't handle more than one file at the same time.\n");
			usage();
			System.exit(ARG_ERROR);
		}
	}
}

/*
File argument not found or file not exist
*/
if(file == null || file == "" || !FileSystem.isRegularFile(file))
{
	trace("Invalid file.\n");
	usage();
	System.exit(INVALID_FILE);
}

/*
Alias is set
*/
if(alias != null && alias != "")
	fontSWFJarCmd += " -a " + alias;

/*
Bold
*/
if(bold)
	fontSWFJarCmd += " -b";

/*
Italic
*/
if(italic)
	fontSWFJarCmd += " -i";

var max:uint = 0xFFFF;
var i:uint = 0;
while(last < max)
{
	var first:uint = i++ * chunkLength;
	last = first + chunkLength - 1;
	var range:String = "U+" + ("000" + first.toString(16).toUpperCase()).substr(-4, 4) + "-U+" + ("000" + last.toString(16).toUpperCase()).substr(-4, 4);
	var cmd:String = javaCmd + fontSWFJarCmd + "-u \"%range\" -o \"%range\" \"%file\"".replace("%range", range).replace("%file", file);
	trace(System.popen(cmd));
}

Add fsdgen Redtamarin script

Add fsdgen Redtamarin script


/*****************************************************
*
*  Copyright 2009 Adobe Systems Incorporated.  All Rights Reserved.
*
*****************************************************
*  The contents of this file are subject to the Mozilla Public License
*  Version 1.1 (the "License"); you may not use this file except in
*  compliance with the License. You may obtain a copy of the License at
*  http://www.mozilla.org/MPL/
*
*  Software distributed under the License is distributed on an "AS IS"
*  basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
*  License for the specific language governing rights and limitations
*  under the License.
*
*
*  The Initial Developer of the Original Code is Adobe Systems Incorporated.
*  Portions created by Adobe Systems Incorporated are Copyright (C) 2009 Adobe Systems
*  Incorporated. All Rights Reserved.
*
*****************************************************/
package com.castlabs.dash.utils
{
	//[ExcludeClass]

	/**
	 * @private
	 *
	 * The NetStreamCodes class provides static constants for event types
	 * that a NetStream dispatches as NetStatusEvents.
	 *
A NetClient uses some of these codes to register handlers for
	 * callbacks.

	 * @see flash.events.NetStatusEvent
	 * @see flash.net.NetStream
	 *
	 *  @langversion 3.0
	 *  @playerversion Flash 10
	 *  @playerversion AIR 1.5
	 *  @productversion OSMF 1.0
	 */
	public final class NetStreamCodes
	{
		/**
		 * "status"
		 * Data is not being received quickly enough to fill the buffer.
		 * Data flow will be interrupted until the buffer refills,
		 * at which time a NetStream.Buffer.Full message will be sent and the stream will begin playing again.
		 *
		 *  @langversion 3.0
		 *  @playerversion Flash 10
		 *  @playerversion AIR 1.5
		 *  @productversion OSMF 1.0
		 */
		public static const NETSTREAM_BUFFER_EMPTY:String	  		= "NetStream.Buffer.Empty";

		/**
		 * "status"
		 * The buffer is full and the stream will begin playing.
		 *
		 *  @langversion 3.0
		 *  @playerversion Flash 10
		 *  @playerversion AIR 1.5
		 *  @productversion OSMF 1.0
		 */
		public static const NETSTREAM_BUFFER_FULL:String 			= "NetStream.Buffer.Full";

		/**
		 * "status"
		 * Data has finished streaming, and the remaining buffer will be emptied.
		 *
		 *  @langversion 3.0
		 *  @playerversion Flash 10
		 *  @playerversion AIR 1.5
		 *  @productversion OSMF 1.0
		 */
		public static const NETSTREAM_BUFFER_FLUSH:String 			= "NetStream.Buffer.Flush";

		CONFIG::FLASH_10_1
		{
		/**
		 * This code is sent by the NetStream when the DRM subsystem needs to be
		 * updated.
		 *
		 *  @langversion 3.0
		 *  @playerversion Flash 10
		 *  @playerversion AIR 1.5
		 *  @productversion OSMF 1.0
		 */
		public static const NETSTREAM_DRM_UPDATE:String 			= "DRM.UpdateNeeded";
		}

		/**
		 * "error"
		 * Flash Media Server only. An error has occurred for a reason other
		 *  than those listed in other event codes.
		 *
		 *  @langversion 3.0
		 *  @playerversion Flash 10
		 *  @playerversion AIR 1.5
		 *  @productversion OSMF 1.0
		 */
		public static const NETSTREAM_FAILED:String 				= "NetStream.Failed";

		/**
		 * "status"
		 * 	Playback has started.
		 *
		 *  @langversion 3.0
		 *  @playerversion Flash 10
		 *  @playerversion AIR 1.5
		 *  @productversion OSMF 1.0
		 */
		public static const NETSTREAM_PLAY_START:String				= "NetStream.Play.Start";

		/**
		 * "status"
		 * 	Playback has stopped.
		 *
		 *  @langversion 3.0
		 *  @playerversion Flash 10
		 *  @playerversion AIR 1.5
		 *  @productversion OSMF 1.0
		 */
		public static const NETSTREAM_PLAY_STOP:String				= "NetStream.Play.Stop";

		/** "error"	An error has occurred in playback for a reason
		 * other than those listed elsewhere in this table, such as the subscriber not having read access.
		 *
		 *  @langversion 3.0
		 *  @playerversion Flash 10
		 *  @playerversion AIR 1.5
		 *  @productversion OSMF 1.0
		 */
		public static const NETSTREAM_PLAY_FAILED:String			= "NetStream.Play.Failed";

		/**
		 * "error"
		 * The FLV passed to the play() method can't be found.
		 *
		 *  @langversion 3.0
		 *  @playerversion Flash 10
		 *  @playerversion AIR 1.5
		 *  @productversion OSMF 1.0
		 */
		public static const NETSTREAM_PLAY_STREAMNOTFOUND:String	= "NetStream.Play.StreamNotFound";

		/**
		 * "status"
		 * Caused by a play list reset.
		 *
		 *  @langversion 3.0
		 *  @playerversion Flash 10
		 *  @playerversion AIR 1.5
		 *  @productversion OSMF 1.0
		 */
		public static const NETSTREAM_PLAY_RESET:String				= "NetStream.Play.Reset";

		/**
		 * "warning"
		 * Flash Media Server only. The client does not have sufficient bandwidth to play the data at normal speed.
		 *
		 *  @langversion 3.0
		 *  @playerversion Flash 10
		 *  @playerversion AIR 1.5
		 *  @productversion OSMF 1.0
		 */
		public static const NETSTREAM_PLAY_INSUFFICIENTBW:String	= "NetStream.Play.InsufficientBW";

		/** "error"
		 * The application detects an invalid file structure and will not try to play this type of file.
		 *  For AIR and for Flash Player 9.0.115.0 and later.
		 *
		 *  @langversion 3.0
		 *  @playerversion Flash 10
		 *  @playerversion AIR 1.5
		 *  @productversion OSMF 1.0
		 */
		public static const NETSTREAM_PLAY_FILESTRUCTUREINVALID:String= "NetStream.Play.FileStructureInvalid";

		 /** "error"
		 * The application does not detect any supported tracks (video, audio or data) and
		 * will not try to play the file. For AIR and for Flash Player 9.0.115.0 and later.
		 *
		 *  @langversion 3.0
		 *  @playerversion Flash 10
		 *  @playerversion AIR 1.5
		 *  @productversion OSMF 1.0
		 */
		public static const NETSTREAM_PLAY_NOSUPPORTEDTRACKFOUND:String= "NetStream.Play.NoSupportedTrackFound";

		/**
		 * "status"
		 * Flash Media Server 3.5 and later only. The server received the command to transition to another stream
		 * as a result of bitrate stream switching. This code indicates a success status event for the NETSTREAM_play2()
		 * call to initiate a stream switch. If the switch does not succeed, the server sends a NETSTREAM_PLAY.Failed event instead.
		 * When the stream switch occurs, an onPlayStatus event with a code of "NetStream.Play.TransitionComplete" is dispatched.
		 * For Flash Player 10 and later.
		 *
		 *  @langversion 3.0
		 *  @playerversion Flash 10
		 *  @playerversion AIR 1.5
		 *  @productversion OSMF 1.0
		 */
		public static const NETSTREAM_PLAY_TRANSITION:String		= "NetStream.Play.Transition";

		/**
		 * "status"
		 * The stream is paused.
		 *
		 *  @langversion 3.0
		 *  @playerversion Flash 10
		 *  @playerversion AIR 1.5
		 *  @productversion OSMF 1.0
		 */
		public static const NETSTREAM_PAUSE_NOTIFY:String			= "NetStream.Pause.Notify";

		/**
		 * "status"
		 * The initial publish to a stream is sent to all subscribers.
		 *
		 *  @langversion 3.0
		 *  @playerversion Flash 10
		 *  @playerversion AIR 1.5
		 *  @productversion OSMF 1.0
		 */
		public static const NETSTREAM_PLAY_PUBLISH_NOTIFY:String	= "NetStream.Play.PublishNotify";

		/**
		 * "status"
		 * An unpublish from a stream is sent to all subscribers.
		 *
		 *  @langversion 3.0
		 *  @playerversion Flash 10
		 *  @playerversion AIR 1.5
		 *  @productversion OSMF 1.0
		 */
		public static const NETSTREAM_PLAY_UNPUBLISH_NOTIFY:String	= "NetStream.Play.UnpublishNotify";

		/**
		 * "status"
		 * The stream is resumed.
		 *
		 *  @langversion 3.0
		 *  @playerversion Flash 10
		 *  @playerversion AIR 1.5
		 *  @productversion OSMF 1.0
		 */
		public static const NETSTREAM_UNPAUSE_NOTIFY:String			= "NetStream.Unpause.Notify";

		/**
		 * "error"
		 * The seek fails, which happens if the stream is not seekable.
		 *
		 *  @langversion 3.0
		 *  @playerversion Flash 10
		 *  @playerversion AIR 1.5
		 *  @productversion OSMF 1.0
		 */
		public static const NETSTREAM_SEEK_FAILED:String			= "NetStream.Seek.Failed";

		/**
		 * "error"
		 * For video downloaded with progressive download,
		 * the user has tried to seek or play past the end of the video data that has downloaded thus far,
		 *  or past the end of the video once the entire file has downloaded.
		 * The message.details property contains a time code that indicates the last valid position to which the user can seek.
		 *
		 *  @langversion 3.0
		 *  @playerversion Flash 10
		 *  @playerversion AIR 1.5
		 *  @productversion OSMF 1.0
		 */
		public static const NETSTREAM_SEEK_INVALIDTIME:String		= "NetStream.Seek.InvalidTime";

		/**
		 * "status"
		 * The seek operation is complete.
		 *
		 *  @langversion 3.0
		 *  @playerversion Flash 10
		 *  @playerversion AIR 1.5
		 *  @productversion OSMF 1.0
		 */
		public static const NETSTREAM_SEEK_NOTIFY:String			= "NetStream.Seek.Notify";

		//onPlayStatus

		/**
		 * "status"
		 * Playback has completed. Fires only for streaming connections.
		 *
		 *  @langversion 3.0
		 *  @playerversion Flash 10
		 *  @playerversion AIR 1.5
		 *  @productversion OSMF 1.0
		 */
		public static const NETSTREAM_PLAY_COMPLETE:String			= "NetStream.Play.Complete";

		/**
		 * "status"
		 * The subscriber is switching to a new stream as a result of stream bit-rate switching. Fires only for streaming connections.
		 *
		 *  @langversion 3.0
		 *  @playerversion Flash 10
		 *  @playerversion AIR 1.5
		 *  @productversion OSMF 1.0
		 */
		public static const NETSTREAM_PLAY_TRANSITION_COMPLETE:String = "NetStream.Play.TransitionComplete";

		/**
		 * "status"
		 * The seek operation is started.
		 *
		 *  @langversion 3.0
		 *  @playerversion Flash 10
		 *  @playerversion AIR 1.5
		 *  @productversion OSMF 2.0
		 */
		public static const NETSTREAM_SEEK_START:String = "NetStream.Seek.Start";

		/**
		 * "status"
		 * Playback reached the end of live content, but the stream is not done. Fires only for streaming connections.
		 *
		 *  @langversion 3.0
		 *  @playerversion Flash 10
		 *  @playerversion AIR 1.5
		 *  @productversion OSMF 1.0
		 */
		public static const NETSTREAM_PLAY_LIVE_STALL:String			= "NetStream.Play.LiveStall";

		/**
		 * "status"
		 * Playback was previously stalled and has now unstalled. Fires only for streaming connections.
		 *
		 *  @langversion 3.0
		 *  @playerversion Flash 10
		 *  @playerversion AIR 1.5
		 *  @productversion OSMF 1.0
		 */
		public static const NETSTREAM_PLAY_LIVE_RESUME:String			= "NetStream.Play.LiveResume";

		// NetStream events

		/**
		 * Dispatched when the application receives descriptive information embedded in the video being played.
		 * For information about video file formats supported by Flash Media Server, see the Flash Media Server documentation.
		 *
		 *  @langversion 3.0
		 *  @playerversion Flash 10
		 *  @playerversion AIR 1.5
		 *  @productversion OSMF 1.0
		 */
		public static const ON_META_DATA:String						= "onMetaData";

		/**
		 * 	Establishes a listener to respond when an embedded cue point is reached while playing a video file.
		 *
		 *  @langversion 3.0
		 *  @playerversion Flash 10
		 *  @playerversion AIR 1.5
		 *  @productversion OSMF 1.0
		 */
		public static const ON_CUE_POINT:String						= "onCuePoint";

		/**
		 *  * Establishes a listener to respond when a NetStream object has completely played a stream.
		 *
		 *  @langversion 3.0
		 *  @playerversion Flash 10
		 *  @playerversion AIR 1.5
		 *  @productversion OSMF 1.0
		 */
		public static const ON_PLAY_STATUS:String					= "onPlayStatus";
	}
}

Add OSMF NetStreamCodes to com.castlabs.dash.utils package


// ===================================================================================================
//                           _  __     _ _
//                          | |/ /__ _| | |_ _  _ _ _ __ _
//                          | ' </ _` | |  _| || | '_/ _` |
//                          |_|\_\__,_|_|\__|\_,_|_| \__,_|
//
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
//
// Copyright (C) 2006-2011  Kaltura Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//
// @ignore
// ===================================================================================================
package com.kaltura.delegates {

	import com.kaltura.config.IKalturaConfig;
	import com.kaltura.config.KalturaConfig;
	import com.kaltura.core.KClassFactory;
	import com.kaltura.errors.KalturaError;
	import com.kaltura.events.KalturaEvent;
	import com.kaltura.net.KalturaCall;
	import com.kaltura.encryption.MD5;

	import flash.events.ErrorEvent;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.HTTPStatusEvent;
	import flash.events.IOErrorEvent;
	import flash.events.SecurityErrorEvent;
	import flash.events.TimerEvent;
	import flash.net.FileReference;
	import flash.net.URLLoader;
	import flash.net.URLLoaderDataFormat;
	import flash.net.URLRequest;
	import flash.net.URLRequestMethod;
	import flash.utils.Timer;
	import flash.utils.getDefinitionByName;

	public class WebDelegateBase extends EventDispatcher implements IKalturaCallDelegate {

		public static var CONNECT_TIME:int = 60000; //60 secs
		public static var LOAD_TIME:int = 60000; //60 secs

		protected var connectTimer:Timer;
		protected var loadTimer:Timer;

		protected var _call:KalturaCall;
		protected var _config:KalturaConfig;

		protected var loader:URLLoader;
		protected var fileRef:FileReference;

		//Setters & getters
		public function get call():KalturaCall {
			return _call;
		}

		public function set call(newVal:KalturaCall):void {
			_call = newVal;
		}

		public function get config():IKalturaConfig {
			return _config;
		}

		public function set config(newVal:IKalturaConfig):void {
			_config = newVal as KalturaConfig;
		}

		public function WebDelegateBase(call:KalturaCall = null, config:KalturaConfig = null) {
			this.call = call;
			this.config = config;
			if (!call)
				return; //maybe a multi request
			if (call.useTimeout) {
				connectTimer = new Timer(CONNECT_TIME, 1);
				connectTimer.addEventListener(TimerEvent.TIMER_COMPLETE, onConnectTimeout);

				loadTimer = new Timer(LOAD_TIME, 1);
				loadTimer.addEventListener(TimerEvent.TIMER_COMPLETE, onLoadTimeOut);
			}
			execute();
		}

		public function close():void {
			try {
				loader.close();
			}
			catch (e:*) {
			}

			if (call.useTimeout) {
				connectTimer.stop();
				loadTimer.stop();
			}
		}

		protected function onConnectTimeout(event:TimerEvent):void {
			var kError:KalturaError = new KalturaError();
			//kError.errorCode =
			kError.errorMsg = "Connection Timeout: " + CONNECT_TIME / 1000 + " sec with no post command from kaltura client.";
			_call.handleError(kError);
			dispatchEvent(new KalturaEvent(KalturaEvent.FAILED, false, false, false, null, kError));

			loadTimer.stop();
			close();
		}

		protected function onLoadTimeOut(event:TimerEvent):void {
			connectTimer.stop();

			close();

			var kError:KalturaError = new KalturaError();
			kError.errorMsg = "Post Timeout: " + LOAD_TIME / 1000 + " sec with no post result.";
			_call.handleError(kError);
			dispatchEvent(new KalturaEvent(KalturaEvent.FAILED, false, false, false, null, kError));
		}

		protected function execute():void {
			if (call == null) {
				throw new Error('No call defined.');
			}
			post(); //post the call
		}

		/**
		* Helper function for sending the call straight to the server
		*/
		protected function post():void {

			addOptionalArguments();

			formatRequest();

			sendRequest();

			if (call.useTimeout) {
				connectTimer.start();
			}
		}

		protected function formatRequest():void {
			//The configuration is stronger then the args
			if (_config.partnerId != null && _call.args["partnerId"] == -1)
				_call.setRequestArgument("partnerId", _config.partnerId);

			if (_config.ks != null)
				_call.setRequestArgument("ks", _config.ks);

			if (_config.clientTag != null)
				_call.setRequestArgument("clientTag", _config.clientTag);

			_call.setRequestArgument("ignoreNull", _config.ignoreNull);

			//Create signature hash.
			//call.setRequestArgument("kalsig", getMD5Checksum(call));
		}

		protected function getMD5Checksum(call:KalturaCall):String {
			var props:Array = new Array();
			for each (var prop:String in call.args)
				props.push(prop);

			props.push("service");
			props.push("action");
			props.sort();

			var s:String;
			for each (prop in props) {
				s += prop;

				if (prop == "service")
					s += call.service;
				else if (prop == "action")
					s += call.action;
				else
					s += call.args[prop];
			}

			return MD5.encrypt(s);
		}

		protected function sendRequest():void {

			//construct the loader
			createURLLoader();

			//Create signature hash.
			var kalsig:String = getMD5Checksum(call);

			//create the service request for normal calls
			var url:String = _config.protocol + _config.domain + "/" + _config.srvUrl + "?service=" + call.service + "&action=" + call.action + "&kalsig=" + kalsig;;

			if (_call.method == URLRequestMethod.GET)
				url += "&";

			var req:URLRequest = new URLRequest(url);
			req.contentType = "application/x-www-form-urlencoded";
			req.method = call.method;
			req.data = call.args;

			loader.dataFormat = URLLoaderDataFormat.TEXT;
			loader.load(req);
		}

		protected function createURLLoader():void {
			loader = new URLLoader();
			loader.addEventListener(Event.COMPLETE, onDataComplete);
			loader.addEventListener(HTTPStatusEvent.HTTP_STATUS, onHTTPStatus);
			loader.addEventListener(IOErrorEvent.IO_ERROR, onError);
			loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onError);
			loader.addEventListener(Event.OPEN, onOpen);
		}

		protected function onHTTPStatus(event:HTTPStatusEvent):void {
		}

		protected function onOpen(event:Event):void {
			if (call.useTimeout) {
				connectTimer.stop();
				loadTimer.start();
			}
		}

		protected function addOptionalArguments():void {
			//add optional args here
		}

		// Event Handlers
		protected function onDataComplete(event:Event):void {
			try {
				handleResult(XML(event.target.data));
			}
			catch (e:Error) {
				var kErr:KalturaError = new KalturaError();
				kErr.errorCode = String(e.errorID);
				kErr.errorMsg = e.message;
				_call.handleError(kErr);
			}
		}

		protected function onError(event:ErrorEvent):void {
			clean();
			var kError:KalturaError = createKalturaError(event, loader.data);

			if (!kError) {
				kError.errorMsg = event.text;
					//kError.errorCode;
			}

			call.handleError(kError);

			dispatchEvent(new KalturaEvent(KalturaEvent.FAILED, false, false, false, null, kError));
		}

		/**
		* parse the server's response and let the call process it.
		 * @param result  server's response
		*/
		protected function handleResult(result:XML):void {
			clean();

			var error:KalturaError = validateKalturaResponse(result);

			if (error == null) {
				var digestedResult:Object = parse(result);
				call.handleResult(digestedResult);
			}
			else {
				call.handleError(error);
			}
		}

		/**
		* stop timers and clean event listeners
		 */
		protected function clean():void {
			if (call.useTimeout) {
				connectTimer.stop();
				loadTimer.stop();
			}

			if (loader == null) {
				return;
			}

			loader.removeEventListener(Event.COMPLETE, onDataComplete);
			loader.removeEventListener(IOErrorEvent.IO_ERROR, onError);
			loader.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, onError);
			loader.removeEventListener(Event.OPEN, onOpen);
		}

		/**
		* create the correct object and populate it with the given values. if the needed class is not found
		 * in the file, a generic object is created with attributes matching the XML attributes.
		* Override this parssing function in the specific delegate to create the correct object.
		* @param   result      instance attributes
		* @return an instance of the class declared by the given XML.
		* */
		public function parse(result:XML):* {
			//by defualt create the response object
			var cls:Class;
			try {
				cls = getDefinitionByName('com.kaltura.vo.' + result.result.objectType) as Class;
			}
			catch (e:Error) {
				cls = Object;
			}
			var obj:* = (new KClassFactory(cls)).newInstanceFromXML(result.result);
			return obj;
		}

		/**
		* If the result string holds an error, return a KalturaError object with
		 * relevant values. <br/>
		* Overide this to create validation object and fill it.
		* @param result  the string returned from the server.
		* @return  matching error object
		 */
		protected function validateKalturaResponse(result:String):KalturaError {
			var kError:KalturaError = null;
			var xml:XML = XML(result);
			if (xml.result.hasOwnProperty('error')) {
				kError = new KalturaError();
				kError.errorCode = String(xml.result.error.code);
				kError.errorMsg = xml.result.error.message;
				dispatchEvent(new KalturaEvent(KalturaEvent.FAILED, false, false, false, null, kError));
			}

			return kError;
		}

		//Overide this to create error object and fill it
		protected function createKalturaError(event:ErrorEvent, loaderData:*):KalturaError {
			var ke:KalturaError = new KalturaError();
			return ke;
		}

		/**
		* create the url that is used for serve actions
		* @param call    the KalturaCall that defines the required parameters
		 * @return URLRequest with relevant parameters
		* */
		public function getServeUrl(call:KalturaCall):URLRequest {
			var url:String = _config.protocol + _config.domain + "/" + _config.srvUrl + "?service=" + call.service + "&action=" + call.action;
			for (var key:String in call.args) {
				url += "&" + key + "=" + call.args[key];
			}
			var req:URLRequest = new URLRequest(url);
			req.contentType = "application/x-www-form-urlencoded";
			req.method = call.method;
//          req.data = call.args;
			return req;
		}

	}
}

// ===================================================================================================
//                           _  __     _ _
//                          | |/ /__ _| | |_ _  _ _ _ __ _
//                          | ' </ _` | |  _| || | '_/ _` |
//                          |_|\_\__,_|_|\__|\_,_|_| \__,_|
//
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
//
// Copyright (C) 2006-2011  Kaltura Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//
// @ignore
// ===================================================================================================
package com.kaltura.delegates {

	import com.kaltura.config.IKalturaConfig;
	import com.kaltura.config.KalturaConfig;
	import com.kaltura.core.KClassFactory;
	import com.kaltura.errors.KalturaError;
	import com.kaltura.events.KalturaEvent;
	import com.kaltura.net.KalturaCall;
	import com.kaltura.encryption.MD5;

	import flash.events.ErrorEvent;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.HTTPStatusEvent;
	import flash.events.IOErrorEvent;
	import flash.events.SecurityErrorEvent;
	import flash.events.TimerEvent;
	import flash.net.FileReference;
	import flash.net.URLLoader;
	import flash.net.URLLoaderDataFormat;
	import flash.net.URLRequest;
	import flash.net.URLRequestMethod;
	import flash.utils.Timer;
	import flash.utils.getDefinitionByName;

	public class WebDelegateBase extends EventDispatcher implements IKalturaCallDelegate {

		public static var CONNECT_TIME:int = 60000; //60 secs
		public static var LOAD_TIME:int = 120000; //120 secs

		protected var connectTimer:Timer;
		protected var loadTimer:Timer;

		protected var _call:KalturaCall;
		protected var _config:KalturaConfig;

		protected var loader:URLLoader;
		protected var fileRef:FileReference;

		//Setters & getters
		public function get call():KalturaCall {
			return _call;
		}

		public function set call(newVal:KalturaCall):void {
			_call = newVal;
		}

		public function get config():IKalturaConfig {
			return _config;
		}

		public function set config(newVal:IKalturaConfig):void {
			_config = newVal as KalturaConfig;
		}

		public function WebDelegateBase(call:KalturaCall = null, config:KalturaConfig = null) {
			this.call = call;
			this.config = config;
			if (!call)
				return; //maybe a multi request
			if (call.useTimeout) {
				connectTimer = new Timer(CONNECT_TIME, 1);
				connectTimer.addEventListener(TimerEvent.TIMER_COMPLETE, onConnectTimeout);

				loadTimer = new Timer(LOAD_TIME, 1);
				loadTimer.addEventListener(TimerEvent.TIMER_COMPLETE, onLoadTimeOut);
			}
			execute();
		}

		public function close():void {
			try {
				loader.close();
			}
			catch (e:*) {
			}

			if (call.useTimeout) {
				connectTimer.stop();
				loadTimer.stop();
			}
		}

		protected function onConnectTimeout(event:TimerEvent):void {
			var kError:KalturaError = new KalturaError();
			kError.errorCode = "KMC_CONNECTION_TIMEOUT";
			kError.errorMsg = "Connection Timeout: " + CONNECT_TIME / 1000 + " sec with no post command from kaltura client.";
			_call.handleError(kError);
			dispatchEvent(new KalturaEvent(KalturaEvent.FAILED, false, false, false, null, kError));

			loadTimer.stop();
			close();
		}

		protected function onLoadTimeOut(event:TimerEvent):void {
			connectTimer.stop();

			close();

			var kError:KalturaError = new KalturaError();
			kError.errorCode = "KMC_POST_TIMEOUT";
			kError.errorMsg = "Post Timeout: " + LOAD_TIME / 1000 + " sec with no post result.";
			_call.handleError(kError);
			dispatchEvent(new KalturaEvent(KalturaEvent.FAILED, false, false, false, null, kError));
		}

		protected function execute():void {
			if (call == null) {
				throw new Error('No call defined.');
			}
			post(); //post the call
		}

		/**
		* Helper function for sending the call straight to the server
		*/
		protected function post():void {

			addOptionalArguments();

			formatRequest();

			sendRequest();

			if (call.useTimeout) {
				connectTimer.start();
			}
		}

		protected function formatRequest():void {
			//The configuration is stronger then the args
			if (_config.partnerId != null && _call.args["partnerId"] == -1)
				_call.setRequestArgument("partnerId", _config.partnerId);

			if (_config.ks != null)
				_call.setRequestArgument("ks", _config.ks);

			if (_config.clientTag != null)
				_call.setRequestArgument("clientTag", _config.clientTag);

			_call.setRequestArgument("ignoreNull", _config.ignoreNull);

			//Create signature hash.
			//call.setRequestArgument("kalsig", getMD5Checksum(call));
		}

		protected function getMD5Checksum(call:KalturaCall):String {
			var props:Array = new Array();
			for each (var prop:String in call.args)
				props.push(prop);

			props.push("service");
			props.push("action");
			props.sort();

			var s:String;
			for each (prop in props) {
				s += prop;

				if (prop == "service")
					s += call.service;
				else if (prop == "action")
					s += call.action;
				else
					s += call.args[prop];
			}

			return MD5.encrypt(s);
		}

		protected function sendRequest():void {

			//construct the loader
			createURLLoader();

			//Create signature hash.
			var kalsig:String = getMD5Checksum(call);

			//create the service request for normal calls
			var url:String = _config.protocol + _config.domain + "/" + _config.srvUrl + "?service=" + call.service + "&action=" + call.action + "&kalsig=" + kalsig;;

			if (_call.method == URLRequestMethod.GET)
				url += "&";

			var req:URLRequest = new URLRequest(url);
			req.contentType = "application/x-www-form-urlencoded";
			req.method = call.method;
			req.data = call.args;

			loader.dataFormat = URLLoaderDataFormat.TEXT;
			loader.load(req);
		}

		protected function createURLLoader():void {
			loader = new URLLoader();
			loader.addEventListener(Event.COMPLETE, onDataComplete);
			loader.addEventListener(HTTPStatusEvent.HTTP_STATUS, onHTTPStatus);
			loader.addEventListener(IOErrorEvent.IO_ERROR, onError);
			loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onError);
			loader.addEventListener(Event.OPEN, onOpen);
		}

		protected function onHTTPStatus(event:HTTPStatusEvent):void {
		}

		protected function onOpen(event:Event):void {
			if (call.useTimeout) {
				connectTimer.stop();
				loadTimer.start();
			}
		}

		protected function addOptionalArguments():void {
			//add optional args here
		}

		// Event Handlers
		protected function onDataComplete(event:Event):void {
			try {
				handleResult(XML(event.target.data));
			}
			catch (e:Error) {
				var kErr:KalturaError = new KalturaError();
				kErr.errorCode = String(e.errorID);
				kErr.errorMsg = e.message;
				_call.handleError(kErr);
			}
		}

		protected function onError(event:ErrorEvent):void {
			clean();
			var kError:KalturaError = createKalturaError(event, loader.data);

			if (!kError) {
				kError.errorMsg = event.text;
					//kError.errorCode;
			}

			call.handleError(kError);

			dispatchEvent(new KalturaEvent(KalturaEvent.FAILED, false, false, false, null, kError));
		}

		/**
		* parse the server's response and let the call process it.
		 * @param result  server's response
		*/
		protected function handleResult(result:XML):void {
			clean();

			var error:KalturaError = validateKalturaResponse(result);

			if (error == null) {
				var digestedResult:Object = parse(result);
				call.handleResult(digestedResult);
			}
			else {
				call.handleError(error);
			}
		}

		/**
		* stop timers and clean event listeners
		 */
		protected function clean():void {
			if (call.useTimeout) {
				connectTimer.stop();
				loadTimer.stop();
			}

			if (loader == null) {
				return;
			}

			loader.removeEventListener(Event.COMPLETE, onDataComplete);
			loader.removeEventListener(IOErrorEvent.IO_ERROR, onError);
			loader.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, onError);
			loader.removeEventListener(Event.OPEN, onOpen);
		}

		/**
		* create the correct object and populate it with the given values. if the needed class is not found
		 * in the file, a generic object is created with attributes matching the XML attributes.
		* Override this parssing function in the specific delegate to create the correct object.
		* @param   result      instance attributes
		* @return an instance of the class declared by the given XML.
		* */
		public function parse(result:XML):* {
			//by defualt create the response object
			var cls:Class;
			try {
				cls = getDefinitionByName('com.kaltura.vo.' + result.result.objectType) as Class;
			}
			catch (e:Error) {
				cls = Object;
			}
			var obj:* = (new KClassFactory(cls)).newInstanceFromXML(result.result);
			return obj;
		}

		/**
		* If the result string holds an error, return a KalturaError object with
		 * relevant values. <br/>
		* Overide this to create validation object and fill it.
		* @param result  the string returned from the server.
		* @return  matching error object
		 */
		protected function validateKalturaResponse(result:String):KalturaError {
			var kError:KalturaError = null;
			var xml:XML = XML(result);
			if (xml.result.hasOwnProperty('error')) {
				kError = new KalturaError();
				kError.errorCode = String(xml.result.error.code);
				kError.errorMsg = xml.result.error.message;
				dispatchEvent(new KalturaEvent(KalturaEvent.FAILED, false, false, false, null, kError));
			}

			return kError;
		}

		//Overide this to create error object and fill it
		protected function createKalturaError(event:ErrorEvent, loaderData:*):KalturaError {
			var ke:KalturaError = new KalturaError();
			return ke;
		}

		/**
		* create the url that is used for serve actions
		* @param call    the KalturaCall that defines the required parameters
		 * @return URLRequest with relevant parameters
		* */
		public function getServeUrl(call:KalturaCall):URLRequest {
			var url:String = _config.protocol + _config.domain + "/" + _config.srvUrl + "?service=" + call.service + "&action=" + call.action;
			for (var key:String in call.args) {
				url += "&" + key + "=" + call.args[key];
			}
			var req:URLRequest = new URLRequest(url);
			req.contentType = "application/x-www-form-urlencoded";
			req.method = call.method;
//          req.data = call.args;
			return req;
		}

	}
}

fwr: set FlexClient timeout to 120 secs, add error codes to timeout errors

git-svn-id: 8a2ccb88241e16c78017770bc38d91d6d5396a5a@86267 6b8eccd3-e8c5-4e7d-8186-e12b5326b719


package
{
    import flash.display.Sprite;
    import flash.text.TextField;
    import flash.net.XMLSocket;

    public class swfcat extends Sprite
    {
        private var output_text:TextField;

        private function puts(s:String):void
        {
            output_text.appendText(s + "\n");
        }

        public function swfcat()
        {
            output_text = new TextField();
            output_text.width = 400;
            output_text.height = 300;
            output_text.background = true;
            output_text.backgroundColor = 0x001f0f;
            output_text.textColor = 0x44CC44;
            addChild(output_text);
        }
    }
}

Add a simple terminal-like output.

Add a simple terminal-like output.


package dolly {
public class Cloner {
	public function Cloner() {
	}
}
}

Create empty Cloner class.

Create empty Cloner class.


package aerys.minko.render.material.phong
{
    import aerys.minko.render.RenderTarget;
    import aerys.minko.render.material.basic.BasicShader;
    import aerys.minko.render.shader.SFloat;
    import aerys.minko.render.shader.ShaderSettings;
    import aerys.minko.render.shader.part.phong.PhongShaderPart;
    import aerys.minko.type.enum.Blending;

    public class AmbientShader extends BasicShader
    {
        private var _phong : PhongShaderPart;

        public function AmbientShader(renderTarget  : RenderTarget  = null,
                                      priority      : Number        = 0.0)
        {
            super(renderTarget, priority);

            _phong = new PhongShaderPart(this);
        }

        override protected function initializeSettings(settings:ShaderSettings):void
        {
            super.initializeSettings(settings);

            settings.blending = Blending.OPAQUE;
        }

        override protected function getPixelColor() : SFloat
        {
            var diffuse : SFloat    = super.getPixelColor();

            return float4(multiply(diffuse.rgb, _phong.getAmbientLighting()), diffuse.a);
        }
    }
}

add missing AmbientShader

add missing AmbientShader


/*
 * Copyright (c) 2009-2011 the original author or authors
 *
 * Permission is hereby granted to use, modify, and distribute this file
 * in accordance with the terms of the license agreement accompanying it.
 */

package org.swiftsuspenders
{
	import flash.system.ApplicationDomain;
	import flash.utils.Dictionary;
	import flash.utils.getQualifiedClassName;

	import org.swiftsuspenders.injectionpoints.InjectionPoint;
	import org.swiftsuspenders.injectionpoints.InjectionPointConfig;
	import org.swiftsuspenders.utils.ClassDescription;
	import org.swiftsuspenders.utils.ClassDescriptor;
	import org.swiftsuspenders.utils.SsInternal;
	import org.swiftsuspenders.utils.getConstructor;

	use namespace SsInternal;

	public class Injector
	{
		//----------------------       Private / Protected Properties       ----------------------//
		private static var INJECTION_POINTS_CACHE : Dictionary = new Dictionary(true);

		private var _parentInjector : Injector;
        private var _applicationDomain:ApplicationDomain;
		private var _classDescriptor : ClassDescriptor;
		private var _mappings : Dictionary;
		private var _namedInjectionsManager : NamedInjectionsManager;

		//----------------------               Public Methods               ----------------------//
		public function Injector()
		{
			_mappings = new Dictionary();
			_namedInjectionsManager = new NamedInjectionsManager(this);
			_classDescriptor = new ClassDescriptor(INJECTION_POINTS_CACHE);
		}

		public function map(dependency : Class) : InjectionRule
		{
			return _mappings[dependency] ||= createRule(dependency);
		}

		public function unmap(dependency : Class) : void
		{
			var rule : InjectionRule = _mappings[dependency];
			if (!rule)
			{
				throw new InjectorError('Error while removing an injector mapping: ' +
						'No rule defined for dependency ' + getQualifiedClassName(dependency));
			}
			rule.setProvider(null);
		}

		/**
		 * Indicates whether the injector can supply a response for the specified dependency either
		 * by using a rule mapped directly on itself or by querying one of its ancestor injectors.
		 *
		 * @param dependency The dependency under query
		 * @return true if the dependency can be satisfied, false if not
		 */
		public function satisfies(dependency : Class) : Boolean
		{
			var rule : InjectionRule = getMapping(dependency);
			return rule && rule.hasProvider();
		}

		/**
		 * Indicates whether the injector can directly supply a response for the specified
		 * dependency
		 *
		 * In contrast to satisfies, satisfiesDirectly only informs
		 * about rules mapped directly on itself, without querying its ancestor injectors.
		 *
		 * @param dependency The dependency under query
		 * @return true if the dependency can be satisfied, false if not
		 */
		public function satisfiesDirectly(dependency : Class) : Boolean
		{
			var rule : InjectionRule = _mappings[dependency];
			return rule && rule.hasProvider();
		}

		/**
		 * Returns the rule mapped to the specified dependency class
		 *
		 * Note that getRule will only return rules mapped in exactly this injector, not ones
		 * mapped in an ancestor injector. To get rules from ancestor injectors, query them using
		 * parentInjector.
		 * This restriction is in place to prevent accidential changing of rules in ancestor
		 * injectors where only the child's response is meant to be altered.
		 *
		 * @param dependency The dependency to return the mapped rule for
		 * @return The rule mapped to the specified dependency class
		 * @throws InjectorError when no rule was found for the specified dependency
		 */
		public function getRule(dependency : Class) : InjectionRule
		{
			var rule : InjectionRule = _mappings[dependency];
			if (!rule)
			{
				throw new InjectorError('Error while retrieving an injector mapping: ' +
						'No rule defined for dependency ' + getQualifiedClassName(dependency));
			}
			return rule;
		}

		public function injectInto(target : Object) : void
		{
			var injecteeDescription : ClassDescription =
					_classDescriptor.getDescription(getConstructor(target));

			var injectionPoints : Array = injecteeDescription.injectionPoints;
			var length : int = injectionPoints.length;
			for (var i : int = 0; i < length; i++)
			{
				var injectionPoint : InjectionPoint = injectionPoints[i];
				injectionPoint.applyInjection(target, this);
			}
		}

		public function getInstance(type : Class) : *
		{
			var mapping : InjectionRule = getMapping(type);
			if (!mapping || !mapping.hasProvider())
			{
				return instantiateUnmapped(type);
			}
			return mapping.apply(this);
		}

		public function createChildInjector(applicationDomain : ApplicationDomain = null) : Injector
		{
			var injector : Injector = new Injector();
            injector.applicationDomain = applicationDomain;
			injector.parentInjector = this;
			return injector;
		}

		public function set parentInjector(parentInjector : Injector) : void
		{
			_parentInjector = parentInjector;
		}
		public function get parentInjector() : Injector
		{
			return _parentInjector;
		}

		public function set applicationDomain(applicationDomain : ApplicationDomain) : void
		{
			_applicationDomain = applicationDomain;
		}
		public function get applicationDomain() : ApplicationDomain
		{
			return _applicationDomain ? _applicationDomain : ApplicationDomain.currentDomain;
		}

		public function usingName(name : String) : NamedInjectionsManager
		{
			_namedInjectionsManager.setRequestName(name);
			return _namedInjectionsManager;
		}

		//----------------------             Internal Methods               ----------------------//
		SsInternal static function purgeInjectionPointsCache() : void
		{
			INJECTION_POINTS_CACHE = new Dictionary(true);
		}

		SsInternal function getMapping(requestType : Class) : InjectionRule
		{
			return _mappings[requestType] || getAncestorMapping(requestType);
		}

		SsInternal function getAncestorMapping(whenAskedFor : Class) : InjectionRule
		{
			return _parentInjector ? _parentInjector.getMapping(whenAskedFor) : null;
		}

		SsInternal function getRuleForInjectionPointConfig(
				config : InjectionPointConfig) : InjectionRule
		{
			var type : Class = Class(applicationDomain.getDefinition(config.typeName));
			if (config.injectionName)
			{
				return usingName(config.injectionName).getMapping(type);
			}
			return getMapping(type);
		}

		SsInternal function instantiateUnmapped(type : Class) : *
		{
			var typeDescription : ClassDescription = _classDescriptor.getDescription(type);
			var injectionPoint : InjectionPoint = typeDescription.ctor;
			if (!injectionPoint)
			{
				throw new InjectorError("Can't instantiate interface " + getQualifiedClassName(type));
			}
			var instance : * = injectionPoint.applyInjection(type, this);
			injectInto(instance);
			return instance;
		}

		//----------------------         Private / Protected Methods        ----------------------//
		private function createRule(requestType : Class) : InjectionRule
		{
			return new InjectionRule(this, requestType);
		}
	}
}

/*
 * Copyright (c) 2009-2011 the original author or authors
 *
 * Permission is hereby granted to use, modify, and distribute this file
 * in accordance with the terms of the license agreement accompanying it.
 */

package org.swiftsuspenders
{
	import flash.system.ApplicationDomain;
	import flash.utils.Dictionary;
	import flash.utils.getQualifiedClassName;

	import org.swiftsuspenders.injectionpoints.InjectionPoint;
	import org.swiftsuspenders.injectionpoints.InjectionPointConfig;
	import org.swiftsuspenders.utils.ClassDescription;
	import org.swiftsuspenders.utils.ClassDescriptor;
	import org.swiftsuspenders.utils.SsInternal;
	import org.swiftsuspenders.utils.getConstructor;

	use namespace SsInternal;

	public class Injector
	{
		//----------------------       Private / Protected Properties       ----------------------//
		private static var INJECTION_POINTS_CACHE : Dictionary = new Dictionary(true);

		private var _parentInjector : Injector;
        private var _applicationDomain:ApplicationDomain;
		private var _classDescriptor : ClassDescriptor;
		private var _mappings : Dictionary;
		private var _namedInjectionsManager : NamedInjectionsManager;

		//----------------------               Public Methods               ----------------------//
		public function Injector()
		{
			_mappings = new Dictionary();
			_namedInjectionsManager = new NamedInjectionsManager(this);
			_classDescriptor = new ClassDescriptor(INJECTION_POINTS_CACHE);
			_applicationDomain = ApplicationDomain.currentDomain;
		}

		public function map(dependency : Class) : InjectionRule
		{
			return _mappings[dependency] ||= createRule(dependency);
		}

		public function unmap(dependency : Class) : void
		{
			var rule : InjectionRule = _mappings[dependency];
			if (!rule)
			{
				throw new InjectorError('Error while removing an injector mapping: ' +
						'No rule defined for dependency ' + getQualifiedClassName(dependency));
			}
			rule.setProvider(null);
		}

		/**
		 * Indicates whether the injector can supply a response for the specified dependency either
		 * by using a rule mapped directly on itself or by querying one of its ancestor injectors.
		 *
		 * @param dependency The dependency under query
		 * @return true if the dependency can be satisfied, false if not
		 */
		public function satisfies(dependency : Class) : Boolean
		{
			var rule : InjectionRule = getMapping(dependency);
			return rule && rule.hasProvider();
		}

		/**
		 * Indicates whether the injector can directly supply a response for the specified
		 * dependency
		 *
		 * In contrast to satisfies, satisfiesDirectly only informs
		 * about rules mapped directly on itself, without querying its ancestor injectors.
		 *
		 * @param dependency The dependency under query
		 * @return true if the dependency can be satisfied, false if not
		 */
		public function satisfiesDirectly(dependency : Class) : Boolean
		{
			var rule : InjectionRule = _mappings[dependency];
			return rule && rule.hasProvider();
		}

		/**
		 * Returns the rule mapped to the specified dependency class
		 *
		 * Note that getRule will only return rules mapped in exactly this injector, not ones
		 * mapped in an ancestor injector. To get rules from ancestor injectors, query them using
		 * parentInjector.
		 * This restriction is in place to prevent accidential changing of rules in ancestor
		 * injectors where only the child's response is meant to be altered.
		 *
		 * @param dependency The dependency to return the mapped rule for
		 * @return The rule mapped to the specified dependency class
		 * @throws InjectorError when no rule was found for the specified dependency
		 */
		public function getRule(dependency : Class) : InjectionRule
		{
			var rule : InjectionRule = _mappings[dependency];
			if (!rule)
			{
				throw new InjectorError('Error while retrieving an injector mapping: ' +
						'No rule defined for dependency ' + getQualifiedClassName(dependency));
			}
			return rule;
		}

		public function injectInto(target : Object) : void
		{
			var injecteeDescription : ClassDescription =
					_classDescriptor.getDescription(getConstructor(target));

			var injectionPoints : Array = injecteeDescription.injectionPoints;
			var length : int = injectionPoints.length;
			for (var i : int = 0; i < length; i++)
			{
				var injectionPoint : InjectionPoint = injectionPoints[i];
				injectionPoint.applyInjection(target, this);
			}
		}

		public function getInstance(type : Class) : *
		{
			var mapping : InjectionRule = getMapping(type);
			if (!mapping || !mapping.hasProvider())
			{
				return instantiateUnmapped(type);
			}
			return mapping.apply(this);
		}

		public function createChildInjector(applicationDomain : ApplicationDomain = null) : Injector
		{
			var injector : Injector = new Injector();
            injector.applicationDomain = applicationDomain;
			injector.parentInjector = this;
			return injector;
		}

		public function set parentInjector(parentInjector : Injector) : void
		{
			_parentInjector = parentInjector;
		}
		public function get parentInjector() : Injector
		{
			return _parentInjector;
		}

		public function set applicationDomain(applicationDomain : ApplicationDomain) : void
		{
			_applicationDomain = applicationDomain || ApplicationDomain.currentDomain;
		}
		public function get applicationDomain() : ApplicationDomain
		{
			return _applicationDomain;
		}

		public function usingName(name : String) : NamedInjectionsManager
		{
			_namedInjectionsManager.setRequestName(name);
			return _namedInjectionsManager;
		}

		//----------------------             Internal Methods               ----------------------//
		SsInternal static function purgeInjectionPointsCache() : void
		{
			INJECTION_POINTS_CACHE = new Dictionary(true);
		}

		SsInternal function getMapping(requestType : Class) : InjectionRule
		{
			return _mappings[requestType] || getAncestorMapping(requestType);
		}

		SsInternal function getAncestorMapping(whenAskedFor : Class) : InjectionRule
		{
			return _parentInjector ? _parentInjector.getMapping(whenAskedFor) : null;
		}

		SsInternal function getRuleForInjectionPointConfig(
				config : InjectionPointConfig) : InjectionRule
		{
			var type : Class = Class(applicationDomain.getDefinition(config.typeName));
			if (config.injectionName)
			{
				return usingName(config.injectionName).getMapping(type);
			}
			return getMapping(type);
		}

		SsInternal function instantiateUnmapped(type : Class) : *
		{
			var typeDescription : ClassDescription = _classDescriptor.getDescription(type);
			var injectionPoint : InjectionPoint = typeDescription.ctor;
			if (!injectionPoint)
			{
				throw new InjectorError("Can't instantiate interface " + getQualifiedClassName(type));
			}
			var instance : * = injectionPoint.applyInjection(type, this);
			injectInto(instance);
			return instance;
		}

		//----------------------         Private / Protected Methods        ----------------------//
		private function createRule(requestType : Class) : InjectionRule
		{
			return new InjectionRule(this, requestType);
		}
	}
}

Store ApplicationDomain.currentDomain in Injector#_applicationDomain in case of no explicit domain being set. Turns out that calling ApplicationDomain.currentDomain has a huge cost that can thus be saved in 99.9% of all cases


package {
  public class console {
    public static function log(string: String): void {
      process.puts(string)
    }
  }
}

Add console.log.

Add console.log.


package io.github.jwhile.impetus
{
    import flash.media.SoundChannel;

    public class ImpetusChannel
    {
        this.channel:SoundChannel;

        public function ImpetusChannel(channel:SoundChannel):void
        {
            this.channel = channel;
        }
    }
}

Add class ImpetusChannel

Add class ImpetusChannel


/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

package corsaair.server.spitfire
{

    import C.errno.*;
    import C.arpa.inet.*;
    import C.netdb.*;
    import C.netinet.*;
    import C.sys.socket.*;
    import C.stdlib.*;
    import C.unistd.*;

    import flash.utils.ByteArray;

    /**
     * A simple socket server.
     *
     * This mainyl show how you use BSD sockets to setup a listenign server,
     * the server does not have a loop to listen on multiple connections
     * to deal with numerous clients.
     *
     * You run the server, connect to it with telnet or netcat,
     * the server send a message to the client and then close the connection.
     *
     * @see http://beej.us/guide/bgnet/output/html/singlepage/bgnet.html#simpleserver A Simple Stream Server
     */
    public class SimpleSocketServer
    {

        // the port users will be connecting to
        public const PORT:String = "3490";

        // how many pending connections queue will hold
        public const BACKLOG:uint = 10;

        public function SimpleSocketServer()
        {
            super();
        }

        /* Note:
           This is our first server
           we do the basic and the very raw stuff
           using BSD sockets with comments :)

           this code is ported directly from C source code
           http://beej.us/guide/bgnet/output/html/singlepage/bgnet.html#simpleserver
           from the excellent
           Beej's Guide to Network Programming
           Using Internet Sockets
        */
        public function main():void
        {
            // listen on sock_fd
            var sockfd:int;
            // new connection on new_fd
            var new_fd:int;

            var hints:addrinfo = new addrinfo();
            var servinfo:addrinfo;

            /* Note:
               With BSD sockets the constants are very important
               it's how we configure everything

               ai_family = AF_UNSPEC
               if we want to use either IPv4 or IPv6

               ai_family = AF_INET
               to use only IPv4

               ai_family = AF_INET6
               to use only IPv6

               SOCK_STREAM for TCP (stream) sockets
               SOCK_DGRAM for UDP (datagram) sockets
            */
            hints.ai_family   = AF_UNSPEC;
            hints.ai_socktype = SOCK_STREAM;
            hints.ai_flags    = AI_PASSIVE; // use my IP

            /* Note:
               getaddrinfo() works a bit differently compared to C
               instead of passing a list by reference and return an int
               our AS3 getaddrinfo()
               - return null if an error occured
                 and will fill the details into the CEAIrror object
               - or return an array of addrinfo found
            */
            var eaierr:CEAIrror = new CEAIrror();
            var addrlist:Array  = getaddrinfo( null, PORT, hints, eaierr );

            if( !addrlist )
            {
                throw eaierr;
            }

            var option:int;
            var bound:int;

            // loop through all the results and bind to the first we can
            for( var i:uint = 0; i < addrlist.length; i++ )
            {
                servinfo = addrlist[i];

                sockfd = socket( servinfo.ai_family, servinfo.ai_socktype, servinfo.ai_protocol );
                if( sockfd == -1 )
                {
                    trace( "server: socket" )
                    trace( new CError( "", errno ) );
                    continue;
                }

                option = setsockopt( sockfd, SOL_SOCKET, SO_REUSEADDR, 1 );
                if( option == -1 )
                {
                    trace( "setsockopt" );
                    trace( new CError( "", errno ) );
                    exit( 1 );
                }

                bound = bind( sockfd, servinfo.ai_addr );
                if( bound == -1 )
                {
                    close( sockfd );
                    trace( "server: bind" );
                    trace( new CError( "", errno ) );
                    continue;
                }

                /* Note:
                   If we reach here that means we could
                   open a socket and bind to it
                */
                break;
            }

            /* Note:
               If this happen that means
               we looped trough all the address of getaddrinfo()
               but we could not open/bind any of them
            */
            if( servinfo == null )
            {
                trace( "server: failed to bind" );
                exit( 1 );
            }

            /* Note:
               that's the basic of a "socket server"
               - socket() : Create an endpoint for communication.
               - bind()   : Bind a name to a socket.
               - listen() : Listen for socket connections
                            and limit the queue of incoming connections.

               socket() is mainly describing what kind of socket we want to use
               and then return a file descriptor (the ID of the socket if you want)

               bind() is here to "connect" the socket ID to a network interface
               on the same computer you could have different IP address:
               127.0.0.1 the localhost
               192.168.0.1 the IP adress on your local network
               255.165.225.235 the IP adress assigned by your ISP
               etc.

               and finally listen() is here to say on which port we want
               to receive data, or which service
               port 80 is for HTTP web server
               port 21 is for FTP server
               etc.
            */
            var listening:int = listen( sockfd, BACKLOG );
            if( listening == -1 )
            {
                trace( "listen" );
                trace( new CError( "", errno ) );
                exit( 1 );
            }

            trace( "server: waiting for connections..." );

            var client_addr:sockaddr_in = new sockaddr_in();

            // main accept() loop
            while( 1 )
            {
                new_fd = accept( sockfd, client_addr );
                if( new_fd == -1 )
                {
                    trace( "accept" );
                    trace( new CError( "", errno ) );
                    continue;
                }

                var s:String = inet_ntop( client_addr.sin_family, client_addr );
                if( !s )
                {
                    trace( "inet_ntop" );
                    trace( new CError( "", errno ) );
                    continue;
                }
                trace( "server: got connection from " + s );

                /* Note:
                   we prepare the message into a ByteArray and send it

                   If you comapre with server.c you will see that
                   we do not use fork()
                   this is on purpose
                   fork() is a very unixy thing that just does not work
                   under Windows, but next example will show how to do
                   like fork() but with Workers :)
                */
                var msg:String = "Hello, world!\n";
                var bytes:ByteArray = new ByteArray();
                    bytes.writeUTFBytes( msg );
                    bytes.position = 0;
                var sent:int = send( new_fd, bytes );
                if( sent == -1 )
                {
                    trace( "send" );
                    trace( new CError( "", errno ) );
                    continue;
                }
                else
                {
                    trace( "sent " + sent + " bytes to the client" );
                    break;
                }

            }

            trace( "disconnecting client" );
            close( new_fd );

            trace( "shutting down server" );
            close( sockfd );

            exit( 0 );

        }

    }
}

add simple socket server

add simple socket server

git-svn-id: 44dac414ef660a76a1e627c7b7c0e36d248d62e4@13 c2cce57b-6cbb-4450-ba62-5fdab5196ef5


/*
 * Copyright 2014 Mozilla Foundation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package flash.utils {

[native(cls='ObjectOutputClass')]
internal class ObjectOutput implements IDataOutput {
  public native function get objectEncoding(): uint;
  public native function set objectEncoding(version: uint): void;
  public native function get endian(): String;
  public native function set endian(type: String): void;
  public native function writeBytes(bytes: ByteArray, offset: uint = 0, length: uint = 0): void;
  public native function writeBoolean(value: Boolean): void;
  public native function writeByte(value: int): void;
  public native function writeShort(value: int): void;
  public native function writeInt(value: int): void;
  public native function writeUnsignedInt(value: uint): void;
  public native function writeFloat(value: Number): void;
  public native function writeDouble(value: Number): void;
  public native function writeMultiByte(value: String, charSet: String): void;
  public native function writeUTF(value: String): void;
  public native function writeUTFBytes(value: String): void;
  public native function writeObject(object: *): void;
}
}

Add missing builtin flash.utils.ObjectOutput


Refactor Injector#injectInto to fix bug in Reflector#getClass passing Proxy.

Signed-off-by: Till Schneidereit <feeaf94ce47b255f6cb8c38100dc87ac3794b0b3@gmail.com>


package aerys.minko.render.shader.compiler
{
    public final class ShaderCompilerError extends Error
    {
        public static const TOO_MANY_VERTEX_OPERATIONS            : uint  = 1 << 0;
        public static const TOO_MANY_VERTEX_CONSTANTS             : uint  = 1 << 1;
        public static const TOO_MANY_VERTEX_TEMPORARIES           : uint  = 1 << 2;
        public static const TOO_MANY_VERTEX_ATTRIBUTES            : uint  = 1 << 3;

        public static const TOO_MANY_VARYINGS                     : uint  = 1 << 4;

        public static const TOO_MANY_FRAGMENT_OPERATIONS          : uint  = 1 << 5;
        public static const TOO_MANY_FRAGMENT_CONSTANTS           : uint  = 1 << 6;
        public static const TOO_MANY_FRAGMENT_TEMPORARIES         : uint  = 1 << 7;

        public static const TOO_MANY_FRAGMENT_SAMPLERS    : uint  = 1 << 8;

        public static const OUT_OF_REGISTERS                      : uint  =
              TOO_MANY_VERTEX_CONSTANTS
            | TOO_MANY_VERTEX_TEMPORARIES
            | TOO_MANY_VERTEX_ATTRIBUTES
            | TOO_MANY_FRAGMENT_CONSTANTS
            | TOO_MANY_FRAGMENT_TEMPORARIES
            | TOO_MANY_FRAGMENT_SAMPLERS;

        public function ShaderCompilerError(id : uint = 0)
        {
            super(message, id);
        }
    }
}

add missing ShaderCompilerError class

add missing ShaderCompilerError class


// ActionScript file
package aerys.minko.ns
{
	public namespace minko_animation;
}

Add Animation namespace and modification for timelines

A New namespace to access confidential information inside timelines
M Each timeline has two new getter, need namespace minko_animation to use them


package dolly {
import dolly.core.dolly_internal;
import dolly.data.PropertyLevelCopyableClass;

import org.as3commons.reflect.Field;
import org.as3commons.reflect.Type;
import org.flexunit.asserts.assertEquals;
import org.flexunit.asserts.assertFalse;
import org.flexunit.asserts.assertNotNull;

use namespace dolly_internal;

public class CopyingOfPropertyLevelCopyableClassTest {

	private var propertyLevelCopyableClass:PropertyLevelCopyableClass;
	private var propertyLevelCopyableClassType:Type;

	[Before]
	public function before():void {
		propertyLevelCopyableClass = new PropertyLevelCopyableClass();
		propertyLevelCopyableClass.property1 = "property1 value";
		propertyLevelCopyableClass.property2 = "property2 value";
		propertyLevelCopyableClass.writableField1 = "writableField1 value";

		propertyLevelCopyableClassType = Type.forInstance(propertyLevelCopyableClass);
	}

	[After]
	public function after():void {
		propertyLevelCopyableClass = null;
		propertyLevelCopyableClassType = null;
	}

	[Test]
	public function findingAllCopyableFieldsForType():void {
		const copyableFields:Vector.<Field> = Copier.findCopyableFieldsForType(propertyLevelCopyableClassType);
		assertNotNull(copyableFields);
		assertEquals(2, copyableFields.length);
		assertNotNull(copyableFields[0]);
		assertNotNull(copyableFields[1]);
	}

	[Test]
	public function copyingByCopier():void {
		const copyInstance:PropertyLevelCopyableClass = Copier.copy(propertyLevelCopyableClass);
		assertNotNull(copyInstance);
		assertNotNull(copyInstance.property1);
		assertEquals(copyInstance.property1, propertyLevelCopyableClass.property1);
		assertNotNull(copyInstance.property2);
		assertFalse(copyInstance.property2 == propertyLevelCopyableClass.property2);
		assertNotNull(copyInstance.writableField1);
		assertEquals(copyInstance.writableField1, propertyLevelCopyableClass.writableField1);
	}

	[Test]
	public function copyingByCopyFunction():void {
		const copyInstance:PropertyLevelCopyableClass = copy(propertyLevelCopyableClass);
		assertNotNull(copyInstance);
		assertNotNull(copyInstance.property1);
		assertEquals(copyInstance.property1, propertyLevelCopyableClass.property1);
		assertNotNull(copyInstance.property2);
		assertFalse(copyInstance.property2 == propertyLevelCopyableClass.property2);
		assertNotNull(copyInstance.writableField1);
		assertEquals(copyInstance.writableField1, propertyLevelCopyableClass.writableField1);
	}
}
}

Create new test class: CopyingOfPropertyLevelCopyableClassTest.


package {
    import flash.display.Sprite;

    [SWF(backgroundColor='#000000', frameRate='32', width='720', height='480')]
    public final class boot extends Sprite {

        public function boot() {
            super();
        }

        protected function initialize():void {
            // N/A yet.
        }

        protected function finalize():void {
            // N/A yet.
        }

        public function arrange():void {
            // N/A yet.
        }

        private function removeLoader():void {
            // N/A yet.
        }

        private function ready():void {
            // N/A yet.
        }

        private function progress(event:*):void {
            // N/A yet.
        }

        private function complete(event:*):void {
            // N/A yet.
        }

        private function setup():void {
            // N/A yet.
        }

        private function run():void {
            removeLoader();
            arrange();
        }
    }
}

Create boot.as

Create boot.as