check in basic flex demo as basis to develop a client application

This commit is contained in:
Anthony Minessale 2011-07-05 11:16:31 -05:00
parent cad68d53f5
commit 25be760bbc
76 changed files with 20572 additions and 0 deletions

Binary file not shown.

2
clients/flex/build.sh Executable file
View File

@ -0,0 +1,2 @@
#!/bin/sh
mxmlc -static-link-runtime-shared-libraries freeswitch.mxml

View File

@ -0,0 +1,313 @@
/*
Copyright (c) 2009, Adobe Systems Incorporated
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Adobe Systems Incorporated nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.adobe.air.crypto
{
import com.adobe.crypto.SHA256;
import flash.data.EncryptedLocalStore;
import flash.utils.ByteArray;
/**
* The EncryptionKeyGenerator class generates an encryption key value, such as you would use
* to encrypt files or data. For example, the encryption key is suitable to use as
* an encryption key for an encrypted AIR local SQL (SQLite) database.
*
* <p>This class uses techniques and algorithms that are designed for maximum
* data privacy and security. Use this class to generate an encryption key if your
* application requires data to be encrypted on a per-user level (in other words,
* if only one user of the application should be able to access his or her data).
* In some situations you may also want to use per-user encryption for data even
* if the application design specifies that other users can access the data. For more
* information, see
* "<a href="http://help.adobe.com/en_US/AIR/1.5/devappsflex/WS34990ABF-C893-47ec-B813-9C9D9587A398.html">Considerations for using encryption with a database</a>"
* in the guide
* "<a href="http://help.adobe.com/en_US/AIR/1.5/devappsflex/">Developing Adobe AIR Applications with Flex</a>."</p>
*
* <p>The generated encryption key is based on a password that you provide. For any given
* password, in the same AIR application
* running in the same user account on the same machine, the encryption key result is
* the same.</p>
*
* <p>To generate an encryption key from a password, use the <code>getEncryptionKey()</code>
* method. To confirm that a password is a "strong" password before calling the
* <code>getEncryptionKey()</code> method, use the <code>validateStrongPassword()</code>
* method.</p>
*
* <p>In addition, the EncryptionKeyGenerator includes a utility constant,
* <code>ENCRYPTED_DB_PASSWORD_ERROR_ID</code>. This constant matches the error ID of
* the SQLError error that occurs when code that is attempting to open an encrypted database
* provides the wrong encryption key.</p>
*
* <p>This class is designed to create an encryption key suitable for providing the highest
* level of data privacy and security. In order to achieve that level of security, a few
* security principles must be followed:</p>
*
* <ul>
* <li>Your application should never store the user-entered password</li>
* <li>Your application should never store the encryption key returned by the
* <code>getEncryptionKey()</code> method.</li>
* <li>Instead, each time the user runs the application and attempts to access the database,
* your application code should call the <code>getEncryptionKey()</code> method to
* regenerate the encryption key.</li>
* </ul>
*
* <p>For more information about data security, and an explanation of the security techniques
* used in the EncryptionKeyGenerator class, see
* "<a href="http://help.adobe.com/en_US/AIR/1.5/devappsflex/WS61068DCE-9499-4d40-82B8-B71CC35D832C.html">Example: Generating and using an encryption key</a>"
* in the guide
* "<a href="http://help.adobe.com/en_US/AIR/1.5/devappsflex/">Developing Adobe AIR Applications with Flex</a>."</p>
*/
public class EncryptionKeyGenerator
{
// ------- Constants -------
/**
* This constant matches the error ID (3138) of the SQLError error that occurs when
* code that is attempting to open an encrypted database provides the wrong
* encryption key.
*/
public static const ENCRYPTED_DB_PASSWORD_ERROR_ID:uint = 3138;
private static const STRONG_PASSWORD_PATTERN:RegExp = /(?=^.{8,32}$)((?=.*\d)|(?=.*\W+))(?![.\n])(?=.*[A-Z])(?=.*[a-z]).*$/;
private static const SALT_ELS_KEY:String = "com.adobe.air.crypto::EncryptedDBSalt$$$";
// ------- Constructor -------
/**
* Creates a new EncryptionKeyGenerator instance.
*/
public function EncryptionKeyGenerator() {}
// ------- Public methods -------
/**
* Checks a password and returns a value indicating whether the password is a "strong"
* password. The criteria for a strong password are:
*
* <ul>
* <li>Minimum 8 characters</li>
* <li>Maxmium 32 characters</li>
* <li>Contains at least one lowercase letter</li>
* <li>Contains at least one uppercase letter</li>
* <li>Contains at least one number or symbol character</li>
* </ul>
*
* @param password The password to check
*
* @return A value indicating whether the password is a strong password (<code>true</code>)
* or not (<code>false</code>).
*/
public function validateStrongPassword(password:String):Boolean
{
if (password == null || password.length <= 0)
{
return false;
}
return STRONG_PASSWORD_PATTERN.test(password);
}
/**
* Uses a password to generate a 16-byte encryption key. The return value is suitable
* to use as an encryption key for an encrypted AIR local SQL (SQLite) database.
*
* <p>For any given
* password, calling the <code>getEncryptionKey()</code> method from the same AIR application
* running in the same user account on the same machine, the encryption key result is
* the same.
*
* <p>This method is designed to create an encryption key suitable for providing the highest
* level of data privacy and security. In order to achieve that level of security, your
* application must follow several security principles:</p>
*
* <ul>
* <li>Your application can never store the user-entered password</li>
* <li>Your application can never store the encryption key returned by the
* <code>getEncryptionKey()</code> method.</li>
* <li>Instead, each time the user runs the application and attempts to access the database,
* call the <code>getEncryptionKey()</code> method to regenerate the encryption key.</li>
* </ul>
*
* <p>For more information about data security, and an explanation of the security techniques
* used in the EncryptionKeyGenerator class, see
* "<a href="http://help.adobe.com/en_US/AIR/1.5/devappsflex/WS61068DCE-9499-4d40-82B8-B71CC35D832C.html">Example: Generating and using an encryption key</a>"
* in the guide
* "<a href="http://help.adobe.com/en_US/AIR/1.5/devappsflex/">Developing Adobe AIR Applications with Flex</a>."</p>
*
* @param password The password to use to generate the encryption key.
* @param overrideSaltELSKey The EncryptionKeyGenerator creates and stores a random value
* (known as a <i>salt</i>) as part of the process of
* generating the encryption key. The first time an application
* calls the <code>getEncryptionKey()</code> method, the salt
* value is created and stored in the AIR application's encrypted
* local store (ELS). From then on, the salt value is loaded from the
* ELS.
* <p>If you wish to provide a custom String ELS key for storing
* the salt value, specify a value for the <code>overrideSaltELSKey</code>
* parameter. If the parameter is <code>null</code> (the default)
* a default key name is used.</p>
*
* @return The generated encryption key, a 16-byte ByteArray object.
*
* @throws ArgumentError If the specified password is not a "strong" password according to the
* criteria explained in the <code>validateStrongPassword()</code>
* method description
*
* @throws ArgumentError If a non-<code>null</code> value is specified for the <code>overrideSaltELSKey</code>
* parameter, and the value is an empty String (<code>""</code>)
*/
public function getEncryptionKey(password:String, overrideSaltELSKey:String=null):ByteArray
{
if (!validateStrongPassword(password))
{
throw new ArgumentError("The password must be a strong password. It must be 8-32 characters long. It must contain at least one uppercase letter, at least one lowercase letter, and at least one number or symbol.");
}
if (overrideSaltELSKey != null && overrideSaltELSKey.length <= 0)
{
throw new ArgumentError("If an overrideSaltELSKey parameter value is specified, it can't be an empty String.");
}
var concatenatedPassword:String = concatenatePassword(password);
var saltKey:String;
if (overrideSaltELSKey == null)
{
saltKey = SALT_ELS_KEY;
}
else
{
saltKey = overrideSaltELSKey;
}
var salt:ByteArray = EncryptedLocalStore.getItem(saltKey);
if (salt == null)
{
salt = makeSalt();
EncryptedLocalStore.setItem(saltKey, salt);
}
var unhashedKey:ByteArray = xorBytes(concatenatedPassword, salt);
var hashedKey:String = SHA256.hashBytes(unhashedKey);
var encryptionKey:ByteArray = generateEncryptionKey(hashedKey);
return encryptionKey;
}
// ------- Creating encryption key -------
private function concatenatePassword(pwd:String):String
{
var len:int = pwd.length;
var targetLength:int = 32;
if (len == targetLength)
{
return pwd;
}
var repetitions:int = Math.floor(targetLength / len);
var excess:int = targetLength % len;
var result:String = "";
for (var i:uint = 0; i < repetitions; i++)
{
result += pwd;
}
result += pwd.substr(0, excess);
return result;
}
private function makeSalt():ByteArray
{
var result:ByteArray = new ByteArray;
for (var i:uint = 0; i < 8; i++)
{
result.writeUnsignedInt(Math.round(Math.random() * uint.MAX_VALUE));
}
return result;
}
private function xorBytes(passwordString:String, salt:ByteArray):ByteArray
{
var result:ByteArray = new ByteArray();
for (var i:uint = 0; i < 32; i += 4)
{
// Extract 4 bytes from the password string and convert to a uint
var o1:uint = passwordString.charCodeAt(i) << 24;
o1 += passwordString.charCodeAt(i + 1) << 16;
o1 += passwordString.charCodeAt(i + 2) << 8;
o1 += passwordString.charCodeAt(i + 3);
salt.position = i;
var o2:uint = salt.readUnsignedInt();
var xor:uint = o1 ^ o2;
result.writeUnsignedInt(xor);
}
return result;
}
private function generateEncryptionKey(hash:String):ByteArray
{
var result:ByteArray = new ByteArray();
// select a range of 128 bits (32 hex characters) from the hash
// In this case, we'll use the bits starting from position 17
for (var i:uint = 0; i < 32; i += 2)
{
var position:uint = i + 17;
var hex:String = hash.substr(position, 2);
var byte:int = parseInt(hex, 16);
result.writeByte(byte);
}
return result;
}
}
}

View File

@ -0,0 +1,245 @@
/*
Copyright (c) 2009, Adobe Systems Incorporated
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Adobe Systems Incorporated nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.adobe.air.filesystem
{
import flash.filesystem.File;
import flash.utils.Timer;
import flash.events.TimerEvent;
import flash.events.Event;
import flash.events.EventDispatcher;
import com.adobe.air.filesystem.events.FileMonitorEvent;
/*
Todo:
-Cmonitor changes in multiple attributes
-add support for monitoring multiple files
*/
/**
* Dispatched when the modified date of the file being modified changes.
*
* @eventType com.adobe.air.filesystem.events.FileMonitor.CHANGE
*/
[Event(name="CHANGE", type="com.adobe.air.filesystem.events.FileMonitor")]
/**
* Dispatched when the file being monitored is moved or deleted. The file
* will be unwatched.
*
* @eventType com.adobe.air.filesystem.events.FileMonitor.MOVE
*/
[Event(name="MOVE", type="com.adobe.air.filesystem.events.FileMonitor")]
/**
* Dispatched when the file being monitored is created.
*
* @eventType com.adobe.air.filesystem.events.FileMonitor.CREATE
*/
[Event(name="CREATE", type="com.adobe.air.filesystem.events.FileMonitor")]
/**
* Class that monitors files for changes.
*/
public class FileMonitor extends EventDispatcher
{
private var _file:File;
private var timer:Timer;
public static const DEFAULT_MONITOR_INTERVAL:Number = 1000;
private var _interval:Number;
private var fileExists:Boolean = false;
private var lastModifiedTime:Number;
/**
* Constructor
*
* @parameter file The File that will be monitored for changes.
*
* @param interval How often in milliseconds the file is polled for
* change events. Default value is 1000, minimum value is 1000
*/
public function FileMonitor(file:File = null, interval:Number = -1)
{
this.file = file;
if(interval != -1)
{
if(interval < 1000)
{
_interval = 1000;
}
else
{
_interval = interval;
}
}
else
{
_interval = DEFAULT_MONITOR_INTERVAL;
}
}
/**
* File being monitored for changes.
*
* Setting the property will result in unwatch() being called.
*/
public function get file():File
{
return _file;
}
public function set file(file:File):void
{
if(timer && timer.running)
{
unwatch();
}
_file = file;
if(!_file)
{
fileExists = false;
return;
}
//note : this will throw an error if new File() is passed in.
fileExists = _file.exists;
if(fileExists)
{
lastModifiedTime = _file.modificationDate.getTime();
}
}
/**
* How often the system is polled for Volume change events.
*/
public function get interval():Number
{
return _interval;
}
/**
* Begins monitoring the specified file for changes.
*
* Broadcasts Event.CHANGE event when the file's modification date has changed.
*/
public function watch():void
{
if(!file)
{
//should we throw an error?
return;
}
if(timer && timer.running)
{
return;
}
//check and see if timer is active. if it is, return
if(!timer)
{
timer = new Timer(_interval);
timer.addEventListener(TimerEvent.TIMER, onTimerEvent, false, 0, true);
}
timer.start();
}
/**
* Stops watching the specified file for changes.
*/
public function unwatch():void
{
if(!timer)
{
return;
}
timer.stop();
timer.removeEventListener(TimerEvent.TIMER, onTimerEvent);
}
private function onTimerEvent(e:TimerEvent):void
{
var outEvent:FileMonitorEvent;
if(fileExists != _file.exists)
{
if(_file.exists)
{
//file was created
outEvent = new FileMonitorEvent(FileMonitorEvent.CREATE);
lastModifiedTime = _file.modificationDate.getTime();
}
else
{
//file was moved / deleted
outEvent = new FileMonitorEvent(FileMonitorEvent.MOVE);
unwatch();
}
fileExists = _file.exists;
}
else
{
if(!_file.exists)
{
return;
}
var modifiedTime:Number = _file.modificationDate.getTime();
if(modifiedTime == lastModifiedTime)
{
return;
}
lastModifiedTime = modifiedTime;
//file modified
outEvent = new FileMonitorEvent(FileMonitorEvent.CHANGE);
}
if(outEvent)
{
outEvent.file = _file;
dispatchEvent(outEvent);
}
}
}
}

View File

@ -0,0 +1,63 @@
/*
Copyright (c) 2009, Adobe Systems Incorporated
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Adobe Systems Incorporated nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.adobe.air.filesystem
{
import flash.system.Capabilities;
import flash.filesystem.File;
public class FileUtil
{
/**
* @return An Array of Files representing the root directories of the
* operating system.
*/
public static function getRootDirectories():Array
{
var v:Array = File.getRootDirectories();
var os:String = Capabilities.os;
if(os.indexOf("Mac") > -1)
{
v = File(v[0]).resolvePath("Volumes").getDirectoryListing();
}
else if(os.indexOf("Linux") > -1)
{
//todo: need to impliment Linux
}
return v;
}
}
}

View File

@ -0,0 +1,184 @@
/*
Copyright (c) 2009, Adobe Systems Incorporated
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Adobe Systems Incorporated nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.adobe.air.filesystem
{
import flash.events.EventDispatcher;
import flash.utils.Timer;
import flash.events.TimerEvent;
import flash.filesystem.File;
import flash.utils.Dictionary;
import com.adobe.air.filesystem.events.FileMonitorEvent;
import com.adobe.utils.ArrayUtil;
/**
* Dispatched when a volume is added to the system.
*
* @eventType com.adobe.air.filesystem.events.FileMonitor.ADD_VOLUME
*/
[Event(name="ADD_VOLUME", type="com.adobe.air.filesystem.events.FileMonitor")]
/**
* Dispatched when a volume is removed from the system.
*
* @eventType com.adobe.air.filesystem.events.FileMonitor.REMOVE_VOLUME
*/
[Event(name="REMOVE_VOLUME", type="com.adobe.air.filesystem.events.FileMonitor")]
/**
* Class that monitors changes to the File volumes attached to the operating
* system.
*/
public class VolumeMonitor extends EventDispatcher
{
private var timer:Timer;
private var _interval:Number;
private static const DEFAULT_MONITOR_INTERVAL:Number = 2000;
private var volumes:Dictionary;
/**
* Constructor.
*
* @param interval How often in milliseconds the system is polled for
* volume change events. Default value is 2000, minimum value is 1000
*/
public function VolumeMonitor(interval:Number = -1)
{
if(interval != -1)
{
if(interval < 1000)
{
_interval = 1000;
}
else
{
_interval = interval;
}
}
else
{
_interval = DEFAULT_MONITOR_INTERVAL;
}
}
/**
* How often the system is polled for Volume change events.
*/
public function get interval():Number
{
return _interval;
}
/**
* Begins the monitoring of changes to the attached File volumes.
*/
public function watch():void
{
if(!timer)
{
timer = new Timer(_interval);
timer.addEventListener(TimerEvent.TIMER, onTimerEvent,false,0, true);
}
//we reinitialize the hash everytime we start watching
volumes = new Dictionary();
var v:Array = FileUtil.getRootDirectories();
for each(var f:File in v)
{
//null or undefined
if(volumes[f.url] == null)
{
volumes[f.url] = f;
}
}
timer.start();
}
/**
* Stops monitoring for changes to the attached File volumes.
*/
public function unwatch():void
{
timer.stop();
timer.removeEventListener(TimerEvent.TIMER, onTimerEvent);
}
private function onTimerEvent(e:TimerEvent):void
{
var v:Array = FileUtil.getRootDirectories();
var outEvent:FileMonitorEvent;
var found:Boolean = false;
for(var key:String in volumes)
{
for each(var f:File in v)
{
//trace("--\n" + key);
//trace(f.url);
if(f.url == key)
{
found = true;
break;
}
}
if(!found)
{
outEvent = new FileMonitorEvent(FileMonitorEvent.REMOVE_VOLUME);
outEvent.file = volumes[key];
dispatchEvent(outEvent);
delete volumes[key];
}
found = false;
}
for each(var f2:File in v)
{
//null or undefined
if(volumes[f2.url] == null)
{
volumes[f2.url] = f2;
outEvent = new FileMonitorEvent(FileMonitorEvent.ADD_VOLUME);
outEvent.file = f2;
dispatchEvent(outEvent);
}
}
}
}
}

View File

@ -0,0 +1,61 @@
/*
Copyright (c) 2009, Adobe Systems Incorporated
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Adobe Systems Incorporated nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.adobe.air.filesystem.events
{
import flash.events.Event;
import flash.filesystem.File;
public class FileMonitorEvent extends Event
{
public static const CHANGE:String = "onFileChange";
public static const MOVE:String = "onFileMove";
public static const CREATE:String = "onFileCreate";
public static const ADD_VOLUME:String = "onVolumeAdd";
public static const REMOVE_VOLUME:String = "onVolumeRemove";
public var file:File;
public function FileMonitorEvent(type:String, bubbles:Boolean=false,
cancelable:Boolean=false)
{
super(type, bubbles, cancelable);
}
public override function clone():Event
{
var out:FileMonitorEvent = new FileMonitorEvent(type, bubbles, cancelable);
out.file = file;
return out;
}
}
}

View File

@ -0,0 +1,95 @@
/*
Copyright (c) 2008, Adobe Systems Incorporated
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Adobe Systems Incorporated nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.adobe.air.logging
{
import flash.filesystem.File;
import flash.filesystem.FileMode;
import flash.filesystem.FileStream;
import mx.core.mx_internal;
import mx.logging.targets.LineFormattedTarget;
use namespace mx_internal;
/**
* An Adobe AIR only class that provides a log target for the Flex logging
* framework, that logs files to a file on the user's system.
*
* This class will only work when running within Adobe AIR>
*/
public class FileTarget extends LineFormattedTarget
{
private const DEFAULT_LOG_PATH:String = "app-storage:/application.log";
private var log:File;
public function FileTarget(logFile:File = null)
{
if(logFile != null)
{
log = logFile;
}
else
{
log = new File(DEFAULT_LOG_PATH);
}
}
public function get logURI():String
{
return log.url;
}
mx_internal override function internalLog(message:String):void
{
write(message);
}
private function write(msg:String):void
{
var fs:FileStream = new FileStream();
fs.open(log, FileMode.APPEND);
fs.writeUTFBytes(msg + File.lineEnding);
fs.close();
}
public function clear():void
{
var fs:FileStream = new FileStream();
fs.open(log, FileMode.WRITE);
fs.writeUTFBytes("");
fs.close();
}
}
}

View File

@ -0,0 +1,165 @@
/*
Copyright (c) 2009, Adobe Systems Incorporated
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Adobe Systems Incorporated nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.adobe.air.net
{
import com.adobe.crypto.MD5;
import com.adobe.net.DynamicURLLoader;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.IOErrorEvent;
import flash.filesystem.File;
import flash.filesystem.FileMode;
import flash.filesystem.FileStream;
import flash.net.URLLoaderDataFormat;
import flash.net.URLRequest;
import flash.utils.ByteArray;
import com.adobe.air.net.events.ResourceCacheEvent;
//todo: add event metadata
public class ResourceCache extends EventDispatcher
{
private var _cacheName:String;
//maybe rename to make it clearer it loads data
public function ResourceCache(cacheName:String)
{
_cacheName = cacheName;
}
public function get cacheName():String
{
return _cacheName;
}
private function getStorageDir():File
{
return File.applicationStorageDirectory.resolvePath(_cacheName);
}
public function itemExists(key:String):Boolean
{
return getItemFile(key).exists;
}
public function clearCache():void
{
var cacheDir:File = getStorageDir();
try
{
cacheDir.deleteDirectory(true);
}
catch (e:IOErrorEvent)
{
// we tried!
}
}
public function getItemFile(key:String):File
{
var dir:File = getStorageDir();
var fName:String = generateKeyHash(key);
var file:File = dir.resolvePath(fName);
return file;
}
public function retrieve(url:String):void
{
var key:String = generateKeyHash(url);
var file:File = getItemFile(key);
//todo: do we need to check if the dir exists?
if(file.exists)
{
var e:ResourceCacheEvent = new ResourceCacheEvent(ResourceCacheEvent.ITEM_READY);
e.key = key;
e.file = file;
dispatchEvent(e);
return;
}
var loader:DynamicURLLoader = new DynamicURLLoader();
loader.file = file;
loader.key = key;
loader.addEventListener(Event.COMPLETE, onDataLoad);
loader.addEventListener(IOErrorEvent.IO_ERROR, onLoadError);
loader.dataFormat = URLLoaderDataFormat.BINARY;
loader.load(new URLRequest(url));
}
private function onLoadError(event:IOErrorEvent):void
{
trace("onLoadError : could not cache item");
}
private function onDataLoad(event:Event):void
{
var loader:DynamicURLLoader = DynamicURLLoader(event.target);
var f:File = File(loader.file);
var key:String = String(loader.key);
var fileStream:FileStream = new FileStream();
fileStream.open(f, FileMode.WRITE);
fileStream.writeBytes(loader.data as ByteArray);
fileStream.close();
var g:ResourceCacheEvent = new ResourceCacheEvent(ResourceCacheEvent.ITEM_CACHED);
g.key = key;
g.file = f;
dispatchEvent(g);
var e:ResourceCacheEvent = new ResourceCacheEvent(ResourceCacheEvent.ITEM_READY);
e.key = key;
e.file = f;
dispatchEvent(e);
}
private function generateKeyHash(key:String):String
{
return MD5.hash(key);
}
}
}

View File

@ -0,0 +1,70 @@
/*
Copyright (c) 2009, Adobe Systems Incorporated
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Adobe Systems Incorporated nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.adobe.air.net.events
{
import flash.events.Event;
import flash.filesystem.File;
public class ResourceCacheEvent extends Event
{
public static const ITEM_READY:String = "onPathReady";
public static const ITEM_CACHED:String = "onItemCached";
[Bindable]
public var key:String;
[Bindable]
public var file:File;
public function ResourceCacheEvent(type:String,
bubbles:Boolean=false,
cancelable:Boolean=false)
{
super(type, bubbles, cancelable);
}
public override function clone():Event
{
var out:ResourceCacheEvent = new ResourceCacheEvent(type,
bubbles,
cancelable);
out.key = key;
out.file = file;
return out;
}
}
}

View File

@ -0,0 +1,127 @@
/*
Copyright (c) 2008, Adobe Systems Incorporated
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Adobe Systems Incorporated nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.adobe.crypto {
import flash.utils.ByteArray;
import flash.utils.Endian;
import flash.utils.describeType;
/**
* Keyed-Hashing for Message Authentication
* Implementation based on algorithm description at
* http://www.faqs.org/rfcs/rfc2104.html
*/
public class HMAC
{
/**
* Performs the HMAC hash algorithm using byte arrays.
*
* @param secret The secret key
* @param message The message to hash
* @param algorithm Hash object to use
* @return A string containing the hash value of message
* @langversion ActionScript 3.0
* @playerversion Flash 8.5
* @tiptext
*/
public static function hash( secret:String, message:String, algorithm:Object = null ):String
{
var text:ByteArray = new ByteArray();
var k_secret:ByteArray = new ByteArray();
text.writeUTFBytes(message);
k_secret.writeUTFBytes(secret);
return hashBytes(k_secret, text, algorithm);
}
/**
* Performs the HMAC hash algorithm using string.
*
* @param secret The secret key
* @param message The message to hash
* @param algorithm Hash object to use
* @return A string containing the hash value of message
* @langversion ActionScript 3.0
* @playerversion Flash 8.5
* @tiptext
*/
public static function hashBytes( secret:ByteArray, message:ByteArray, algorithm:Object = null ):String
{
var ipad:ByteArray = new ByteArray();
var opad:ByteArray = new ByteArray();
var endian:String = Endian.BIG_ENDIAN;
if(algorithm == null){
algorithm = MD5;
}
if ( describeType(algorithm).@name.toString() == "com.adobe.crypto::MD5" ) {
endian = Endian.LITTLE_ENDIAN;
}
if ( secret.length > 64 ) {
algorithm.hashBytes(secret);
secret = new ByteArray();
secret.endian = endian;
while ( algorithm.digest.bytesAvailable != 0 ) {
secret.writeInt(algorithm.digest.readInt());
}
}
secret.length = 64
secret.position = 0;
for ( var x:int = 0; x < 64; x++ ) {
var byte:int = secret.readByte();
ipad.writeByte(0x36 ^ byte);
opad.writeByte(0x5c ^ byte);
}
ipad.writeBytes(message);
algorithm.hashBytes(ipad);
var tmp:ByteArray = new ByteArray();
tmp.endian = endian;
while ( algorithm.digest.bytesAvailable != 0 ) {
tmp.writeInt(algorithm.digest.readInt());
}
tmp.position = 0;
while ( tmp.bytesAvailable != 0 ) {
opad.writeByte(tmp.readUnsignedByte());
}
return algorithm.hashBytes( opad );
}
}
}

View File

@ -0,0 +1,99 @@
/*
Copyright (c) 2008, Adobe Systems Incorporated
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Adobe Systems Incorporated nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.adobe.crypto {
import flash.utils.Endian;
/**
* Contains reusable methods for operations pertaining
* to int values.
*/
public class IntUtil {
/**
* Rotates x left n bits
*
* @langversion ActionScript 3.0
* @playerversion Flash 9.0
* @tiptext
*/
public static function rol ( x:int, n:int ):int {
return ( x << n ) | ( x >>> ( 32 - n ) );
}
/**
* Rotates x right n bits
*
* @langversion ActionScript 3.0
* @playerversion Flash 9.0
* @tiptext
*/
public static function ror ( x:int, n:int ):uint {
var nn:int = 32 - n;
return ( x << nn ) | ( x >>> ( 32 - nn ) );
}
/** String for quick lookup of a hex character based on index */
private static var hexChars:String = "0123456789abcdef";
/**
* Outputs the hex value of a int, allowing the developer to specify
* the endinaness in the process. Hex output is lowercase.
*
* @param n The int value to output as hex
* @param bigEndian Flag to output the int as big or little endian
* @return A string of length 8 corresponding to the
* hex representation of n ( minus the leading "0x" )
* @langversion ActionScript 3.0
* @playerversion Flash 9.0
* @tiptext
*/
public static function toHex( n:int, bigEndian:Boolean = false ):String {
var s:String = "";
if ( bigEndian ) {
for ( var i:int = 0; i < 4; i++ ) {
s += hexChars.charAt( ( n >> ( ( 3 - i ) * 8 + 4 ) ) & 0xF )
+ hexChars.charAt( ( n >> ( ( 3 - i ) * 8 ) ) & 0xF );
}
} else {
for ( var x:int = 0; x < 4; x++ ) {
s += hexChars.charAt( ( n >> ( x * 8 + 4 ) ) & 0xF )
+ hexChars.charAt( ( n >> ( x * 8 ) ) & 0xF );
}
}
return s;
}
}
}

View File

@ -0,0 +1,281 @@
/*
Copyright (c) 2008, Adobe Systems Incorporated
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Adobe Systems Incorporated nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.adobe.crypto {
import com.adobe.crypto.IntUtil;
import flash.utils.ByteArray;
/**
* The MD5 Message-Digest Algorithm
*
* Implementation based on algorithm description at
* http://www.faqs.org/rfcs/rfc1321.html
*/
public class MD5 {
public static var digest:ByteArray;
/**
* Performs the MD5 hash algorithm on a string.
*
* @param s The string to hash
* @return A string containing the hash value of s
* @langversion ActionScript 3.0
* @playerversion Flash 8.5
* @tiptext
*/
public static function hash(s:String) :String{
//Convert to byteArray and send through hashBinary function
// so as to only have complex code in one location
var ba:ByteArray = new ByteArray();
ba.writeUTFBytes(s);
return hashBinary(ba);
}
public static function hashBytes(s:ByteArray) :String{
return hashBinary(s);
}
/**
* Performs the MD5 hash algorithm on a ByteArray.
*
* @param s The string to hash
* @return A string containing the hash value of s
* @langversion ActionScript 3.0
* @playerversion Flash 8.5
* @tiptext
*/
public static function hashBinary( s:ByteArray ):String {
// initialize the md buffers
var a:int = 1732584193;
var b:int = -271733879;
var c:int = -1732584194;
var d:int = 271733878;
// variables to store previous values
var aa:int;
var bb:int;
var cc:int;
var dd:int;
// create the blocks from the string and
// save the length as a local var to reduce
// lookup in the loop below
var x:Array = createBlocks( s );
var len:int = x.length;
// loop over all of the blocks
for ( var i:int = 0; i < len; i += 16) {
// save previous values
aa = a;
bb = b;
cc = c;
dd = d;
// Round 1
a = ff( a, b, c, d, x[int(i+ 0)], 7, -680876936 ); // 1
d = ff( d, a, b, c, x[int(i+ 1)], 12, -389564586 ); // 2
c = ff( c, d, a, b, x[int(i+ 2)], 17, 606105819 ); // 3
b = ff( b, c, d, a, x[int(i+ 3)], 22, -1044525330 ); // 4
a = ff( a, b, c, d, x[int(i+ 4)], 7, -176418897 ); // 5
d = ff( d, a, b, c, x[int(i+ 5)], 12, 1200080426 ); // 6
c = ff( c, d, a, b, x[int(i+ 6)], 17, -1473231341 ); // 7
b = ff( b, c, d, a, x[int(i+ 7)], 22, -45705983 ); // 8
a = ff( a, b, c, d, x[int(i+ 8)], 7, 1770035416 ); // 9
d = ff( d, a, b, c, x[int(i+ 9)], 12, -1958414417 ); // 10
c = ff( c, d, a, b, x[int(i+10)], 17, -42063 ); // 11
b = ff( b, c, d, a, x[int(i+11)], 22, -1990404162 ); // 12
a = ff( a, b, c, d, x[int(i+12)], 7, 1804603682 ); // 13
d = ff( d, a, b, c, x[int(i+13)], 12, -40341101 ); // 14
c = ff( c, d, a, b, x[int(i+14)], 17, -1502002290 ); // 15
b = ff( b, c, d, a, x[int(i+15)], 22, 1236535329 ); // 16
// Round 2
a = gg( a, b, c, d, x[int(i+ 1)], 5, -165796510 ); // 17
d = gg( d, a, b, c, x[int(i+ 6)], 9, -1069501632 ); // 18
c = gg( c, d, a, b, x[int(i+11)], 14, 643717713 ); // 19
b = gg( b, c, d, a, x[int(i+ 0)], 20, -373897302 ); // 20
a = gg( a, b, c, d, x[int(i+ 5)], 5, -701558691 ); // 21
d = gg( d, a, b, c, x[int(i+10)], 9, 38016083 ); // 22
c = gg( c, d, a, b, x[int(i+15)], 14, -660478335 ); // 23
b = gg( b, c, d, a, x[int(i+ 4)], 20, -405537848 ); // 24
a = gg( a, b, c, d, x[int(i+ 9)], 5, 568446438 ); // 25
d = gg( d, a, b, c, x[int(i+14)], 9, -1019803690 ); // 26
c = gg( c, d, a, b, x[int(i+ 3)], 14, -187363961 ); // 27
b = gg( b, c, d, a, x[int(i+ 8)], 20, 1163531501 ); // 28
a = gg( a, b, c, d, x[int(i+13)], 5, -1444681467 ); // 29
d = gg( d, a, b, c, x[int(i+ 2)], 9, -51403784 ); // 30
c = gg( c, d, a, b, x[int(i+ 7)], 14, 1735328473 ); // 31
b = gg( b, c, d, a, x[int(i+12)], 20, -1926607734 ); // 32
// Round 3
a = hh( a, b, c, d, x[int(i+ 5)], 4, -378558 ); // 33
d = hh( d, a, b, c, x[int(i+ 8)], 11, -2022574463 ); // 34
c = hh( c, d, a, b, x[int(i+11)], 16, 1839030562 ); // 35
b = hh( b, c, d, a, x[int(i+14)], 23, -35309556 ); // 36
a = hh( a, b, c, d, x[int(i+ 1)], 4, -1530992060 ); // 37
d = hh( d, a, b, c, x[int(i+ 4)], 11, 1272893353 ); // 38
c = hh( c, d, a, b, x[int(i+ 7)], 16, -155497632 ); // 39
b = hh( b, c, d, a, x[int(i+10)], 23, -1094730640 ); // 40
a = hh( a, b, c, d, x[int(i+13)], 4, 681279174 ); // 41
d = hh( d, a, b, c, x[int(i+ 0)], 11, -358537222 ); // 42
c = hh( c, d, a, b, x[int(i+ 3)], 16, -722521979 ); // 43
b = hh( b, c, d, a, x[int(i+ 6)], 23, 76029189 ); // 44
a = hh( a, b, c, d, x[int(i+ 9)], 4, -640364487 ); // 45
d = hh( d, a, b, c, x[int(i+12)], 11, -421815835 ); // 46
c = hh( c, d, a, b, x[int(i+15)], 16, 530742520 ); // 47
b = hh( b, c, d, a, x[int(i+ 2)], 23, -995338651 ); // 48
// Round 4
a = ii( a, b, c, d, x[int(i+ 0)], 6, -198630844 ); // 49
d = ii( d, a, b, c, x[int(i+ 7)], 10, 1126891415 ); // 50
c = ii( c, d, a, b, x[int(i+14)], 15, -1416354905 ); // 51
b = ii( b, c, d, a, x[int(i+ 5)], 21, -57434055 ); // 52
a = ii( a, b, c, d, x[int(i+12)], 6, 1700485571 ); // 53
d = ii( d, a, b, c, x[int(i+ 3)], 10, -1894986606 ); // 54
c = ii( c, d, a, b, x[int(i+10)], 15, -1051523 ); // 55
b = ii( b, c, d, a, x[int(i+ 1)], 21, -2054922799 ); // 56
a = ii( a, b, c, d, x[int(i+ 8)], 6, 1873313359 ); // 57
d = ii( d, a, b, c, x[int(i+15)], 10, -30611744 ); // 58
c = ii( c, d, a, b, x[int(i+ 6)], 15, -1560198380 ); // 59
b = ii( b, c, d, a, x[int(i+13)], 21, 1309151649 ); // 60
a = ii( a, b, c, d, x[int(i+ 4)], 6, -145523070 ); // 61
d = ii( d, a, b, c, x[int(i+11)], 10, -1120210379 ); // 62
c = ii( c, d, a, b, x[int(i+ 2)], 15, 718787259 ); // 63
b = ii( b, c, d, a, x[int(i+ 9)], 21, -343485551 ); // 64
a += aa;
b += bb;
c += cc;
d += dd;
}
digest = new ByteArray()
digest.writeInt(a);
digest.writeInt(b);
digest.writeInt(c);
digest.writeInt(d);
digest.position = 0;
// Finish up by concatening the buffers with their hex output
return IntUtil.toHex( a ) + IntUtil.toHex( b ) + IntUtil.toHex( c ) + IntUtil.toHex( d );
}
/**
* Auxiliary function f as defined in RFC
*/
private static function f( x:int, y:int, z:int ):int {
return ( x & y ) | ( (~x) & z );
}
/**
* Auxiliary function g as defined in RFC
*/
private static function g( x:int, y:int, z:int ):int {
return ( x & z ) | ( y & (~z) );
}
/**
* Auxiliary function h as defined in RFC
*/
private static function h( x:int, y:int, z:int ):int {
return x ^ y ^ z;
}
/**
* Auxiliary function i as defined in RFC
*/
private static function i( x:int, y:int, z:int ):int {
return y ^ ( x | (~z) );
}
/**
* A generic transformation function. The logic of ff, gg, hh, and
* ii are all the same, minus the function used, so pull that logic
* out and simplify the method bodies for the transoformation functions.
*/
private static function transform( func:Function, a:int, b:int, c:int, d:int, x:int, s:int, t:int):int {
var tmp:int = a + int( func( b, c, d ) ) + x + t;
return IntUtil.rol( tmp, s ) + b;
}
/**
* ff transformation function
*/
private static function ff ( a:int, b:int, c:int, d:int, x:int, s:int, t:int ):int {
return transform( f, a, b, c, d, x, s, t );
}
/**
* gg transformation function
*/
private static function gg ( a:int, b:int, c:int, d:int, x:int, s:int, t:int ):int {
return transform( g, a, b, c, d, x, s, t );
}
/**
* hh transformation function
*/
private static function hh ( a:int, b:int, c:int, d:int, x:int, s:int, t:int ):int {
return transform( h, a, b, c, d, x, s, t );
}
/**
* ii transformation function
*/
private static function ii ( a:int, b:int, c:int, d:int, x:int, s:int, t:int ):int {
return transform( i, a, b, c, d, x, s, t );
}
/**
* Converts a string to a sequence of 16-word blocks
* that we'll do the processing on. Appends padding
* and length in the process.
*
* @param s The string to split into blocks
* @return An array containing the blocks that s was
* split into.
*/
private static function createBlocks( s:ByteArray ):Array {
var blocks:Array = new Array();
var len:int = s.length * 8;
var mask:int = 0xFF; // ignore hi byte of characters > 0xFF
for( var i:int = 0; i < len; i += 8 ) {
blocks[ int(i >> 5) ] |= ( s[ i / 8 ] & mask ) << ( i % 32 );
}
// append padding and length
blocks[ int(len >> 5) ] |= 0x80 << ( len % 32 );
blocks[ int(( ( ( len + 64 ) >>> 9 ) << 4 ) + 14) ] = len;
return blocks;
}
}
}

View File

@ -0,0 +1,402 @@
/*
Copyright (c) 2008, Adobe Systems Incorporated
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Adobe Systems Incorporated nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.adobe.crypto
{
import com.adobe.utils.IntUtil;
import flash.utils.ByteArray;
/**
* Perform MD5 hash of an input stream in chunks. This class is
* based on com.adobe.crypto.MD5 and can process data in
* chunks. Both block creation and hash computation are done
* together for whatever input is available so that the memory
* overhead at a time is always fixed. Memory usage is governed by
* two parameters: one is the amount of data passed in to update()
* and the other is memoryBlockSize. The latter comes into play
* only when the memory window exceeds the pre allocated memory
* window of flash player. Usage: create an instance, call
* update(data) repeatedly for all chunks and finally complete()
* which will return the md5 hash.
*/
public class MD5Stream
{
private static var mask:int = 0xFF;
private var arr:Array = [];
/* running count of length */
private var arrLen:int;
// initialize the md buffers
private var a:int = 1732584193;
private var b:int = -271733879;
private var c:int = -1732584194;
private var d:int = 271733878;
// variables to store previous values
private var aa:int;
private var bb:int;
private var cc:int;
private var dd:int;
/* index for data read */
private var arrIndexLen:int = 0;
/* index for hash computation */
private var arrProcessIndex:int = 0;
/* index for removing stale arr values */
private var cleanIndex:int = 0;
/**
* Change this value from the default (16384) in the range of
* MBs to actually affect GC as GC allocates in pools of
* memory */
public var memoryBlockSize:int = 16384;
public function MD5Stream()
{
}
/**
* Pass in chunks of the input data with update(), call
* complete() with an optional chunk which will return the
* final hash. Equivalent to the way
* java.security.MessageDigest works.
*
* @param input The optional bytearray chunk which is the final part of the input
* @return A string containing the hash value
* @langversion ActionScript 3.0
* @playerversion Flash 8.5
* @tiptext
*/
public function complete(input:ByteArray=null):String
{
if ( arr.length == 0 )
{
if ( input == null )
{
throw new Error("null input to complete without prior call to update. At least an empty bytearray must be passed.");
}
}
if ( input != null )
{
readIntoArray(input);
}
//pad, append length
padArray(arrLen);
hashRemainingChunks(false);
var res:String = IntUtil.toHex( a ) + IntUtil.toHex( b ) +
IntUtil.toHex( c ) + IntUtil.toHex( d );
resetFields();
return res;
}
/**
* Pass in chunks of the input data with update(), call
* complete() with an optional chunk which will return the
* final hash. Equivalent to the way
* java.security.MessageDigest works.
*
* @param input The bytearray chunk to perform the hash on
* @langversion ActionScript 3.0
* @playerversion Flash 8.5
* @tiptext
*/
public function update(input:ByteArray):void
{
readIntoArray(input);
hashRemainingChunks();
}
/**
* Re-initialize this instance for use to perform hashing on
* another input stream. This is called automatically by
* complete().
*
* @langversion ActionScript 3.0
* @playerversion Flash 8.5
* @tiptext
*/
public function resetFields():void
{
//truncate array
arr.length = 0;
arrLen = 0;
// initialize the md buffers
a = 1732584193;
b = -271733879;
c = -1732584194;
d = 271733878;
// variables to store previous values
aa = 0;
bb = 0;
cc = 0;
dd = 0;
arrIndexLen = 0;
arrProcessIndex = 0;
cleanIndex = 0;
}
/** read into arr and free up used blocks of arr */
private function readIntoArray(input:ByteArray):void
{
var closestChunkLen:int = input.length * 8;
arrLen += closestChunkLen;
/* clean up memory. if there are entries in the array that
* are already processed and the amount is greater than
* memoryBlockSize, create a new array, copy the last
* block into it and let the old one get picked up by
* GC. */
if ( arrProcessIndex - cleanIndex > memoryBlockSize )
{
var newarr:Array= new Array();
/* AS Arrays in sparse arrays. arr[2002] can exist
* without values for arr[0] - arr[2001] */
for ( var j:int = arrProcessIndex; j < arr.length; j++ )
{
newarr[j] = arr[j];
}
cleanIndex = arrProcessIndex;
arr = null;
arr = newarr;
}
for ( var k:int = 0; k < closestChunkLen; k+=8 )
{
//discard high bytes (convert to uint)
arr[ int(arrIndexLen >> 5) ] |= ( input[ k / 8 ] & mask ) << ( arrIndexLen % 32 );
arrIndexLen += 8;
}
}
private function hashRemainingChunks(bUpdate:Boolean=true):void
{
var len:int = arr.length;
/* leave a 16 word block untouched if we are called from
* update. This is because, padArray() can modify the last
* block and this modification has to happen before we
* compute the hash. */
if ( bUpdate )
{
len -= 16;
}
/* don't do anything if don't have a 16 word block. */
if ( arrProcessIndex >= len || len - arrProcessIndex < 15 )
{
return;
}
for ( var i:int = arrProcessIndex; i < len ; i += 16, arrProcessIndex += 16)
{
// save previous values
aa = a;
bb = b;
cc = c;
dd = d;
// Round 1
a = ff( a, b, c, d, arr[int(i+ 0)], 7, -680876936 ); // 1
d = ff( d, a, b, c, arr[int(i+ 1)], 12, -389564586 ); // 2
c = ff( c, d, a, b, arr[int(i+ 2)], 17, 606105819 ); // 3
b = ff( b, c, d, a, arr[int(i+ 3)], 22, -1044525330 ); // 4
a = ff( a, b, c, d, arr[int(i+ 4)], 7, -176418897 ); // 5
d = ff( d, a, b, c, arr[int(i+ 5)], 12, 1200080426 ); // 6
c = ff( c, d, a, b, arr[int(i+ 6)], 17, -1473231341 ); // 7
b = ff( b, c, d, a, arr[int(i+ 7)], 22, -45705983 ); // 8
a = ff( a, b, c, d, arr[int(i+ 8)], 7, 1770035416 ); // 9
d = ff( d, a, b, c, arr[int(i+ 9)], 12, -1958414417 ); // 10
c = ff( c, d, a, b, arr[int(i+10)], 17, -42063 ); // 11
b = ff( b, c, d, a, arr[int(i+11)], 22, -1990404162 ); // 12
a = ff( a, b, c, d, arr[int(i+12)], 7, 1804603682 ); // 13
d = ff( d, a, b, c, arr[int(i+13)], 12, -40341101 ); // 14
c = ff( c, d, a, b, arr[int(i+14)], 17, -1502002290 ); // 15
b = ff( b, c, d, a, arr[int(i+15)], 22, 1236535329 ); // 16
// Round 2
a = gg( a, b, c, d, arr[int(i+ 1)], 5, -165796510 ); // 17
d = gg( d, a, b, c, arr[int(i+ 6)], 9, -1069501632 ); // 18
c = gg( c, d, a, b, arr[int(i+11)], 14, 643717713 ); // 19
b = gg( b, c, d, a, arr[int(i+ 0)], 20, -373897302 ); // 20
a = gg( a, b, c, d, arr[int(i+ 5)], 5, -701558691 ); // 21
d = gg( d, a, b, c, arr[int(i+10)], 9, 38016083 ); // 22
c = gg( c, d, a, b, arr[int(i+15)], 14, -660478335 ); // 23
b = gg( b, c, d, a, arr[int(i+ 4)], 20, -405537848 ); // 24
a = gg( a, b, c, d, arr[int(i+ 9)], 5, 568446438 ); // 25
d = gg( d, a, b, c, arr[int(i+14)], 9, -1019803690 ); // 26
c = gg( c, d, a, b, arr[int(i+ 3)], 14, -187363961 ); // 27
b = gg( b, c, d, a, arr[int(i+ 8)], 20, 1163531501 ); // 28
a = gg( a, b, c, d, arr[int(i+13)], 5, -1444681467 ); // 29
d = gg( d, a, b, c, arr[int(i+ 2)], 9, -51403784 ); // 30
c = gg( c, d, a, b, arr[int(i+ 7)], 14, 1735328473 ); // 31
b = gg( b, c, d, a, arr[int(i+12)], 20, -1926607734 ); // 32
// Round 3
a = hh( a, b, c, d, arr[int(i+ 5)], 4, -378558 ); // 33
d = hh( d, a, b, c, arr[int(i+ 8)], 11, -2022574463 ); // 34
c = hh( c, d, a, b, arr[int(i+11)], 16, 1839030562 ); // 35
b = hh( b, c, d, a, arr[int(i+14)], 23, -35309556 ); // 36
a = hh( a, b, c, d, arr[int(i+ 1)], 4, -1530992060 ); // 37
d = hh( d, a, b, c, arr[int(i+ 4)], 11, 1272893353 ); // 38
c = hh( c, d, a, b, arr[int(i+ 7)], 16, -155497632 ); // 39
b = hh( b, c, d, a, arr[int(i+10)], 23, -1094730640 ); // 40
a = hh( a, b, c, d, arr[int(i+13)], 4, 681279174 ); // 41
d = hh( d, a, b, c, arr[int(i+ 0)], 11, -358537222 ); // 42
c = hh( c, d, a, b, arr[int(i+ 3)], 16, -722521979 ); // 43
b = hh( b, c, d, a, arr[int(i+ 6)], 23, 76029189 ); // 44
a = hh( a, b, c, d, arr[int(i+ 9)], 4, -640364487 ); // 45
d = hh( d, a, b, c, arr[int(i+12)], 11, -421815835 ); // 46
c = hh( c, d, a, b, arr[int(i+15)], 16, 530742520 ); // 47
b = hh( b, c, d, a, arr[int(i+ 2)], 23, -995338651 ); // 48
// Round 4
a = ii( a, b, c, d, arr[int(i+ 0)], 6, -198630844 ); // 49
d = ii( d, a, b, c, arr[int(i+ 7)], 10, 1126891415 ); // 50
c = ii( c, d, a, b, arr[int(i+14)], 15, -1416354905 ); // 51
b = ii( b, c, d, a, arr[int(i+ 5)], 21, -57434055 ); // 52
a = ii( a, b, c, d, arr[int(i+12)], 6, 1700485571 ); // 53
d = ii( d, a, b, c, arr[int(i+ 3)], 10, -1894986606 ); // 54
c = ii( c, d, a, b, arr[int(i+10)], 15, -1051523 ); // 55
b = ii( b, c, d, a, arr[int(i+ 1)], 21, -2054922799 ); // 56
a = ii( a, b, c, d, arr[int(i+ 8)], 6, 1873313359 ); // 57
d = ii( d, a, b, c, arr[int(i+15)], 10, -30611744 ); // 58
c = ii( c, d, a, b, arr[int(i+ 6)], 15, -1560198380 ); // 59
b = ii( b, c, d, a, arr[int(i+13)], 21, 1309151649 ); // 60
a = ii( a, b, c, d, arr[int(i+ 4)], 6, -145523070 ); // 61
d = ii( d, a, b, c, arr[int(i+11)], 10, -1120210379 ); // 62
c = ii( c, d, a, b, arr[int(i+ 2)], 15, 718787259 ); // 63
b = ii( b, c, d, a, arr[int(i+ 9)], 21, -343485551 ); // 64
a += aa;
b += bb;
c += cc;
d += dd;
}
}
private function padArray(len:int):void
{
arr[ int(len >> 5) ] |= 0x80 << ( len % 32 );
arr[ int(( ( ( len + 64 ) >>> 9 ) << 4 ) + 14) ] = len;
arrLen = arr.length;
}
/* Code below same as com.adobe.crypto.MD5 */
/**
* Auxiliary function f as defined in RFC
*/
private static function f( x:int, y:int, z:int ):int {
return ( x & y ) | ( (~x) & z );
}
/**
* Auxiliary function g as defined in RFC
*/
private static function g( x:int, y:int, z:int ):int {
return ( x & z ) | ( y & (~z) );
}
/**
* Auxiliary function h as defined in RFC
*/
private static function h( x:int, y:int, z:int ):int {
return x ^ y ^ z;
}
/**
* Auxiliary function i as defined in RFC
*/
private static function i( x:int, y:int, z:int ):int {
return y ^ ( x | (~z) );
}
/**
* A generic transformation function. The logic of ff, gg, hh, and
* ii are all the same, minus the function used, so pull that logic
* out and simplify the method bodies for the transoformation functions.
*/
private static function transform( func:Function, a:int, b:int, c:int, d:int, x:int, s:int, t:int):int {
var tmp:int = a + int( func( b, c, d ) ) + x + t;
return IntUtil.rol( tmp, s ) + b;
}
/**
* ff transformation function
*/
private static function ff ( a:int, b:int, c:int, d:int, x:int, s:int, t:int ):int {
return transform( f, a, b, c, d, x, s, t );
}
/**
* gg transformation function
*/
private static function gg ( a:int, b:int, c:int, d:int, x:int, s:int, t:int ):int {
return transform( g, a, b, c, d, x, s, t );
}
/**
* hh transformation function
*/
private static function hh ( a:int, b:int, c:int, d:int, x:int, s:int, t:int ):int {
return transform( h, a, b, c, d, x, s, t );
}
/**
* ii transformation function
*/
private static function ii ( a:int, b:int, c:int, d:int, x:int, s:int, t:int ):int {
return transform( i, a, b, c, d, x, s, t );
}
}
}

View File

@ -0,0 +1,289 @@
/*
Copyright (c) 2008, Adobe Systems Incorporated
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Adobe Systems Incorporated nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.adobe.crypto
{
import com.adobe.utils.IntUtil;
import flash.utils.ByteArray;
import mx.utils.Base64Encoder;
/**
* US Secure Hash Algorithm 1 (SHA1)
*
* Implementation based on algorithm description at
* http://www.faqs.org/rfcs/rfc3174.html
*/
public class SHA1
{
public static var digest:ByteArray;
/**
* Performs the SHA1 hash algorithm on a string.
*
* @param s The string to hash
* @return A string containing the hash value of s
* @langversion ActionScript 3.0
* @playerversion 9.0
* @tiptext
*/
public static function hash( s:String ):String
{
var blocks:Array = createBlocksFromString( s );
var byteArray:ByteArray = hashBlocks( blocks );
return IntUtil.toHex( byteArray.readInt(), true )
+ IntUtil.toHex( byteArray.readInt(), true )
+ IntUtil.toHex( byteArray.readInt(), true )
+ IntUtil.toHex( byteArray.readInt(), true )
+ IntUtil.toHex( byteArray.readInt(), true );
}
/**
* Performs the SHA1 hash algorithm on a ByteArray.
*
* @param data The ByteArray data to hash
* @return A string containing the hash value of data
* @langversion ActionScript 3.0
* @playerversion 9.0
*/
public static function hashBytes( data:ByteArray ):String
{
var blocks:Array = SHA1.createBlocksFromByteArray( data );
var byteArray:ByteArray = hashBlocks(blocks);
return IntUtil.toHex( byteArray.readInt(), true )
+ IntUtil.toHex( byteArray.readInt(), true )
+ IntUtil.toHex( byteArray.readInt(), true )
+ IntUtil.toHex( byteArray.readInt(), true )
+ IntUtil.toHex( byteArray.readInt(), true );
}
/**
* Performs the SHA1 hash algorithm on a string, then does
* Base64 encoding on the result.
*
* @param s The string to hash
* @return The base64 encoded hash value of s
* @langversion ActionScript 3.0
* @playerversion 9.0
* @tiptext
*/
public static function hashToBase64( s:String ):String
{
var blocks:Array = SHA1.createBlocksFromString( s );
var byteArray:ByteArray = hashBlocks(blocks);
// ByteArray.toString() returns the contents as a UTF-8 string,
// which we can't use because certain byte sequences might trigger
// a UTF-8 conversion. Instead, we convert the bytes to characters
// one by one.
var charsInByteArray:String = "";
byteArray.position = 0;
for (var j:int = 0; j < byteArray.length; j++)
{
var byte:uint = byteArray.readUnsignedByte();
charsInByteArray += String.fromCharCode(byte);
}
var encoder:Base64Encoder = new Base64Encoder();
encoder.encode(charsInByteArray);
return encoder.flush();
}
private static function hashBlocks( blocks:Array ):ByteArray
{
// initialize the h's
var h0:int = 0x67452301;
var h1:int = 0xefcdab89;
var h2:int = 0x98badcfe;
var h3:int = 0x10325476;
var h4:int = 0xc3d2e1f0;
var len:int = blocks.length;
var w:Array = new Array( 80 );
var temp:int;
// loop over all of the blocks
for ( var i:int = 0; i < len; i += 16 ) {
// 6.1.c
var a:int = h0;
var b:int = h1;
var c:int = h2;
var d:int = h3;
var e:int = h4;
// 80 steps to process each block
var t:int;
for ( t = 0; t < 20; t++ ) {
if ( t < 16 ) {
// 6.1.a
w[ t ] = blocks[ i + t ];
} else {
// 6.1.b
temp = w[ t - 3 ] ^ w[ t - 8 ] ^ w[ t - 14 ] ^ w[ t - 16 ];
w[ t ] = ( temp << 1 ) | ( temp >>> 31 )
}
// 6.1.d
temp = ( ( a << 5 ) | ( a >>> 27 ) ) + ( ( b & c ) | ( ~b & d ) ) + e + int( w[ t ] ) + 0x5a827999;
e = d;
d = c;
c = ( b << 30 ) | ( b >>> 2 );
b = a;
a = temp;
}
for ( ; t < 40; t++ )
{
// 6.1.b
temp = w[ t - 3 ] ^ w[ t - 8 ] ^ w[ t - 14 ] ^ w[ t - 16 ];
w[ t ] = ( temp << 1 ) | ( temp >>> 31 )
// 6.1.d
temp = ( ( a << 5 ) | ( a >>> 27 ) ) + ( b ^ c ^ d ) + e + int( w[ t ] ) + 0x6ed9eba1;
e = d;
d = c;
c = ( b << 30 ) | ( b >>> 2 );
b = a;
a = temp;
}
for ( ; t < 60; t++ )
{
// 6.1.b
temp = w[ t - 3 ] ^ w[ t - 8 ] ^ w[ t - 14 ] ^ w[ t - 16 ];
w[ t ] = ( temp << 1 ) | ( temp >>> 31 )
// 6.1.d
temp = ( ( a << 5 ) | ( a >>> 27 ) ) + ( ( b & c ) | ( b & d ) | ( c & d ) ) + e + int( w[ t ] ) + 0x8f1bbcdc;
e = d;
d = c;
c = ( b << 30 ) | ( b >>> 2 );
b = a;
a = temp;
}
for ( ; t < 80; t++ )
{
// 6.1.b
temp = w[ t - 3 ] ^ w[ t - 8 ] ^ w[ t - 14 ] ^ w[ t - 16 ];
w[ t ] = ( temp << 1 ) | ( temp >>> 31 )
// 6.1.d
temp = ( ( a << 5 ) | ( a >>> 27 ) ) + ( b ^ c ^ d ) + e + int( w[ t ] ) + 0xca62c1d6;
e = d;
d = c;
c = ( b << 30 ) | ( b >>> 2 );
b = a;
a = temp;
}
// 6.1.e
h0 += a;
h1 += b;
h2 += c;
h3 += d;
h4 += e;
}
var byteArray:ByteArray = new ByteArray();
byteArray.writeInt(h0);
byteArray.writeInt(h1);
byteArray.writeInt(h2);
byteArray.writeInt(h3);
byteArray.writeInt(h4);
byteArray.position = 0;
digest = new ByteArray();
digest.writeBytes(byteArray);
digest.position = 0;
return byteArray;
}
/**
* Converts a ByteArray to a sequence of 16-word blocks
* that we'll do the processing on. Appends padding
* and length in the process.
*
* @param data The data to split into blocks
* @return An array containing the blocks into which data was split
*/
private static function createBlocksFromByteArray( data:ByteArray ):Array
{
var oldPosition:int = data.position;
data.position = 0;
var blocks:Array = new Array();
var len:int = data.length * 8;
var mask:int = 0xFF; // ignore hi byte of characters > 0xFF
for( var i:int = 0; i < len; i += 8 )
{
blocks[ i >> 5 ] |= ( data.readByte() & mask ) << ( 24 - i % 32 );
}
// append padding and length
blocks[ len >> 5 ] |= 0x80 << ( 24 - len % 32 );
blocks[ ( ( ( len + 64 ) >> 9 ) << 4 ) + 15 ] = len;
data.position = oldPosition;
return blocks;
}
/**
* Converts a string to a sequence of 16-word blocks
* that we'll do the processing on. Appends padding
* and length in the process.
*
* @param s The string to split into blocks
* @return An array containing the blocks that s was split into.
*/
private static function createBlocksFromString( s:String ):Array
{
var blocks:Array = new Array();
var len:int = s.length * 8;
var mask:int = 0xFF; // ignore hi byte of characters > 0xFF
for( var i:int = 0; i < len; i += 8 ) {
blocks[ i >> 5 ] |= ( s.charCodeAt( i / 8 ) & mask ) << ( 24 - i % 32 );
}
// append padding and length
blocks[ len >> 5 ] |= 0x80 << ( 24 - len % 32 );
blocks[ ( ( ( len + 64 ) >> 9 ) << 4 ) + 15 ] = len;
return blocks;
}
}
}

View File

@ -0,0 +1,257 @@
/*
Copyright (c) 2008, Adobe Systems Incorporated
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Adobe Systems Incorporated nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.adobe.crypto
{
import com.adobe.utils.IntUtil;
import flash.utils.ByteArray;
import mx.utils.Base64Encoder;
/**
* The SHA-224 algorithm
*
* @see http://csrc.nist.gov/publications/fips/fips180-2/fips180-2withchangenotice.pdf
*/
public class SHA224
{
public static var digest:ByteArray;
/**
* Performs the SHA224 hash algorithm on a string.
*
* @param s The string to hash
* @return A string containing the hash value of s
* @langversion ActionScript 3.0
* @playerversion 9.0
* @tiptext
*/
public static function hash( s:String ):String {
var blocks:Array = createBlocksFromString( s );
var byteArray:ByteArray = hashBlocks( blocks );
return IntUtil.toHex( byteArray.readInt(), true )
+ IntUtil.toHex( byteArray.readInt(), true )
+ IntUtil.toHex( byteArray.readInt(), true )
+ IntUtil.toHex( byteArray.readInt(), true )
+ IntUtil.toHex( byteArray.readInt(), true )
+ IntUtil.toHex( byteArray.readInt(), true )
+ IntUtil.toHex( byteArray.readInt(), true );
}
/**
* Performs the SHA224 hash algorithm on a ByteArray.
*
* @param data The ByteArray data to hash
* @return A string containing the hash value of data
* @langversion ActionScript 3.0
* @playerversion 9.0
*/
public static function hashBytes( data:ByteArray ):String
{
var blocks:Array = createBlocksFromByteArray( data );
var byteArray:ByteArray = hashBlocks(blocks);
return IntUtil.toHex( byteArray.readInt(), true )
+ IntUtil.toHex( byteArray.readInt(), true )
+ IntUtil.toHex( byteArray.readInt(), true )
+ IntUtil.toHex( byteArray.readInt(), true )
+ IntUtil.toHex( byteArray.readInt(), true )
+ IntUtil.toHex( byteArray.readInt(), true )
+ IntUtil.toHex( byteArray.readInt(), true );
}
/**
* Performs the SHA224 hash algorithm on a string, then does
* Base64 encoding on the result.
*
* @param s The string to hash
* @return The base64 encoded hash value of s
* @langversion ActionScript 3.0
* @playerversion 9.0
* @tiptext
*/
public static function hashToBase64( s:String ):String
{
var blocks:Array = createBlocksFromString( s );
var byteArray:ByteArray = hashBlocks(blocks);
// ByteArray.toString() returns the contents as a UTF-8 string,
// which we can't use because certain byte sequences might trigger
// a UTF-8 conversion. Instead, we convert the bytes to characters
// one by one.
var charsInByteArray:String = "";
byteArray.position = 0;
for (var j:int = 0; j < byteArray.length; j++)
{
var byte:uint = byteArray.readUnsignedByte();
charsInByteArray += String.fromCharCode(byte);
}
var encoder:Base64Encoder = new Base64Encoder();
encoder.encode(charsInByteArray);
return encoder.flush();
}
private static function hashBlocks( blocks:Array ):ByteArray {
var h0:int = 0xc1059ed8;
var h1:int = 0x367cd507;
var h2:int = 0x3070dd17;
var h3:int = 0xf70e5939;
var h4:int = 0xffc00b31;
var h5:int = 0x68581511;
var h6:int = 0x64f98fa7;
var h7:int = 0xbefa4fa4;
var k:Array = new Array(0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2);
var len:int = blocks.length;
var w:Array = new Array();
// loop over all of the blocks
for ( var i:int = 0; i < len; i += 16 ) {
var a:int = h0;
var b:int = h1;
var c:int = h2;
var d:int = h3;
var e:int = h4;
var f:int = h5;
var g:int = h6;
var h:int = h7;
for(var t:int = 0; t < 64; t++) {
if ( t < 16 ) {
w[t] = blocks[ i + t ];
if(isNaN(w[t])) { w[t] = 0; }
} else {
var ws0:int = IntUtil.ror(w[t-15], 7) ^ IntUtil.ror(w[t-15], 18) ^ (w[t-15] >>> 3);
var ws1:int = IntUtil.ror(w[t-2], 17) ^ IntUtil.ror(w[t-2], 19) ^ (w[t-2] >>> 10);
w[t] = w[t-16] + ws0 + w[t-7] + ws1;
}
var s0:int = IntUtil.ror(a, 2) ^ IntUtil.ror(a, 13) ^ IntUtil.ror(a, 22);
var maj:int = (a & b) ^ (a & c) ^ (b & c);
var t2:int = s0 + maj;
var s1:int = IntUtil.ror(e, 6) ^ IntUtil.ror(e, 11) ^ IntUtil.ror(e, 25);
var ch:int = (e & f) ^ ((~e) & g);
var t1:int = h + s1 + ch + k[t] + w[t];
h = g;
g = f;
f = e;
e = d + t1;
d = c;
c = b;
b = a;
a = t1 + t2;
}
//Add this chunk's hash to result so far:
h0 += a;
h1 += b;
h2 += c;
h3 += d;
h4 += e;
h5 += f;
h6 += g;
h7 += h;
}
var byteArray:ByteArray = new ByteArray();
byteArray.writeInt(h0);
byteArray.writeInt(h1);
byteArray.writeInt(h2);
byteArray.writeInt(h3);
byteArray.writeInt(h4);
byteArray.writeInt(h5);
byteArray.writeInt(h6);
byteArray.position = 0;
digest = new ByteArray();
digest.writeBytes(byteArray);
digest.position = 0;
return byteArray;
}
/**
* Converts a ByteArray to a sequence of 16-word blocks
* that we'll do the processing on. Appends padding
* and length in the process.
*
* @param data The data to split into blocks
* @return An array containing the blocks into which data was split
*/
private static function createBlocksFromByteArray( data:ByteArray ):Array
{
var oldPosition:int = data.position;
data.position = 0;
var blocks:Array = new Array();
var len:int = data.length * 8;
var mask:int = 0xFF; // ignore hi byte of characters > 0xFF
for( var i:int = 0; i < len; i += 8 )
{
blocks[ i >> 5 ] |= ( data.readByte() & mask ) << ( 24 - i % 32 );
}
// append padding and length
blocks[ len >> 5 ] |= 0x80 << ( 24 - len % 32 );
blocks[ ( ( ( len + 64 ) >> 9 ) << 4 ) + 15 ] = len;
data.position = oldPosition;
return blocks;
}
/**
* Converts a string to a sequence of 16-word blocks
* that we'll do the processing on. Appends padding
* and length in the process.
*
* @param s The string to split into blocks
* @return An array containing the blocks that s was split into.
*/
private static function createBlocksFromString( s:String ):Array
{
var blocks:Array = new Array();
var len:int = s.length * 8;
var mask:int = 0xFF; // ignore hi byte of characters > 0xFF
for( var i:int = 0; i < len; i += 8 ) {
blocks[ i >> 5 ] |= ( s.charCodeAt( i / 8 ) & mask ) << ( 24 - i % 32 );
}
// append padding and length
blocks[ len >> 5 ] |= 0x80 << ( 24 - len % 32 );
blocks[ ( ( ( len + 64 ) >> 9 ) << 4 ) + 15 ] = len;
return blocks;
}
}
}

View File

@ -0,0 +1,261 @@
/*
Copyright (c) 2008, Adobe Systems Incorporated
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Adobe Systems Incorporated nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.adobe.crypto
{
import com.adobe.utils.IntUtil;
import flash.utils.ByteArray;
import mx.utils.Base64Encoder;
/**
* The SHA-256 algorithm
*
* @see http://csrc.nist.gov/publications/fips/fips180-2/fips180-2withchangenotice.pdf
*/
public class SHA256
{
public static var digest:ByteArray;
/**
* Performs the SHA256 hash algorithm on a string.
*
* @param s The string to hash
* @return A string containing the hash value of s
* @langversion ActionScript 3.0
* @playerversion 9.0
* @tiptext
*/
public static function hash( s:String ):String {
var blocks:Array = createBlocksFromString( s );
var byteArray:ByteArray = hashBlocks( blocks );
return IntUtil.toHex( byteArray.readInt(), true )
+ IntUtil.toHex( byteArray.readInt(), true )
+ IntUtil.toHex( byteArray.readInt(), true )
+ IntUtil.toHex( byteArray.readInt(), true )
+ IntUtil.toHex( byteArray.readInt(), true )
+ IntUtil.toHex( byteArray.readInt(), true )
+ IntUtil.toHex( byteArray.readInt(), true )
+ IntUtil.toHex( byteArray.readInt(), true );
}
/**
* Performs the SHA256 hash algorithm on a ByteArray.
*
* @param data The ByteArray data to hash
* @return A string containing the hash value of data
* @langversion ActionScript 3.0
* @playerversion 9.0
*/
public static function hashBytes( data:ByteArray ):String
{
var blocks:Array = createBlocksFromByteArray( data );
var byteArray:ByteArray = hashBlocks(blocks);
return IntUtil.toHex( byteArray.readInt(), true )
+ IntUtil.toHex( byteArray.readInt(), true )
+ IntUtil.toHex( byteArray.readInt(), true )
+ IntUtil.toHex( byteArray.readInt(), true )
+ IntUtil.toHex( byteArray.readInt(), true )
+ IntUtil.toHex( byteArray.readInt(), true )
+ IntUtil.toHex( byteArray.readInt(), true )
+ IntUtil.toHex( byteArray.readInt(), true );
}
/**
* Performs the SHA256 hash algorithm on a string, then does
* Base64 encoding on the result.
*
* @param s The string to hash
* @return The base64 encoded hash value of s
* @langversion ActionScript 3.0
* @playerversion 9.0
* @tiptext
*/
public static function hashToBase64( s:String ):String
{
var blocks:Array = createBlocksFromString( s );
var byteArray:ByteArray = hashBlocks(blocks);
// ByteArray.toString() returns the contents as a UTF-8 string,
// which we can't use because certain byte sequences might trigger
// a UTF-8 conversion. Instead, we convert the bytes to characters
// one by one.
var charsInByteArray:String = "";
byteArray.position = 0;
for (var j:int = 0; j < byteArray.length; j++)
{
var byte:uint = byteArray.readUnsignedByte();
charsInByteArray += String.fromCharCode(byte);
}
var encoder:Base64Encoder = new Base64Encoder();
encoder.encode(charsInByteArray);
return encoder.flush();
}
private static function hashBlocks( blocks:Array ):ByteArray {
var h0:int = 0x6a09e667;
var h1:int = 0xbb67ae85;
var h2:int = 0x3c6ef372;
var h3:int = 0xa54ff53a;
var h4:int = 0x510e527f;
var h5:int = 0x9b05688c;
var h6:int = 0x1f83d9ab;
var h7:int = 0x5be0cd19;
var k:Array = new Array(0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2);
var len:int = blocks.length;
var w:Array = new Array( 64 );
// loop over all of the blocks
for ( var i:int = 0; i < len; i += 16 ) {
var a:int = h0;
var b:int = h1;
var c:int = h2;
var d:int = h3;
var e:int = h4;
var f:int = h5;
var g:int = h6;
var h:int = h7;
for(var t:int = 0; t < 64; t++) {
if ( t < 16 ) {
w[t] = blocks[ i + t ];
if(isNaN(w[t])) { w[t] = 0; }
} else {
var ws0:int = IntUtil.ror(w[t-15], 7) ^ IntUtil.ror(w[t-15], 18) ^ (w[t-15] >>> 3);
var ws1:int = IntUtil.ror(w[t-2], 17) ^ IntUtil.ror(w[t-2], 19) ^ (w[t-2] >>> 10);
w[t] = w[t-16] + ws0 + w[t-7] + ws1;
}
var s0:int = IntUtil.ror(a, 2) ^ IntUtil.ror(a, 13) ^ IntUtil.ror(a, 22);
var maj:int = (a & b) ^ (a & c) ^ (b & c);
var t2:int = s0 + maj;
var s1:int = IntUtil.ror(e, 6) ^ IntUtil.ror(e, 11) ^ IntUtil.ror(e, 25);
var ch:int = (e & f) ^ ((~e) & g);
var t1:int = h + s1 + ch + k[t] + w[t];
h = g;
g = f;
f = e;
e = d + t1;
d = c;
c = b;
b = a;
a = t1 + t2;
}
//Add this chunk's hash to result so far:
h0 += a;
h1 += b;
h2 += c;
h3 += d;
h4 += e;
h5 += f;
h6 += g;
h7 += h;
}
var byteArray:ByteArray = new ByteArray();
byteArray.writeInt(h0);
byteArray.writeInt(h1);
byteArray.writeInt(h2);
byteArray.writeInt(h3);
byteArray.writeInt(h4);
byteArray.writeInt(h5);
byteArray.writeInt(h6);
byteArray.writeInt(h7);
byteArray.position = 0;
digest = new ByteArray();
digest.writeBytes(byteArray);
digest.position = 0;
return byteArray;
}
/**
* Converts a ByteArray to a sequence of 16-word blocks
* that we'll do the processing on. Appends padding
* and length in the process.
*
* @param data The data to split into blocks
* @return An array containing the blocks into which data was split
*/
private static function createBlocksFromByteArray( data:ByteArray ):Array
{
var oldPosition:int = data.position;
data.position = 0;
var blocks:Array = new Array();
var len:int = data.length * 8;
var mask:int = 0xFF; // ignore hi byte of characters > 0xFF
for( var i:int = 0; i < len; i += 8 )
{
blocks[ i >> 5 ] |= ( data.readByte() & mask ) << ( 24 - i % 32 );
}
// append padding and length
blocks[ len >> 5 ] |= 0x80 << ( 24 - len % 32 );
blocks[ ( ( ( len + 64 ) >> 9 ) << 4 ) + 15 ] = len;
data.position = oldPosition;
return blocks;
}
/**
* Converts a string to a sequence of 16-word blocks
* that we'll do the processing on. Appends padding
* and length in the process.
*
* @param s The string to split into blocks
* @return An array containing the blocks that s was split into.
*/
private static function createBlocksFromString( s:String ):Array
{
var blocks:Array = new Array();
var len:int = s.length * 8;
var mask:int = 0xFF; // ignore hi byte of characters > 0xFF
for( var i:int = 0; i < len; i += 8 ) {
blocks[ i >> 5 ] |= ( s.charCodeAt( i / 8 ) & mask ) << ( 24 - i % 32 );
}
// append padding and length
blocks[ len >> 5 ] |= 0x80 << ( 24 - len % 32 );
blocks[ ( ( ( len + 64 ) >> 9 ) << 4 ) + 15 ] = len;
return blocks;
}
}
}

View File

@ -0,0 +1,114 @@
/*
Copyright (c) 2008, Adobe Systems Incorporated
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Adobe Systems Incorporated nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.adobe.crypto
{
import mx.formatters.DateFormatter;
import mx.utils.Base64Encoder;
/**
* Web Services Security Username Token
*
* Implementation based on algorithm description at
* http://www.oasis-open.org/committees/wss/documents/WSS-Username-02-0223-merged.pdf
*/
public class WSSEUsernameToken
{
/**
* Generates a WSSE Username Token.
*
* @param username The username
* @param password The password
* @param nonce A cryptographically random nonce (if null, the nonce
* will be generated)
* @param timestamp The time at which the token is generated (if null,
* the time will be set to the moment of execution)
* @return The generated token
* @langversion ActionScript 3.0
* @playerversion Flash 9.0
* @tiptext
*/
public static function getUsernameToken(username:String, password:String, nonce:String=null, timestamp:Date=null):String
{
if (nonce == null)
{
nonce = generateNonce();
}
nonce = base64Encode(nonce);
var created:String = generateTimestamp(timestamp);
var password64:String = getBase64Digest(nonce,
created,
password);
var token:String = new String("UsernameToken Username=\"");
token += username + "\", " +
"PasswordDigest=\"" + password64 + "\", " +
"Nonce=\"" + nonce + "\", " +
"Created=\"" + created + "\"";
return token;
}
private static function generateNonce():String
{
// Math.random returns a Number between 0 and 1. We don't want our
// nonce to contain invalid characters (e.g. the period) so we
// strip them out before returning the result.
var s:String = Math.random().toString();
return s.replace(".", "");
}
internal static function base64Encode(s:String):String
{
var encoder:Base64Encoder = new Base64Encoder();
encoder.encode(s);
return encoder.flush();
}
internal static function generateTimestamp(timestamp:Date):String
{
if (timestamp == null)
{
timestamp = new Date();
}
var dateFormatter:DateFormatter = new DateFormatter();
dateFormatter.formatString = "YYYY-MM-DDTJJ:NN:SS"
return dateFormatter.format(timestamp) + "Z";
}
internal static function getBase64Digest(nonce:String, created:String, password:String):String
{
return SHA1.hashToBase64(nonce + created + password);
}
}
}

View File

@ -0,0 +1,63 @@
/*
Copyright (c) 2008, Adobe Systems Incorporated
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Adobe Systems Incorporated nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.adobe.errors
{
/**
* This class represents an Error that is thrown when a method is called when
* the receiving instance is in an invalid state.
*
* For example, this may occur if a method has been called, and other properties
* in the instance have not been initialized properly.
*
* @langversion ActionScript 3.0
* @playerversion Flash 9.0
* @tiptext
*
*/
public class IllegalStateError extends Error
{
/**
* Constructor
*
* @param message A message describing the error in detail.
*
* @langversion ActionScript 3.0
* @playerversion Flash 9.0
* @tiptext
*/
public function IllegalStateError(message:String)
{
super(message);
}
}
}

View File

@ -0,0 +1,47 @@
/*
Copyright (c) 2008, Adobe Systems Incorporated
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Adobe Systems Incorporated nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.adobe.fileformats.vcard
{
public class Address
{
public var type:String;
public var street:String;
public var city:String;
public var state:String;
public var postalCode:String;
public function toString():String
{
return (street + " " + city + ", " + state + " " + postalCode);
}
}
}

View File

@ -0,0 +1,39 @@
/*
Copyright (c) 2008, Adobe Systems Incorporated
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Adobe Systems Incorporated nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.adobe.fileformats.vcard
{
public class Email
{
public var type:String;
public var address:String;
}
}

View File

@ -0,0 +1,39 @@
/*
Copyright (c) 2008, Adobe Systems Incorporated
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Adobe Systems Incorporated nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.adobe.fileformats.vcard
{
public class Phone
{
public var type:String;
public var number:String;
}
}

View File

@ -0,0 +1,54 @@
/*
Copyright (c) 2008, Adobe Systems Incorporated
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Adobe Systems Incorporated nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.adobe.fileformats.vcard
{
import flash.utils.ByteArray;
public class VCard
{
public var fullName:String;
public var orgs:Array;
public var title:String;
public var image:ByteArray;
public var phones:Array;
public var emails:Array;
public var addresses:Array;
public function VCard()
{
orgs = new Array();
phones = new Array();
emails = new Array();
addresses = new Array();
}
}
}

View File

@ -0,0 +1,246 @@
/*
Copyright (c) 2008, Adobe Systems Incorporated
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Adobe Systems Incorporated nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.adobe.fileformats.vcard
{
import mx.utils.Base64Decoder;
import mx.utils.StringUtil;
public class VCardParser
{
public static function parse(vcardStr:String):Array
{
var vcards:Array = new Array();
var lines:Array = vcardStr.split(/\r\n/);
var vcard:VCard;
var type:String;
var typeTmp:String;
var line:String;
for (var i:uint = 0; i < lines.length; ++i)
{
line = lines[i];
if (line == "BEGIN:VCARD")
{
vcard = new VCard();
}
else if (line == "END:VCARD")
{
if (vcard != null)
{
vcards.push(vcard);
}
}
else if(line.search(/^ORG/i) != -1)
{
var org:String = line.substring(4, line.length);
var orgArray:Array = org.split(";");
for each (var orgToken:String in orgArray)
{
if (StringUtil.trim(orgToken).length > 0)
{
vcard.orgs.push(orgToken);
}
}
}
else if(line.search(/^TITLE/i) != -1)
{
var title:String = line.substring(6, line.length);
vcard.title = title;
}
else if (line.search(/^FN:/i) != -1)
{
var fullName:String = line.substring(3, line.length);
vcard.fullName = fullName;
}
else if (line.search(/^TEL/i) != -1)
{
type = new String();
typeTmp = new String();
var phone:Phone = new Phone();
var number:String;
var phoneTokens:Array = line.split(";");
for each (var phoneToken:String in phoneTokens)
{
if (phoneToken.search(/^TYPE=/i) != -1)
{
if (phoneToken.indexOf(":") != -1)
{
typeTmp = phoneToken.substring(5, phoneToken.indexOf(":"));
number = phoneToken.substring(phoneToken.indexOf(":")+1, phoneToken.length);
}
else
{
typeTmp = phoneToken.substring(5, phoneToken.length);
}
typeTmp = typeTmp.toLocaleLowerCase();
if (typeTmp == "pref")
{
continue;
}
if (type.length != 0)
{
type += (" ");
}
type += typeTmp;
}
}
if (type.length > 0 && number != null)
{
phone.type = type;
phone.number = number;
}
vcard.phones.push(phone);
}
else if (line.search(/^EMAIL/i) != -1)
{
type = new String();
typeTmp = new String();
var email:Email = new Email();
var emailAddress:String;
var emailTokens:Array = line.split(";");
for each (var emailToken:String in emailTokens)
{
if (emailToken.search(/^TYPE=/i) != -1)
{
if (emailToken.indexOf(":") != -1)
{
typeTmp = emailToken.substring(5, emailToken.indexOf(":"));
emailAddress = emailToken.substring(emailToken.indexOf(":")+1, emailToken.length);
}
else
{
typeTmp = emailToken.substring(5, emailToken.length);
}
typeTmp = typeTmp.toLocaleLowerCase();
if (typeTmp == "pref" || typeTmp == "internet")
{
continue;
}
if (type.length != 0)
{
type += (" ");
}
type += typeTmp;
}
}
if (type.length > 0 && emailAddress != null)
{
email.type = type;
email.address = emailAddress;
}
vcard.emails.push(email);
}
else if (line.indexOf("ADR;") != -1)
{
var addressTokens:Array = line.split(";");
var address:Address = new Address();
for (var j:uint = 0; j < addressTokens.length; ++j)
{
var addressToken:String = addressTokens[j];
if (addressToken.search(/^home:+$/i) != -1) // For Outlook, which uses non-standard vCards.
{
address.type = "home";
}
else if (addressToken.search(/^work:+$/i) != -1) // For Outlook, which uses non-standard vCards.
{
address.type = "work";
}
if (addressToken.search(/^type=/i) != -1) // The "type" parameter is the standard way (which Address Book uses)
{
// First, remove the optional ":" character.
addressToken = addressToken.replace(/:/,"");
var addressType:String = addressToken.substring(5, addressToken.length).toLowerCase();
if (addressType == "pref") // Not interested in which one is preferred.
{
continue;
}
else if (addressType.indexOf("home") != -1) // home
{
addressType = "home";
}
else if (addressType.indexOf("work") != -1) // work
{
addressType = "work";
}
else if (addressType.indexOf(",") != -1) // if the comma technique is used, just use the first one
{
var typeTokens:Array = addressType.split(",");
for each (var typeToken:String in typeTokens)
{
if (typeToken != "pref")
{
addressType = typeToken;
break;
}
}
}
address.type = addressType;
}
else if (addressToken.search(/^\d/) != -1 && address.street == null)
{
address.street = addressToken.replace(/\\n/, "");
address.city = addressTokens[j+1];
address.state = addressTokens[j+2];
address.postalCode = addressTokens[j+3];
}
}
if (address.type != null && address.street != null)
{
vcard.addresses.push(address);
}
}
else if (line.search(/^PHOTO;BASE64/i) != -1)
{
var imageStr:String = new String();
for (var k:uint = i+1; k < lines.length; ++k)
{
imageStr += lines[k];
//if (lines[k].search(/.+\=$/) != -1) // Very slow in Mac due to RegEx bug
if (lines[k].indexOf('=') != -1)
{
var decoder:Base64Decoder = new Base64Decoder();
decoder.decode(imageStr);
vcard.image = decoder.flush();
break;
}
}
}
}
return vcards;
}
}
}

View File

@ -0,0 +1,39 @@
/*
Copyright (c) 2008, Adobe Systems Incorporated
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Adobe Systems Incorporated nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.adobe.images
{
public class BitString
{
public var len:int = 0;
public var val:int = 0;
}
}

View File

@ -0,0 +1,648 @@
/*
Copyright (c) 2008, Adobe Systems Incorporated
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Adobe Systems Incorporated nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.adobe.images
{
import flash.geom.*;
import flash.display.*;
import flash.utils.*;
/**
* Class that converts BitmapData into a valid JPEG
*/
public class JPGEncoder
{
// Static table initialization
private var ZigZag:Array = [
0, 1, 5, 6,14,15,27,28,
2, 4, 7,13,16,26,29,42,
3, 8,12,17,25,30,41,43,
9,11,18,24,31,40,44,53,
10,19,23,32,39,45,52,54,
20,22,33,38,46,51,55,60,
21,34,37,47,50,56,59,61,
35,36,48,49,57,58,62,63
];
private var YTable:Array = new Array(64);
private var UVTable:Array = new Array(64);
private var fdtbl_Y:Array = new Array(64);
private var fdtbl_UV:Array = new Array(64);
private function initQuantTables(sf:int):void
{
var i:int;
var t:Number;
var YQT:Array = [
16, 11, 10, 16, 24, 40, 51, 61,
12, 12, 14, 19, 26, 58, 60, 55,
14, 13, 16, 24, 40, 57, 69, 56,
14, 17, 22, 29, 51, 87, 80, 62,
18, 22, 37, 56, 68,109,103, 77,
24, 35, 55, 64, 81,104,113, 92,
49, 64, 78, 87,103,121,120,101,
72, 92, 95, 98,112,100,103, 99
];
for (i = 0; i < 64; i++) {
t = Math.floor((YQT[i]*sf+50)/100);
if (t < 1) {
t = 1;
} else if (t > 255) {
t = 255;
}
YTable[ZigZag[i]] = t;
}
var UVQT:Array = [
17, 18, 24, 47, 99, 99, 99, 99,
18, 21, 26, 66, 99, 99, 99, 99,
24, 26, 56, 99, 99, 99, 99, 99,
47, 66, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99
];
for (i = 0; i < 64; i++) {
t = Math.floor((UVQT[i]*sf+50)/100);
if (t < 1) {
t = 1;
} else if (t > 255) {
t = 255;
}
UVTable[ZigZag[i]] = t;
}
var aasf:Array = [
1.0, 1.387039845, 1.306562965, 1.175875602,
1.0, 0.785694958, 0.541196100, 0.275899379
];
i = 0;
for (var row:int = 0; row < 8; row++)
{
for (var col:int = 0; col < 8; col++)
{
fdtbl_Y[i] = (1.0 / (YTable [ZigZag[i]] * aasf[row] * aasf[col] * 8.0));
fdtbl_UV[i] = (1.0 / (UVTable[ZigZag[i]] * aasf[row] * aasf[col] * 8.0));
i++;
}
}
}
private var YDC_HT:Array;
private var UVDC_HT:Array;
private var YAC_HT:Array;
private var UVAC_HT:Array;
private function computeHuffmanTbl(nrcodes:Array, std_table:Array):Array
{
var codevalue:int = 0;
var pos_in_table:int = 0;
var HT:Array = new Array();
for (var k:int=1; k<=16; k++) {
for (var j:int=1; j<=nrcodes[k]; j++) {
HT[std_table[pos_in_table]] = new BitString();
HT[std_table[pos_in_table]].val = codevalue;
HT[std_table[pos_in_table]].len = k;
pos_in_table++;
codevalue++;
}
codevalue*=2;
}
return HT;
}
private var std_dc_luminance_nrcodes:Array = [0,0,1,5,1,1,1,1,1,1,0,0,0,0,0,0,0];
private var std_dc_luminance_values:Array = [0,1,2,3,4,5,6,7,8,9,10,11];
private var std_ac_luminance_nrcodes:Array = [0,0,2,1,3,3,2,4,3,5,5,4,4,0,0,1,0x7d];
private var std_ac_luminance_values:Array = [
0x01,0x02,0x03,0x00,0x04,0x11,0x05,0x12,
0x21,0x31,0x41,0x06,0x13,0x51,0x61,0x07,
0x22,0x71,0x14,0x32,0x81,0x91,0xa1,0x08,
0x23,0x42,0xb1,0xc1,0x15,0x52,0xd1,0xf0,
0x24,0x33,0x62,0x72,0x82,0x09,0x0a,0x16,
0x17,0x18,0x19,0x1a,0x25,0x26,0x27,0x28,
0x29,0x2a,0x34,0x35,0x36,0x37,0x38,0x39,
0x3a,0x43,0x44,0x45,0x46,0x47,0x48,0x49,
0x4a,0x53,0x54,0x55,0x56,0x57,0x58,0x59,
0x5a,0x63,0x64,0x65,0x66,0x67,0x68,0x69,
0x6a,0x73,0x74,0x75,0x76,0x77,0x78,0x79,
0x7a,0x83,0x84,0x85,0x86,0x87,0x88,0x89,
0x8a,0x92,0x93,0x94,0x95,0x96,0x97,0x98,
0x99,0x9a,0xa2,0xa3,0xa4,0xa5,0xa6,0xa7,
0xa8,0xa9,0xaa,0xb2,0xb3,0xb4,0xb5,0xb6,
0xb7,0xb8,0xb9,0xba,0xc2,0xc3,0xc4,0xc5,
0xc6,0xc7,0xc8,0xc9,0xca,0xd2,0xd3,0xd4,
0xd5,0xd6,0xd7,0xd8,0xd9,0xda,0xe1,0xe2,
0xe3,0xe4,0xe5,0xe6,0xe7,0xe8,0xe9,0xea,
0xf1,0xf2,0xf3,0xf4,0xf5,0xf6,0xf7,0xf8,
0xf9,0xfa
];
private var std_dc_chrominance_nrcodes:Array = [0,0,3,1,1,1,1,1,1,1,1,1,0,0,0,0,0];
private var std_dc_chrominance_values:Array = [0,1,2,3,4,5,6,7,8,9,10,11];
private var std_ac_chrominance_nrcodes:Array = [0,0,2,1,2,4,4,3,4,7,5,4,4,0,1,2,0x77];
private var std_ac_chrominance_values:Array = [
0x00,0x01,0x02,0x03,0x11,0x04,0x05,0x21,
0x31,0x06,0x12,0x41,0x51,0x07,0x61,0x71,
0x13,0x22,0x32,0x81,0x08,0x14,0x42,0x91,
0xa1,0xb1,0xc1,0x09,0x23,0x33,0x52,0xf0,
0x15,0x62,0x72,0xd1,0x0a,0x16,0x24,0x34,
0xe1,0x25,0xf1,0x17,0x18,0x19,0x1a,0x26,
0x27,0x28,0x29,0x2a,0x35,0x36,0x37,0x38,
0x39,0x3a,0x43,0x44,0x45,0x46,0x47,0x48,
0x49,0x4a,0x53,0x54,0x55,0x56,0x57,0x58,
0x59,0x5a,0x63,0x64,0x65,0x66,0x67,0x68,
0x69,0x6a,0x73,0x74,0x75,0x76,0x77,0x78,
0x79,0x7a,0x82,0x83,0x84,0x85,0x86,0x87,
0x88,0x89,0x8a,0x92,0x93,0x94,0x95,0x96,
0x97,0x98,0x99,0x9a,0xa2,0xa3,0xa4,0xa5,
0xa6,0xa7,0xa8,0xa9,0xaa,0xb2,0xb3,0xb4,
0xb5,0xb6,0xb7,0xb8,0xb9,0xba,0xc2,0xc3,
0xc4,0xc5,0xc6,0xc7,0xc8,0xc9,0xca,0xd2,
0xd3,0xd4,0xd5,0xd6,0xd7,0xd8,0xd9,0xda,
0xe2,0xe3,0xe4,0xe5,0xe6,0xe7,0xe8,0xe9,
0xea,0xf2,0xf3,0xf4,0xf5,0xf6,0xf7,0xf8,
0xf9,0xfa
];
private function initHuffmanTbl():void
{
YDC_HT = computeHuffmanTbl(std_dc_luminance_nrcodes,std_dc_luminance_values);
UVDC_HT = computeHuffmanTbl(std_dc_chrominance_nrcodes,std_dc_chrominance_values);
YAC_HT = computeHuffmanTbl(std_ac_luminance_nrcodes,std_ac_luminance_values);
UVAC_HT = computeHuffmanTbl(std_ac_chrominance_nrcodes,std_ac_chrominance_values);
}
private var bitcode:Array = new Array(65535);
private var category:Array = new Array(65535);
private function initCategoryNumber():void
{
var nrlower:int = 1;
var nrupper:int = 2;
var nr:int;
for (var cat:int=1; cat<=15; cat++) {
//Positive numbers
for (nr=nrlower; nr<nrupper; nr++) {
category[32767+nr] = cat;
bitcode[32767+nr] = new BitString();
bitcode[32767+nr].len = cat;
bitcode[32767+nr].val = nr;
}
//Negative numbers
for (nr=-(nrupper-1); nr<=-nrlower; nr++) {
category[32767+nr] = cat;
bitcode[32767+nr] = new BitString();
bitcode[32767+nr].len = cat;
bitcode[32767+nr].val = nrupper-1+nr;
}
nrlower <<= 1;
nrupper <<= 1;
}
}
// IO functions
private var byteout:ByteArray;
private var bytenew:int = 0;
private var bytepos:int = 7;
private function writeBits(bs:BitString):void
{
var value:int = bs.val;
var posval:int = bs.len-1;
while ( posval >= 0 ) {
if (value & uint(1 << posval) ) {
bytenew |= uint(1 << bytepos);
}
posval--;
bytepos--;
if (bytepos < 0) {
if (bytenew == 0xFF) {
writeByte(0xFF);
writeByte(0);
}
else {
writeByte(bytenew);
}
bytepos=7;
bytenew=0;
}
}
}
private function writeByte(value:int):void
{
byteout.writeByte(value);
}
private function writeWord(value:int):void
{
writeByte((value>>8)&0xFF);
writeByte((value )&0xFF);
}
// DCT & quantization core
private function fDCTQuant(data:Array, fdtbl:Array):Array
{
var tmp0:Number, tmp1:Number, tmp2:Number, tmp3:Number, tmp4:Number, tmp5:Number, tmp6:Number, tmp7:Number;
var tmp10:Number, tmp11:Number, tmp12:Number, tmp13:Number;
var z1:Number, z2:Number, z3:Number, z4:Number, z5:Number, z11:Number, z13:Number;
var i:int;
/* Pass 1: process rows. */
var dataOff:int=0;
for (i=0; i<8; i++) {
tmp0 = data[dataOff+0] + data[dataOff+7];
tmp7 = data[dataOff+0] - data[dataOff+7];
tmp1 = data[dataOff+1] + data[dataOff+6];
tmp6 = data[dataOff+1] - data[dataOff+6];
tmp2 = data[dataOff+2] + data[dataOff+5];
tmp5 = data[dataOff+2] - data[dataOff+5];
tmp3 = data[dataOff+3] + data[dataOff+4];
tmp4 = data[dataOff+3] - data[dataOff+4];
/* Even part */
tmp10 = tmp0 + tmp3; /* phase 2 */
tmp13 = tmp0 - tmp3;
tmp11 = tmp1 + tmp2;
tmp12 = tmp1 - tmp2;
data[dataOff+0] = tmp10 + tmp11; /* phase 3 */
data[dataOff+4] = tmp10 - tmp11;
z1 = (tmp12 + tmp13) * 0.707106781; /* c4 */
data[dataOff+2] = tmp13 + z1; /* phase 5 */
data[dataOff+6] = tmp13 - z1;
/* Odd part */
tmp10 = tmp4 + tmp5; /* phase 2 */
tmp11 = tmp5 + tmp6;
tmp12 = tmp6 + tmp7;
/* The rotator is modified from fig 4-8 to avoid extra negations. */
z5 = (tmp10 - tmp12) * 0.382683433; /* c6 */
z2 = 0.541196100 * tmp10 + z5; /* c2-c6 */
z4 = 1.306562965 * tmp12 + z5; /* c2+c6 */
z3 = tmp11 * 0.707106781; /* c4 */
z11 = tmp7 + z3; /* phase 5 */
z13 = tmp7 - z3;
data[dataOff+5] = z13 + z2; /* phase 6 */
data[dataOff+3] = z13 - z2;
data[dataOff+1] = z11 + z4;
data[dataOff+7] = z11 - z4;
dataOff += 8; /* advance pointer to next row */
}
/* Pass 2: process columns. */
dataOff = 0;
for (i=0; i<8; i++) {
tmp0 = data[dataOff+ 0] + data[dataOff+56];
tmp7 = data[dataOff+ 0] - data[dataOff+56];
tmp1 = data[dataOff+ 8] + data[dataOff+48];
tmp6 = data[dataOff+ 8] - data[dataOff+48];
tmp2 = data[dataOff+16] + data[dataOff+40];
tmp5 = data[dataOff+16] - data[dataOff+40];
tmp3 = data[dataOff+24] + data[dataOff+32];
tmp4 = data[dataOff+24] - data[dataOff+32];
/* Even part */
tmp10 = tmp0 + tmp3; /* phase 2 */
tmp13 = tmp0 - tmp3;
tmp11 = tmp1 + tmp2;
tmp12 = tmp1 - tmp2;
data[dataOff+ 0] = tmp10 + tmp11; /* phase 3 */
data[dataOff+32] = tmp10 - tmp11;
z1 = (tmp12 + tmp13) * 0.707106781; /* c4 */
data[dataOff+16] = tmp13 + z1; /* phase 5 */
data[dataOff+48] = tmp13 - z1;
/* Odd part */
tmp10 = tmp4 + tmp5; /* phase 2 */
tmp11 = tmp5 + tmp6;
tmp12 = tmp6 + tmp7;
/* The rotator is modified from fig 4-8 to avoid extra negations. */
z5 = (tmp10 - tmp12) * 0.382683433; /* c6 */
z2 = 0.541196100 * tmp10 + z5; /* c2-c6 */
z4 = 1.306562965 * tmp12 + z5; /* c2+c6 */
z3 = tmp11 * 0.707106781; /* c4 */
z11 = tmp7 + z3; /* phase 5 */
z13 = tmp7 - z3;
data[dataOff+40] = z13 + z2; /* phase 6 */
data[dataOff+24] = z13 - z2;
data[dataOff+ 8] = z11 + z4;
data[dataOff+56] = z11 - z4;
dataOff++; /* advance pointer to next column */
}
// Quantize/descale the coefficients
for (i=0; i<64; i++) {
// Apply the quantization and scaling factor & Round to nearest integer
data[i] = Math.round((data[i]*fdtbl[i]));
}
return data;
}
// Chunk writing
private function writeAPP0():void
{
writeWord(0xFFE0); // marker
writeWord(16); // length
writeByte(0x4A); // J
writeByte(0x46); // F
writeByte(0x49); // I
writeByte(0x46); // F
writeByte(0); // = "JFIF",'\0'
writeByte(1); // versionhi
writeByte(1); // versionlo
writeByte(0); // xyunits
writeWord(1); // xdensity
writeWord(1); // ydensity
writeByte(0); // thumbnwidth
writeByte(0); // thumbnheight
}
private function writeSOF0(width:int, height:int):void
{
writeWord(0xFFC0); // marker
writeWord(17); // length, truecolor YUV JPG
writeByte(8); // precision
writeWord(height);
writeWord(width);
writeByte(3); // nrofcomponents
writeByte(1); // IdY
writeByte(0x11); // HVY
writeByte(0); // QTY
writeByte(2); // IdU
writeByte(0x11); // HVU
writeByte(1); // QTU
writeByte(3); // IdV
writeByte(0x11); // HVV
writeByte(1); // QTV
}
private function writeDQT():void
{
writeWord(0xFFDB); // marker
writeWord(132); // length
writeByte(0);
var i:int;
for (i=0; i<64; i++) {
writeByte(YTable[i]);
}
writeByte(1);
for (i=0; i<64; i++) {
writeByte(UVTable[i]);
}
}
private function writeDHT():void
{
writeWord(0xFFC4); // marker
writeWord(0x01A2); // length
var i:int;
writeByte(0); // HTYDCinfo
for (i=0; i<16; i++) {
writeByte(std_dc_luminance_nrcodes[i+1]);
}
for (i=0; i<=11; i++) {
writeByte(std_dc_luminance_values[i]);
}
writeByte(0x10); // HTYACinfo
for (i=0; i<16; i++) {
writeByte(std_ac_luminance_nrcodes[i+1]);
}
for (i=0; i<=161; i++) {
writeByte(std_ac_luminance_values[i]);
}
writeByte(1); // HTUDCinfo
for (i=0; i<16; i++) {
writeByte(std_dc_chrominance_nrcodes[i+1]);
}
for (i=0; i<=11; i++) {
writeByte(std_dc_chrominance_values[i]);
}
writeByte(0x11); // HTUACinfo
for (i=0; i<16; i++) {
writeByte(std_ac_chrominance_nrcodes[i+1]);
}
for (i=0; i<=161; i++) {
writeByte(std_ac_chrominance_values[i]);
}
}
private function writeSOS():void
{
writeWord(0xFFDA); // marker
writeWord(12); // length
writeByte(3); // nrofcomponents
writeByte(1); // IdY
writeByte(0); // HTY
writeByte(2); // IdU
writeByte(0x11); // HTU
writeByte(3); // IdV
writeByte(0x11); // HTV
writeByte(0); // Ss
writeByte(0x3f); // Se
writeByte(0); // Bf
}
// Core processing
private var DU:Array = new Array(64);
private function processDU(CDU:Array, fdtbl:Array, DC:Number, HTDC:Array, HTAC:Array):Number
{
var EOB:BitString = HTAC[0x00];
var M16zeroes:BitString = HTAC[0xF0];
var i:int;
var DU_DCT:Array = fDCTQuant(CDU, fdtbl);
//ZigZag reorder
for (i=0;i<64;i++) {
DU[ZigZag[i]]=DU_DCT[i];
}
var Diff:int = DU[0] - DC; DC = DU[0];
//Encode DC
if (Diff==0) {
writeBits(HTDC[0]); // Diff might be 0
} else {
writeBits(HTDC[category[32767+Diff]]);
writeBits(bitcode[32767+Diff]);
}
//Encode ACs
var end0pos:int = 63;
for (; (end0pos>0)&&(DU[end0pos]==0); end0pos--) {
};
//end0pos = first element in reverse order !=0
if ( end0pos == 0) {
writeBits(EOB);
return DC;
}
i = 1;
while ( i <= end0pos ) {
var startpos:int = i;
for (; (DU[i]==0) && (i<=end0pos); i++) {
}
var nrzeroes:int = i-startpos;
if ( nrzeroes >= 16 ) {
for (var nrmarker:int=1; nrmarker <= nrzeroes/16; nrmarker++) {
writeBits(M16zeroes);
}
nrzeroes = int(nrzeroes&0xF);
}
writeBits(HTAC[nrzeroes*16+category[32767+DU[i]]]);
writeBits(bitcode[32767+DU[i]]);
i++;
}
if ( end0pos != 63 ) {
writeBits(EOB);
}
return DC;
}
private var YDU:Array = new Array(64);
private var UDU:Array = new Array(64);
private var VDU:Array = new Array(64);
private function RGB2YUV(img:BitmapData, xpos:int, ypos:int):void
{
var pos:int=0;
for (var y:int=0; y<8; y++) {
for (var x:int=0; x<8; x++) {
var P:uint = img.getPixel32(xpos+x,ypos+y);
var R:Number = Number((P>>16)&0xFF);
var G:Number = Number((P>> 8)&0xFF);
var B:Number = Number((P )&0xFF);
YDU[pos]=((( 0.29900)*R+( 0.58700)*G+( 0.11400)*B))-128;
UDU[pos]=(((-0.16874)*R+(-0.33126)*G+( 0.50000)*B));
VDU[pos]=((( 0.50000)*R+(-0.41869)*G+(-0.08131)*B));
pos++;
}
}
}
/**
* Constructor for JPEGEncoder class
*
* @param quality The quality level between 1 and 100 that detrmines the
* level of compression used in the generated JPEG
* @langversion ActionScript 3.0
* @playerversion Flash 9.0
* @tiptext
*/
public function JPGEncoder(quality:Number = 50)
{
if (quality <= 0) {
quality = 1;
}
if (quality > 100) {
quality = 100;
}
var sf:int = 0;
if (quality < 50) {
sf = int(5000 / quality);
} else {
sf = int(200 - quality*2);
}
// Create tables
initHuffmanTbl();
initCategoryNumber();
initQuantTables(sf);
}
/**
* Created a JPEG image from the specified BitmapData
*
* @param image The BitmapData that will be converted into the JPEG format.
* @return a ByteArray representing the JPEG encoded image data.
* @langversion ActionScript 3.0
* @playerversion Flash 9.0
* @tiptext
*/
public function encode(image:BitmapData):ByteArray
{
// Initialize bit writer
byteout = new ByteArray();
bytenew=0;
bytepos=7;
// Add JPEG headers
writeWord(0xFFD8); // SOI
writeAPP0();
writeDQT();
writeSOF0(image.width,image.height);
writeDHT();
writeSOS();
// Encode 8x8 macroblocks
var DCY:Number=0;
var DCU:Number=0;
var DCV:Number=0;
bytenew=0;
bytepos=7;
for (var ypos:int=0; ypos<image.height; ypos+=8) {
for (var xpos:int=0; xpos<image.width; xpos+=8) {
RGB2YUV(image, xpos, ypos);
DCY = processDU(YDU, fdtbl_Y, DCY, YDC_HT, YAC_HT);
DCU = processDU(UDU, fdtbl_UV, DCU, UVDC_HT, UVAC_HT);
DCV = processDU(VDU, fdtbl_UV, DCV, UVDC_HT, UVAC_HT);
}
}
// Do the bit alignment of the EOI marker
if ( bytepos >= 0 ) {
var fillbits:BitString = new BitString();
fillbits.len = bytepos+1;
fillbits.val = (1<<(bytepos+1))-1;
writeBits(fillbits);
}
writeWord(0xFFD9); //EOI
return byteout;
}
}
}

View File

@ -0,0 +1,141 @@
/*
Copyright (c) 2008, Adobe Systems Incorporated
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Adobe Systems Incorporated nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.adobe.images
{
import flash.geom.*;
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.utils.ByteArray;
/**
* Class that converts BitmapData into a valid PNG
*/
public class PNGEncoder
{
/**
* Created a PNG image from the specified BitmapData
*
* @param image The BitmapData that will be converted into the PNG format.
* @return a ByteArray representing the PNG encoded image data.
* @langversion ActionScript 3.0
* @playerversion Flash 9.0
* @tiptext
*/
public static function encode(img:BitmapData):ByteArray {
// Create output byte array
var png:ByteArray = new ByteArray();
// Write PNG signature
png.writeUnsignedInt(0x89504e47);
png.writeUnsignedInt(0x0D0A1A0A);
// Build IHDR chunk
var IHDR:ByteArray = new ByteArray();
IHDR.writeInt(img.width);
IHDR.writeInt(img.height);
IHDR.writeUnsignedInt(0x08060000); // 32bit RGBA
IHDR.writeByte(0);
writeChunk(png,0x49484452,IHDR);
// Build IDAT chunk
var IDAT:ByteArray= new ByteArray();
for(var i:int=0;i < img.height;i++) {
// no filter
IDAT.writeByte(0);
var p:uint;
var j:int;
if ( !img.transparent ) {
for(j=0;j < img.width;j++) {
p = img.getPixel(j,i);
IDAT.writeUnsignedInt(
uint(((p&0xFFFFFF) << 8)|0xFF));
}
} else {
for(j=0;j < img.width;j++) {
p = img.getPixel32(j,i);
IDAT.writeUnsignedInt(
uint(((p&0xFFFFFF) << 8)|
(p>>>24)));
}
}
}
IDAT.compress();
writeChunk(png,0x49444154,IDAT);
// Build IEND chunk
writeChunk(png,0x49454E44,null);
// return PNG
return png;
}
private static var crcTable:Array;
private static var crcTableComputed:Boolean = false;
private static function writeChunk(png:ByteArray,
type:uint, data:ByteArray):void {
if (!crcTableComputed) {
crcTableComputed = true;
crcTable = [];
var c:uint;
for (var n:uint = 0; n < 256; n++) {
c = n;
for (var k:uint = 0; k < 8; k++) {
if (c & 1) {
c = uint(uint(0xedb88320) ^
uint(c >>> 1));
} else {
c = uint(c >>> 1);
}
}
crcTable[n] = c;
}
}
var len:uint = 0;
if (data != null) {
len = data.length;
}
png.writeUnsignedInt(len);
var p:uint = png.position;
png.writeUnsignedInt(type);
if ( data != null ) {
png.writeBytes(data);
}
var e:uint = png.position;
png.position = p;
c = 0xffffffff;
for (var i:int = 0; i < (e-p); i++) {
c = uint(crcTable[
(c ^ png.readUnsignedByte()) &
uint(0xff)] ^ uint(c >>> 8));
}
c = uint(c^uint(0xffffffff));
png.position = e;
png.writeUnsignedInt(c);
}
}
}

View File

@ -0,0 +1,55 @@
/*
Copyright (c) 2008, Adobe Systems Incorporated
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Adobe Systems Incorporated nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.adobe.net
{
import flash.net.URLLoader;
/**
* Class that provides a dynamic implimentation of the URLLoader class.
*
* This class provides no API implimentations. However, since the class is
* declared as dynamic, it can be used in place of URLLoader, and allow
* you to dynamically attach properties to it (which URLLoader does not allow).
*
* @langversion ActionScript 3.0
* @playerversion Flash 9.0
* @tiptext
*/
public dynamic class DynamicURLLoader extends URLLoader
{
public function DynamicURLLoader()
{
super();
}
}
}

View File

@ -0,0 +1,76 @@
/*
Copyright (c) 2008, Adobe Systems Incorporated
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Adobe Systems Incorporated nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.adobe.net
{
/**
* The URI class cannot know about DNS aliases, virtual hosts, or
* symbolic links that may be involved. The application can provide
* an implementation of this interface to resolve the URI before the
* URI class makes any comparisons. For example, a web host has
* two aliases:
*
* <p><code>
* http://www.site.com/
* http://www.site.net/
* </code></p>
*
* <p>The application can provide an implementation that automatically
* resolves site.net to site.com before URI compares two URI objects.
* Only the application can know and understand the context in which
* the URI's are being used.</p>
*
* <p>Use the URI.resolver accessor to assign a custom resolver to
* the URI class. Any resolver specified is global to all instances
* of URI.</p>
*
* <p>URI will call this before performing URI comparisons in the
* URI.getRelation() and URI.getCommonParent() functions.
*
* @see URI.getRelation
* @see URI.getCommonParent
*
* @langversion ActionScript 3.0
* @playerversion Flash 9.0
*/
public interface IURIResolver
{
/**
* Implement this method to provide custom URI resolution for
* your application.
*
* @langversion ActionScript 3.0
* @playerversion Flash 9.0
*/
function resolve(uri:URI) : URI;
}
}

View File

@ -0,0 +1,200 @@
/*
Copyright (c) 2008, Adobe Systems Incorporated
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Adobe Systems Incorporated nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.adobe.net
{
public class MimeTypeMap
{
private var types:Array =
[["application/andrew-inset","ez"],
["application/atom+xml","atom"],
["application/mac-binhex40","hqx"],
["application/mac-compactpro","cpt"],
["application/mathml+xml","mathml"],
["application/msword","doc"],
["application/octet-stream","bin","dms","lha","lzh","exe","class","so","dll","dmg"],
["application/oda","oda"],
["application/ogg","ogg"],
["application/pdf","pdf"],
["application/postscript","ai","eps","ps"],
["application/rdf+xml","rdf"],
["application/smil","smi","smil"],
["application/srgs","gram"],
["application/srgs+xml","grxml"],
["application/vnd.adobe.apollo-application-installer-package+zip","air"],
["application/vnd.mif","mif"],
["application/vnd.mozilla.xul+xml","xul"],
["application/vnd.ms-excel","xls"],
["application/vnd.ms-powerpoint","ppt"],
["application/vnd.rn-realmedia","rm"],
["application/vnd.wap.wbxml","wbxml"],
["application/vnd.wap.wmlc","wmlc"],
["application/vnd.wap.wmlscriptc","wmlsc"],
["application/voicexml+xml","vxml"],
["application/x-bcpio","bcpio"],
["application/x-cdlink","vcd"],
["application/x-chess-pgn","pgn"],
["application/x-cpio","cpio"],
["application/x-csh","csh"],
["application/x-director","dcr","dir","dxr"],
["application/x-dvi","dvi"],
["application/x-futuresplash","spl"],
["application/x-gtar","gtar"],
["application/x-hdf","hdf"],
["application/x-javascript","js"],
["application/x-koan","skp","skd","skt","skm"],
["application/x-latex","latex"],
["application/x-netcdf","nc","cdf"],
["application/x-sh","sh"],
["application/x-shar","shar"],
["application/x-shockwave-flash","swf"],
["application/x-stuffit","sit"],
["application/x-sv4cpio","sv4cpio"],
["application/x-sv4crc","sv4crc"],
["application/x-tar","tar"],
["application/x-tcl","tcl"],
["application/x-tex","tex"],
["application/x-texinfo","texinfo","texi"],
["application/x-troff","t","tr","roff"],
["application/x-troff-man","man"],
["application/x-troff-me","me"],
["application/x-troff-ms","ms"],
["application/x-ustar","ustar"],
["application/x-wais-source","src"],
["application/xhtml+xml","xhtml","xht"],
["application/xml","xml","xsl"],
["application/xml-dtd","dtd"],
["application/xslt+xml","xslt"],
["application/zip","zip"],
["audio/basic","au","snd"],
["audio/midi","mid","midi","kar"],
["audio/mp4","f4a"],
["audio/mp4","f4b"],
["audio/mpeg","mp3","mpga","mp2"],
["audio/x-aiff","aif","aiff","aifc"],
["audio/x-mpegurl","m3u"],
["audio/x-pn-realaudio","ram","ra"],
["audio/x-wav","wav"],
["chemical/x-pdb","pdb"],
["chemical/x-xyz","xyz"],
["image/bmp","bmp"],
["image/cgm","cgm"],
["image/gif","gif"],
["image/ief","ief"],
["image/jpeg","jpg","jpeg","jpe"],
["image/png","png"],
["image/svg+xml","svg"],
["image/tiff","tiff","tif"],
["image/vnd.djvu","djvu","djv"],
["image/vnd.wap.wbmp","wbmp"],
["image/x-cmu-raster","ras"],
["image/x-icon","ico"],
["image/x-portable-anymap","pnm"],
["image/x-portable-bitmap","pbm"],
["image/x-portable-graymap","pgm"],
["image/x-portable-pixmap","ppm"],
["image/x-rgb","rgb"],
["image/x-xbitmap","xbm"],
["image/x-xpixmap","xpm"],
["image/x-xwindowdump","xwd"],
["model/iges","igs","iges"],
["model/mesh","msh","mesh","silo"],
["model/vrml","wrl","vrml"],
["text/calendar","ics","ifb"],
["text/css","css"],
["text/html","html","htm"],
["text/plain","txt","asc"],
["text/richtext","rtx"],
["text/rtf","rtf"],
["text/sgml","sgml","sgm"],
["text/tab-separated-values","tsv"],
["text/vnd.wap.wml","wml"],
["text/vnd.wap.wmlscript","wmls"],
["text/x-setext","etx"],
["video/mp4","f4v"],
["video/mp4","f4p"],
["video/mpeg","mpg","mpeg","mpe"],
["video/quicktime","mov","qt"],
["video/vnd.mpegurl","m4u","mxu"],
["video/x-flv","flv"],
["video/x-msvideo","avi"],
["video/x-sgi-movie","movie"],
["x-conference/x-cooltalk","ice"]];
/**
* Returns the mimetype for the given extension.
*/
public function getMimeType(extension:String):String
{
extension = extension.toLocaleLowerCase();
for each (var a:Array in types)
{
for each (var b:String in a)
{
if (b == extension)
{
return a[0];
}
}
}
return null;
}
/**
* Returns the prefered extension for the given mimetype.
*/
public function getExtension(mimetype:String):String
{
mimetype = mimetype.toLocaleLowerCase();
for each (var a:Array in types)
{
if (a[0] == mimetype)
{
return a[1];
}
}
return null;
}
/**
* Adds a mimetype to the map. The order of the extensions matters. The most preferred should come first.
*/
public function addMimeType(mimetype:String, extensions:Array):void
{
var newType:Array = [mimetype];
for each (var a:String in extensions)
{
newType.push(a);
}
types.push(newType);
}
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,139 @@
/*
Copyright (c) 2008, Adobe Systems Incorporated
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Adobe Systems Incorporated nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.adobe.net
{
import flash.utils.ByteArray;
/**
* This class implements an efficient lookup table for URI
* character escaping. This class is only needed if you
* create a derived class of URI to handle custom URI
* syntax. This class is used internally by URI.
*
* @langversion ActionScript 3.0
* @playerversion Flash 9.0*
*/
public class URIEncodingBitmap extends ByteArray
{
/**
* Constructor. Creates an encoding bitmap using the given
* string of characters as the set of characters that need
* to be URI escaped.
*
* @langversion ActionScript 3.0
* @playerversion Flash 9.0
*/
public function URIEncodingBitmap(charsToEscape:String) : void
{
var i:int;
var data:ByteArray = new ByteArray();
// Initialize our 128 bits (16 bytes) to zero
for (i = 0; i < 16; i++)
this.writeByte(0);
data.writeUTFBytes(charsToEscape);
data.position = 0;
while (data.bytesAvailable)
{
var c:int = data.readByte();
if (c > 0x7f)
continue; // only escape low bytes
var enc:int;
this.position = (c >> 3);
enc = this.readByte();
enc |= 1 << (c & 0x7);
this.position = (c >> 3);
this.writeByte(enc);
}
}
/**
* Based on the data table contained in this object, check
* if the given character should be escaped.
*
* @param char the character to be escaped. Only the first
* character in the string is used. Any other characters
* are ignored.
*
* @return the integer value of the raw UTF8 character. For
* example, if '%' is given, the return value is 37 (0x25).
* If the character given does not need to be escaped, the
* return value is zero.
*
* @langversion ActionScript 3.0
* @playerversion Flash 9.0
*/
public function ShouldEscape(char:String) : int
{
var data:ByteArray = new ByteArray();
var c:int, mask:int;
// write the character into a ByteArray so
// we can pull it out as a raw byte value.
data.writeUTFBytes(char);
data.position = 0;
c = data.readByte();
if (c & 0x80)
{
// don't escape high byte characters. It can make international
// URI's unreadable. We just want to escape characters that would
// make URI syntax ambiguous.
return 0;
}
else if ((c < 0x1f) || (c == 0x7f))
{
// control characters must be escaped.
return c;
}
this.position = (c >> 3);
mask = this.readByte();
if (mask & (1 << (c & 0x7)))
{
// we need to escape this, return the numeric value
// of the character
return c;
}
else
{
return 0;
}
}
}
}

View File

@ -0,0 +1,198 @@
/*
Copyright (c) 2008, Adobe Systems Incorporated
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Adobe Systems Incorporated nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.adobe.net.proxies
{
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.net.Socket;
/**
* This class allows TCP socket connections through HTTP proxies in accordance with
* RFC 2817:
*
* ftp://ftp.rfc-editor.org/in-notes/rfc2817.txt
*
* It can also be used to make direct connections to a destination, as well. If you
* pass the host and port into the constructor, no proxy will be used. You can also
* call connect, passing in the host and the port, and if you didn't set the proxy
* info, a direct connection will be made. A proxy is only used after you have called
* the setProxyInfo function.
*
* The connection to and negotiation with the proxy is completely hidden. All the
* same events are thrown whether you are using a proxy or not, and the data you
* receive from the target server will look exact as it would if you were connected
* to it directly rather than through a proxy.
*
* @author Christian Cantrell
*
**/
public class RFC2817Socket
extends Socket
{
private var proxyHost:String = null;
private var host:String = null;
private var proxyPort:int = 0;
private var port:int = 0;
private var deferredEventHandlers:Object = new Object();
private var buffer:String = new String();
/**
* Construct a new RFC2817Socket object. If you pass in the host and the port,
* no proxy will be used. If you want to use a proxy, instantiate with no
* arguments, call setProxyInfo, then call connect.
**/
public function RFC2817Socket(host:String = null, port:int = 0)
{
super(host, port);
}
/**
* Set the proxy host and port number. Your connection will only proxied if
* this function has been called.
**/
public function setProxyInfo(host:String, port:int):void
{
this.proxyHost = host;
this.proxyPort = port;
var deferredSocketDataHandler:Object = this.deferredEventHandlers[ProgressEvent.SOCKET_DATA];
var deferredConnectHandler:Object = this.deferredEventHandlers[Event.CONNECT];
if (deferredSocketDataHandler != null)
{
super.removeEventListener(ProgressEvent.SOCKET_DATA, deferredSocketDataHandler.listener, deferredSocketDataHandler.useCapture);
}
if (deferredConnectHandler != null)
{
super.removeEventListener(Event.CONNECT, deferredConnectHandler.listener, deferredConnectHandler.useCapture);
}
}
/**
* Connect to the specified host over the specified port. If you want your
* connection proxied, call the setProxyInfo function first.
**/
public override function connect(host:String, port:int):void
{
if (this.proxyHost == null)
{
this.redirectConnectEvent();
this.redirectSocketDataEvent();
super.connect(host, port);
}
else
{
this.host = host;
this.port = port;
super.addEventListener(Event.CONNECT, this.onConnect);
super.addEventListener(ProgressEvent.SOCKET_DATA, this.onSocketData);
super.connect(this.proxyHost, this.proxyPort);
}
}
private function onConnect(event:Event):void
{
this.writeUTFBytes("CONNECT "+this.host+":"+this.port+" HTTP/1.1\n\n");
this.flush();
this.redirectConnectEvent();
}
private function onSocketData(event:ProgressEvent):void
{
while (this.bytesAvailable != 0)
{
this.buffer += this.readUTFBytes(1);
if (this.buffer.search(/\r?\n\r?\n$/) != -1)
{
this.checkResponse(event);
break;
}
}
}
private function checkResponse(event:ProgressEvent):void
{
var responseCode:String = this.buffer.substr(this.buffer.indexOf(" ")+1, 3);
if (responseCode.search(/^2/) == -1)
{
var ioError:IOErrorEvent = new IOErrorEvent(IOErrorEvent.IO_ERROR);
ioError.text = "Error connecting to the proxy ["+this.proxyHost+"] on port ["+this.proxyPort+"]: " + this.buffer;
this.dispatchEvent(ioError);
}
else
{
this.redirectSocketDataEvent();
this.dispatchEvent(new Event(Event.CONNECT));
if (this.bytesAvailable > 0)
{
this.dispatchEvent(event);
}
}
this.buffer = null;
}
private function redirectConnectEvent():void
{
super.removeEventListener(Event.CONNECT, onConnect);
var deferredEventHandler:Object = this.deferredEventHandlers[Event.CONNECT];
if (deferredEventHandler != null)
{
super.addEventListener(Event.CONNECT, deferredEventHandler.listener, deferredEventHandler.useCapture, deferredEventHandler.priority, deferredEventHandler.useWeakReference);
}
}
private function redirectSocketDataEvent():void
{
super.removeEventListener(ProgressEvent.SOCKET_DATA, onSocketData);
var deferredEventHandler:Object = this.deferredEventHandlers[ProgressEvent.SOCKET_DATA];
if (deferredEventHandler != null)
{
super.addEventListener(ProgressEvent.SOCKET_DATA, deferredEventHandler.listener, deferredEventHandler.useCapture, deferredEventHandler.priority, deferredEventHandler.useWeakReference);
}
}
public override function addEventListener(type:String, listener:Function, useCapture:Boolean = false, priority:int=0.0, useWeakReference:Boolean=false):void
{
if (type == Event.CONNECT || type == ProgressEvent.SOCKET_DATA)
{
this.deferredEventHandlers[type] = {listener:listener,useCapture:useCapture, priority:priority, useWeakReference:useWeakReference};
}
else
{
super.addEventListener(type, listener, useCapture, priority, useWeakReference);
}
}
}
}

View File

@ -0,0 +1,66 @@
/*
Copyright (c) 2009, Adobe Systems Incorporated
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Adobe Systems Incorporated nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.adobe.protocols.dict
{
public class Database
{
private var _name:String;
private var _description:String;
public function Database(name:String, description:String)
{
this._name = name;
this._description = description;
}
public function set name(name:String):void
{
this._name = name;
}
public function get name():String
{
return this._name;
}
public function set description(description:String):void
{
this._description = description;
}
public function get description():String
{
return this._description;
}
}
}

View File

@ -0,0 +1,71 @@
/*
Copyright (c) 2009, Adobe Systems Incorporated
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Adobe Systems Incorporated nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.adobe.protocols.dict
{
public class Definition
{
private var _definition:String;
private var _database:String;
private var _term:String;
public function set definition(definition:String):void
{
this._definition = definition;
}
public function get definition():String
{
return this._definition;
}
public function set database(database:String):void
{
this._database = database;
}
public function get database():String
{
return this._database;
}
public function set term(term:String):void
{
this._term = term;
}
public function get term():String
{
return this._term;
}
}
}

View File

@ -0,0 +1,360 @@
/*
Copyright (c) 2009, Adobe Systems Incorporated
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Adobe Systems Incorporated nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.adobe.protocols.dict
{
import com.adobe.protocols.dict.events.*;
import com.adobe.protocols.dict.util.*;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.events.SecurityErrorEvent;
import flash.net.Socket;
import mx.rpc.http.HTTPService;
import mx.rpc.events.ResultEvent;
import mx.rpc.events.FaultEvent;
import flash.xml.XMLNode;
import mx.utils.StringUtil;
public class Dict
extends EventDispatcher
{
// Event type names.
//public static var CONNECTED:String = "connected";
//public static var DISCONNECTED:String = "disconnected";
public static var IO_ERROR:String = IOErrorEvent.IO_ERROR;
//public static var ERROR:String = "error";
//public static var SERVERS:String = "servers";
//public static var DATABASES:String = "databases";
//public static var MATCH_STRATEGIES:String = "matchStrategies";
//public static var DEFINITION:String = "definition";
//public static var DEFINITION_HEADER:String = "definitionHeader";
//public static var MATCH:String = "match";
//public static var NO_MATCH:String = "noMatch";
public static var FIRST_MATCH:uint = 0;
public static var ALL_DATABASES:uint = 1;
private var socket:SocketHelper;
private var dbShortList:Boolean;
public function Dict()
{
this.socket = new SocketHelper();
this.socket.addEventListener(Event.CONNECT, connected);
this.socket.addEventListener(Event.CLOSE, disconnected);
this.socket.addEventListener(SocketHelper.COMPLETE_RESPONSE, incomingData);
this.socket.addEventListener(IOErrorEvent.IO_ERROR, ioError);
this.socket.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityError);
}
public function connect(server:String, port:uint = 2628):void
{
if (this.socket.connected)
{
this.socket.close();
}
this.socket.connect(server, port);
}
public function connectThroughProxy(proxyServer:String,
proxyPort:int,
server:String,
port:uint = 2628):void
{
if (this.socket.connected)
{
this.socket.close();
}
this.socket.setProxyInfo(proxyServer, proxyPort);
this.socket.connect(server, port);
}
public function disconnect():void
{
this.socket.close();
this.disconnected(null);
}
public function getServers():void
{
var http:HTTPService = new HTTPService();
http.url = "http://luetzschena-stahmeln.de/dictd/xmllist.php";
http.addEventListener(ResultEvent.RESULT, incomingServerXML);
http.addEventListener(FaultEvent.FAULT, httpError);
http.resultFormat = HTTPService.RESULT_FORMAT_E4X;
http.send();
}
public function getDatabases(shortList:Boolean=true):void
{
this.dbShortList = shortList;
this.socket.writeUTFBytes("show db\r\n");
this.socket.flush();
}
public function getMatchStrategies():void
{
this.socket.writeUTFBytes("show strat\r\n");
this.socket.flush();
}
public function match(database:String, term:String, scope:String="prefix"):void
{
this.socket.writeUTFBytes("match " + database + " " + scope + " \"" + term + "\"\r\n");
this.socket.flush();
}
public function define(database:String, term:String):void
{
this.socket.writeUTFBytes("define " + database + " \"" + term + "\"\r\n");
this.socket.flush();
}
public function lookup(term:String, scope:uint):void
{
var flag:String;
if (scope == Dict.ALL_DATABASES)
{
flag = "*";
}
else if (scope == Dict.FIRST_MATCH)
{
flag = "!";
}
this.socket.writeUTFBytes("define " + flag + " \"" + term + "\"\r\n");
this.socket.flush();
}
//// Private functions ////
private function connected(event:Event):void
{
// Wait to dispatch an event until we get the 220 response.
}
private function disconnected(event:Event):void
{
dispatchEvent(new DisconnectedEvent(DisconnectedEvent.DISCONNECTED));
}
private function incomingServerXML(event:ResultEvent):void
{
var dictd:Namespace = new Namespace("http://www.luetzschena-stahmeln.de/dictd/");
var result:XML = event.result as XML;
var server:String, description:String;
var servers:Array = new Array();
for each (var serverNode:XML in result.dictd::server)
{
server = serverNode.dictd::dictdurl;
description = serverNode.dictd::description;
if (StringUtil.trim(server).length != 0 &&
StringUtil.trim(description).length != 0)
{
var dServer:DictionaryServer = new DictionaryServer();
dServer.server = server.replace("dict://", "");
dServer.description = description;
servers.push(dServer);
}
}
var dEvent:DictionaryServerEvent = new DictionaryServerEvent(DictionaryServerEvent.SERVERS);
dEvent.servers = servers;
dispatchEvent(dEvent);
}
private function incomingData(event:CompleteResponseEvent):void
{
var rawResponse:String = event.response;
var response:Response = this.parseRawResponse(rawResponse);
var responseCode:uint = response.code;
if (responseCode == 552) // no matches
{
throwNoMatchEvent(response);
}
else if (responseCode >= 400 && responseCode <= 599) // error
{
throwErrorEvent(response);
}
else if (responseCode == 220) // successful connection
{
dispatchEvent(new ConnectedEvent(ConnectedEvent.CONNECTED));
}
else if (responseCode == 110) // databases are being returned
{
throwDatabasesEvent(response);
}
else if (responseCode == 111) // matches strategies
{
throwMatchStrategiesEvent(response);
}
else if (responseCode == 152) // matches
{
throwMatchEvent(response);
}
else if (responseCode == 150)
{
throwDefinitionHeaderEvent(response);
}
else if (responseCode == 151)
{
throwDefinitionEvent(response);
}
}
private function ioError(event:IOErrorEvent):void
{
dispatchEvent(event);
}
private function httpError(event:FaultEvent):void
{
trace("httpError!");
}
private function securityError(event:SecurityErrorEvent):void
{
trace("security error!");
trace(event.text);
}
// Dispatch new events.
private function throwDatabasesEvent(response:Response):void
{
var databases:Array = new Array();
var responseArray:Array = response.body.split("\r\n");
for each (var line:String in responseArray)
{
var name:String = line.substring(0, line.indexOf(" "));
if (name == "--exit--")
{
if (this.dbShortList)
{
break;
}
continue;
}
var description:String = line.substring(line.indexOf(" ")+1, line.length).replace(/\"/g,"");
databases.push(new Database(name, description));
}
var event:DatabaseEvent = new DatabaseEvent(DatabaseEvent.DATABASES);
event.databases = databases;
dispatchEvent(event);
}
private function throwMatchStrategiesEvent(response:Response):void
{
var strategies:Array = new Array();
var responseArray:Array = response.body.split("\r\n");
for each (var line:String in responseArray)
{
var name:String = line.substring(0, line.indexOf(" "));
var description:String = line.substring(line.indexOf(" ")+1, line.length).replace(/\"/g,"");
strategies.push(new MatchStrategy(name, description));
}
var event:MatchStrategiesEvent = new MatchStrategiesEvent(MatchStrategiesEvent.MATCH_STRATEGIES);
event.strategies = strategies;
dispatchEvent(event);
}
private function throwMatchEvent(response:Response):void
{
var matches:Array = new Array();
var responseArray:Array = response.body.split("\r\n");
for each (var line:String in responseArray)
{
var match:String = line.substring(line.indexOf(" ")+1, line.length).replace(/\"/g,"");
matches.push(match);
}
var event:MatchEvent = new MatchEvent(MatchEvent.MATCH);
event.matches = matches;
dispatchEvent(event);
}
private function throwErrorEvent(response:Response):void
{
var event:ErrorEvent = new ErrorEvent(ErrorEvent.ERROR);
event.code = response.code;
event.message = response.headerText;
dispatchEvent(event);
}
private function throwNoMatchEvent(response:Response):void
{
dispatchEvent(new NoMatchEvent(NoMatchEvent.NO_MATCH));
}
private function throwDefinitionHeaderEvent(response:Response):void
{
var event:DefinitionHeaderEvent = new DefinitionHeaderEvent(DefinitionHeaderEvent.DEFINITION_HEADER);
event.definitionCount = uint(response.headerText.substring(0, response.headerText.indexOf(" ")));
dispatchEvent(event);
}
private function throwDefinitionEvent(response:Response):void
{
var event:DefinitionEvent = new DefinitionEvent(DefinitionEvent.DEFINITION);
var def:Definition = new Definition();
var headerText:String = response.headerText;
var tokens:Array = headerText.match(/"[^"]+"/g);
def.term = String(tokens[0]).replace(/"/g, "");
def.database = String(tokens[1]).replace(/"/g, "");
def.definition = response.body;
event.definition = def;
dispatchEvent(event);
}
private function parseRawResponse(rawResponse:String):Response
{
var response:Response = new Response();
var fullHeader:String;
if (rawResponse.indexOf("\r\n") != -1)
{
fullHeader = rawResponse.substring(0, rawResponse.indexOf("\r\n"));
}
else
{
fullHeader = rawResponse;
}
var responseCodeMatch:Array = fullHeader.match(/^\d{3}/);
response.code = uint(responseCodeMatch[0]);
response.headerText = fullHeader.substring(fullHeader.indexOf(" ")+1, fullHeader.length);
var body:String = rawResponse.substring(rawResponse.indexOf("\r\n")+2, rawResponse.length);
body = body.replace(/\r\n\.\./, "\r\n.");
response.body = body;
return response;
}
}
}

View File

@ -0,0 +1,60 @@
/*
Copyright (c) 2009, Adobe Systems Incorporated
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Adobe Systems Incorporated nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.adobe.protocols.dict
{
public class DictionaryServer
{
private var _server:String;
private var _description:String;
public function set server(server:String):void
{
this._server = server;
}
public function get server():String
{
return this._server;
}
public function set description(description:String):void
{
this._description = description;
}
public function get description():String
{
return this._description;
}
}
}

View File

@ -0,0 +1,66 @@
/*
Copyright (c) 2009, Adobe Systems Incorporated
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Adobe Systems Incorporated nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.adobe.protocols.dict
{
public class MatchStrategy
{
private var _name:String;
private var _description:String;
public function MatchStrategy(name:String, description:String)
{
this._name = name;
this._description = description;
}
public function set name(name:String):void
{
this._name = name;
}
public function get name():String
{
return this._name;
}
public function set description(description:String):void
{
this._description = description;
}
public function get description():String
{
return this._description;
}
}
}

View File

@ -0,0 +1,71 @@
/*
Copyright (c) 2009, Adobe Systems Incorporated
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Adobe Systems Incorporated nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.adobe.protocols.dict
{
public class Response
{
private var _code:uint;
private var _headerText:String;
private var _body:String;
public function set code(code:uint):void
{
this._code = code;
}
public function set headerText(headerText:String):void
{
this._headerText = headerText;
}
public function set body(body:String):void
{
this._body = body;
}
public function get code():uint
{
return this._code;
}
public function get headerText():String
{
return this._headerText;
}
public function get body():String
{
return this._body;
}
}
}

View File

@ -0,0 +1,53 @@
/*
Copyright (c) 2009, Adobe Systems Incorporated
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Adobe Systems Incorporated nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.adobe.protocols.dict.events
{
import flash.events.Event;
public class ConnectedEvent extends Event
{
public static const CONNECTED:String = "connected";
public function ConnectedEvent(type:String, bubbles:Boolean = false,
cancelable:Boolean = false)
{
super(type, bubbles, cancelable);
}
public override function clone():Event
{
var out:ConnectedEvent = new ConnectedEvent(type, bubbles, cancelable);
return out;
}
}
}

View File

@ -0,0 +1,67 @@
/*
Copyright (c) 2009, Adobe Systems Incorporated
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Adobe Systems Incorporated nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.adobe.protocols.dict.events
{
import flash.events.Event;
public class DatabaseEvent extends Event
{
private var _databases:Array;
public static const DATABASES:String = "databases";
public function DatabaseEvent(type:String, bubbles:Boolean = false,
cancelable:Boolean = false)
{
super(type, bubbles, cancelable);
}
public function set databases(databases:Array):void
{
this._databases = databases;
}
public function get databases():Array
{
return this._databases;
}
public override function clone():Event
{
var out:DatabaseEvent = new DatabaseEvent(type, bubbles, cancelable);
out.databases = _databases;
return out;
}
}
}

View File

@ -0,0 +1,70 @@
/*
Copyright (c) 2009, Adobe Systems Incorporated
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Adobe Systems Incorporated nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.adobe.protocols.dict.events
{
import com.adobe.protocols.dict.Definition;
import flash.events.Event;
public class DefinitionEvent extends Event
{
public static const DEFINITION:String = "definition";
private var _definition:Definition;
public function DefinitionEvent(type:String, bubbles:Boolean = false,
cancelable:Boolean = false)
{
super(type, bubbles, cancelable);
}
public function set definition(definition:Definition):void
{
this._definition = definition;
}
public function get definition():Definition
{
return this._definition;
}
public override function clone():Event
{
var out:DefinitionEvent = new DefinitionEvent(type, bubbles, cancelable);
out.definition = _definition;
return out;
}
}
}

View File

@ -0,0 +1,69 @@
/*
Copyright (c) 2009, Adobe Systems Incorporated
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Adobe Systems Incorporated nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.adobe.protocols.dict.events
{
import flash.events.Event;
public class DefinitionHeaderEvent extends Event
{
public static const DEFINITION_HEADER:String = "definitionHeader";
private var _definitionCount:uint;
public function DefinitionHeaderEvent(type:String, bubbles:Boolean = false,
cancelable:Boolean = false)
{
super(type, bubbles, cancelable);
}
public function set definitionCount(definitionCount:uint):void
{
this._definitionCount = definitionCount;
}
public function get definitionCount():uint
{
return this._definitionCount;
}
public override function clone():Event
{
var out:DefinitionHeaderEvent = new DefinitionHeaderEvent(type,
bubbles, cancelable);
out.definitionCount = _definitionCount;
return out;
}
}
}

View File

@ -0,0 +1,69 @@
/*
Copyright (c) 2009, Adobe Systems Incorporated
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Adobe Systems Incorporated nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.adobe.protocols.dict.events
{
import flash.events.Event;
public class DictionaryServerEvent extends Event
{
public static const SERVERS:String = "servers";
private var _servers:Array;
public function DictionaryServerEvent(type:String, bubbles:Boolean = false,
cancelable:Boolean = false)
{
super(type, bubbles, cancelable);
}
public function set servers(servers:Array):void
{
this._servers = servers;
}
public function get servers():Array
{
return this._servers;
}
public override function clone():Event
{
var out:DictionaryServerEvent = new DictionaryServerEvent(type,
bubbles, cancelable);
out.servers = _servers;
return out;
}
}
}

View File

@ -0,0 +1,55 @@
/*
Copyright (c) 2009, Adobe Systems Incorporated
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Adobe Systems Incorporated nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.adobe.protocols.dict.events
{
import flash.events.Event;
public class DisconnectedEvent extends Event
{
public static const DISCONNECTED:String = "disconnected";
public function DisconnectedEvent(type:String, bubbles:Boolean = false,
cancelable:Boolean = false)
{
super(type, bubbles, cancelable);
}
public override function clone():Event
{
var out:DisconnectedEvent = new DisconnectedEvent(type, bubbles, cancelable);
return out;
}
}
}

View File

@ -0,0 +1,80 @@
/*
Copyright (c) 2009, Adobe Systems Incorporated
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Adobe Systems Incorporated nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.adobe.protocols.dict.events
{
import flash.events.Event;
public class ErrorEvent extends Event
{
public static const ERROR:String = "error";
private var _code:uint;
private var _message:String;
public function ErrorEvent(type:String, bubbles:Boolean = false,
cancelable:Boolean = false)
{
super(type, bubbles, cancelable);
}
public function set code(code:uint):void
{
this._code = code;
}
public function set message(message:String):void
{
this._message = message;
}
public function get code():uint
{
return this._code;
}
public function get message():String
{
return this._message;
}
public override function clone():Event
{
var out:ErrorEvent = new ErrorEvent(type, bubbles, cancelable);
out.message = _message;
out.code = _code;
return out;
}
}
}

View File

@ -0,0 +1,67 @@
/*
Copyright (c) 2009, Adobe Systems Incorporated
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Adobe Systems Incorporated nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.adobe.protocols.dict.events
{
import flash.events.Event;
public class MatchEvent extends Event
{
private var _matches:Array;
public static const MATCH:String = "match";
public function MatchEvent(type:String, bubbles:Boolean = false,
cancelable:Boolean = false)
{
super(type, bubbles, cancelable);
}
public function set matches(matches:Array):void
{
this._matches = matches;
}
public function get matches():Array
{
return this._matches;
}
public override function clone():Event
{
var out:MatchEvent = new MatchEvent(type, bubbles, cancelable);
out.matches = _matches;
return out;
}
}
}

View File

@ -0,0 +1,70 @@
/*
Copyright (c) 2009, Adobe Systems Incorporated
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Adobe Systems Incorporated nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.adobe.protocols.dict.events
{
import flash.events.Event;
public class MatchStrategiesEvent
extends Event
{
private var _strategies:Array;
public static const MATCH_STRATEGIES:String = "matchStrategies";
public function MatchStrategiesEvent(type:String, bubbles:Boolean = false,
cancelable:Boolean = false)
{
super(type, bubbles, cancelable);
}
public function set strategies(strategies:Array):void
{
this._strategies = strategies;
}
public function get strategies():Array
{
return this._strategies;
}
public override function clone():Event
{
var out:MatchStrategiesEvent = new MatchStrategiesEvent(type,
bubbles, cancelable);
out.strategies = _strategies;
return out;
}
}
}

View File

@ -0,0 +1,54 @@
/*
Copyright (c) 2009, Adobe Systems Incorporated
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Adobe Systems Incorporated nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.adobe.protocols.dict.events
{
import flash.events.Event;
public class NoMatchEvent extends Event
{
public static const NO_MATCH:String = "noMatch";
public function NoMatchEvent(type:String, bubbles:Boolean = false,
cancelable:Boolean = false)
{
super(type, bubbles, cancelable);
}
public override function clone():Event
{
var out:NoMatchEvent = new NoMatchEvent(type, bubbles, cancelable);
return out;
}
}
}

View File

@ -0,0 +1,68 @@
/*
Copyright (c) 2009, Adobe Systems Incorporated
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Adobe Systems Incorporated nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.adobe.protocols.dict.util
{
import flash.events.Event;
public class CompleteResponseEvent extends Event
{
private var _response:String;
public static const COMPLETE_RESPONSE:String = "completeResponse"
public function CompleteResponseEvent(type:String, bubbles:Boolean = false,
cancelable:Boolean = false)
{
super(type, bubbles, cancelable);
}
public function set response(response:String):void
{
this._response = response;
}
public function get response():String
{
return this._response;
}
public override function clone():Event
{
var out:CompleteResponseEvent = new CompleteResponseEvent(type,
bubbles, cancelable);
out.response = _response;
return out;
}
}
}

View File

@ -0,0 +1,81 @@
/*
Copyright (c) 2009, Adobe Systems Incorporated
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Adobe Systems Incorporated nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.adobe.protocols.dict.util
{
import com.adobe.net.proxies.RFC2817Socket;
import flash.events.ProgressEvent;
public class SocketHelper
extends RFC2817Socket
{
private var terminator:String = "\r\n.\r\n";
private var buffer:String;
public static var COMPLETE_RESPONSE:String = "completeResponse";
public function SocketHelper()
{
super();
buffer = new String();
addEventListener(ProgressEvent.SOCKET_DATA, incomingData);
}
private function incomingData(event:ProgressEvent):void
{
buffer += readUTFBytes(bytesAvailable);
buffer = buffer.replace(/250[^\r\n]+\r\n/, ""); // Get rid of all 250s. Don't need them.
var codeStr:String = buffer.substring(0, 3);
if (!isNaN(parseInt(codeStr)))
{
var code:uint = uint(codeStr);
if (code == 150 || code >= 200)
{
buffer = buffer.replace("\r\n", this.terminator);
}
}
while (buffer.indexOf(this.terminator) != -1)
{
var chunk:String = buffer.substring(0, buffer.indexOf(this.terminator));
buffer = buffer.substring(chunk.length + this.terminator.length, buffer.length);
throwResponseEvent(chunk);
}
}
private function throwResponseEvent(response:String):void
{
var responseEvent:CompleteResponseEvent = new CompleteResponseEvent(CompleteResponseEvent.COMPLETE_RESPONSE);
responseEvent.response = response;
dispatchEvent(responseEvent);
}
}
}

View File

@ -0,0 +1,86 @@
/*
Copyright (c) 2008, Adobe Systems Incorporated
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Adobe Systems Incorporated nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.adobe.serialization.json
{
/**
* This class provides encoding and decoding of the JSON format.
*
* Example usage:
* <code>
* // create a JSON string from an internal object
* JSON.encode( myObject );
*
* // read a JSON string into an internal object
* var myObject:Object = JSON.decode( jsonString );
* </code>
*/
public class JSON
{
/**
* Encodes a object into a JSON string.
*
* @param o The object to create a JSON string for
* @return the JSON string representing o
* @langversion ActionScript 3.0
* @playerversion Flash 9.0
* @tiptext
*/
public static function encode( o:Object ):String
{
return new JSONEncoder( o ).getString();
}
/**
* Decodes a JSON string into a native object.
*
* @param s The JSON string representing the object
* @param strict Flag indicating if the decoder should strictly adhere
* to the JSON standard or not. The default of <code>true</code>
* throws errors if the format does not match the JSON syntax exactly.
* Pass <code>false</code> to allow for non-properly-formatted JSON
* strings to be decoded with more leniancy.
* @return A native object as specified by s
* @throw JSONParseError
* @langversion ActionScript 3.0
* @playerversion Flash 9.0
* @tiptext
*/
public static function decode( s:String, strict:Boolean = true ):*
{
return new JSONDecoder( s, strict ).getValue();
}
}
}

View File

@ -0,0 +1,327 @@
/*
Copyright (c) 2008, Adobe Systems Incorporated
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Adobe Systems Incorporated nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.adobe.serialization.json
{
public class JSONDecoder
{
/**
* Flag indicating if the parser should be strict about the format
* of the JSON string it is attempting to decode.
*/
private var strict:Boolean;
/** The value that will get parsed from the JSON string */
private var value:*;
/** The tokenizer designated to read the JSON string */
private var tokenizer:JSONTokenizer;
/** The current token from the tokenizer */
private var token:JSONToken;
/**
* Constructs a new JSONDecoder to parse a JSON string
* into a native object.
*
* @param s The JSON string to be converted
* into a native object
* @param strict Flag indicating if the JSON string needs to
* strictly match the JSON standard or not.
* @langversion ActionScript 3.0
* @playerversion Flash 9.0
* @tiptext
*/
public function JSONDecoder( s:String, strict:Boolean )
{
this.strict = strict;
tokenizer = new JSONTokenizer( s, strict );
nextToken();
value = parseValue();
// Make sure the input stream is empty
if ( strict && nextToken() != null )
{
tokenizer.parseError( "Unexpected characters left in input stream" );
}
}
/**
* Gets the internal object that was created by parsing
* the JSON string passed to the constructor.
*
* @return The internal object representation of the JSON
* string that was passed to the constructor
* @langversion ActionScript 3.0
* @playerversion Flash 9.0
* @tiptext
*/
public function getValue():*
{
return value;
}
/**
* Returns the next token from the tokenzier reading
* the JSON string
*/
private function nextToken():JSONToken
{
return token = tokenizer.getNextToken();
}
/**
* Attempt to parse an array.
*/
private function parseArray():Array
{
// create an array internally that we're going to attempt
// to parse from the tokenizer
var a:Array = new Array();
// grab the next token from the tokenizer to move
// past the opening [
nextToken();
// check to see if we have an empty array
if ( token.type == JSONTokenType.RIGHT_BRACKET )
{
// we're done reading the array, so return it
return a;
}
// in non-strict mode an empty array is also a comma
// followed by a right bracket
else if ( !strict && token.type == JSONTokenType.COMMA )
{
// move past the comma
nextToken();
// check to see if we're reached the end of the array
if ( token.type == JSONTokenType.RIGHT_BRACKET )
{
return a;
}
else
{
tokenizer.parseError( "Leading commas are not supported. Expecting ']' but found " + token.value );
}
}
// deal with elements of the array, and use an "infinite"
// loop because we could have any amount of elements
while ( true )
{
// read in the value and add it to the array
a.push( parseValue() );
// after the value there should be a ] or a ,
nextToken();
if ( token.type == JSONTokenType.RIGHT_BRACKET )
{
// we're done reading the array, so return it
return a;
}
else if ( token.type == JSONTokenType.COMMA )
{
// move past the comma and read another value
nextToken();
// Allow arrays to have a comma after the last element
// if the decoder is not in strict mode
if ( !strict )
{
// Reached ",]" as the end of the array, so return it
if ( token.type == JSONTokenType.RIGHT_BRACKET )
{
return a;
}
}
}
else
{
tokenizer.parseError( "Expecting ] or , but found " + token.value );
}
}
return null;
}
/**
* Attempt to parse an object.
*/
private function parseObject():Object
{
// create the object internally that we're going to
// attempt to parse from the tokenizer
var o:Object = new Object();
// store the string part of an object member so
// that we can assign it a value in the object
var key:String
// grab the next token from the tokenizer
nextToken();
// check to see if we have an empty object
if ( token.type == JSONTokenType.RIGHT_BRACE )
{
// we're done reading the object, so return it
return o;
}
// in non-strict mode an empty object is also a comma
// followed by a right bracket
else if ( !strict && token.type == JSONTokenType.COMMA )
{
// move past the comma
nextToken();
// check to see if we're reached the end of the object
if ( token.type == JSONTokenType.RIGHT_BRACE )
{
return o;
}
else
{
tokenizer.parseError( "Leading commas are not supported. Expecting '}' but found " + token.value );
}
}
// deal with members of the object, and use an "infinite"
// loop because we could have any amount of members
while ( true )
{
if ( token.type == JSONTokenType.STRING )
{
// the string value we read is the key for the object
key = String( token.value );
// move past the string to see what's next
nextToken();
// after the string there should be a :
if ( token.type == JSONTokenType.COLON )
{
// move past the : and read/assign a value for the key
nextToken();
o[key] = parseValue();
// move past the value to see what's next
nextToken();
// after the value there's either a } or a ,
if ( token.type == JSONTokenType.RIGHT_BRACE )
{
// we're done reading the object, so return it
return o;
}
else if ( token.type == JSONTokenType.COMMA )
{
// skip past the comma and read another member
nextToken();
// Allow objects to have a comma after the last member
// if the decoder is not in strict mode
if ( !strict )
{
// Reached ",}" as the end of the object, so return it
if ( token.type == JSONTokenType.RIGHT_BRACE )
{
return o;
}
}
}
else
{
tokenizer.parseError( "Expecting } or , but found " + token.value );
}
}
else
{
tokenizer.parseError( "Expecting : but found " + token.value );
}
}
else
{
tokenizer.parseError( "Expecting string but found " + token.value );
}
}
return null;
}
/**
* Attempt to parse a value
*/
private function parseValue():Object
{
// Catch errors when the input stream ends abruptly
if ( token == null )
{
tokenizer.parseError( "Unexpected end of input" );
}
switch ( token.type )
{
case JSONTokenType.LEFT_BRACE:
return parseObject();
case JSONTokenType.LEFT_BRACKET:
return parseArray();
case JSONTokenType.STRING:
case JSONTokenType.NUMBER:
case JSONTokenType.TRUE:
case JSONTokenType.FALSE:
case JSONTokenType.NULL:
return token.value;
case JSONTokenType.NAN:
if ( !strict )
{
return token.value;
}
else
{
tokenizer.parseError( "Unexpected " + token.value );
}
default:
tokenizer.parseError( "Unexpected " + token.value );
}
return null;
}
}
}

View File

@ -0,0 +1,312 @@
/*
Copyright (c) 2008, Adobe Systems Incorporated
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Adobe Systems Incorporated nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.adobe.serialization.json
{
import flash.utils.describeType;
public class JSONEncoder {
/** The string that is going to represent the object we're encoding */
private var jsonString:String;
/**
* Creates a new JSONEncoder.
*
* @param o The object to encode as a JSON string
* @langversion ActionScript 3.0
* @playerversion Flash 9.0
* @tiptext
*/
public function JSONEncoder( value:* ) {
jsonString = convertToString( value );
}
/**
* Gets the JSON string from the encoder.
*
* @return The JSON string representation of the object
* that was passed to the constructor
* @langversion ActionScript 3.0
* @playerversion Flash 9.0
* @tiptext
*/
public function getString():String {
return jsonString;
}
/**
* Converts a value to it's JSON string equivalent.
*
* @param value The value to convert. Could be any
* type (object, number, array, etc)
*/
private function convertToString( value:* ):String {
// determine what value is and convert it based on it's type
if ( value is String ) {
// escape the string so it's formatted correctly
return escapeString( value as String );
} else if ( value is Number ) {
// only encode numbers that finate
return isFinite( value as Number) ? value.toString() : "null";
} else if ( value is Boolean ) {
// convert boolean to string easily
return value ? "true" : "false";
} else if ( value is Array ) {
// call the helper method to convert an array
return arrayToString( value as Array );
} else if ( value is Object && value != null ) {
// call the helper method to convert an object
return objectToString( value );
}
return "null";
}
/**
* Escapes a string accoding to the JSON specification.
*
* @param str The string to be escaped
* @return The string with escaped special characters
* according to the JSON specification
*/
private function escapeString( str:String ):String {
// create a string to store the string's jsonstring value
var s:String = "";
// current character in the string we're processing
var ch:String;
// store the length in a local variable to reduce lookups
var len:Number = str.length;
// loop over all of the characters in the string
for ( var i:int = 0; i < len; i++ ) {
// examine the character to determine if we have to escape it
ch = str.charAt( i );
switch ( ch ) {
case '"': // quotation mark
s += "\\\"";
break;
//case '/': // solidus
// s += "\\/";
// break;
case '\\': // reverse solidus
s += "\\\\";
break;
case '\b': // bell
s += "\\b";
break;
case '\f': // form feed
s += "\\f";
break;
case '\n': // newline
s += "\\n";
break;
case '\r': // carriage return
s += "\\r";
break;
case '\t': // horizontal tab
s += "\\t";
break;
default: // everything else
// check for a control character and escape as unicode
if ( ch < ' ' ) {
// get the hex digit(s) of the character (either 1 or 2 digits)
var hexCode:String = ch.charCodeAt( 0 ).toString( 16 );
// ensure that there are 4 digits by adjusting
// the # of zeros accordingly.
var zeroPad:String = hexCode.length == 2 ? "00" : "000";
// create the unicode escape sequence with 4 hex digits
s += "\\u" + zeroPad + hexCode;
} else {
// no need to do any special encoding, just pass-through
s += ch;
}
} // end switch
} // end for loop
return "\"" + s + "\"";
}
/**
* Converts an array to it's JSON string equivalent
*
* @param a The array to convert
* @return The JSON string representation of <code>a</code>
*/
private function arrayToString( a:Array ):String {
// create a string to store the array's jsonstring value
var s:String = "";
// loop over the elements in the array and add their converted
// values to the string
for ( var i:int = 0; i < a.length; i++ ) {
// when the length is 0 we're adding the first element so
// no comma is necessary
if ( s.length > 0 ) {
// we've already added an element, so add the comma separator
s += ","
}
// convert the value to a string
s += convertToString( a[i] );
}
// KNOWN ISSUE: In ActionScript, Arrays can also be associative
// objects and you can put anything in them, ie:
// myArray["foo"] = "bar";
//
// These properties aren't picked up in the for loop above because
// the properties don't correspond to indexes. However, we're
// sort of out luck because the JSON specification doesn't allow
// these types of array properties.
//
// So, if the array was also used as an associative object, there
// may be some values in the array that don't get properly encoded.
//
// A possible solution is to instead encode the Array as an Object
// but then it won't get decoded correctly (and won't be an
// Array instance)
// close the array and return it's string value
return "[" + s + "]";
}
/**
* Converts an object to it's JSON string equivalent
*
* @param o The object to convert
* @return The JSON string representation of <code>o</code>
*/
private function objectToString( o:Object ):String
{
// create a string to store the object's jsonstring value
var s:String = "";
// determine if o is a class instance or a plain object
var classInfo:XML = describeType( o );
if ( classInfo.@name.toString() == "Object" )
{
// the value of o[key] in the loop below - store this
// as a variable so we don't have to keep looking up o[key]
// when testing for valid values to convert
var value:Object;
// loop over the keys in the object and add their converted
// values to the string
for ( var key:String in o )
{
// assign value to a variable for quick lookup
value = o[key];
// don't add function's to the JSON string
if ( value is Function )
{
// skip this key and try another
continue;
}
// when the length is 0 we're adding the first item so
// no comma is necessary
if ( s.length > 0 ) {
// we've already added an item, so add the comma separator
s += ","
}
s += escapeString( key ) + ":" + convertToString( value );
}
}
else // o is a class instance
{
// Loop over all of the variables and accessors in the class and
// serialize them along with their values.
for each ( var v:XML in classInfo..*.(
name() == "variable"
||
(
name() == "accessor"
// Issue #116 - Make sure accessors are readable
&& attribute( "access" ).charAt( 0 ) == "r" )
) )
{
// Issue #110 - If [Transient] metadata exists, then we should skip
if ( v.metadata && v.metadata.( @name == "Transient" ).length() > 0 )
{
continue;
}
// When the length is 0 we're adding the first item so
// no comma is necessary
if ( s.length > 0 ) {
// We've already added an item, so add the comma separator
s += ","
}
s += escapeString( v.@name.toString() ) + ":"
+ convertToString( o[ v.@name ] );
}
}
return "{" + s + "}";
}
}
}

View File

@ -0,0 +1,87 @@
/*
Copyright (c) 2008, Adobe Systems Incorporated
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Adobe Systems Incorporated nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.adobe.serialization.json {
/**
*
*
*/
public class JSONParseError extends Error {
/** The location in the string where the error occurred */
private var _location:int;
/** The string in which the parse error occurred */
private var _text:String;
/**
* Constructs a new JSONParseError.
*
* @param message The error message that occured during parsing
* @langversion ActionScript 3.0
* @playerversion Flash 9.0
* @tiptext
*/
public function JSONParseError( message:String = "", location:int = 0, text:String = "") {
super( message );
name = "JSONParseError";
_location = location;
_text = text;
}
/**
* Provides read-only access to the location variable.
*
* @return The location in the string where the error occurred
* @langversion ActionScript 3.0
* @playerversion Flash 9.0
* @tiptext
*/
public function get location():int {
return _location;
}
/**
* Provides read-only access to the text variable.
*
* @return The string in which the error occurred
* @langversion ActionScript 3.0
* @playerversion Flash 9.0
* @tiptext
*/
public function get text():String {
return _text;
}
}
}

View File

@ -0,0 +1,104 @@
/*
Copyright (c) 2008, Adobe Systems Incorporated
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Adobe Systems Incorporated nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.adobe.serialization.json {
public class JSONToken {
private var _type:int;
private var _value:Object;
/**
* Creates a new JSONToken with a specific token type and value.
*
* @param type The JSONTokenType of the token
* @param value The value of the token
* @langversion ActionScript 3.0
* @playerversion Flash 9.0
* @tiptext
*/
public function JSONToken( type:int = -1 /* JSONTokenType.UNKNOWN */, value:Object = null ) {
_type = type;
_value = value;
}
/**
* Returns the type of the token.
*
* @see com.adobe.serialization.json.JSONTokenType
* @langversion ActionScript 3.0
* @playerversion Flash 9.0
* @tiptext
*/
public function get type():int {
return _type;
}
/**
* Sets the type of the token.
*
* @see com.adobe.serialization.json.JSONTokenType
* @langversion ActionScript 3.0
* @playerversion Flash 9.0
* @tiptext
*/
public function set type( value:int ):void {
_type = value;
}
/**
* Gets the value of the token
*
* @see com.adobe.serialization.json.JSONTokenType
* @langversion ActionScript 3.0
* @playerversion Flash 9.0
* @tiptext
*/
public function get value():Object {
return _value;
}
/**
* Sets the value of the token
*
* @see com.adobe.serialization.json.JSONTokenType
* @langversion ActionScript 3.0
* @playerversion Flash 9.0
* @tiptext
*/
public function set value ( v:Object ):void {
_value = v;
}
}
}

View File

@ -0,0 +1,69 @@
/*
Copyright (c) 2008, Adobe Systems Incorporated
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Adobe Systems Incorporated nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.adobe.serialization.json {
/**
* Class containing constant values for the different types
* of tokens in a JSON encoded string.
*/
public class JSONTokenType {
public static const UNKNOWN:int = -1;
public static const COMMA:int = 0;
public static const LEFT_BRACE:int = 1;
public static const RIGHT_BRACE:int = 2;
public static const LEFT_BRACKET:int = 3;
public static const RIGHT_BRACKET:int = 4;
public static const COLON:int = 6;
public static const TRUE:int = 7;
public static const FALSE:int = 8;
public static const NULL:int = 9;
public static const STRING:int = 10;
public static const NUMBER:int = 11;
public static const NAN:int = 12;
}
}

View File

@ -0,0 +1,702 @@
/*
Copyright (c) 2008, Adobe Systems Incorporated
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Adobe Systems Incorporated nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.adobe.serialization.json {
public class JSONTokenizer {
/**
* Flag indicating if the tokenizer should only recognize
* standard JSON tokens. Setting to <code>false</code> allows
* tokens such as NaN and allows numbers to be formatted as
* hex, etc.
*/
private var strict:Boolean;
/** The object that will get parsed from the JSON string */
private var obj:Object;
/** The JSON string to be parsed */
private var jsonString:String;
/** The current parsing location in the JSON string */
private var loc:int;
/** The current character in the JSON string during parsing */
private var ch:String;
/**
* The regular expression used to make sure the string does not
* contain invalid control characters.
*/
private var controlCharsRegExp:RegExp = /[\x00-\x1F]/;
/**
* Constructs a new JSONDecoder to parse a JSON string
* into a native object.
*
* @param s The JSON string to be converted
* into a native object
*/
public function JSONTokenizer( s:String, strict:Boolean )
{
jsonString = s;
this.strict = strict;
loc = 0;
// prime the pump by getting the first character
nextChar();
}
/**
* Gets the next token in the input sting and advances
* the character to the next character after the token
*/
public function getNextToken():JSONToken
{
var token:JSONToken = new JSONToken();
// skip any whitespace / comments since the last
// token was read
skipIgnored();
// examine the new character and see what we have...
switch ( ch )
{
case '{':
token.type = JSONTokenType.LEFT_BRACE;
token.value = '{';
nextChar();
break
case '}':
token.type = JSONTokenType.RIGHT_BRACE;
token.value = '}';
nextChar();
break
case '[':
token.type = JSONTokenType.LEFT_BRACKET;
token.value = '[';
nextChar();
break
case ']':
token.type = JSONTokenType.RIGHT_BRACKET;
token.value = ']';
nextChar();
break
case ',':
token.type = JSONTokenType.COMMA;
token.value = ',';
nextChar();
break
case ':':
token.type = JSONTokenType.COLON;
token.value = ':';
nextChar();
break;
case 't': // attempt to read true
var possibleTrue:String = "t" + nextChar() + nextChar() + nextChar();
if ( possibleTrue == "true" )
{
token.type = JSONTokenType.TRUE;
token.value = true;
nextChar();
}
else
{
parseError( "Expecting 'true' but found " + possibleTrue );
}
break;
case 'f': // attempt to read false
var possibleFalse:String = "f" + nextChar() + nextChar() + nextChar() + nextChar();
if ( possibleFalse == "false" )
{
token.type = JSONTokenType.FALSE;
token.value = false;
nextChar();
}
else
{
parseError( "Expecting 'false' but found " + possibleFalse );
}
break;
case 'n': // attempt to read null
var possibleNull:String = "n" + nextChar() + nextChar() + nextChar();
if ( possibleNull == "null" )
{
token.type = JSONTokenType.NULL;
token.value = null;
nextChar();
}
else
{
parseError( "Expecting 'null' but found " + possibleNull );
}
break;
case 'N': // attempt to read NaN
var possibleNaN:String = "N" + nextChar() + nextChar();
if ( possibleNaN == "NaN" )
{
token.type = JSONTokenType.NAN;
token.value = NaN;
nextChar();
}
else
{
parseError( "Expecting 'NaN' but found " + possibleNaN );
}
break;
case '"': // the start of a string
token = readString();
break;
default:
// see if we can read a number
if ( isDigit( ch ) || ch == '-' )
{
token = readNumber();
}
else if ( ch == '' )
{
// check for reading past the end of the string
return null;
}
else
{
// not sure what was in the input string - it's not
// anything we expected
parseError( "Unexpected " + ch + " encountered" );
}
}
return token;
}
/**
* Attempts to read a string from the input string. Places
* the character location at the first character after the
* string. It is assumed that ch is " before this method is called.
*
* @return the JSONToken with the string value if a string could
* be read. Throws an error otherwise.
*/
private function readString():JSONToken
{
// Rather than examine the string character-by-character, it's
// faster to use indexOf to try to and find the closing quote character
// and then replace escape sequences after the fact.
// Start at the current input stream position
var quoteIndex:int = loc;
do
{
// Find the next quote in the input stream
quoteIndex = jsonString.indexOf( "\"", quoteIndex );
if ( quoteIndex >= 0 )
{
// We found the next double quote character in the string, but we need
// to make sure it is not part of an escape sequence.
// Keep looping backwards while the previous character is a backslash
var backspaceCount:int = 0;
var backspaceIndex:int = quoteIndex - 1;
while ( jsonString.charAt( backspaceIndex ) == "\\" )
{
backspaceCount++;
backspaceIndex--;
}
// If we have an even number of backslashes, that means this is the ending quote
if ( backspaceCount % 2 == 0 )
{
break;
}
// At this point, the quote was determined to be part of an escape sequence
// so we need to move past the quote index to look for the next one
quoteIndex++;
}
else // There are no more quotes in the string and we haven't found the end yet
{
parseError( "Unterminated string literal" );
}
} while ( true );
// Unescape the string
// the token for the string we'll try to read
var token:JSONToken = new JSONToken();
token.type = JSONTokenType.STRING;
// Attach resulting string to the token to return it
token.value = unescapeString( jsonString.substr( loc, quoteIndex - loc ) );
// Move past the closing quote in the input string. This updates the next
// character in the input stream to be the character one after the closing quote
loc = quoteIndex + 1;
nextChar();
return token;
}
/**
* Convert all JavaScript escape characters into normal characters
*
* @param input The input string to convert
* @return Original string with escape characters replaced by real characters
*/
public function unescapeString( input:String ):String
{
// Issue #104 - If the string contains any unescaped control characters, this
// is an error in strict mode
if ( strict && controlCharsRegExp.test( input ) )
{
parseError( "String contains unescaped control character (0x00-0x1F)" );
}
var result:String = "";
var backslashIndex:int = 0;
var nextSubstringStartPosition:int = 0;
var len:int = input.length;
do
{
// Find the next backslash in the input
backslashIndex = input.indexOf( '\\', nextSubstringStartPosition );
if ( backslashIndex >= 0 )
{
result += input.substr( nextSubstringStartPosition, backslashIndex - nextSubstringStartPosition );
// Move past the backslash and next character (all escape sequences are
// two characters, except for \u, which will advance this further)
nextSubstringStartPosition = backslashIndex + 2;
// Check the next character so we know what to escape
var afterBackslashIndex:int = backslashIndex + 1;
var escapedChar:String = input.charAt( afterBackslashIndex );
switch ( escapedChar )
{
// Try to list the most common expected cases first to improve performance
case '"': result += '"'; break; // quotation mark
case '\\': result += '\\'; break; // reverse solidus
case 'n': result += '\n'; break; // newline
case 'r': result += '\r'; break; // carriage return
case 't': result += '\t'; break; // horizontal tab
// Convert a unicode escape sequence to it's character value
case 'u':
// Save the characters as a string we'll convert to an int
var hexValue:String = "";
// Make sure there are enough characters in the string leftover
if ( nextSubstringStartPosition + 4 > len )
{
parseError( "Unexpected end of input. Expecting 4 hex digits after \\u." );
}
// Try to find 4 hex characters
for ( var i:int = nextSubstringStartPosition; i < nextSubstringStartPosition + 4; i++ )
{
// get the next character and determine
// if it's a valid hex digit or not
var possibleHexChar:String = input.charAt( i );
if ( !isHexDigit( possibleHexChar ) )
{
parseError( "Excepted a hex digit, but found: " + possibleHexChar );
}
// Valid hex digit, add it to the value
hexValue += possibleHexChar;
}
// Convert hexValue to an integer, and use that
// integer value to create a character to add
// to our string.
result += String.fromCharCode( parseInt( hexValue, 16 ) );
// Move past the 4 hex digits that we just read
nextSubstringStartPosition += 4;
break;
case 'f': result += '\f'; break; // form feed
case '/': result += '/'; break; // solidus
case 'b': result += '\b'; break; // bell
default: result += '\\' + escapedChar; // Couldn't unescape the sequence, so just pass it through
}
}
else
{
// No more backslashes to replace, append the rest of the string
result += input.substr( nextSubstringStartPosition );
break;
}
} while ( nextSubstringStartPosition < len );
return result;
}
/**
* Attempts to read a number from the input string. Places
* the character location at the first character after the
* number.
*
* @return The JSONToken with the number value if a number could
* be read. Throws an error otherwise.
*/
private function readNumber():JSONToken
{
// the string to accumulate the number characters
// into that we'll convert to a number at the end
var input:String = "";
// check for a negative number
if ( ch == '-' )
{
input += '-';
nextChar();
}
// the number must start with a digit
if ( !isDigit( ch ) )
{
parseError( "Expecting a digit" );
}
// 0 can only be the first digit if it
// is followed by a decimal point
if ( ch == '0' )
{
input += ch;
nextChar();
// make sure no other digits come after 0
if ( isDigit( ch ) )
{
parseError( "A digit cannot immediately follow 0" );
}
// unless we have 0x which starts a hex number, but this
// doesn't match JSON spec so check for not strict mode.
else if ( !strict && ch == 'x' )
{
// include the x in the input
input += ch;
nextChar();
// need at least one hex digit after 0x to
// be valid
if ( isHexDigit( ch ) )
{
input += ch;
nextChar();
}
else
{
parseError( "Number in hex format require at least one hex digit after \"0x\"" );
}
// consume all of the hex values
while ( isHexDigit( ch ) )
{
input += ch;
nextChar();
}
}
}
else
{
// read numbers while we can
while ( isDigit( ch ) )
{
input += ch;
nextChar();
}
}
// check for a decimal value
if ( ch == '.' )
{
input += '.';
nextChar();
// after the decimal there has to be a digit
if ( !isDigit( ch ) )
{
parseError( "Expecting a digit" );
}
// read more numbers to get the decimal value
while ( isDigit( ch ) )
{
input += ch;
nextChar();
}
}
// check for scientific notation
if ( ch == 'e' || ch == 'E' )
{
input += "e"
nextChar();
// check for sign
if ( ch == '+' || ch == '-' )
{
input += ch;
nextChar();
}
// require at least one number for the exponent
// in this case
if ( !isDigit( ch ) )
{
parseError( "Scientific notation number needs exponent value" );
}
// read in the exponent
while ( isDigit( ch ) )
{
input += ch;
nextChar();
}
}
// convert the string to a number value
var num:Number = Number( input );
if ( isFinite( num ) && !isNaN( num ) )
{
// the token for the number that we've read
var token:JSONToken = new JSONToken();
token.type = JSONTokenType.NUMBER;
token.value = num;
return token;
}
else
{
parseError( "Number " + num + " is not valid!" );
}
return null;
}
/**
* Reads the next character in the input
* string and advances the character location.
*
* @return The next character in the input string, or
* null if we've read past the end.
*/
private function nextChar():String
{
return ch = jsonString.charAt( loc++ );
}
/**
* Advances the character location past any
* sort of white space and comments
*/
private function skipIgnored():void
{
var originalLoc:int;
// keep trying to skip whitespace and comments as long
// as we keep advancing past the original location
do
{
originalLoc = loc;
skipWhite();
skipComments();
}
while ( originalLoc != loc );
}
/**
* Skips comments in the input string, either
* single-line or multi-line. Advances the character
* to the first position after the end of the comment.
*/
private function skipComments():void
{
if ( ch == '/' )
{
// Advance past the first / to find out what type of comment
nextChar();
switch ( ch )
{
case '/': // single-line comment, read through end of line
// Loop over the characters until we find
// a newline or until there's no more characters left
do
{
nextChar();
}
while ( ch != '\n' && ch != '' )
// move past the \n
nextChar();
break;
case '*': // multi-line comment, read until closing */
// move past the opening *
nextChar();
// try to find a trailing */
while ( true )
{
if ( ch == '*' )
{
// check to see if we have a closing /
nextChar();
if ( ch == '/')
{
// move past the end of the closing */
nextChar();
break;
}
}
else
{
// move along, looking if the next character is a *
nextChar();
}
// when we're here we've read past the end of
// the string without finding a closing */, so error
if ( ch == '' )
{
parseError( "Multi-line comment not closed" );
}
}
break;
// Can't match a comment after a /, so it's a parsing error
default:
parseError( "Unexpected " + ch + " encountered (expecting '/' or '*' )" );
}
}
}
/**
* Skip any whitespace in the input string and advances
* the character to the first character after any possible
* whitespace.
*/
private function skipWhite():void
{
// As long as there are spaces in the input
// stream, advance the current location pointer
// past them
while ( isWhiteSpace( ch ) )
{
nextChar();
}
}
/**
* Determines if a character is whitespace or not.
*
* @return True if the character passed in is a whitespace
* character
*/
private function isWhiteSpace( ch:String ):Boolean
{
// Check for the whitespace defined in the spec
if ( ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r' )
{
return true;
}
// If we're not in strict mode, we also accept non-breaking space
else if ( !strict && ch.charCodeAt( 0 ) == 160 )
{
return true;
}
return false;
}
/**
* Determines if a character is a digit [0-9].
*
* @return True if the character passed in is a digit
*/
private function isDigit( ch:String ):Boolean
{
return ( ch >= '0' && ch <= '9' );
}
/**
* Determines if a character is a hex digit [0-9A-Fa-f].
*
* @return True if the character passed in is a hex digit
*/
private function isHexDigit( ch:String ):Boolean
{
return ( isDigit( ch ) || ( ch >= 'A' && ch <= 'F' ) || ( ch >= 'a' && ch <= 'f' ) );
}
/**
* Raises a parsing error with a specified message, tacking
* on the error location and the original string.
*
* @param message The message indicating why the error occurred
*/
public function parseError( message:String ):void
{
throw new JSONParseError( message, loc, jsonString );
}
}
}

View File

@ -0,0 +1,187 @@
/*
Copyright (c) 2008, Adobe Systems Incorporated
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Adobe Systems Incorporated nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.adobe.utils
{
/**
* Class that contains static utility methods for manipulating and working
* with Arrays.
*
* Note that all APIs assume that they are working with well formed arrays.
* i.e. they will only manipulate indexed values.
*
* @langversion ActionScript 3.0
* @playerversion Flash 9.0
* @tiptext
*/
public class ArrayUtil
{
/**
* Determines whether the specified array contains the specified value.
*
* @param arr The array that will be checked for the specified value.
*
* @param value The object which will be searched for within the array
*
* @return True if the array contains the value, False if it does not.
*
* @langversion ActionScript 3.0
* @playerversion Flash 9.0
* @tiptext
*/
public static function arrayContainsValue(arr:Array, value:Object):Boolean
{
return (arr.indexOf(value) != -1);
}
/**
* Remove all instances of the specified value from the array,
*
* @param arr The array from which the value will be removed
*
* @param value The object that will be removed from the array.
*
* @langversion ActionScript 3.0
* @playerversion Flash 9.0
* @tiptext
*/
public static function removeValueFromArray(arr:Array, value:Object):void
{
var len:uint = arr.length;
for(var i:Number = len; i > -1; i--)
{
if(arr[i] === value)
{
arr.splice(i, 1);
}
}
}
/**
* Create a new array that only contains unique instances of objects
* in the specified array.
*
* Basically, this can be used to remove duplication object instances
* from an array
*
* @param arr The array which contains the values that will be used to
* create the new array that contains no duplicate values.
*
* @return A new array which only contains unique items from the specified
* array.
*
* @langversion ActionScript 3.0
* @playerversion Flash 9.0
* @tiptext
*/
public static function createUniqueCopy(a:Array):Array
{
var newArray:Array = new Array();
var len:Number = a.length;
var item:Object;
for (var i:uint = 0; i < len; ++i)
{
item = a[i];
if(ArrayUtil.arrayContainsValue(newArray, item))
{
continue;
}
newArray.push(item);
}
return newArray;
}
/**
* Creates a copy of the specified array.
*
* Note that the array returned is a new array but the items within the
* array are not copies of the items in the original array (but rather
* references to the same items)
*
* @param arr The array that will be copies
*
* @return A new array which contains the same items as the array passed
* in.
*
* @langversion ActionScript 3.0
* @playerversion Flash 9.0
* @tiptext
*/
public static function copyArray(arr:Array):Array
{
return arr.slice();
}
/**
* Compares two arrays and returns a boolean indicating whether the arrays
* contain the same values at the same indexes.
*
* @param arr1 The first array that will be compared to the second.
*
* @param arr2 The second array that will be compared to the first.
*
* @return True if the arrays contains the same values at the same indexes.
False if they do not.
*
* @langversion ActionScript 3.0
* @playerversion Flash 9.0
* @tiptext
*/
public static function arraysAreEqual(arr1:Array, arr2:Array):Boolean
{
if(arr1.length != arr2.length)
{
return false;
}
var len:Number = arr1.length;
for(var i:Number = 0; i < len; i++)
{
if(arr1[i] !== arr2[i])
{
return false;
}
}
return true;
}
}
}

View File

@ -0,0 +1,701 @@
/*
Copyright (c) 2008, Adobe Systems Incorporated
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Adobe Systems Incorporated nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.adobe.utils
{
import mx.formatters.DateBase;
/**
* Class that contains static utility methods for manipulating and working
* with Dates.
*
* @langversion ActionScript 3.0
* @playerversion Flash 9.0
* @tiptext
*/
public class DateUtil
{
/**
* Returns the English Short Month name (3 letters) for the Month that
* the Date represents.
*
* @param d The Date instance whose month will be used to retrieve the
* short month name.
*
* @return An English 3 Letter Month abbreviation.
*
* @langversion ActionScript 3.0
* @playerversion Flash 9.0
* @tiptext
*
* @see SHORT_MONTH
*/
public static function getShortMonthName(d:Date):String
{
return DateBase.monthNamesShort[d.getMonth()];
}
/**
* Returns the index of the month that the short month name string
* represents.
*
* @param m The 3 letter abbreviation representing a short month name.
*
* @param Optional parameter indicating whether the search should be case
* sensitive
*
* @return A int that represents that month represented by the specifed
* short name.
*
* @langversion ActionScript 3.0
* @playerversion Flash 9.0
* @tiptext
*
* @see SHORT_MONTH
*/
public static function getShortMonthIndex(m:String):int
{
return DateBase.monthNamesShort.indexOf(m);
}
/**
* Returns the English full Month name for the Month that
* the Date represents.
*
* @param d The Date instance whose month will be used to retrieve the
* full month name.
*
* @return An English full month name.
*
* @langversion ActionScript 3.0
* @playerversion Flash 9.0
* @tiptext
*
* @see FULL_MONTH
*/
public static function getFullMonthName(d:Date):String
{
return DateBase.monthNamesLong[d.getMonth()];
}
/**
* Returns the index of the month that the full month name string
* represents.
*
* @param m A full month name.
*
* @return A int that represents that month represented by the specifed
* full month name.
*
* @langversion ActionScript 3.0
* @playerversion Flash 9.0
* @tiptext
*
* @see FULL_MONTH
*/
public static function getFullMonthIndex(m:String):int
{
return DateBase.monthNamesLong.indexOf(m);
}
/**
* Returns the English Short Day name (3 letters) for the day that
* the Date represents.
*
* @param d The Date instance whose day will be used to retrieve the
* short day name.
*
* @return An English 3 Letter day abbreviation.
*
* @langversion ActionScript 3.0
* @playerversion Flash 9.0
* @tiptext
*
* @see SHORT_DAY
*/
public static function getShortDayName(d:Date):String
{
return DateBase.dayNamesShort[d.getDay()];
}
/**
* Returns the index of the day that the short day name string
* represents.
*
* @param m A short day name.
*
* @return A int that represents that short day represented by the specifed
* full month name.
*
* @langversion ActionScript 3.0
* @playerversion Flash 9.0
* @tiptext
*
* @see SHORT_DAY
*/
public static function getShortDayIndex(d:String):int
{
return DateBase.dayNamesShort.indexOf(d);
}
/**
* Returns the English full day name for the day that
* the Date represents.
*
* @param d The Date instance whose day will be used to retrieve the
* full day name.
*
* @return An English full day name.
*
* @langversion ActionScript 3.0
* @playerversion Flash 9.0
* @tiptext
*
* @see FULL_DAY
*/
public static function getFullDayName(d:Date):String
{
return DateBase.dayNamesLong[d.getDay()];
}
/**
* Returns the index of the day that the full day name string
* represents.
*
* @param m A full day name.
*
* @return A int that represents that full day represented by the specifed
* full month name.
*
* @langversion ActionScript 3.0
* @playerversion Flash 9.0
* @tiptext
*
* @see FULL_DAY
*/
public static function getFullDayIndex(d:String):int
{
return DateBase.dayNamesLong.indexOf(d);
}
/**
* Returns a two digit representation of the year represented by the
* specified date.
*
* @param d The Date instance whose year will be used to generate a two
* digit string representation of the year.
*
* @return A string that contains a 2 digit representation of the year.
* Single digits will be padded with 0.
*
* @langversion ActionScript 3.0
* @playerversion Flash 9.0
* @tiptext
*/
public static function getShortYear(d:Date):String
{
var dStr:String = String(d.getFullYear());
if(dStr.length < 3)
{
return dStr;
}
return (dStr.substr(dStr.length - 2));
}
/**
* Compares two dates and returns an integer depending on their relationship.
*
* Returns -1 if d1 is greater than d2.
* Returns 1 if d2 is greater than d1.
* Returns 0 if both dates are equal.
*
* @param d1 The date that will be compared to the second date.
* @param d2 The date that will be compared to the first date.
*
* @return An int indicating how the two dates compare.
*
* @langversion ActionScript 3.0
* @playerversion Flash 9.0
* @tiptext
*/
public static function compareDates(d1:Date, d2:Date):int
{
var d1ms:Number = d1.getTime();
var d2ms:Number = d2.getTime();
if(d1ms > d2ms)
{
return -1;
}
else if(d1ms < d2ms)
{
return 1;
}
else
{
return 0;
}
}
/**
* Returns a short hour (0 - 12) represented by the specified date.
*
* If the hour is less than 12 (0 - 11 AM) then the hour will be returned.
*
* If the hour is greater than 12 (12 - 23 PM) then the hour minus 12
* will be returned.
*
* @param d1 The Date from which to generate the short hour
*
* @return An int between 0 and 13 ( 1 - 12 ) representing the short hour.
*
* @langversion ActionScript 3.0
* @playerversion Flash 9.0
* @tiptext
*/
public static function getShortHour(d:Date):int
{
var h:int = d.hours;
if(h == 0 || h == 12)
{
return 12;
}
else if(h > 12)
{
return h - 12;
}
else
{
return h;
}
}
/**
* Returns a string indicating whether the date represents a time in the
* ante meridiem (AM) or post meridiem (PM).
*
* If the hour is less than 12 then "AM" will be returned.
*
* If the hour is greater than 12 then "PM" will be returned.
*
* @param d1 The Date from which to generate the 12 hour clock indicator.
*
* @return A String ("AM" or "PM") indicating which half of the day the
* hour represents.
*
* @langversion ActionScript 3.0
* @playerversion Flash 9.0
* @tiptext
*/
public static function getAMPM(d:Date):String
{
return (d.hours > 11)? "PM" : "AM";
}
/**
* Parses dates that conform to RFC822 into Date objects. This method also
* supports four-digit years (not supported in RFC822), but two-digit years
* (referring to the 20th century) are fine, too.
*
* This function is useful for parsing RSS .91, .92, and 2.0 dates.
*
* @param str
*
* @returns
*
* @langversion ActionScript 3.0
* @playerversion Flash 9.0
* @tiptext
*
* @see http://asg.web.cmu.edu/rfc/rfc822.html
*/
public static function parseRFC822(str:String):Date
{
var finalDate:Date;
try
{
var dateParts:Array = str.split(" ");
var day:String = null;
if (dateParts[0].search(/\d/) == -1)
{
day = dateParts.shift().replace(/\W/, "");
}
var date:Number = Number(dateParts.shift());
var month:Number = Number(DateUtil.getShortMonthIndex(dateParts.shift()));
var year:Number = Number(dateParts.shift());
var timeParts:Array = dateParts.shift().split(":");
var hour:Number = int(timeParts.shift());
var minute:Number = int(timeParts.shift());
var second:Number = (timeParts.length > 0) ? int(timeParts.shift()): 0;
var milliseconds:Number = Date.UTC(year, month, date, hour, minute, second, 0);
var timezone:String = dateParts.shift();
var offset:Number = 0;
if (timezone.search(/\d/) == -1)
{
switch(timezone)
{
case "UT":
offset = 0;
break;
case "UTC":
offset = 0;
break;
case "GMT":
offset = 0;
break;
case "EST":
offset = (-5 * 3600000);
break;
case "EDT":
offset = (-4 * 3600000);
break;
case "CST":
offset = (-6 * 3600000);
break;
case "CDT":
offset = (-5 * 3600000);
break;
case "MST":
offset = (-7 * 3600000);
break;
case "MDT":
offset = (-6 * 3600000);
break;
case "PST":
offset = (-8 * 3600000);
break;
case "PDT":
offset = (-7 * 3600000);
break;
case "Z":
offset = 0;
break;
case "A":
offset = (-1 * 3600000);
break;
case "M":
offset = (-12 * 3600000);
break;
case "N":
offset = (1 * 3600000);
break;
case "Y":
offset = (12 * 3600000);
break;
default:
offset = 0;
}
}
else
{
var multiplier:Number = 1;
var oHours:Number = 0;
var oMinutes:Number = 0;
if (timezone.length != 4)
{
if (timezone.charAt(0) == "-")
{
multiplier = -1;
}
timezone = timezone.substr(1, 4);
}
oHours = Number(timezone.substr(0, 2));
oMinutes = Number(timezone.substr(2, 2));
offset = (((oHours * 3600000) + (oMinutes * 60000)) * multiplier);
}
finalDate = new Date(milliseconds - offset);
if (finalDate.toString() == "Invalid Date")
{
throw new Error("This date does not conform to RFC822.");
}
}
catch (e:Error)
{
var eStr:String = "Unable to parse the string [" +str+ "] into a date. ";
eStr += "The internal error was: " + e.toString();
throw new Error(eStr);
}
return finalDate;
}
/**
* Returns a date string formatted according to RFC822.
*
* @param d
*
* @returns
*
* @langversion ActionScript 3.0
* @playerversion Flash 9.0
* @tiptext
*
* @see http://asg.web.cmu.edu/rfc/rfc822.html
*/
public static function toRFC822(d:Date):String
{
var date:Number = d.getUTCDate();
var hours:Number = d.getUTCHours();
var minutes:Number = d.getUTCMinutes();
var seconds:Number = d.getUTCSeconds();
var sb:String = new String();
sb += DateBase.dayNamesShort[d.getUTCDay()];
sb += ", ";
if (date < 10)
{
sb += "0";
}
sb += date;
sb += " ";
//sb += DateUtil.SHORT_MONTH[d.getUTCMonth()];
sb += DateBase.monthNamesShort[d.getUTCMonth()];
sb += " ";
sb += d.getUTCFullYear();
sb += " ";
if (hours < 10)
{
sb += "0";
}
sb += hours;
sb += ":";
if (minutes < 10)
{
sb += "0";
}
sb += minutes;
sb += ":";
if (seconds < 10)
{
sb += "0";
}
sb += seconds;
sb += " GMT";
return sb;
}
/**
* Parses dates that conform to the W3C Date-time Format into Date objects.
*
* This function is useful for parsing RSS 1.0 and Atom 1.0 dates.
*
* @param str
*
* @returns
*
* @langversion ActionScript 3.0
* @playerversion Flash 9.0
* @tiptext
*
* @see http://www.w3.org/TR/NOTE-datetime
*/
public static function parseW3CDTF(str:String):Date
{
var finalDate:Date;
try
{
var dateStr:String = str.substring(0, str.indexOf("T"));
var timeStr:String = str.substring(str.indexOf("T")+1, str.length);
var dateArr:Array = dateStr.split("-");
var year:Number = Number(dateArr.shift());
var month:Number = Number(dateArr.shift());
var date:Number = Number(dateArr.shift());
var multiplier:Number;
var offsetHours:Number;
var offsetMinutes:Number;
var offsetStr:String;
if (timeStr.indexOf("Z") != -1)
{
multiplier = 1;
offsetHours = 0;
offsetMinutes = 0;
timeStr = timeStr.replace("Z", "");
}
else if (timeStr.indexOf("+") != -1)
{
multiplier = 1;
offsetStr = timeStr.substring(timeStr.indexOf("+")+1, timeStr.length);
offsetHours = Number(offsetStr.substring(0, offsetStr.indexOf(":")));
offsetMinutes = Number(offsetStr.substring(offsetStr.indexOf(":")+1, offsetStr.length));
timeStr = timeStr.substring(0, timeStr.indexOf("+"));
}
else // offset is -
{
multiplier = -1;
offsetStr = timeStr.substring(timeStr.indexOf("-")+1, timeStr.length);
offsetHours = Number(offsetStr.substring(0, offsetStr.indexOf(":")));
offsetMinutes = Number(offsetStr.substring(offsetStr.indexOf(":")+1, offsetStr.length));
timeStr = timeStr.substring(0, timeStr.indexOf("-"));
}
var timeArr:Array = timeStr.split(":");
var hour:Number = Number(timeArr.shift());
var minutes:Number = Number(timeArr.shift());
var secondsArr:Array = (timeArr.length > 0) ? String(timeArr.shift()).split(".") : null;
var seconds:Number = (secondsArr != null && secondsArr.length > 0) ? Number(secondsArr.shift()) : 0;
//var milliseconds:Number = (secondsArr != null && secondsArr.length > 0) ? Number(secondsArr.shift()) : 0;
var milliseconds:Number = (secondsArr != null && secondsArr.length > 0) ? 1000*parseFloat("0." + secondsArr.shift()) : 0;
var utc:Number = Date.UTC(year, month-1, date, hour, minutes, seconds, milliseconds);
var offset:Number = (((offsetHours * 3600000) + (offsetMinutes * 60000)) * multiplier);
finalDate = new Date(utc - offset);
if (finalDate.toString() == "Invalid Date")
{
throw new Error("This date does not conform to W3CDTF.");
}
}
catch (e:Error)
{
var eStr:String = "Unable to parse the string [" +str+ "] into a date. ";
eStr += "The internal error was: " + e.toString();
throw new Error(eStr);
}
return finalDate;
}
/**
* Returns a date string formatted according to W3CDTF.
*
* @param d
* @param includeMilliseconds Determines whether to include the
* milliseconds value (if any) in the formatted string.
*
* @returns
*
* @langversion ActionScript 3.0
* @playerversion Flash 9.0
* @tiptext
*
* @see http://www.w3.org/TR/NOTE-datetime
*/
public static function toW3CDTF(d:Date,includeMilliseconds:Boolean=false):String
{
var date:Number = d.getUTCDate();
var month:Number = d.getUTCMonth();
var hours:Number = d.getUTCHours();
var minutes:Number = d.getUTCMinutes();
var seconds:Number = d.getUTCSeconds();
var milliseconds:Number = d.getUTCMilliseconds();
var sb:String = new String();
sb += d.getUTCFullYear();
sb += "-";
//thanks to "dom" who sent in a fix for the line below
if (month + 1 < 10)
{
sb += "0";
}
sb += month + 1;
sb += "-";
if (date < 10)
{
sb += "0";
}
sb += date;
sb += "T";
if (hours < 10)
{
sb += "0";
}
sb += hours;
sb += ":";
if (minutes < 10)
{
sb += "0";
}
sb += minutes;
sb += ":";
if (seconds < 10)
{
sb += "0";
}
sb += seconds;
if (includeMilliseconds && milliseconds > 0)
{
sb += ".";
sb += milliseconds;
}
sb += "-00:00";
return sb;
}
/**
* Converts a date into just after midnight.
*/
public static function makeMorning(d:Date):Date
{
var d:Date = new Date(d.time);
d.hours = 0;
d.minutes = 0;
d.seconds = 0;
d.milliseconds = 0;
return d;
}
/**
* Converts a date into just befor midnight.
*/
public static function makeNight(d:Date):Date
{
var d:Date = new Date(d.time);
d.hours = 23;
d.minutes = 59;
d.seconds = 59;
d.milliseconds = 999;
return d;
}
/**
* Sort of converts a date into UTC.
*/
public static function getUTCDate(d:Date):Date
{
var nd:Date = new Date();
var offset:Number = d.getTimezoneOffset() * 60 * 1000;
nd.setTime(d.getTime() + offset);
return nd;
}
}
}

View File

@ -0,0 +1,87 @@
/*
Copyright (c) 2008, Adobe Systems Incorporated
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Adobe Systems Incorporated nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.adobe.utils
{
import flash.utils.Dictionary;
public class DictionaryUtil
{
/**
* Returns an Array of all keys within the specified dictionary.
*
* @param d The Dictionary instance whose keys will be returned.
*
* @return Array of keys contained within the Dictionary
*
* @langversion ActionScript 3.0
* @playerversion Flash 9.0
* @tiptext
*/
public static function getKeys(d:Dictionary):Array
{
var a:Array = new Array();
for (var key:Object in d)
{
a.push(key);
}
return a;
}
/**
* Returns an Array of all values within the specified dictionary.
*
* @param d The Dictionary instance whose values will be returned.
*
* @return Array of values contained within the Dictionary
*
* @langversion ActionScript 3.0
* @playerversion Flash 9.0
* @tiptext
*/
public static function getValues(d:Dictionary):Array
{
var a:Array = new Array();
for each (var value:Object in d)
{
a.push(value);
}
return a;
}
}
}

View File

@ -0,0 +1,99 @@
/*
Copyright (c) 2008, Adobe Systems Incorporated
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Adobe Systems Incorporated nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.adobe.utils {
import flash.utils.Endian;
/**
* Contains reusable methods for operations pertaining
* to int values.
*/
public class IntUtil {
/**
* Rotates x left n bits
*
* @langversion ActionScript 3.0
* @playerversion Flash 9.0
* @tiptext
*/
public static function rol ( x:int, n:int ):int {
return ( x << n ) | ( x >>> ( 32 - n ) );
}
/**
* Rotates x right n bits
*
* @langversion ActionScript 3.0
* @playerversion Flash 9.0
* @tiptext
*/
public static function ror ( x:int, n:int ):uint {
var nn:int = 32 - n;
return ( x << nn ) | ( x >>> ( 32 - nn ) );
}
/** String for quick lookup of a hex character based on index */
private static var hexChars:String = "0123456789abcdef";
/**
* Outputs the hex value of a int, allowing the developer to specify
* the endinaness in the process. Hex output is lowercase.
*
* @param n The int value to output as hex
* @param bigEndian Flag to output the int as big or little endian
* @return A string of length 8 corresponding to the
* hex representation of n ( minus the leading "0x" )
* @langversion ActionScript 3.0
* @playerversion Flash 9.0
* @tiptext
*/
public static function toHex( n:int, bigEndian:Boolean = false ):String {
var s:String = "";
if ( bigEndian ) {
for ( var i:int = 0; i < 4; i++ ) {
s += hexChars.charAt( ( n >> ( ( 3 - i ) * 8 + 4 ) ) & 0xF )
+ hexChars.charAt( ( n >> ( ( 3 - i ) * 8 ) ) & 0xF );
}
} else {
for ( var x:int = 0; x < 4; x++ ) {
s += hexChars.charAt( ( n >> ( x * 8 + 4 ) ) & 0xF )
+ hexChars.charAt( ( n >> ( x * 8 ) ) & 0xF );
}
}
return s;
}
}
}

View File

@ -0,0 +1,74 @@
/*
Copyright (c) 2008, Adobe Systems Incorporated
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Adobe Systems Incorporated nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.adobe.utils
{
/**
* Class that contains static utility methods for formatting Numbers
*
* @langversion ActionScript 3.0
* @playerversion Flash 9.0
* @tiptext
*
* @see #mx.formatters.NumberFormatter
*/
public class NumberFormatter
{
/**
* Formats a number to include a leading zero if it is a single digit
* between -1 and 10.
*
* @param n The number that will be formatted
*
* @return A string with single digits between -1 and 10 padded with a
* leading zero.
*
* @langversion ActionScript 3.0
* @playerversion Flash 9.0
* @tiptext
*/
public static function addLeadingZero(n:Number):String
{
var out:String = String(n);
if(n < 10 && n > -1)
{
out = "0" + out;
}
return out;
}
}
}

View File

@ -0,0 +1,239 @@
/*
Copyright (c) 2008, Adobe Systems Incorporated
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Adobe Systems Incorporated nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.adobe.utils
{
/**
* Class that contains static utility methods for manipulating Strings.
*
* @langversion ActionScript 3.0
* @playerversion Flash 9.0
* @tiptext
*/
public class StringUtil
{
/**
* Does a case insensitive compare or two strings and returns true if
* they are equal.
*
* @param s1 The first string to compare.
*
* @param s2 The second string to compare.
*
* @returns A boolean value indicating whether the strings' values are
* equal in a case sensitive compare.
*
* @langversion ActionScript 3.0
* @playerversion Flash 9.0
* @tiptext
*/
public static function stringsAreEqual(s1:String, s2:String,
caseSensitive:Boolean):Boolean
{
if(caseSensitive)
{
return (s1 == s2);
}
else
{
return (s1.toUpperCase() == s2.toUpperCase());
}
}
/**
* Removes whitespace from the front and the end of the specified
* string.
*
* @param input The String whose beginning and ending whitespace will
* will be removed.
*
* @returns A String with whitespace removed from the begining and end
*
* @langversion ActionScript 3.0
* @playerversion Flash 9.0
* @tiptext
*/
public static function trim(input:String):String
{
return StringUtil.ltrim(StringUtil.rtrim(input));
}
/**
* Removes whitespace from the front of the specified string.
*
* @param input The String whose beginning whitespace will will be removed.
*
* @returns A String with whitespace removed from the begining
*
* @langversion ActionScript 3.0
* @playerversion Flash 9.0
* @tiptext
*/
public static function ltrim(input:String):String
{
var size:Number = input.length;
for(var i:Number = 0; i < size; i++)
{
if(input.charCodeAt(i) > 32)
{
return input.substring(i);
}
}
return "";
}
/**
* Removes whitespace from the end of the specified string.
*
* @param input The String whose ending whitespace will will be removed.
*
* @returns A String with whitespace removed from the end
*
* @langversion ActionScript 3.0
* @playerversion Flash 9.0
* @tiptext
*/
public static function rtrim(input:String):String
{
var size:Number = input.length;
for(var i:Number = size; i > 0; i--)
{
if(input.charCodeAt(i - 1) > 32)
{
return input.substring(0, i);
}
}
return "";
}
/**
* Determines whether the specified string begins with the spcified prefix.
*
* @param input The string that the prefix will be checked against.
*
* @param prefix The prefix that will be tested against the string.
*
* @returns True if the string starts with the prefix, false if it does not.
*
* @langversion ActionScript 3.0
* @playerversion Flash 9.0
* @tiptext
*/
public static function beginsWith(input:String, prefix:String):Boolean
{
return (prefix == input.substring(0, prefix.length));
}
/**
* Determines whether the specified string ends with the spcified suffix.
*
* @param input The string that the suffic will be checked against.
*
* @param prefix The suffic that will be tested against the string.
*
* @returns True if the string ends with the suffix, false if it does not.
*
* @langversion ActionScript 3.0
* @playerversion Flash 9.0
* @tiptext
*/
public static function endsWith(input:String, suffix:String):Boolean
{
return (suffix == input.substring(input.length - suffix.length));
}
/**
* Removes all instances of the remove string in the input string.
*
* @param input The string that will be checked for instances of remove
* string
*
* @param remove The string that will be removed from the input string.
*
* @returns A String with the remove string removed.
*
* @langversion ActionScript 3.0
* @playerversion Flash 9.0
* @tiptext
*/
public static function remove(input:String, remove:String):String
{
return StringUtil.replace(input, remove, "");
}
/**
* Replaces all instances of the replace string in the input string
* with the replaceWith string.
*
* @param input The string that instances of replace string will be
* replaces with removeWith string.
*
* @param replace The string that will be replaced by instances of
* the replaceWith string.
*
* @param replaceWith The string that will replace instances of replace
* string.
*
* @returns A new String with the replace string replaced with the
* replaceWith string.
*
* @langversion ActionScript 3.0
* @playerversion Flash 9.0
* @tiptext
*/
public static function replace(input:String, replace:String, replaceWith:String):String
{
return input.split(replace).join(replaceWith);
}
/**
* Specifies whether the specified string is either non-null, or contains
* characters (i.e. length is greater that 0)
*
* @param s The string which is being checked for a value
*
* @langversion ActionScript 3.0
* @playerversion Flash 9.0
* @tiptext
*/
public static function stringHasValue(s:String):Boolean
{
//todo: this needs a unit test
return (s != null && s.length > 0);
}
}
}

View File

@ -0,0 +1,168 @@
/*
Copyright (c) 2008, Adobe Systems Incorporated
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Adobe Systems Incorporated nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.adobe.utils
{
public class XMLUtil
{
/**
* Constant representing a text node type returned from XML.nodeKind.
*
* @see XML.nodeKind()
*
* @langversion ActionScript 3.0
* @playerversion Flash 9.0
*/
public static const TEXT:String = "text";
/**
* Constant representing a comment node type returned from XML.nodeKind.
*
* @see XML.nodeKind()
*
* @langversion ActionScript 3.0
* @playerversion Flash 9.0
*/
public static const COMMENT:String = "comment";
/**
* Constant representing a processing instruction type returned from XML.nodeKind.
*
* @see XML.nodeKind()
*
* @langversion ActionScript 3.0
* @playerversion Flash 9.0
*/
public static const PROCESSING_INSTRUCTION:String = "processing-instruction";
/**
* Constant representing an attribute type returned from XML.nodeKind.
*
* @see XML.nodeKind()
*
* @langversion ActionScript 3.0
* @playerversion Flash 9.0
*/
public static const ATTRIBUTE:String = "attribute";
/**
* Constant representing a element type returned from XML.nodeKind.
*
* @see XML.nodeKind()
*
* @langversion ActionScript 3.0
* @playerversion Flash 9.0
*/
public static const ELEMENT:String = "element";
/**
* Checks whether the specified string is valid and well formed XML.
*
* @param data The string that is being checked to see if it is valid XML.
*
* @return A Boolean value indicating whether the specified string is
* valid XML.
*
* @langversion ActionScript 3.0
* @playerversion Flash 9.0
*/
public static function isValidXML(data:String):Boolean
{
var xml:XML;
try
{
xml = new XML(data);
}
catch(e:Error)
{
return false;
}
if(xml.nodeKind() != XMLUtil.ELEMENT)
{
return false;
}
return true;
}
/**
* Returns the next sibling of the specified node relative to the node's parent.
*
* @param x The node whose next sibling will be returned.
*
* @return The next sibling of the node. null if the node does not have
* a sibling after it, or if the node has no parent.
*
* @langversion ActionScript 3.0
* @playerversion Flash 9.0
*/
public static function getNextSibling(x:XML):XML
{
return XMLUtil.getSiblingByIndex(x, 1);
}
/**
* Returns the sibling before the specified node relative to the node's parent.
*
* @param x The node whose sibling before it will be returned.
*
* @return The sibling before the node. null if the node does not have
* a sibling before it, or if the node has no parent.
*
* @langversion ActionScript 3.0
* @playerversion Flash 9.0
*/
public static function getPreviousSibling(x:XML):XML
{
return XMLUtil.getSiblingByIndex(x, -1);
}
protected static function getSiblingByIndex(x:XML, count:int):XML
{
var out:XML;
try
{
out = x.parent().children()[x.childIndex() + count];
}
catch(e:Error)
{
return null;
}
return out;
}
}
}

View File

@ -0,0 +1,48 @@
/*
Copyright (c) 2008, Adobe Systems Incorporated
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Adobe Systems Incorporated nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.adobe.webapis
{
import flash.events.EventDispatcher;
/**
* Base class for remote service classes.
*/
public class ServiceBase extends EventDispatcher
{
public function ServiceBase()
{
}
}
}

View File

@ -0,0 +1,108 @@
/*
Copyright (c) 2008, Adobe Systems Incorporated
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Adobe Systems Incorporated nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.adobe.webapis
{
import flash.events.IOErrorEvent;
import flash.events.SecurityErrorEvent;
import flash.events.ProgressEvent;
import com.adobe.net.DynamicURLLoader;
/**
* Dispatched when data is
* received as the download operation progresses.
*
* @eventType flash.events.ProgressEvent.PROGRESS
*
* @langversion ActionScript 3.0
* @playerversion Flash 9.0
*/
[Event(name="progress", type="flash.events.ProgressEvent")]
/**
* Dispatched if a call to the server results in a fatal
* error that terminates the download.
*
* @eventType flash.events.IOErrorEvent.IO_ERROR
*
* @langversion ActionScript 3.0
* @playerversion Flash 9.0
*/
[Event(name="ioError", type="flash.events.IOErrorEvent")]
/**
* A securityError event occurs if a call attempts to
* load data from a server outside the security sandbox.
*
* @eventType flash.events.SecurityErrorEvent.SECURITY_ERROR
*
* @langversion ActionScript 3.0
* @playerversion Flash 9.0
*/
[Event(name="securityError", type="flash.events.SecurityErrorEvent")]
/**
* Base class for services that utilize URLLoader
* to communicate with remote APIs / Services.
*
* @langversion ActionScript 3.0
* @playerversion Flash 9.0
*/
public class URLLoaderBase extends ServiceBase
{
protected function getURLLoader():DynamicURLLoader
{
var loader:DynamicURLLoader = new DynamicURLLoader();
loader.addEventListener("progress", onProgress);
loader.addEventListener("ioError", onIOError);
loader.addEventListener("securityError", onSecurityError);
return loader;
}
private function onIOError(event:IOErrorEvent):void
{
dispatchEvent(event);
}
private function onSecurityError(event:SecurityErrorEvent):void
{
dispatchEvent(event);
}
private function onProgress(event:ProgressEvent):void
{
dispatchEvent(event);
}
}
}

View File

@ -0,0 +1,82 @@
/*
Copyright (c) 2008, Adobe Systems Incorporated
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Adobe Systems Incorporated nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.adobe.webapis.events
{
import flash.events.Event;
/**
* Event class that contains data loaded from remote services.
*
* @author Mike Chambers
*/
public class ServiceEvent extends Event
{
private var _data:Object = new Object();;
/**
* Constructor for ServiceEvent class.
*
* @param type The type of event that the instance represents.
*/
public function ServiceEvent(type:String, bubbles:Boolean = false,
cancelable:Boolean=false)
{
super(type, bubbles, cancelable);
}
/**
* This object contains data loaded in response
* to remote service calls, and properties associated with that call.
*/
public function get data():Object
{
return _data;
}
public function set data(d:Object):void
{
_data = d;
}
public override function clone():Event
{
var out:ServiceEvent = new ServiceEvent(type, bubbles, cancelable);
out.data = data;
return out;
}
}
}

View File

@ -0,0 +1,657 @@
<html>
<head>
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Expires" content="-1">
<meta http-equiv="cache-control" content="no-store">
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
<script language="javascript" content-type="text/javascript" src="swfobject.js"></script>
<script language="javascript" content-type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.3/jquery-ui.min.js" ></script>
<script language="javascript" type="text/javascript" src="jquery.query-2.1.7.js"></script>
<script language="javascript" type="text/javascript" src="jquery.tmpl.js"></script>
<script language="javascript" type="text/javascript" src="http://js-hotkeys.googlecode.com/files/jquery.hotkeys-0.7.9.min.js"></script>
<script language="javascript" content-type="text/javascript">
var flashvars = {
rtmp_url: 'rtmp://deathstar.freeswitch.org/phone'
};
var params = {
allowScriptAccess: 'always'
};
function makeCall(number, account, options) {
$("#flash")[0].makeCall(number, account, options);
}
function sendDTMF(digit, duration) {
$("#flash")[0].sendDTMF(digit, duration);
}
function onDisplayUpdate(uuid, name, number) {
var elm = $("#call_" + uuid);
elm.children(".callerid_name").text(name);
elm.children(".callerid_number").text(number);
elm.data("name", name);
elm.data("number", number);
if (uuid == $("#incoming_call").data("uuid")) {
$("#incoming_name").text(name);
$("#incoming_number").text(number);
}
}
function hangup(uuid) {
$("#flash")[0].hangup(uuid);
}
function answer(uuid) {
$("#flash")[0].answer(uuid);
}
function attach(uuid) {
$("#flash")[0].attach(uuid);
}
function transfer(uuid, dest) {
$("#flash")[0].transfer(uuid, dest);
}
function ui_transfer(uuid) {
$("#transfer").data("uuid", uuid);
$("#transfer").dialog('open');
}
function three_way(uuid1, uuid2) {
$("#flash")[0].three_way(uuid1, uuid2);
}
function do_three_way(uuid) {
var a = $(".active_call").data("uuid");
if (a != "") {
three_way(a, uuid);
}
}
function do_join(uuid) {
var a = $(".active_call").data("uuid");
if (a != "") {
join(a, uuid);
}
}
function join(uuid1, uuid2) {
$("#flash")[0].join(uuid1, uuid2);
}
function onCallState(uuid, state) {
$("#call_"+uuid).children('.call_state').text(state);
}
function onIncomingCall(uuid, name, number, account, evt) {
if (name == "") {
name = "Unknown Name";
}
if (number == "") {
number = "Unknown Number";
}
add_call(uuid, name, number);
$("#incoming_call").data("uuid", uuid);
$("#incoming_name").text(name);
$("#incoming_number").text(number);
$("#incoming_account").text(account);
$("#incoming_call").dialog('open');
}
function onDisconnected() {
$("#status").text("Disconnected");
$("#sessionid").text("");
setTimeout(function() {
$("#status").text("Connecting...");
$("#flash")[0].connect();
}, 5000);
}
function onMakeCall(uuid, number, account) {
add_call(uuid, "", number, account);
}
function onHangup(uuid, cause) {
if ($("#incoming_call").data("uuid") == uuid) {
$("#incoming_call").dialog('close');
}
$("#call_" + uuid).children(".hangupcause").text(cause);
setTimeout(function() {
remove_call(uuid);
}, 1000);
}
function onDebug(message) {
$("#log").append(message + "<br/>");
}
function onAttach(uuid) {
$(".active_call").removeClass('active_call');
if (uuid == "") {
$("a", "#controls").button("option", "disabled", true);
} else {
$("a", "#controls").button("option", "disabled", false);
$("#call_" + uuid).addClass('active_call');
}
}
function checkMic() {
try {
if ($("#flash")[0].isMuted()) {
$("#no_mic").show();
$("#input_source").hide();
return false;
} else {
$("#no_mic").hide();
$("#input_source").show();
return true;
}
} catch(err) {
return false;
}
}
function onConnected(sessionid) {
$("#sessionid").text(sessionid);
$(".call", "#call_container").remove();
$(".account", "#account_container").remove();
$("#status").text("Connected");
if (!checkMic()) {
$("#security").dialog('open');
}
}
function login(user,pass) {
$("#flash")[0].login(user,pass);
}
function logout(account) {
$("#flash")[0].logout(account);
}
function onLogin(status, user, domain) {
if (status != "success") {
softAlert("Authentication failed!", "onAuth");
} else {
//$("#status").html("Connected as <span class='user'>" + user + "</span>@<span class='domain'>" + domain + "</span>");
var u = user + '@' + domain;
$("#flash")[0].register(u, $.query.get('code'));
add_account(user, domain);
}
}
function onLogout(user,domain) {
remove_account(user, domain);
}
function onInit() {
var mics = eval($("#flash")[0].micList());
var sources = $("#input_source");
var current_mic = $("#flash")[0].getMic();
sources.children().remove();
$("#status").text("Connecting...");
for (i = 0; i < mics.length; i++) {
var a = (i == current_mic) ? "selected" : "";
sources.append("<option value='"+ i + "' " + a + " >" + mics[i] + "</option");
}
}
function onEvent(data) {
onDebug("Got event: " + data);
}
function softAlert(message,title) {
$("#message_text").text(message);
$("#message").dialog('option', 'title', title);
$("#message").dialog('open');
}
function get_uuid(object) {
return object.parent(".call").data("uuid");
}
function add_call(uuid, name, number, account) {
var c = [ {uuid: uuid, name: name, number: number, account: account } ];
var elm = $("#call_template").render(c);
elm.data("uuid", uuid);
elm.data("name", name);
elm.data("number", number);
elm.data("account", account);
elm.appendTo("#call_container");
}
function remove_call(uuid) {
var c = $('#call_'+ uuid);
c.fadeOut("slow", function() { c.remove() } );
}
function get_user(object) {
return object.parent(".account").data("user");
}
function add_account(suser, domain) {
var u = suser + "@" + domain;
var sid = u.replace("@", "_").replace(/\./g, "_");
var c = [ { id: sid, user: u} ];
var elm = $("#account_template").render(c);
elm.data("user", u);
elm.appendTo("#account_container");
$("a", "#account_" + sid).button();
}
function remove_account(suser,domain) {
var u = suser + "_" + domain;
var sid = u.replace(/\./g, "_")
var c = $('#account_'+ sid);
c.fadeOut("slow", function() { c.remove() } );
}
function showSecurity() {
$("#security").dialog('open');
}
function newcall(account) {
$("#callout").data('account', account);
$("#callout").dialog('open');
}
$(document).ready(function() {
swfobject.embedSWF("freeswitch.swf", "flash", "250", "150", "9.0.0", "expressInstall.swf", flashvars, params, []);
if (swfobject.ua.ie) {
$("#flash").css("top", "-500px");
$("#flash").css("left", "-500px");
} else {
$("#flash").css("visibility", "hidden");
}
$("#incoming_call").dialog({
autoOpen: false,
resizable: false,
buttons: {
"Answer": function() {
answer($(this).data("uuid"));
$(this).dialog("close");
},
"Decline": function() {
hangup($(this).data("uuid"));
$(this).dialog("close");
}
}});
$("#callout").dialog({
autoOpen: false,
resizable: false,
width: 600,
buttons: {
"Call": function() {
makeCall($("#number").val(), $(this).data('account'), []);
$(this).dialog("close");
},
"Cancel": function() {
$(this).dialog("close"); }
}
});
$("#message").dialog({
autoOpen: false,
resizable: false,
buttons: {
"Ok": function() {
$(this).dialog("close");
}
}});
$("#controls").dialog({
title: "Keypad",
autoOpen: false,
resizable: false,
width: 200,
height: 220
});
$("#auth").dialog({
modal: true,
autoOpen: false,
resizable: false,
buttons: {
"Ok": function() {
login($("#username").val(), $("#password").val());
$("#password").val('');
$(this).dialog('close');
},
"Cancel": function() {
$(this).dialog('close');
}
}
});
$("#transfer").dialog({
autoOpen: false,
resizable: false,
width: 600,
buttons: {
"Ok": function() {
transfer($(this).data("uuid"), $("#transfer_number").val());
$(this).dialog('close');
},
"Cancel": function() {
$(this).dialog('close');
}
}
});
$("#security").dialog({
autoOpen: false,
modal: true,
resizable: false,
buttons: {
"Ok": function() {
$(this).dialog("close");
}
},
minWidth: 300,
minHeight: 170,
drag: function () {
var flash = $("#flash");
var fake_flash = $("#fake_flash");
var offset = fake_flash.offset();
flash.css("left", offset.left);
flash.css("top", offset.top + 20);
},
open: function () {
var flash = $("#flash");
var fake_flash = $("#fake_flash");
var offset = fake_flash.offset();
fake_flash.css("width", flash.width())
fake_flash.css("height", flash.height() + 20)
flash.css("left", offset.left);
flash.css("top", offset.top + 20);
flash.css("visibility", "visible");
flash.css("z-index", $("#security").parent(".ui-dialog").css("z-index") + 1);
flash[0].showPrivacy();
},
close: function() {
var flash = $("#flash");
flash.css("visibility", "hidden");
flash.css("left", 0);
flash.css("top", 0);
flash.css("z-index", "auto");
checkMic();
}
});
$("a", "#controls").button({ disabled: true });
$("a", "#call_container").button();
$("a", "#guest_account").button();
/*
$(document).bind('keydown', '1', function() { sendDTMF('1', 2000); return false; });
$(document).bind('keydown', '2', function() { sendDTMF('2', 2000); return false; });
$(document).bind('keydown', '3', function() { sendDTMF('3', 2000); return false; });
$(document).bind('keydown', '4', function() { sendDTMF('4', 2000); return false; });
$(document).bind('keydown', '5', function() { sendDTMF('5', 2000); return false; });
$(document).bind('keydown', '6', function() { sendDTMF('6', 2000); return false; });
$(document).bind('keydown', '7', function() { sendDTMF('7', 2000); return false; });
$(document).bind('keydown', '8', function() { sendDTMF('8', 2000); return false; });
$(document).bind('keydown', '9', function() { sendDTMF('9', 2000); return false; });
$(document).bind('keydown', '0', function() { sendDTMF('0', 2000); return false; });
$(document).bind('keydown', '#', function() { sendDTMF('#', 2000); return false; });
$(document).bind('keydown', '*', function() { sendDTMF('*', 2000); return false; });
*/
});
function testevent() {
var evt = {
test1: "hello",
test2: "hallo",
test3: "allo"
};
$("#flash")[0].sendevent(evt);
}
</script>
<style type="text/css">
.dtmfrow {
min-width: 50px;
width: 20px;
height: 20px;
text-align: center;
vertical-align: center;
}
#call_container {
float: right;
}
#account_container {
float: left;
}
.call {
border: 1px solid #181469;
width: 400px;
height: 120px;
}
.account, #guest_account {
border: 1px solid #181469;
height: 100px;
width: 300px;
padding-left: 20px;
}
#call_add {
width: 400px;
text-align: right;
}
.active_call {
background-color: #DBF2C2;
}
.three_way {
background-color: #C0DAF2;
}
#controls {
float: left;
}
#flash {
float: left;
visibility: hidden;
position: absolute;
top: 0;
left: 0;
}
#log {
font-size: 13px;
}
#header {
background-color: #003366;
color: white;
height: 30px;
width: 100%;
padding-top: 10px;
padding-left: 5px;
}
#input_source_container {
}
#status {
}
#sessionid {
margin-left: 20px;
}
#header a, #header a:visited, #header a:hover {
color: #white;
text-decoration: underline;
}
#no_mic {
float: right;
padding-right: 10px;
display: none;
}
#input_source {
float: right;
padding-right: 10px;
}
</style>
<script id="call_template" type="text/html">
<div class="call" id="call_{{= uuid}}">
<p class="callerid">
Account: {{= account}}<br/>
<span class="callerid_name">{{= name}}</span> <span class="callerid_number">{{= number}}</span>
</p>
Call state: <span class="call_state"></span> <span class="hangupcause"></span><br/>
<a href="#" onClick="attach(get_uuid($(this)))">Switch</a>
<a href="#" onClick="hangup(get_uuid($(this)))">Hangup</a>
<a href="#" onClick="do_three_way(get_uuid($(this)))">3-way</a>
<a href="#" onClick="do_join(get_uuid($(this)))">Join</a>
<a href="#" onClick="ui_transfer(get_uuid($(this)))">Transfer</a>
</div>
</script>
<script id="account_template" type="text/html">
<div class="account" id="account_{{= id}}">
<p>User: {{= user}}</p>
<a href="#" onClick="logout(get_user($(this)))">Logout</a>
<a href="#" onClick="newcall(get_user($(this)));">+ New Call</a>
</div>
</script>
</head>
<body>
<!-- Dialogs -->
<div id="incoming_call" title="Incoming call">
Account: <span id="incoming_account"></span><br/>
<h3><span id="incoming_name"></span></h3>
<h3><span id="incoming_number"></span></h3>
</div>
<div id="callout" title="Call out">
<input type="text" id="number" value="sip:888@conference.freeswitch.org" size="58" />
</div>
<div id="message">
<span id="message_text"></span>
</div>
<div id="transfer" title="Transfer call">
<input type="text" id="transfer_number" value="sip:888@conference.freeswitch.org" size="58" />
</div>
<div id="security" title="Permissions required">
You must accept to use your microphone on this site in order to be able to make phone calls
<div id="fake_flash" width="300" height="170"></div>
</div>
<div id="auth" title="Login">
Username: <input type="text" name="username" value="" id="username" />
Password: <input type="password" name="password" value="" id="password" />
</div>
<!-- End Dialogs -->
<div id="header">
<span id="status">Waiting for flash...</span>
<span id="sessionid"></span>
<span id="no_mic">
<img src="warning-icon.png" width="21" height="20" />
<a href="#" onClick="showSecurity();">Microphone not allowed</a>
</span>
<select id="input_source" onChange="$('#flash')[0].setMic($(this).val())" >
</select>
</div>
<div id="flash">
<h1>Alternative content</h1>
<p><a href="http://www.adobe.com/go/getflashplayer"><img src="http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif" alt="Get Adobe Flash player" /></a></p>
</div>
<div id="call_container">
<div id="call_add" class="button">
<a href="#" onClick="attach('');">Hold</a>
</div>
</div>
<div>
<a href="#" onClick="showSecurity();">Privacy</a>
<a href="#" onClick="$('#log').html('')" >Clear log</a>
<a href="#" onClick="$('#controls').dialog('open');">Show Keypad</a>
<a href="#" onClick="$('#auth').dialog('open');">Login</a>
</div>
<div id="controls" class="button">
<table cols=3 border=0>
<tr>
<td class="dtmfrow"><a href="#" onClick="sendDTMF('1', 2000)">1</a></td>
<td class="dtmfrow"><a href="#" onClick="sendDTMF('2', 2000)">2</a></td>
<td class="dtmfrow"><a href="#" onClick="sendDTMF('3', 2000)">3</a></td>
</tr>
<tr>
<td class="dtmfrow"><a href="#" onClick="sendDTMF('4', 2000)">4</a></td>
<td class="dtmfrow"><a href="#" onClick="sendDTMF('5', 2000)">5</a></td>
<td class="dtmfrow"><a href="#" onClick="sendDTMF('6', 2000)">6</a></td>
</tr>
<tr>
<td class="dtmfrow"><a href="#" onClick="sendDTMF('7', 2000)">7</a></td>
<td class="dtmfrow"><a href="#" onClick="sendDTMF('8', 2000)">8</a></td>
<td class="dtmfrow"><a href="#" onClick="sendDTMF('9', 2000)">9</a></td>
</tr>
<tr>
<td class="dtmfrow"><a href="#" onClick="sendDTMF('*', 2000)">*</a></td>
<td class="dtmfrow"><a href="#" onClick="sendDTMF('0', 2000)">0</a></td>
<td class="dtmfrow"><a href="#" onClick="sendDTMF('#', 2000)">#</a></td>
</tr>
</table>
<div id="#input_device">
</div>
</div>
<div id="account_container">
<div class="guest_account" id="guest_account">
<p>Guest account</p>
<a href="#" onClick="newcall('');">+ New Call</a>
</div>
</div>
<div id="log">
</div>
</body>
</html>

View File

@ -0,0 +1,508 @@
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationComplete="init()"
preinitialize="presetup()"
width="250" height="150"
xmlns:local="*">
<mx:Script>
<![CDATA[
import flash.external.*;
import flash.net.NetConnection;
import flash.net.NetStream;
import mx.utils.ObjectUtil;
import mx.core.FlexGlobals;
import flash.system.Security;
import flash.system.SecurityPanel;
import flash.media.*;
import com.adobe.crypto.MD5;
import com.adobe.serialization.json.JSON;
[Bindable]
public var netConnection:NetConnection = null;
private var incomingNetStream:NetStream = null;
private var outgoingNetStream:NetStream = null;
private var mic:Microphone = null;
[Bindable] private var microphoneList:Array;
private var sessionid:String;
private var auth_user:String;
private var auth_domain:String;
private var mic_index:int = -1;
private var attachedUUID:String = "";
[Embed(source="Sound_of_phone_ringing2.mp3")]
[Bindable]
private var soundOfPhoneRinging_MP3:Class;
private var ringChannel:SoundChannel = null;
private var ringUUID:String = "";
private var soundOfPhoneRinging:Sound;
public function presetup():void
{
/* Load config here */
soundOfPhoneRinging = new soundOfPhoneRinging_MP3();
}
/********* JavaScript functions *********/
public function makeCall(number:String, account:String, evt:Object):void {
if (netConnection != null) {
if (incomingNetStream == null) {
setupStreams();
}
netConnection.call("makeCall", null, number, account, evt);
}
}
public function sendDTMF(digits:String, duration:int):void {
if (netConnection != null) {
netConnection.call("sendDTMF", null, digits, duration);
}
}
public function answer(uuid:String):void {
if (ringChannel != null) {
ringChannel.stop();
ringChannel = null;
}
if (incomingNetStream == null) {
setupStreams();
}
if (netConnection != null) {
netConnection.call("answer", null, uuid);
}
}
public function hangup(uuid:String):void {
if (uuid == attachedUUID) {
destroyStreams();
}
if (netConnection != null) {
netConnection.call("hangup", null, uuid);
}
}
public function register(account:String, nickname:String):void {
if (netConnection != null) {
netConnection.call("register", null, account, nickname);
}
}
public function unregister(account:String, nickname:String):void {
if (netConnection != null) {
netConnection.call("unregister", null, account, nickname);
}
}
public function attach(uuid:String):void {
if (netConnection != null) {
netConnection.call("attach", null, uuid);
}
}
public function transfer(uuid:String, number:String):void {
if (netConnection != null) {
netConnection.call("transfer", null, uuid, number);
}
}
public function three_way(uuid1:String, uuid2:String):void {
if (netConnection != null) {
netConnection.call("three_way", null, uuid1, uuid2);
}
}
public function join(uuid1:String, uuid2:String):void {
if (netConnection != null) {
netConnection.call("join", null, uuid1, uuid2);
}
}
public function sendevent(data:Object):void {
if (netConnection != null) {
netConnection.call("sendevent", null, data);
}
}
public function getMic():int {
return mic_index;
}
public function micList():Object {
return JSON.encode(microphoneList);
}
public function setMic(index:int):void {
mic_index = index;
setupMic();
}
public function isMuted():Boolean {
if (mic != null) {
return mic.muted;
} else {
return false;
}
}
public function showPrivacy():void {
Security.showSettings(SecurityPanel.PRIVACY);
}
public function login(username:String, password:String):void {
if (netConnection != null) {
netConnection.call("login", null, username, MD5.hash(sessionid + ":" + username + ":" + password));
}
}
public function logout(account:String):void {
if (netConnection != null) {
netConnection.call("logout", null, account);
}
}
public function setVolume(value:Number):void {
if (incomingNetStream != null) {
var st:SoundTransform = new SoundTransform(value);
incomingNetStream.soundTransform = st;
}
}
public function setMicVolume(value:Number):void {
if (outgoingNetStream != null) {
var st:SoundTransform = new SoundTransform(value);
outgoingNetStream.soundTransform = st;
}
}
/********* FreeSWITCH functions *********/
/* XXX: TODO: Move those in a separate object so a malicious server can't setup streams and spy on the user */
public function connected(sid:String):void{
sessionid = sid;
if (ExternalInterface.available) {
ExternalInterface.call("onConnected", sid);
}
}
public function onHangup(uuid:String, cause:String):void {
if (ringUUID == uuid && ringChannel != null) {
ringChannel.stop();
ringChannel = null;
}
if (ExternalInterface.available) {
ExternalInterface.call("onHangup", uuid, cause);
}
}
public function onLogin(result:String, user:String, domain:String):void {
if (result == "success") {
auth_user = user;
auth_domain = domain;
}
if (ExternalInterface.available) {
ExternalInterface.call("onLogin", result, user, domain);
}
}
public function onLogout(user:String, domain:String):void {
if (ExternalInterface.available) {
ExternalInterface.call("onLogout", user, domain);
}
}
public function onAttach(uuid:String):void {
attachedUUID = uuid;
if (ringChannel != null && uuid != "") {
ringChannel.stop();
ringChannel = null;
}
if (attachedUUID == "") {
destroyStreams();
} else if (incomingNetStream == null || outgoingNetStream == null) {
setupStreams();
}
if (ExternalInterface.available) {
ExternalInterface.call("onAttach", uuid);
}
}
public function onMakeCall(uuid:String, number:String, account:String):void {
if (ExternalInterface.available) {
ExternalInterface.call("onMakeCall", uuid, number, account);
}
}
public function callState(uuid:String, state:String):void {
if (ExternalInterface.available) {
ExternalInterface.call("onCallState", uuid, state);
}
}
public function displayUpdate(uuid:String, name:String, number:String):void {
if (ExternalInterface.available) {
ExternalInterface.call("onDisplayUpdate", uuid, name, number);
}
}
public function incomingCall(uuid:String, name:String, number:String, account:String, evt:Object):void {
if (attachedUUID == "" && ringChannel == null) {
ringUUID = uuid;
ringChannel = soundOfPhoneRinging.play(0, 3);
}
if (evt != null) {
if (evt.hasOwnProperty("rtmp_auto_answer")) {
if (evt.rtmp_auto_answer == "true") {
answer(uuid);
}
}
}
if (ExternalInterface.available) {
ExternalInterface.call("onIncomingCall", uuid, name, number, account, evt);
}
}
public function event(event:Object):void {
if (ExternalInterface.available) {
ExternalInterface.call("onEvent", JSON.encode(event));
}
}
/********* Internal functions *********/
private function onDebug(message:String):void {
//statusTxt.text = (statusTxt.text != "") ? statusTxt.text + "\n" + message : message;
if (ExternalInterface.available) {
ExternalInterface.call("onDebug", message);
}
}
private function init():void
{
NetConnection.defaultObjectEncoding = ObjectEncoding.AMF0;
try {
Security.allowDomain("*");
} catch(e:Error) {
onDebug("Exception: " + e.toString());
}
if (ExternalInterface.available) {
try {
ExternalInterface.marshallExceptions = true;
ExternalInterface.addCallback("login", this.login);
ExternalInterface.addCallback("logout", this.logout);
ExternalInterface.addCallback("makeCall", this.makeCall);
ExternalInterface.addCallback("attach", this.attach);
ExternalInterface.addCallback("answer", this.answer);
ExternalInterface.addCallback("hangup", this.hangup);
ExternalInterface.addCallback("sendDTMF", this.sendDTMF);
ExternalInterface.addCallback("register", this.register);
ExternalInterface.addCallback("unregister", this.unregister);
ExternalInterface.addCallback("transfer", this.transfer);
ExternalInterface.addCallback("three_way", this.three_way);
ExternalInterface.addCallback("getMic", this.getMic);
ExternalInterface.addCallback("micList", this.micList);
ExternalInterface.addCallback("setMic", this.setMic);
ExternalInterface.addCallback("isMuted", this.isMuted);
ExternalInterface.addCallback("showPrivacy", this.showPrivacy);
ExternalInterface.addCallback("connect", this.connect);
ExternalInterface.addCallback("disconnect", this.disconnect);
ExternalInterface.addCallback("join", this.join);
ExternalInterface.addCallback("sendevent", this.sendevent);
ExternalInterface.addCallback("setVolume", this.setVolume);
ExternalInterface.addCallback("setMicVolume", this.setMicVolume);
//txtStatus.text = "Connecting...";
} catch(e:Error) {
//txtStatus.text = e.toString();
onDebug("Exception: " + e.toString());
}
} else {
onDebug("ExternalInterface is disabled");
}
try {
microphoneList = Microphone.names;
setupMic();
connect();
} catch(e:Error) {
onDebug("Exception: " + e.toString());
}
if (ExternalInterface.available) {
ExternalInterface.call("onInit");
}
}
public function connect():void{
if (netConnection != null) {
disconnect();
}
netConnection = new NetConnection();
netConnection.client = this;
netConnection.addEventListener( NetStatusEvent.NET_STATUS , netStatus );
netConnection.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
netConnection.connect(FlexGlobals.topLevelApplication.parameters.rtmp_url);
}
public function disconnect():void {
if (netConnection != null) {
netConnection.close();
netConnection = null;
incomingNetStream = null;
outgoingNetStream = null;
}
}
private function destroyStreams():void {
if (outgoingNetStream != null) {
onDebug("Closing media streams")
outgoingNetStream.close();
outgoingNetStream = null;
}
if (incomingNetStream != null) {
incomingNetStream.close();
incomingNetStream = null;
}
}
private function setupMic():void {
try {
mic = Microphone.getMicrophone(mic_index);
mic.addEventListener(ActivityEvent.ACTIVITY, activityHandler);
mic.addEventListener(StatusEvent.STATUS, statusHandler);
mic.codec = SoundCodec.SPEEX;
mic.setUseEchoSuppression(true);
mic.setLoopBack(false);
mic.setSilenceLevel(0,20000);
mic.framesPerPacket = 1;
mic.gain = 55;
mic.rate = 16;
mic_index = mic.index;
if (outgoingNetStream != null) {
outgoingNetStream.close();
outgoingNetStream = new NetStream(netConnection);
outgoingNetStream.addEventListener(NetStatusEvent.NET_STATUS, netStatus);
outgoingNetStream.addEventListener(AsyncErrorEvent.ASYNC_ERROR, asyncErrorHandler);
outgoingNetStream.attachAudio(mic);
outgoingNetStream.publish("publish", "live");
}
} catch(e:Error) {
onDebug("Couldn't setup microphone: " + e.message);
}
}
private function setupStreams():void {
onDebug("Setup media streams");
if (mic == null || mic.index != mic_index) {
setupMic();
}
incomingNetStream = new NetStream(netConnection);
incomingNetStream.addEventListener(NetStatusEvent.NET_STATUS, netStatus);
incomingNetStream.addEventListener(AsyncErrorEvent.ASYNC_ERROR, asyncErrorHandler);
incomingNetStream.client = this;
incomingNetStream.bufferTime = 0.2;
incomingNetStream.play("play");
incomingNetStream.receiveAudio(true);
outgoingNetStream = new NetStream(netConnection);
outgoingNetStream.addEventListener(NetStatusEvent.NET_STATUS, netStatus);
outgoingNetStream.addEventListener(AsyncErrorEvent.ASYNC_ERROR, asyncErrorHandler);
outgoingNetStream.attachAudio(mic);
outgoingNetStream.publish("publish", "live");
}
private function onDisconnected():void {
if (ExternalInterface.available) {
ExternalInterface.call("onDisconnected");
}
}
private function securityErrorHandler(event:SecurityErrorEvent):void {
onDebug("securityErrorHandler: " + event.text);
}
private function asyncErrorHandler(event:AsyncErrorEvent):void {
onDebug("asyncErrorHandler: " + event.text);
}
private function activityHandler(event:ActivityEvent):void {
onDebug("activityHandler: " + event);
}
private function statusHandler(event:StatusEvent):void {
onDebug("statusHandler: " + event);
}
private function netStatus (evt:NetStatusEvent ):void {
onDebug("netStatus: " + evt.info.code);
switch(evt.info.code) {
case "NetConnection.Connect.Success":
//txtStatus.text = "Connected";
break;
case "NetConnection.Connect.Failed":
netConnection = null;
incomingNetStream = null;
outgoingNetStream = null;
//btnCall.label = "Connect";
//txtStatus.text = "Failed";
onDisconnected();
break;
case "NetConnection.Connect.Closed":
netConnection = null;
incomingNetStream = null;
outgoingNetStream = null;
//btnCall.label = "Connect";
//txtStatus.text = "Disconnected";
onDisconnected();
break;
case "NetConnection.Connect.Rejected":
netConnection = null;
incomingNetStream = null;
outgoingNetStream = null;
//btnCall.label = "Connect";
//txtStatus.text = "Rejected";
onDisconnected();
break;
case "NetStream.Play.StreamNotFound":
break;
case "NetStream.Play.Failed":
break;
case "NetStream.Play.Start":
break;
case "NetStream.Play.Stop":
break;
case "NetStream.Buffer.Full":
break;
default:
}
}
]]>
</mx:Script>
<!--<mx:Panel id="reader" title="Test" width="500">
<mx:TextArea width="500" color="#FF0000" id="statusTxt"/>
</mx:Panel>-->
</mx:Application>

BIN
clients/flex/freeswitch.swf Normal file

Binary file not shown.

6240
clients/flex/jquery-1.4.2.js vendored Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,224 @@
/**
* jQuery.query - Query String Modification and Creation for jQuery
* Written by Blair Mitchelmore (blair DOT mitchelmore AT gmail DOT com)
* Licensed under the WTFPL (http://sam.zoy.org/wtfpl/).
* Date: 2009/8/13
*
* @author Blair Mitchelmore
* @version 2.1.7
*
**/
new function(settings) {
// Various Settings
var $separator = settings.separator || '&';
var $spaces = settings.spaces === false ? false : true;
var $suffix = settings.suffix === false ? '' : '[]';
var $prefix = settings.prefix === false ? false : true;
var $hash = $prefix ? settings.hash === true ? "#" : "?" : "";
var $numbers = settings.numbers === false ? false : true;
jQuery.query = new function() {
var is = function(o, t) {
return o != undefined && o !== null && (!!t ? o.constructor == t : true);
};
var parse = function(path) {
var m, rx = /\[([^[]*)\]/g, match = /^([^[]+)(\[.*\])?$/.exec(path), base = match[1], tokens = [];
while (m = rx.exec(match[2])) tokens.push(m[1]);
return [base, tokens];
};
var set = function(target, tokens, value) {
var o, token = tokens.shift();
if (typeof target != 'object') target = null;
if (token === "") {
if (!target) target = [];
if (is(target, Array)) {
target.push(tokens.length == 0 ? value : set(null, tokens.slice(0), value));
} else if (is(target, Object)) {
var i = 0;
while (target[i++] != null);
target[--i] = tokens.length == 0 ? value : set(target[i], tokens.slice(0), value);
} else {
target = [];
target.push(tokens.length == 0 ? value : set(null, tokens.slice(0), value));
}
} else if (token && token.match(/^\s*[0-9]+\s*$/)) {
var index = parseInt(token, 10);
if (!target) target = [];
target[index] = tokens.length == 0 ? value : set(target[index], tokens.slice(0), value);
} else if (token) {
var index = token.replace(/^\s*|\s*$/g, "");
if (!target) target = {};
if (is(target, Array)) {
var temp = {};
for (var i = 0; i < target.length; ++i) {
temp[i] = target[i];
}
target = temp;
}
target[index] = tokens.length == 0 ? value : set(target[index], tokens.slice(0), value);
} else {
return value;
}
return target;
};
var queryObject = function(a) {
var self = this;
self.keys = {};
if (a.queryObject) {
jQuery.each(a.get(), function(key, val) {
self.SET(key, val);
});
} else {
jQuery.each(arguments, function() {
var q = "" + this;
q = q.replace(/^[?#]/,''); // remove any leading ? || #
q = q.replace(/[;&]$/,''); // remove any trailing & || ;
if ($spaces) q = q.replace(/[+]/g,' '); // replace +'s with spaces
jQuery.each(q.split(/[&;]/), function(){
var key = decodeURIComponent(this.split('=')[0] || "");
var val = decodeURIComponent(this.split('=')[1] || "");
if (!key) return;
if ($numbers) {
if (/^[+-]?[0-9]+\.[0-9]*$/.test(val)) // simple float regex
val = parseFloat(val);
else if (/^[+-]?[0-9]+$/.test(val)) // simple int regex
val = parseInt(val, 10);
}
val = (!val && val !== 0) ? true : val;
if (val !== false && val !== true && typeof val != 'number')
val = val;
self.SET(key, val);
});
});
}
return self;
};
queryObject.prototype = {
queryObject: true,
has: function(key, type) {
var value = this.get(key);
return is(value, type);
},
GET: function(key) {
if (!is(key)) return this.keys;
var parsed = parse(key), base = parsed[0], tokens = parsed[1];
var target = this.keys[base];
while (target != null && tokens.length != 0) {
target = target[tokens.shift()];
}
return typeof target == 'number' ? target : target || "";
},
get: function(key) {
var target = this.GET(key);
if (is(target, Object))
return jQuery.extend(true, {}, target);
else if (is(target, Array))
return target.slice(0);
return target;
},
SET: function(key, val) {
var value = !is(val) ? null : val;
var parsed = parse(key), base = parsed[0], tokens = parsed[1];
var target = this.keys[base];
this.keys[base] = set(target, tokens.slice(0), value);
return this;
},
set: function(key, val) {
return this.copy().SET(key, val);
},
REMOVE: function(key) {
return this.SET(key, null).COMPACT();
},
remove: function(key) {
return this.copy().REMOVE(key);
},
EMPTY: function() {
var self = this;
jQuery.each(self.keys, function(key, value) {
delete self.keys[key];
});
return self;
},
load: function(url) {
var hash = url.replace(/^.*?[#](.+?)(?:\?.+)?$/, "$1");
var search = url.replace(/^.*?[?](.+?)(?:#.+)?$/, "$1");
return new queryObject(url.length == search.length ? '' : search, url.length == hash.length ? '' : hash);
},
empty: function() {
return this.copy().EMPTY();
},
copy: function() {
return new queryObject(this);
},
COMPACT: function() {
function build(orig) {
var obj = typeof orig == "object" ? is(orig, Array) ? [] : {} : orig;
if (typeof orig == 'object') {
function add(o, key, value) {
if (is(o, Array))
o.push(value);
else
o[key] = value;
}
jQuery.each(orig, function(key, value) {
if (!is(value)) return true;
add(obj, key, build(value));
});
}
return obj;
}
this.keys = build(this.keys);
return this;
},
compact: function() {
return this.copy().COMPACT();
},
toString: function() {
var i = 0, queryString = [], chunks = [], self = this;
var encode = function(str) {
str = str + "";
if ($spaces) str = str.replace(/ /g, "+");
return encodeURIComponent(str);
};
var addFields = function(arr, key, value) {
if (!is(value) || value === false) return;
var o = [encode(key)];
if (value !== true) {
o.push("=");
o.push(encode(value));
}
arr.push(o.join(""));
};
var build = function(obj, base) {
var newKey = function(key) {
return !base || base == "" ? [key].join("") : [base, "[", key, "]"].join("");
};
jQuery.each(obj, function(key, value) {
if (typeof value == 'object')
build(value, newKey(key));
else
addFields(chunks, newKey(key), value);
});
};
build(this.keys);
if (chunks.length > 0) queryString.push($hash);
queryString.push(chunks.join($separator));
return queryString.join("");
}
};
return new queryObject(location.search, location.hash);
};
}(jQuery.query || {}); // Pass in jQuery.query as settings object

484
clients/flex/jquery.tmpl.js Normal file
View File

@ -0,0 +1,484 @@
/*!
* jQuery Templates Plugin 1.0.0pre
* http://github.com/jquery/jquery-tmpl
* Requires jQuery 1.4.2
*
* Copyright Software Freedom Conservancy, Inc.
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://jquery.org/license
*/
(function( jQuery, undefined ){
var oldManip = jQuery.fn.domManip, tmplItmAtt = "_tmplitem", htmlExpr = /^[^<]*(<[\w\W]+>)[^>]*$|\{\{\! /,
newTmplItems = {}, wrappedItems = {}, appendToTmplItems, topTmplItem = { key: 0, data: {} }, itemKey = 0, cloneIndex = 0, stack = [];
function newTmplItem( options, parentItem, fn, data ) {
// Returns a template item data structure for a new rendered instance of a template (a 'template item').
// The content field is a hierarchical array of strings and nested items (to be
// removed and replaced by nodes field of dom elements, once inserted in DOM).
var newItem = {
data: data || (data === 0 || data === false) ? data : (parentItem ? parentItem.data : {}),
_wrap: parentItem ? parentItem._wrap : null,
tmpl: null,
parent: parentItem || null,
nodes: [],
calls: tiCalls,
nest: tiNest,
wrap: tiWrap,
html: tiHtml,
update: tiUpdate
};
if ( options ) {
jQuery.extend( newItem, options, { nodes: [], parent: parentItem });
}
if ( fn ) {
// Build the hierarchical content to be used during insertion into DOM
newItem.tmpl = fn;
newItem._ctnt = newItem._ctnt || newItem.tmpl( jQuery, newItem );
newItem.key = ++itemKey;
// Keep track of new template item, until it is stored as jQuery Data on DOM element
(stack.length ? wrappedItems : newTmplItems)[itemKey] = newItem;
}
return newItem;
}
// Override appendTo etc., in order to provide support for targeting multiple elements. (This code would disappear if integrated in jquery core).
jQuery.each({
appendTo: "append",
prependTo: "prepend",
insertBefore: "before",
insertAfter: "after",
replaceAll: "replaceWith"
}, function( name, original ) {
jQuery.fn[ name ] = function( selector ) {
var ret = [], insert = jQuery( selector ), elems, i, l, tmplItems,
parent = this.length === 1 && this[0].parentNode;
appendToTmplItems = newTmplItems || {};
if ( parent && parent.nodeType === 11 && parent.childNodes.length === 1 && insert.length === 1 ) {
insert[ original ]( this[0] );
ret = this;
} else {
for ( i = 0, l = insert.length; i < l; i++ ) {
cloneIndex = i;
elems = (i > 0 ? this.clone(true) : this).get();
jQuery( insert[i] )[ original ]( elems );
ret = ret.concat( elems );
}
cloneIndex = 0;
ret = this.pushStack( ret, name, insert.selector );
}
tmplItems = appendToTmplItems;
appendToTmplItems = null;
jQuery.tmpl.complete( tmplItems );
return ret;
};
});
jQuery.fn.extend({
// Use first wrapped element as template markup.
// Return wrapped set of template items, obtained by rendering template against data.
tmpl: function( data, options, parentItem ) {
return jQuery.tmpl( this[0], data, options, parentItem );
},
// Find which rendered template item the first wrapped DOM element belongs to
tmplItem: function() {
return jQuery.tmplItem( this[0] );
},
// Consider the first wrapped element as a template declaration, and get the compiled template or store it as a named template.
template: function( name ) {
return jQuery.template( name, this[0] );
},
domManip: function( args, table, callback, options ) {
if ( args[0] && jQuery.isArray( args[0] )) {
var dmArgs = jQuery.makeArray( arguments ), elems = args[0], elemsLength = elems.length, i = 0, tmplItem;
while ( i < elemsLength && !(tmplItem = jQuery.data( elems[i++], "tmplItem" ))) {}
if ( tmplItem && cloneIndex ) {
dmArgs[2] = function( fragClone ) {
// Handler called by oldManip when rendered template has been inserted into DOM.
jQuery.tmpl.afterManip( this, fragClone, callback );
};
}
oldManip.apply( this, dmArgs );
} else {
oldManip.apply( this, arguments );
}
cloneIndex = 0;
if ( !appendToTmplItems ) {
jQuery.tmpl.complete( newTmplItems );
}
return this;
}
});
jQuery.extend({
// Return wrapped set of template items, obtained by rendering template against data.
tmpl: function( tmpl, data, options, parentItem ) {
var ret, topLevel = !parentItem;
if ( topLevel ) {
// This is a top-level tmpl call (not from a nested template using {{tmpl}})
parentItem = topTmplItem;
tmpl = jQuery.template[tmpl] || jQuery.template( null, tmpl );
wrappedItems = {}; // Any wrapped items will be rebuilt, since this is top level
} else if ( !tmpl ) {
// The template item is already associated with DOM - this is a refresh.
// Re-evaluate rendered template for the parentItem
tmpl = parentItem.tmpl;
newTmplItems[parentItem.key] = parentItem;
parentItem.nodes = [];
if ( parentItem.wrapped ) {
updateWrapped( parentItem, parentItem.wrapped );
}
// Rebuild, without creating a new template item
return jQuery( build( parentItem, null, parentItem.tmpl( jQuery, parentItem ) ));
}
if ( !tmpl ) {
return []; // Could throw...
}
if ( typeof data === "function" ) {
data = data.call( parentItem || {} );
}
if ( options && options.wrapped ) {
updateWrapped( options, options.wrapped );
}
ret = jQuery.isArray( data ) ?
jQuery.map( data, function( dataItem ) {
return dataItem ? newTmplItem( options, parentItem, tmpl, dataItem ) : null;
}) :
[ newTmplItem( options, parentItem, tmpl, data ) ];
return topLevel ? jQuery( build( parentItem, null, ret ) ) : ret;
},
// Return rendered template item for an element.
tmplItem: function( elem ) {
var tmplItem;
if ( elem instanceof jQuery ) {
elem = elem[0];
}
while ( elem && elem.nodeType === 1 && !(tmplItem = jQuery.data( elem, "tmplItem" )) && (elem = elem.parentNode) ) {}
return tmplItem || topTmplItem;
},
// Set:
// Use $.template( name, tmpl ) to cache a named template,
// where tmpl is a template string, a script element or a jQuery instance wrapping a script element, etc.
// Use $( "selector" ).template( name ) to provide access by name to a script block template declaration.
// Get:
// Use $.template( name ) to access a cached template.
// Also $( selectorToScriptBlock ).template(), or $.template( null, templateString )
// will return the compiled template, without adding a name reference.
// If templateString includes at least one HTML tag, $.template( templateString ) is equivalent
// to $.template( null, templateString )
template: function( name, tmpl ) {
if (tmpl) {
// Compile template and associate with name
if ( typeof tmpl === "string" ) {
// This is an HTML string being passed directly in.
tmpl = buildTmplFn( tmpl );
} else if ( tmpl instanceof jQuery ) {
tmpl = tmpl[0] || {};
}
if ( tmpl.nodeType ) {
// If this is a template block, use cached copy, or generate tmpl function and cache.
tmpl = jQuery.data( tmpl, "tmpl" ) || jQuery.data( tmpl, "tmpl", buildTmplFn( tmpl.innerHTML ));
// Issue: In IE, if the container element is not a script block, the innerHTML will remove quotes from attribute values whenever the value does not include white space.
// This means that foo="${x}" will not work if the value of x includes white space: foo="${x}" -> foo=value of x.
// To correct this, include space in tag: foo="${ x }" -> foo="value of x"
}
return typeof name === "string" ? (jQuery.template[name] = tmpl) : tmpl;
}
// Return named compiled template
return name ? (typeof name !== "string" ? jQuery.template( null, name ):
(jQuery.template[name] ||
// If not in map, and not containing at least on HTML tag, treat as a selector.
// (If integrated with core, use quickExpr.exec)
jQuery.template( null, htmlExpr.test( name ) ? name : jQuery( name )))) : null;
},
encode: function( text ) {
// Do HTML encoding replacing < > & and ' and " by corresponding entities.
return ("" + text).split("<").join("&lt;").split(">").join("&gt;").split('"').join("&#34;").split("'").join("&#39;");
}
});
jQuery.extend( jQuery.tmpl, {
tag: {
"tmpl": {
_default: { $2: "null" },
open: "if($notnull_1){__=__.concat($item.nest($1,$2));}"
// tmpl target parameter can be of type function, so use $1, not $1a (so not auto detection of functions)
// This means that {{tmpl foo}} treats foo as a template (which IS a function).
// Explicit parens can be used if foo is a function that returns a template: {{tmpl foo()}}.
},
"wrap": {
_default: { $2: "null" },
open: "$item.calls(__,$1,$2);__=[];",
close: "call=$item.calls();__=call._.concat($item.wrap(call,__));"
},
"each": {
_default: { $2: "$index, $value" },
open: "if($notnull_1){$.each($1a,function($2){with(this){",
close: "}});}"
},
"if": {
open: "if(($notnull_1) && $1a){",
close: "}"
},
"else": {
_default: { $1: "true" },
open: "}else if(($notnull_1) && $1a){"
},
"html": {
// Unecoded expression evaluation.
open: "if($notnull_1){__.push($1a);}"
},
"=": {
// Encoded expression evaluation. Abbreviated form is ${}.
_default: { $1: "$data" },
open: "if($notnull_1){__.push($.encode($1a));}"
},
"!": {
// Comment tag. Skipped by parser
open: ""
}
},
// This stub can be overridden, e.g. in jquery.tmplPlus for providing rendered events
complete: function( items ) {
newTmplItems = {};
},
// Call this from code which overrides domManip, or equivalent
// Manage cloning/storing template items etc.
afterManip: function afterManip( elem, fragClone, callback ) {
// Provides cloned fragment ready for fixup prior to and after insertion into DOM
var content = fragClone.nodeType === 11 ?
jQuery.makeArray(fragClone.childNodes) :
fragClone.nodeType === 1 ? [fragClone] : [];
// Return fragment to original caller (e.g. append) for DOM insertion
callback.call( elem, fragClone );
// Fragment has been inserted:- Add inserted nodes to tmplItem data structure. Replace inserted element annotations by jQuery.data.
storeTmplItems( content );
cloneIndex++;
}
});
//========================== Private helper functions, used by code above ==========================
function build( tmplItem, nested, content ) {
// Convert hierarchical content into flat string array
// and finally return array of fragments ready for DOM insertion
var frag, ret = content ? jQuery.map( content, function( item ) {
return (typeof item === "string") ?
// Insert template item annotations, to be converted to jQuery.data( "tmplItem" ) when elems are inserted into DOM.
(tmplItem.key ? item.replace( /(<\w+)(?=[\s>])(?![^>]*_tmplitem)([^>]*)/g, "$1 " + tmplItmAtt + "=\"" + tmplItem.key + "\" $2" ) : item) :
// This is a child template item. Build nested template.
build( item, tmplItem, item._ctnt );
}) :
// If content is not defined, insert tmplItem directly. Not a template item. May be a string, or a string array, e.g. from {{html $item.html()}}.
tmplItem;
if ( nested ) {
return ret;
}
// top-level template
ret = ret.join("");
// Support templates which have initial or final text nodes, or consist only of text
// Also support HTML entities within the HTML markup.
ret.replace( /^\s*([^<\s][^<]*)?(<[\w\W]+>)([^>]*[^>\s])?\s*$/, function( all, before, middle, after) {
frag = jQuery( middle ).get();
storeTmplItems( frag );
if ( before ) {
frag = unencode( before ).concat(frag);
}
if ( after ) {
frag = frag.concat(unencode( after ));
}
});
return frag ? frag : unencode( ret );
}
function unencode( text ) {
// Use createElement, since createTextNode will not render HTML entities correctly
var el = document.createElement( "div" );
el.innerHTML = text;
return jQuery.makeArray(el.childNodes);
}
// Generate a reusable function that will serve to render a template against data
function buildTmplFn( markup ) {
return new Function("jQuery","$item",
// Use the variable __ to hold a string array while building the compiled template. (See https://github.com/jquery/jquery-tmpl/issues#issue/10).
"var $=jQuery,call,__=[],$data=$item.data;" +
// Introduce the data as local variables using with(){}
"with($data){__.push('" +
// Convert the template into pure JavaScript
jQuery.trim(markup)
.replace( /([\\'])/g, "\\$1" )
.replace( /[\r\t\n]/g, " " )
.replace( /\$\{([^\}]*)\}/g, "{{= $1}}" )
.replace( /\{\{(\/?)(\w+|.)(?:\(((?:[^\}]|\}(?!\}))*?)?\))?(?:\s+(.*?)?)?(\(((?:[^\}]|\}(?!\}))*?)\))?\s*\}\}/g,
function( all, slash, type, fnargs, target, parens, args ) {
var tag = jQuery.tmpl.tag[ type ], def, expr, exprAutoFnDetect;
if ( !tag ) {
throw "Unknown template tag: " + type;
}
def = tag._default || [];
if ( parens && !/\w$/.test(target)) {
target += parens;
parens = "";
}
if ( target ) {
target = unescape( target );
args = args ? ("," + unescape( args ) + ")") : (parens ? ")" : "");
// Support for target being things like a.toLowerCase();
// In that case don't call with template item as 'this' pointer. Just evaluate...
expr = parens ? (target.indexOf(".") > -1 ? target + unescape( parens ) : ("(" + target + ").call($item" + args)) : target;
exprAutoFnDetect = parens ? expr : "(typeof(" + target + ")==='function'?(" + target + ").call($item):(" + target + "))";
} else {
exprAutoFnDetect = expr = def.$1 || "null";
}
fnargs = unescape( fnargs );
return "');" +
tag[ slash ? "close" : "open" ]
.split( "$notnull_1" ).join( target ? "typeof(" + target + ")!=='undefined' && (" + target + ")!=null" : "true" )
.split( "$1a" ).join( exprAutoFnDetect )
.split( "$1" ).join( expr )
.split( "$2" ).join( fnargs || def.$2 || "" ) +
"__.push('";
}) +
"');}return __;"
);
}
function updateWrapped( options, wrapped ) {
// Build the wrapped content.
options._wrap = build( options, true,
// Suport imperative scenario in which options.wrapped can be set to a selector or an HTML string.
jQuery.isArray( wrapped ) ? wrapped : [htmlExpr.test( wrapped ) ? wrapped : jQuery( wrapped ).html()]
).join("");
}
function unescape( args ) {
return args ? args.replace( /\\'/g, "'").replace(/\\\\/g, "\\" ) : null;
}
function outerHtml( elem ) {
var div = document.createElement("div");
div.appendChild( elem.cloneNode(true) );
return div.innerHTML;
}
// Store template items in jQuery.data(), ensuring a unique tmplItem data data structure for each rendered template instance.
function storeTmplItems( content ) {
var keySuffix = "_" + cloneIndex, elem, elems, newClonedItems = {}, i, l, m;
for ( i = 0, l = content.length; i < l; i++ ) {
if ( (elem = content[i]).nodeType !== 1 ) {
continue;
}
elems = elem.getElementsByTagName("*");
for ( m = elems.length - 1; m >= 0; m-- ) {
processItemKey( elems[m] );
}
processItemKey( elem );
}
function processItemKey( el ) {
var pntKey, pntNode = el, pntItem, tmplItem, key;
// Ensure that each rendered template inserted into the DOM has its own template item,
if ( (key = el.getAttribute( tmplItmAtt ))) {
while ( pntNode.parentNode && (pntNode = pntNode.parentNode).nodeType === 1 && !(pntKey = pntNode.getAttribute( tmplItmAtt ))) { }
if ( pntKey !== key ) {
// The next ancestor with a _tmplitem expando is on a different key than this one.
// So this is a top-level element within this template item
// Set pntNode to the key of the parentNode, or to 0 if pntNode.parentNode is null, or pntNode is a fragment.
pntNode = pntNode.parentNode ? (pntNode.nodeType === 11 ? 0 : (pntNode.getAttribute( tmplItmAtt ) || 0)) : 0;
if ( !(tmplItem = newTmplItems[key]) ) {
// The item is for wrapped content, and was copied from the temporary parent wrappedItem.
tmplItem = wrappedItems[key];
tmplItem = newTmplItem( tmplItem, newTmplItems[pntNode]||wrappedItems[pntNode] );
tmplItem.key = ++itemKey;
newTmplItems[itemKey] = tmplItem;
}
if ( cloneIndex ) {
cloneTmplItem( key );
}
}
el.removeAttribute( tmplItmAtt );
} else if ( cloneIndex && (tmplItem = jQuery.data( el, "tmplItem" )) ) {
// This was a rendered element, cloned during append or appendTo etc.
// TmplItem stored in jQuery data has already been cloned in cloneCopyEvent. We must replace it with a fresh cloned tmplItem.
cloneTmplItem( tmplItem.key );
newTmplItems[tmplItem.key] = tmplItem;
pntNode = jQuery.data( el.parentNode, "tmplItem" );
pntNode = pntNode ? pntNode.key : 0;
}
if ( tmplItem ) {
pntItem = tmplItem;
// Find the template item of the parent element.
// (Using !=, not !==, since pntItem.key is number, and pntNode may be a string)
while ( pntItem && pntItem.key != pntNode ) {
// Add this element as a top-level node for this rendered template item, as well as for any
// ancestor items between this item and the item of its parent element
pntItem.nodes.push( el );
pntItem = pntItem.parent;
}
// Delete content built during rendering - reduce API surface area and memory use, and avoid exposing of stale data after rendering...
delete tmplItem._ctnt;
delete tmplItem._wrap;
// Store template item as jQuery data on the element
jQuery.data( el, "tmplItem", tmplItem );
}
function cloneTmplItem( key ) {
key = key + keySuffix;
tmplItem = newClonedItems[key] =
(newClonedItems[key] || newTmplItem( tmplItem, newTmplItems[tmplItem.parent.key + keySuffix] || tmplItem.parent ));
}
}
}
//---- Helper functions for template item ----
function tiCalls( content, tmpl, data, options ) {
if ( !content ) {
return stack.pop();
}
stack.push({ _: content, tmpl: tmpl, item:this, data: data, options: options });
}
function tiNest( tmpl, data, options ) {
// nested template, using {{tmpl}} tag
return jQuery.tmpl( jQuery.template( tmpl ), data, options, this );
}
function tiWrap( call, wrapped ) {
// nested template, using {{wrap}} tag
var options = call.options || {};
options.wrapped = wrapped;
// Apply the template, which may incorporate wrapped content,
return jQuery.tmpl( jQuery.template( call.tmpl ), call.data, options, call.item );
}
function tiHtml( filter, textOnly ) {
var wrapped = this._wrap;
return jQuery.map(
jQuery( jQuery.isArray( wrapped ) ? wrapped.join("") : wrapped ).filter( filter || "*" ),
function(e) {
return textOnly ?
e.innerText || e.textContent :
e.outerHTML || outerHtml(e);
});
}
function tiUpdate() {
var coll = this.nodes;
jQuery.tmpl( null, null, null, this).insertBefore( coll[0] );
jQuery( coll ).remove();
}
})( jQuery );

File diff suppressed because one or more lines are too long

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 KiB