/** BulkLoader: manage multiple loadings in Actioncript 3. * * * @author Arthur Debert */ /** * Licensed under the MIT License * * Copyright (c) 2006-2007 Arthur Debert * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * http://code.google.com/p/bulk-loader/ * http://www.opensource.org/licenses/mit-license.php * */ package br.com.stimuli.loading { import br.com.stimuli.loading.loadingtypes.*; import flash.display.*; import flash.events.*; import flash.media.Sound; import flash.net.*; import flash.utils.*; /** * Dispatched on download progress by any of the items to download. * * @eventType br.com.stimuli.loading.BulkProgressEvent */ [Event(name="progress", type="br.com.stimuli.loading.BulkProgressEvent")]; /** * Dispatched when all items have been downloaded and parsed. Note that this event only fires if there are no errors. * * @eventType br.com.stimuli.loading.BulkProgressEvent */ [Event(name="complete", type="br.com.stimuli.loading.BulkProgressEvent")]; /** * Dispatched if any item has an error while loading. * * @eventType events.ErrorEvent */ [Event(name="error", type="events.ErrorEvent")]; /** * Manages loading for simultaneous items and multiple formats. * Exposes a simpler interface, with callbacks instead of events for each item to be loaded (but still dispatched "global" events). * The number of simultaneous connections is configurable. * * @example Basic usage: import br.com.stimuli.loading.BulkLoader; / /instantiate a BulkLoader with a name : a way to reference this instance from another classes without having to set a explicit reference on many places var bulkLoader : BulkLoader = new BulkLoader("main loading"); // add items to be loaded bulkLoader.add("my_xml_file.xml"); bulkLoader.add("main.swf"); // you can also use a URLRequest object var backgroundURL : URLRequest = new URLRequest("background.jpg"); bulkLoader.add(backgroundURL); // add event listeners for the loader itself : // event fired when all items have been loaded and nothing has failed! bulkLoader.addEventListener(BulkLoader.COMPLETE, onCompleteHandler); // event fired when loading progress has been made: bulkLoader.addEventListener(BulkLoader.PROGRESS, _onProgressHandler); // start loading all items bulkLoader.start(); function _onProgressHandler(evt : ProgressEvent) : void{ trace("Loaded" , evt.bytesLoaded," of ", evt.bytesTotal); } function onCompleteHandler(evt : ProgressEvent) : void{ trace("All items are loaded and ready to consume"); // grab the main movie clip: var mainMovie : MovieClip = bulkLoader.getMovieClip("main.swf"); // Get the xml object: var mXML : XML = bulkLoader.getXML("my_xml_file.xml"); // grab the bitmap for the background image by a string: var myBitmap : Bitmap = bulkLoader.getBitmap("background.jpg"); // grab the bitmap for the background image using the url request object: var myBitmap : Bitmap = bulkLoader.getBitmap(backgroundURL); } // In any other class you can access those assets without having to pass around references to the bulkLoader instance. // In another class you get get a reference to the "main loading" bulkLoader: var mainLoader : BulkLoader = BulkLoader.getLoader("main loading"); // now grab the xml: var mXML : XML = mainLoader.getXML("my_xml_file.xml"); // or shorter: var mXML : XML = BulkLoader.getLoader("main loading").getXML("my_xml_file.xml"); * * @langversion ActionScript 3.0 * @playerversion Flash 9.0 * * @author Arthur Debert * @since 15.09.2007 */ public class BulkLoader extends EventDispatcher { /** Version. Useful for debugging. */ public static const VERSION : String = "$Id: BulkLoader.as 321 2010-04-10 19:11:05Z debert $"; /** Tells this class to use a Loader object to load the item.*/ public static const TYPE_BINARY : String = "binary"; /** Tells this class to use a Loader object to load the item.*/ public static const TYPE_IMAGE : String = "image"; /** Tells this class to use a Loader object to load the item.*/ public static const TYPE_MOVIECLIP : String = "movieclip"; /** Tells this class to use a Sound object to load the item.*/ public static const TYPE_SOUND : String = "sound"; /** Tells this class to use a URLRequest object to load the item.*/ public static const TYPE_TEXT : String = "text"; /** Tells this class to use a XML object to load the item.*/ public static const TYPE_XML : String = "xml"; /** Tells this class to use a NetStream object to load the item.*/ public static const TYPE_VIDEO : String = "video"; public static const AVAILABLE_TYPES : Array = [TYPE_VIDEO, TYPE_XML, TYPE_TEXT, TYPE_SOUND, TYPE_MOVIECLIP, TYPE_IMAGE, TYPE_BINARY]; /** List of all file extensions that the BulkLoader knows how to guess. * Availabe types: swf, jpg, jpeg, gif, png. */ public static var AVAILABLE_EXTENSIONS : Array = ["swf", "jpg", "jpeg", "gif", "png", "flv", "mp3", "xml", "txt", "js" ]; /** List of file extensions that will be automagically use a Loader object for loading. * Availabe types: swf, jpg, jpeg, gif, png, image. */ public static var IMAGE_EXTENSIONS : Array = [ "jpg", "jpeg", "gif", "png"]; public static var MOVIECLIP_EXTENSIONS : Array = ['swf']; /** List of file extensions that will be automagically treated as text for loading. * Availabe types: txt, js, xml, php, asp . */ public static var TEXT_EXTENSIONS : Array = ["txt", "js", "php", "asp", "py" ]; /** List of file extensions that will be automagically treated as video for loading. * Availabe types: flv, f4v, f4p. */ public static var VIDEO_EXTENSIONS : Array = ["flv", "f4v", "f4p", "mp4"]; /** List of file extensions that will be automagically treated as sound for loading. * Availabe types: mp3, f4a, f4b. */ public static var SOUND_EXTENSIONS : Array = ["mp3", "f4a", "f4b"]; public static var XML_EXTENSIONS : Array = ["xml"]; /** @private */ public static var _customTypesExtensions : Object ; /** * The name of the event * @eventType progress */ public static const PROGRESS : String = "progress"; /** * The name of the event * @eventType complete */ public static const COMPLETE : String = "complete"; /** * The name of the event * @eventType httpStatus */ public static const HTTP_STATUS : String = "httpStatus"; /** * The name of the event * @eventType error */ public static const ERROR : String = "error"; /** * The name of the event * @eventType securityError */ public static const SECURITY_ERROR : String = "securityError"; /** * The name of the event * @eventType error */ public static const OPEN : String = "open"; /** * The name of the event * @eventType error */ public static const CAN_BEGIN_PLAYING : String = "canBeginPlaying"; public static const CHECK_POLICY_FILE : String = "checkPolicyFile"; // properties on adding a new url: /** If true a random query (or post data parameter) will be added to prevent caching. Checked when adding a new item to load. * @see #add() */ public static const PREVENT_CACHING : String = "preventCache"; /** An array of RequestHeader objects to be used when contructing the URLRequest object. If the url parameter is passed as a URLRequest object it will be ignored. Checked when adding a new item to load. * @see #add() */ public static const HEADERS : String = "headers"; /** An object definig the loading context for this load operario. If this item is of TYPE_SOUND, a SoundLoaderContext is expected. If it's a TYPE_IMAGE a LoaderContext should be passed. Checked when adding a new item to load. * @see #add() */ public static const CONTEXT : String = "context"; /** A String to be used to identify an item to load, can be used in any method that fetches content (as the key parameters), stops, removes and resume items. Checked when adding a new item to load. * @see #add() * @see #getContent() * @see #pause() * @see #resume() * @see #removeItem() */ public static const ID : String = "id"; /** An int that controls which items are loaded first. Items with a higher PRIORITY will load first. If more than one item has the same PRIORITY number, the order in which they are added will be taken into consideration. Checked when adding a new item to load. * @see #add() */ public static const PRIORITY : String = "priority"; /** The number, as an int, to retry downloading an item in case it fails. Checked when adding a new item to load. * @default 3 * @see #add() */ public static const MAX_TRIES : String = "maxTries"; /* An int that sets a relative size of this item. It's used on the BulkProgressEvent.weightPercent property. This allows bulk downloads with more items that connections and with widely varying file sizes to give a more accurate progress information. Checked when adding a new item to load. * @see #add() * @default 3 */ public static const WEIGHT : String = "weight"; /* An Boolean that if true and applied on a video item will pause the video on the start of the loading operation. * @see #add() * @default false */ public static const PAUSED_AT_START : String = "pausedAtStart"; public static const GENERAL_AVAILABLE_PROPS : Array = [ WEIGHT, MAX_TRIES, HEADERS, ID, PRIORITY, PREVENT_CACHING, "type"]; /** @private */ public var _name : String; /** @private */ public var _id : int; /** @private */ public static var _instancesCreated : int = 0; /** @private */ public var _items : Array = []; /** @private */ public var _contents : Dictionary = new Dictionary(true); /** @private */ public static var _allLoaders : Object = {}; /** @private */ public var _additionIndex : int = 0; // Maximum number of simultaneous open requests public static const DEFAULT_NUM_CONNECTIONS : int = 12; /** @private */ public var _numConnections : int = DEFAULT_NUM_CONNECTIONS; public var maxConnectionsPerHost : int = 2; /** @private */ public var _connections : Object; /** * @private **/ public var _loadedRatio : Number = 0; /** @private */ public var _itemsTotal : int = 0; /** @private */ public var _itemsLoaded : int = 0; /** @private */ public var _totalWeight : int = 0; /** @private */ public var _bytesTotal : int = 0; /** @private */ public var _bytesTotalCurrent : int = 0; /** @private */ public var _bytesLoaded : int = 0; /** @private */ public var _percentLoaded : Number = 0; /** @private */ public var _weightPercent : Number; /**The average latency (in miliseconds) for the entire loading.*/ public var avgLatency : Number; /**The average speed (in kb/s) for the entire loading.*/ public var speedAvg : Number; /** @private */ public var _speedTotal : Number; /** @private */ public var _startTime : int ; /** @private */ public var _endTIme : int; /** @private */ public var _lastSpeedCheck : int; /** @private */ public var _lastBytesCheck : int; /** @private */ public var _speed : Number; /**Time in seconds for the whole loading. Only available after everything is laoded*/ public var totalTime : Number; /** LogLevel: Outputs everything that is happening. Usefull for debugging. */ public static const LOG_VERBOSE : int = 0; /**Ouputs noteworthy events such as when an item is started / finished loading.*/ public static const LOG_INFO : int = 2; /**Ouputs noteworthy events such as when an item is started / finished loading.*/ public static const LOG_WARNINGS : int = 3; /**Will only trace errors. Defaut level*/ public static const LOG_ERRORS : int = 4; /**Nothing will be logged*/ public static const LOG_SILENT : int = 10; /**The logging level BulkLoader will use. * @see #LOG_VERBOSE * @see #LOG_SILENT * @see #LOG_ERRORS * @see #LOG_INFO */ public static const DEFAULT_LOG_LEVEL : int = LOG_ERRORS; /** @private */ public var logLevel: int = DEFAULT_LOG_LEVEL; /** @private */ public var _allowsAutoIDFromFileName : Boolean = false; /** @private */ public var _isRunning : Boolean; /** @private */ public var _isFinished : Boolean; /** @private */ public var _isPaused : Boolean = true; /** @private */ public var _logFunction : Function = trace; /** @private */ public var _stringSubstitutions : Object; /** @private */ public static var _typeClasses : Object = { image: ImageItem, movieclip: ImageItem, xml: XMLItem, video: VideoItem, sound: SoundItem, text: URLItem, binary: BinaryItem }; /** Creates a new BulkLoader object identifiable by the name parameter. The name parameter must be unique, else an Error will be thrown. * * @param name A name that can be used later to reference this loader in a static context. If null, bulkloader will generate a unique name. * @param numConnections The number of maximum simultaneous connections to be open. * @param logLevel At which level should traces be outputed. By default only errors will be traced. * * @see #numConnections * @see #log() */ public function BulkLoader(name : String=null, numConnections : int = BulkLoader.DEFAULT_NUM_CONNECTIONS, logLevel : int = BulkLoader.DEFAULT_LOG_LEVEL){ if (!name){ name = getUniqueName(); } if (Boolean(_allLoaders[name])){ __debug_print_loaders(); throw new Error ("BulkLoader with name'" + name +"' has already been created."); }else if (!name ){ throw new Error ("Cannot create a BulkLoader instance without a name"); } _allLoaders[name] = this; if (numConnections > 0){ this._numConnections = numConnections; } this.logLevel = logLevel; _name = name; _instancesCreated ++; _id = _instancesCreated; _additionIndex = 0; // we create a mock event listener for errors, else Unhandled errors will bubble and display an stack trace to the end user: addEventListener(BulkLoader.ERROR, _swallowError, false, 1, true); } /** Creates a BulkLoader instance with an unique name. This is useful for situations where you might be creating * many BulkLoader instances and it gets tricky to garantee that no other instance is using that name. * @param numConnections The number of maximum simultaneous connections to be open. * @param logLevel At which level should traces be outputed. By default only errors will be traced. * @return A BulkLoader intance, with an unique name. */ public static function createUniqueNamedLoader( numConnections : int=BulkLoader.DEFAULT_NUM_CONNECTIONS, logLevel : int = BulkLoader.DEFAULT_LOG_LEVEL) : BulkLoader{ return new BulkLoader(BulkLoader.getUniqueName(), numConnections, logLevel); } public static function getUniqueName() : String{ return "BulkLoader-" + _instancesCreated; } /** Fetched a BulkLoader object created with the name parameter. * This is usefull if you must access loades assets from another scope, without having to pass direct references to this loader. * @param name The name of the loader to be fetched. * @return The BulkLoader instance that was registred with that name. Returns null if none is found. */ public static function getLoader(name :String) : BulkLoader{ return BulkLoader._allLoaders[name] as BulkLoader; } /** @private */ public static function _hasItemInBulkLoader(key : *, atLoader : BulkLoader) : Boolean{ var item : LoadingItem = atLoader.get(key); if (item && item._isLoaded) { return true; } return false; } /** Checks if there is loaded item in this BulkLoader. * @param The url (as a String or a URLRequest object)or an id (as a String) by which the item is identifiable. * @param searchAll If true will search through all BulkLoader instances. Else will only search this one. * @return True if a loader has a loaded item stored. */ public function hasItem(key : *, searchAll : Boolean = true) : Boolean{ var loaders : *; if (searchAll){ loaders = _allLoaders; }else{ loaders = [this]; } for each (var l : BulkLoader in loaders){ if (_hasItemInBulkLoader(key, l )) return true; } return false; } /** Checks which BulkLoader has an item by the given key. * @param The url (as a String or a URLRequest object)or an id (as a String) by which the item is identifiable. * @return The BulkLoader instance that has the given key or null if no key if found in any loader. */ public static function whichLoaderHasItem(key : *) : BulkLoader{ for each (var l : BulkLoader in _allLoaders){ if (BulkLoader._hasItemInBulkLoader(key, l )) return l; } return null; } /** Adds a new assets to be loaded. The BulkLoader object will manage diferent assets type. If the right type cannot be infered from the url termination (e.g. the url ends with ".swf") the BulkLoader will relly on the type property of the props parameter. If both are set, the type property of the props object will overrite the one defined in the url. In case none is specified and the url won't hint at it, the type TYPE_TEXT will be used. * * @param url String OR URLRequest A String or a URLRequest instance. * @param props An object specifing extra data for this loader. The following properties are supported:

* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
Property nameClass constantData typeDescription
preventCachePREVENT_CACHINGBooleanIf true a random query string will be added to the url (or a post param in case of post reuquest).
idIDStringA string to identify this item. This id can be used in any method that uses the key parameter, such as pause, removeItem, resume, getContent, getBitmap, getBitmapData, getXML, getMovieClip and getText.
priorityPRIORITYintAn int used to order which items till be downloaded first. Items with a higher priority will download first. For items with the same priority they will be loaded in the same order they've been added.
maxTriesMAX_TRIESintThe number of retries in case the lading fails, defaults to 3.
weightWEIGHTintA number that sets an arbitrary relative size for this item. See #weightPercent.
headersHEADERSArrayAn array of RequestHeader objects to be used when constructing the URL. If the url parameter is passed as a string, BulkLoader will use these request headers to construct the url.
contextCONTEXTLoaderContext or SoundLoaderContextAn object definig the loading context for this load operario. If this item is of TYPE_SOUND, a SoundLoaderContext is expected. If it's a TYPE_IMAGE a LoaderContext should be passed.
pausedAtStartPAUSED_AT_STARTBooleanIf true, the nestream will be paused when loading has begun.
* You can use string substitutions (variable expandsion). * @example Retriving contents:

import br.stimuli.loaded.BulkLoader; var bulkLoader : BulkLoader = new BulkLoader("main"); // simple item: bulkLoader.add("config.xml"); // use an id that can be retirved latterL bulkLoader.add("background.jpg", {id:"bg"}); // or use a static var to have auto-complete and static checks on your ide: bulkLoader.add("background.jpg", {BulkLoader.ID:"bg"}); // loads the languages.xml file first and parses before all items are done: public function parseLanguages() : void{ var theLangXML : XML = bulkLoader.getXML("langs"); // do something wih the xml: doSomething(theLangXML); } bulkLoader.add("languages.xml", {priority:10, onComplete:parseLanguages, id:"langs"}); // Start the loading operation with only 3 simultaneous connections: bulkLoader.start(3) * @see #stringSubstitutions * */ public function add(url : *, props : Object= null ) : LoadingItem { if(!_name){ throw new Error("[BulkLoader] Cannot use an instance that has been cleared from memory (.clear())"); } if(!url || !String(url)){ throw new Error("[BulkLoader] Cannot add an item with a null url"); } props = props || {}; if (url is String){ url = new URLRequest(BulkLoader.substituteURLString(url, _stringSubstitutions)); if(props[HEADERS]){ url.requestHeaders = props[HEADERS]; } }else if (!url is URLRequest){ throw new Error("[BulkLoader] cannot add object with bad type for url:'" + url.url); } var item : LoadingItem = get(props[ID]); // have already loaded this? if( item ){ log("Add received an already added id: " + props[ID] + ", not adding a new item"); return item; } var type : String; if (props["type"]) { type = props["type"].toLowerCase(); // does this type exist? if (AVAILABLE_TYPES.indexOf(type)==-1){ log("add received an unknown type:", type, "and will cast it to text", LOG_WARNINGS); } } if (!type){ type = guessType(url.url); } _additionIndex ++; item = new _typeClasses[type] (url, type , _instancesCreated + "_" + String(_additionIndex)); if (!props["id"] && _allowsAutoIDFromFileName){ props["id"] = getFileName(url.url); log("Adding automatic id from file name for item:", item , "( id= " + props["id"] + " )"); } var errors : Array = item._parseOptions(props); for each (var error : String in errors){ log(error, LOG_WARNINGS); } log("Added",item, LOG_VERBOSE); // properties from the props argument item._addedTime = getTimer(); item._additionIndex = _additionIndex; // add a lower priority than default, else the event for all items complete will fire before // individual listerners attached to the item item.addEventListener(Event.COMPLETE, _onItemComplete, false, int.MIN_VALUE, true); // need an extra event listener to increment items loaded, because this must happen // **before** the item's normal event, or else client code will get a dummy value for it item.addEventListener(Event.COMPLETE, _incrementItemsLoaded, false, int.MAX_VALUE, true); item.addEventListener(ERROR, _onItemError, false, 0, true); item.addEventListener(Event.OPEN, _onItemStarted, false, 0, true); item.addEventListener(ProgressEvent.PROGRESS, _onProgress, false, 0, true); _items.push(item); _itemsTotal += 1; _totalWeight += item.weight; sortItemsByPriority(); _isFinished = false; if (!_isPaused){ _loadNext(); } return item; } /** Start loading all items added previously * @param withConnections [optional]The maximum number of connections to make at the same time. If specified, will override the parameter passed (if any) to the constructor. * @see #numConnections * @see #see #BulkLoader() */ public function start(withConnections : int = -1 ) : void{ if (withConnections > 0){ _numConnections = withConnections; } if(_connections){ _loadNext(); return; } _startTime = getTimer(); _connections = {}; _loadNext(); _isRunning = true; _lastBytesCheck = 0; _lastSpeedCheck = getTimer(); _isPaused = false; } /** Forces the item specified by key to be reloaded right away. This will stop any open connection as needed. * @param key The url request, url as a string or a id from which the asset was created. * @return True if an item with that key is found, false otherwise. */ public function reload(key : *) : Boolean{ var item : LoadingItem = get(key); if(!item){ return false; } _removeFromItems(item); _removeFromConnections(item); item.stop(); item.cleanListeners(); item.status = null; _isFinished = false; item._addedTime = getTimer(); item._additionIndex = _additionIndex ++; item.addEventListener(Event.COMPLETE, _onItemComplete, false, int.MIN_VALUE, true); item.addEventListener(Event.COMPLETE, _incrementItemsLoaded, false, int.MAX_VALUE, true); item.addEventListener(ERROR, _onItemError, false, 0, true); item.addEventListener(Event.OPEN, _onItemStarted, false, 0, true); item.addEventListener(ProgressEvent.PROGRESS, _onProgress, false, 0, true); _items.push(item); _itemsTotal += 1; _totalWeight += item.weight; sortItemsByPriority(); _isFinished = false; loadNow(item); return true; } /** Forces the item specified by key to be loaded right away. This will stop any open connection as needed. * If needed, the connection to be closed will be the one with the lower priority. In case of a tie, the one * that has more bytes to complete will be removed. The item to load now will be automatically be set the highest priority value in this BulkLoader instance. * @param key The url request, url as a string or a id from which the asset was created. * @return True if an item with that key is found, false otherwise. */ public function loadNow(key : *) : Boolean{ var item : LoadingItem = get(key); if(!item){ return false; } if(!_connections){ _connections = {}; } // is this item already loaded or loading? if (item.status == LoadingItem.STATUS_FINISHED || item.status == LoadingItem.STATUS_STARTED){ return true; } // do we need to remove an item from the open connections? if (_getNumConnections() >= numConnections || _getNumConnectionsForItem(item) >= maxConnectionsPerHost ){ //which item should we remove? var itemToRemove : LoadingItem = _getLeastUrgentOpenedItem(); pause(itemToRemove); _removeFromConnections(itemToRemove); itemToRemove.status = null; } // update the item's piority so that subsequent calls to loadNow don't close a // connection we've just started to load item._priority = highestPriority; _loadNext(item); return true; } /** @private * Figures out which item to remove from open connections, comparation is done by priority * and then by bytes remaining */ public function _getLeastUrgentOpenedItem() : LoadingItem{ // TODO: make sure we remove from the righ hostname var itemsToLoad : Array = _getAllConnections(); itemsToLoad.sortOn(["priority", "bytesRemaining", "_additionIndex"], [Array.NUMERIC, Array.DESCENDING , Array.NUMERIC, Array.NUMERIC]) var toRemove : LoadingItem = LoadingItem(itemsToLoad[0]); return toRemove; } /** Register a new file extension to be loaded as a given type. This is used both in the guessing of types from the url and affects how loading is done for each type. * If you are adding an extension to be of a type you are creating, you must pass the withClass parameter, which should be a class that extends LoadingItem. * @param extension The file extension to be used (can include the dot or not) * @param atType Which type this extension will be associated with. * @param withClass For new types (not new extensions) wich class that extends LoadingItem should be used to mange this item. * @see #TYPE_IMAGE * @see #TYPE_VIDEO * @see #TYPE_SOUND * @see #TYPE_TEXT * @see #TYPE_XML * @see #TYPE_MOVIECLIP * @see #LoadingItem * * @return A Boolean indicating if the new extension was registered. */ public static function registerNewType( extension : String, atType : String, withClass : Class = null) : Boolean { // Normalize extension if (extension.charAt(0) == ".") extension = extension.substring(1); if(!_customTypesExtensions) _customTypesExtensions = {}; atType = atType.toLowerCase(); // Is this a new type? if (AVAILABLE_TYPES.indexOf(atType) == -1){ // new type: we need a class for that: if (!Boolean(withClass) ){ throw new Error("[BulkLoader]: When adding a new type and extension, you must determine which class to use"); } // add that class to the available classes _typeClasses[atType] = withClass; if(!_customTypesExtensions[atType]){ _customTypesExtensions[atType] = []; AVAILABLE_TYPES.push(atType); } _customTypesExtensions[atType].push( extension); return true; }else{ // do have this exension registred for this type? if(_customTypesExtensions[atType]) _customTypesExtensions[atType].push( extension); } var extensions : Array ; var options : Object = { }; options[TYPE_IMAGE] = IMAGE_EXTENSIONS; options[TYPE_MOVIECLIP] = MOVIECLIP_EXTENSIONS; options[TYPE_VIDEO] = VIDEO_EXTENSIONS; options[TYPE_SOUND] = SOUND_EXTENSIONS; options[TYPE_TEXT] = TEXT_EXTENSIONS; options[TYPE_XML] = XML_EXTENSIONS; extensions = options[atType]; if (extensions && extensions.indexOf(extension) == -1){ extensions.push(extension); return true; } return false; } public function _getNextItemToLoad() : LoadingItem{ // check for "stale items" _getAllConnections().forEach(function(i : LoadingItem, ...rest) : void{ if(i.status == LoadingItem.STATUS_ERROR && i.numTries >= i.maxTries){ _removeFromConnections(i); } }); for each (var checkItem:LoadingItem in _items){ if (!checkItem._isLoading && checkItem.status != LoadingItem.STATUS_STOPPED && _canOpenConnectioForItem(checkItem)){ return checkItem; } } return null; } // if toLoad is specified it will take precedence over whoever is queued cut line /** @private */ public function _loadNext(toLoad : LoadingItem = null) : Boolean{ if(_isFinished){ return false; }if (!_connections){ _connections = {}; } var next : Boolean = false; toLoad = toLoad || _getNextItemToLoad(); if (toLoad){ next = true; _isRunning = true; // need to check again, as _loadNext might have been called with an item to be loaded forcefully. if(_canOpenConnectioForItem(toLoad)){ var connectionsForItem : Array = _getConnectionsForHostName(toLoad.hostName); connectionsForItem.push(toLoad); toLoad.load(); //trace("begun loading", toLoad.url.url);//, _getNumConnectionsForItem(toLoad) + "/" + maxConnectionsPerHost, _getNumConnections() + "/" + numConnections); log("Will load item:", toLoad, LOG_INFO); } // if we've got any more connections to open, load the next item if(_getNextItemToLoad()){ _loadNext(); } } return next; } /** @private */ public function _onItemComplete(evt : Event) : void { var item : LoadingItem = evt.target as LoadingItem; _removeFromConnections(item); log("Loaded ", item, LOG_INFO); log("Items to load", getNotLoadedItems(), LOG_VERBOSE); item.cleanListeners(); _contents[item.url.url] = item.content; var next : Boolean= _loadNext(); var allDone : Boolean = _isAllDoneP(); if(allDone) { _onAllLoaded(); } evt.stopPropagation(); } /** @private */ public function _incrementItemsLoaded(evt : Event) : void{ _itemsLoaded ++; } /** @private */ public function _updateStats() : void { avgLatency = 0; speedAvg = 0; var totalLatency : Number = 0; var totalBytes : int = 0; _speedTotal = 0; var num : Number = 0; for each(var item : LoadingItem in _items){ if (item._isLoaded && item.status != LoadingItem.STATUS_ERROR){ totalLatency += item.latency; totalBytes += item.bytesTotal; num ++; } } _speedTotal = (totalBytes/1024) / totalTime; avgLatency = totalLatency / num; speedAvg = _speedTotal / num; } /** @private */ public function _removeFromItems(item : LoadingItem) : Boolean{ var removeIndex : int = _items.indexOf(item); if(removeIndex > -1){ _items.splice( removeIndex, 1); }else{ return false; } if(item._isLoaded){ _itemsLoaded --; } _itemsTotal --; _totalWeight -= item.weight; log("Removing " + item, LOG_VERBOSE); item.removeEventListener(Event.COMPLETE, _onItemComplete, false) item.removeEventListener(Event.COMPLETE, _incrementItemsLoaded, false) item.removeEventListener(ERROR, _onItemError, false); item.removeEventListener(Event.OPEN, _onItemStarted, false); item.removeEventListener(ProgressEvent.PROGRESS, _onProgress, false); return true; } /** @private */ public function _removeFromConnections(item : *) : Boolean{ if(!_connections || _getNumConnectionsForItem(item) == 0) return false; var connectionsForHost : Array = _getConnectionsForHostName(item.hostName);(item); var removeIndex : int = connectionsForHost.indexOf(item); if(removeIndex > -1){ connectionsForHost.splice( removeIndex, 1); return true; } return false; } public function _getNumConnectionsForHostname(hostname :String) : int{ var conns : Array = _getConnectionsForHostName(hostname); if (!conns) { return 0; } return conns.length; } /** @private */ public function _getNumConnectionsForItem(item :LoadingItem) : int{ var conns : Array = _getConnectionsForHostName(item.hostName);(item); if (!conns) { return 0; } return conns.length; } /** @private */ public function _getAllConnections() : Array { var conns : Array = []; for (var hostname : String in _connections){ conns = conns.concat ( _connections[hostname] ) ; } return conns; } /** @private **/ public function _getNumConnections() : int{ var connections : int = 0; for (var hostname : String in _connections){ connections += _connections[hostname].length; } return connections; } public function _getConnectionsForHostName (hostname : String) : Array { if (_connections[hostname] == null ){ _connections[hostname] = []; } return _connections[hostname]; } public function _canOpenConnectioForItem(item :LoadingItem) : Boolean{ if (_getNumConnections() >= numConnections) return false; if (_getNumConnectionsForItem(item) >= maxConnectionsPerHost) return false; return true; } /** @private */ public function _onItemError(evt : ErrorEvent) : void{ var item : LoadingItem = evt.target as LoadingItem; _removeFromConnections(item); log("After " + item.numTries + " I am giving up on " + item.url.url, LOG_ERRORS); log("Error loading", item, evt.text, LOG_ERRORS); _loadNext(); //evt.stopPropagation(); //evt.currentTarget = item; dispatchEvent(evt); } /** @private */ public function _onItemStarted(evt : Event) : void{ var item : LoadingItem = evt.target as LoadingItem; log("Started loading", item, LOG_INFO); dispatchEvent(evt); } /** @private */ public function _onProgress(evt : Event = null) : void{ // TODO: check these values are correct! tough _onProgress var e : BulkProgressEvent = getProgressForItems(_items); // update values: _bytesLoaded = e.bytesLoaded; _bytesTotal = e.bytesTotal; _weightPercent = e.weightPercent; _percentLoaded = e.percentLoaded; _bytesTotalCurrent = e.bytesTotalCurrent; _loadedRatio = e.ratioLoaded; dispatchEvent(e); } /** Calculates the progress for a specific set of items. * @param keys An Array containing keys (ids or urls) or LoadingItem objects to measure progress of. * @return A BulkProgressEvent object with the current progress status. * @see BulkProgressEvent */ public function getProgressForItems(keys : Array) : BulkProgressEvent{ _bytesLoaded = _bytesTotal = _bytesTotalCurrent = 0; var localWeightPercent : Number = 0; var localWeightTotal : int = 0; var itemsStarted : int = 0; var localWeightLoaded : Number = 0; var localItemsTotal : int = 0; var localItemsLoaded : int = 0; var localBytesLoaded : int = 0; var localBytesTotal : int = 0; var localBytesTotalCurrent : int = 0; var item : LoadingItem; var theseItems : Array = []; for each (var key: * in keys){ item = get(key); if (!item) continue; localItemsTotal ++; localWeightTotal += item.weight; if (item.status == LoadingItem.STATUS_STARTED || item.status == LoadingItem.STATUS_FINISHED || item.status == LoadingItem.STATUS_STOPPED){ localBytesLoaded += item._bytesLoaded; localBytesTotalCurrent += item._bytesTotal; if (item._bytesTotal > 0){ localWeightLoaded += (item._bytesLoaded / item._bytesTotal) * item.weight; } if(item.status == LoadingItem.STATUS_FINISHED) { localItemsLoaded ++; } itemsStarted ++; } } // only set bytes total if all items have begun loading if (itemsStarted != localItemsTotal){ localBytesTotal = Number.POSITIVE_INFINITY; }else{ localBytesTotal = localBytesTotalCurrent; } localWeightPercent = localWeightLoaded / localWeightTotal; if(localWeightTotal == 0) localWeightPercent = 0; var e : BulkProgressEvent = new BulkProgressEvent(PROGRESS); e.setInfo(localBytesLoaded, localBytesTotal, localBytesTotal, localItemsLoaded, localItemsTotal, localWeightPercent); return e; } /** The number of simultaneous connections to use. This is per BulkLoader instance. * @return The number of connections used. * @see #start() */ public function get numConnections() : int { return _numConnections; } /** Returns an object where the urls are the keys(as strings) and the loaded contents are the value for that key. * Each value is typed as * an the client must check for the right typing. * @return An object hashed by urls, where values are the downloaded content type of each url. The user mut cast as apropriate. */ public function get contents() : Object { return _contents; } /** Returns a copy of all LoadingItem in this intance. This function makes a copy to avoid * users messing with _items (removing items and so forth). Those can be done through functions in BulkLoader. * @return A array that is a shallow copy of all items in the BulkLoader. */ public function get items() : Array { return _items.slice(); } /** * The name by which this loader instance can be identified. * This property is used so you can get a reference to this instance from other classes in your code without having to save and pass it yourself, throught the static method BulkLoader.getLoader(name) .

* Each name should be unique, as instantiating a BulkLoader with a name already taken will throw an error. * @see #getLoaders() */ public function get name() : String { return _name; } /** * The ratio (0->1) of items to load / items total. * This number is always reliable. **/ public function get loadedRatio() : Number { return _loadedRatio; } /** Total number of items to load.*/ public function get itemsTotal() : int { return items.length; } /** * Number of items alrealdy loaded. * Failed or canceled items are not taken into consideration */ public function get itemsLoaded() : int { return _itemsLoaded; } public function set itemsLoaded(value:int) : void { _itemsLoaded = value; } /** The sum of weights in all items to load. * Each item's weight default to 1 */ public function get totalWeight() : int { return _totalWeight; } /** The total bytes to load. * If the number of items to load is larger than the number of simultaneous connections, bytesTotal will be 0 untill all connections are opened and the number of bytes for all items is known. * @see #bytesTotalCurrent */ public function get bytesTotal() : int { return _bytesTotal; } /** The sum of all bytesLoaded for each item. */ public function get bytesLoaded() : int { return _bytesLoaded; } /** The sum of all bytes loaded so far. * If itemsTotal is less than the number of connections, this will be the same as bytesTotal. Else, bytesTotalCurrent will be available as each loading is started. * @see #bytesTotal */ public function get bytesTotalCurrent() : int { return _bytesTotalCurrent; } /** The percentage (0->1) of bytes loaded. * Until all connections are opened this number is not reliable . If you are downloading more items than the number of simultaneous connections, use loadedRatio or weightPercent instead. * @see #loadedRatio * @see #weightPercent */ public function get percentLoaded() : Number { return _percentLoaded; } /** The weighted percent of items loaded(0->1). * This always returns a reliable value. */ public function get weightPercent() : Number { return _weightPercent; } /** A boolean indicating if the instace has started and has not finished loading all items */ public function get isRunning() : Boolean { return _isRunning; } public function get isFinished() : Boolean{ return _isFinished; } /** Returns the highest priority for all items in this BulkLoader instance. This will check all items, * including cancelled items and already downloaded items. */ public function get highestPriority() : int{ var highest : int = int.MIN_VALUE; for each (var item : LoadingItem in _items){ if (item.priority > highest) highest = item.priority; } return highest; } /** The function to be used in logging. By default it's the same as the global function trace. The log function signature is: *

     *   public function myLogFunction(msg : String) : void{}
     *   
*/ public function get logFunction() : Function { return _logFunction; } /** Determines if an autmatic id created from the file name. If true, when adding and item and NOT specifing an "id" props * for its properties, an id with the file name will be created altomatically. * @example Automatic id: * bulkLoader.allowsAutoIDFromFileName = false; * var item : LoadingItem = bulkLoader.add("background.jpg") * trace(item.id) // outputs: null * // now if allowsAutoIDFromFileName is set to true: * bulkLoader.allowsAutoIDFromFileName = true; * var item : LoadingItem = bulkLoader.add("background.jpg") * trace(item.id) // outputs: background * // if you pass an id on the props, it will take precedence over auto created ids: * bulkLoader.allowsAutoIDFromFileName = id; * var item : LoadingItem = bulkLoader.add("background.jpg", {id:"small-bg"}) * trace(item.id) // outputs: small-bg * */ public function get allowsAutoIDFromFileName() : Boolean { return _allowsAutoIDFromFileName; } public function set allowsAutoIDFromFileName(value:Boolean) : void { _allowsAutoIDFromFileName = value; } /** Returns items that haven't been fully loaded. * @return An array with all LoadingItems not fully loaded. */ public function getNotLoadedItems () : Array{ return _items.filter(function(i : LoadingItem, ...rest):Boolean{ return i.status != LoadingItem.STATUS_FINISHED; }); } /* Returns the speed in kilobytes / second for all loadings */ public function get speed() : Number{ // TODO: test get speed var timeElapsed : int = getTimer() - _lastSpeedCheck; var bytesDelta : int = (bytesLoaded - _lastBytesCheck) / 1024; var speed : int = bytesDelta / (timeElapsed/1000); _lastSpeedCheck = timeElapsed; _lastBytesCheck = bytesLoaded; return speed; } /** The function to be called for loggin. The loggin function should receive one parameter, the string to be logged. The logFunction defaults to flash's regular trace function. You can use the logFunction to route traces to an alternative place (such as a textfield or some text component in your application). If the logFunction is set to something else that the global trace function, nothing will be traced. A custom logFunction messages will still be filtered by the logLevel setting. * @param func The function to be used on loggin. */ public function set logFunction(func:Function) : void { _logFunction = func; } /** The id of this bulkLoader instance */ public function get id() : int { return _id; } /** The object, used as a hashed to substitute variables specified on the url used in add. * Allows to keep common part of urls on one spot only. If later the server path changes, you can * change only the stringSubstitutions object to update all items. * This has to be set before the add calls are made, or else strings won't be expanded. * @example Variable sustitution: * // All webservices will be at a common path: * bulkLoader.stringSubstitutions = { * "web_services": "http://somesite.com/webservices" * } * bulkLoader.add("{web_services}/getTime"); * // this will be expanded to http://somesite.com/webservices/getTime * * * The format expected is {var_name} , where var_name is composed of alphanumeric characters and the underscore. Other characters (., *, [, ], etc) won't work, as they'll clash with the regex used in matching. * @see #add */ public function get stringSubstitutions() : Object { return _stringSubstitutions; } public function set stringSubstitutions(value:Object) : void { _stringSubstitutions = value; } /** Updates the priority of item identified by key with a new value, the queue will be re resorted right away. * Changing priorities will not stop currently opened connections. * @param key The url request, url as a string or a id from which the asset was loaded. * @param new The priority to assign to the item. * @return The true if an item with that key was found, false othersiwe. */ public function changeItemPriority(key : *, newPriority : int) : Boolean{ var item : LoadingItem = get(key); if (!item){ return false; } item._priority = newPriority; sortItemsByPriority(); return true; } /** Updates the priority queue */ public function sortItemsByPriority() : void{ // addedTime might not be precise, if subsequent add() calls are whithin getTimer precision // range, so we use _additionIndex _items.sortOn(["priority", "_additionIndex"], [Array.NUMERIC | Array.DESCENDING, Array.NUMERIC ]); } /* ============================================================================== */ /* = Acessing content functions = */ /* ============================================================================== */ /** @private Helper functions to get loaded content. All helpers will be casted to the specific types. If a cast fails it will throw an error. * */ public function _getContentAsType(key : *, type : Class, clearMemory : Boolean = false) : *{ if(!_name){ throw new Error("[BulkLoader] Cannot use an instance that has been cleared from memory (.clear())"); } var item : LoadingItem = get(key); if(!item){ return null; } try{ if (item._isLoaded || item.isStreamable() && item.status == LoadingItem.STATUS_STARTED) { var res : * = item.content as type; if (res == null){ throw new Error("bad cast"); } if(clearMemory){ remove(key); // this needs to try to load a next item, because this might get called inside a // complete handler and if it's on the last item on the open connections, it might stale if (!_isPaused){ _loadNext(); } } return res; } }catch(e : Error){ log("Failed to get content with url: '"+ key + "'as type:", type, LOG_ERRORS); } return null; } /** Returns an untyped object with the downloaded asset for the given key. * @param key The url request, url as a string or a id from which the asset was loaded. * @param clearMemory If this BulkProgressEvent instance should clear all references to the content of this asset. * @return The content retrived from that url */ public function getContent(key : String, clearMemory : Boolean = false) : *{ return _getContentAsType(key, Object, clearMemory); } /** Returns an XML object with the downloaded asset for the given key. * @param key String OR URLRequest The url request, url as a string or a id from which the asset was loaded. Returns null if the cast fails * @param clearMemory If this BulkProgressEvent instance should clear all references to the content of this asset. * @return The content retrived from that url casted to a XML object. Returns null if the cast fails. */ public function getXML(key : *, clearMemory : Boolean = false) : XML{ return XML(_getContentAsType(key, XML, clearMemory)); } /** Returns a String object with the downloaded asset for the given key. * @param key The url request, url as a string or a id from which the asset was loaded. Returns null if the cast fails * @param clearMemory If this BulkProgressEvent instance should clear all references to the content of this asset. * @return The content retrived from that url casted to a String object. Returns null if the cast fails. */ public function getText(key : *, clearMemory : Boolean = false) : String{ return String(_getContentAsType(key, String, clearMemory)); } /** Returns a Sound object with the downloaded asset for the given key. * @param key The url request, url as a string or a id from which the asset was loaded. Returns null if the cast fails * @param clearMemory Boolean If this BulkProgressEvent instance should clear all references to the content of this asset. * @return The content retrived from that url casted to a Sound object. Returns null if the cast fails. */ public function getSound(key : *, clearMemory : Boolean = false) : Sound{ return Sound(_getContentAsType(key, Sound,clearMemory)); } /** Returns a Bitmap object with the downloaded asset for the given key. * @param key The url request, url as a string or a id from which the asset was loaded. Returns null if the cast fails * @param clearMemory If this BulkProgressEvent instance should clear all references to the content of this asset. * @return The content retrived from that url casted to a Bitmap object. Returns null if the cast fails. */ public function getBitmap(key : String, clearMemory : Boolean = false) : Bitmap{ return Bitmap(_getContentAsType(key, Bitmap, clearMemory)); } /** Returns a Loader object with the downloaded asset for the given key. * Had to pick this ugly name since getLoader is currently used for getting a BulkLoader instance. * This is useful if you are loading images but do not have a crossdomain to grant you permissions. In this case, while you * will still find restrictions to how you can use that loaded asset (no BitmapData for it, for example), you still can use it as content. * * @param key The url request, url as a string or a id from which the asset was loaded. Returns null if the cast fails * @param clearMemory If this BulkProgressEvent instance should clear all references to the content of this asset. * @return The content retrived from that url casted to a Loader object. Returns null if the cast fails. */ public function getDisplayObjectLoader(key : String, clearMemory : Boolean = false) : Loader{ if(!_name){ throw new Error("[BulkLoader] Cannot use an instance that has been cleared from memory (.clear())"); } var item : ImageItem = get(key) as ImageItem; if(!item){ return null; } try{ var res : Loader = item.loader as Loader; if (!res){ throw new Error("bad cast"); } if(clearMemory){ remove(key); // this needs to try to load a next item, because this might get called inside a // complete handler and if it's on the last item on the open connections, it might stale if (!_isPaused){ _loadNext(); } } return res; }catch(e : Error){ log("Failed to get content with url: '"+ key + "'as type: Loader", LOG_ERRORS); } return null; } /** Returns a MovieClip object with the downloaded asset for the given key. * @param key The url request, url as a string or a id from which the asset was loaded. Returns null if the cast fails * @param clearMemory If this BulkProgressEvent instance should clear all references to the content of this asset. * @return The content retrived from that url casted to a MovieClip object. Returns null if the cast fails. */ public function getMovieClip(key : String, clearMemory : Boolean = false) : MovieClip{ return MovieClip(_getContentAsType(key, MovieClip, clearMemory)); } /** Returns a Sprite object with the downloaded asset for the given key. * @param key The url request, url as a string or a id from which the asset was loaded. Returns null if the cast fails * @param clearMemory If this BulkProgressEvent instance should clear all references to the content of this asset. * @return The content retrived from that url casted to a Sprite object. Returns null if the cast fails. */ public function getSprite(key : String, clearMemory : Boolean = false) : Sprite{ return Sprite(_getContentAsType(key, Sprite, clearMemory)); } /** Returns a AVM1Movie object with the downloaded asset for the given key. * @param key The url request, url as a string or a id from which the asset was loaded. Returns null if the cast fails * @param clearMemory If this BulkProgressEvent instance should clear all references to the content of this asset. * @return The content retrived from that url casted to a AVM1Movie object. Returns null if the cast fails. */ public function getAVM1Movie(key : String, clearMemory : Boolean = false) : AVM1Movie{ return AVM1Movie(_getContentAsType(key, AVM1Movie, clearMemory)); } /** Returns a NetStream object with the downloaded asset for the given key. * @param key The url request, url as a string or a id from which the asset was loaded. Returns null if the cast fails * @param clearMemory If this BulkProgressEvent instance should clear all references to the content of this asset. * @return The content retrived from that url casted to a NetStream object. Returns null if the cast fails. */ public function getNetStream(key : String, clearMemory : Boolean = false) : NetStream{ return NetStream(_getContentAsType(key, NetStream, clearMemory)); } /** Returns a Object with meta data information for a given NetStream key. * @param key The url request, url as a string or a id from which the asset was loaded. Returns null if the cast fails * @param clearMemory If this BulkProgressEvent instance should clear all references to the content of this asset. * @return The meta data object downloaded with this NetStream. Returns null if the given key does not resolve to a NetStream. */ public function getNetStreamMetaData(key : String, clearMemory : Boolean = false) : Object{ var netStream : NetStream = getNetStream(key, clearMemory); return (Boolean(netStream) ? (get(key) as Object).metaData : null); } /** Returns an BitmapData object with the downloaded asset for the given key. * @param key The url request, url as a string or a id from which the asset was loaded. Returns null if the cast fails. Does not clone the original bitmap data from the bitmap asset. * @param clearMemory If this BulkProgressEvent instance should clear all references to the content of this asset. * @return The content retrived from that url casted to a BitmapData object. Returns null if the cast fails. */ public function getBitmapData(key : *, clearMemory : Boolean = false) : BitmapData{ try{ return getBitmap(key, clearMemory).bitmapData; }catch (e : Error){ log("Failed to get bitmapData with url:", key, LOG_ERRORS); } return null; } /** Returns an ByteArray object with the downloaded asset for the given key. * @param key The url request, url as a string or a id from which the asset was loaded. Returns null if the cast fails. * @param clearMemory If this BulkProgressEvent instance should clear all references to the content of this asset. * @return The content retrived from that url casted to a ByteArray object. Returns null if the cast fails. */ public function getBinary(key : *, clearMemory : Boolean = false) :ByteArray{ return ByteArray(_getContentAsType(key, ByteArray, clearMemory)); } /** Returns a object decoded from a string, by a given encoding function. * @param key The url request, url as a string or a id from which the asset was loaded. Returns null if the encoding fails * @param clearMemory If this BulkProgressEvent instance should clear all references to the content of this asset. * @param encodingFunction A Function object to be passed the string and be encoded into an object. * @return The content retrived from that url encoded by encodingFunction */ public function getSerializedData(key : *, clearMemory : Boolean = false, encodingFunction : Function = null) : *{ try{ var raw : * = _getContentAsType(key, Object, clearMemory); var parsed : * = encodingFunction.apply(null, [raw]); return parsed; }catch (e : Error){ log("Failed to parse key:", key, "with encodingFunction:" + encodingFunction, LOG_ERRORS); } return null; } /** Gets a class definition from a fully qualified path. Note that this will only work if you've loaded the swf with the same LoaderContext of the other swf (using "context" prop on "add"). Else you should use .getClassByName instead. @param className The fully qualified class name as a string. @return The Class object with that name or null of not found. */ // public function getClassByName(className : String) : Class{ // try{ // return getDefinitionByName(className) as Class; // }catch(e : Error){ // // } // return null; // } /** Gets the http status code for the loading item identified by key. * @param key The url request, url as a string or a id from which the asset was loaded. * @return The Http status as an integer. If no item is found returns -1. If the http status cannot be determined but the item was found, returns 0. */ public function getHttpStatus(key : *) : int{ var item : LoadingItem = get(key); if(item){ return item.httpStatus; } return -1; } /** @private */ public function _isAllDoneP() : Boolean{ return _items.every(function(item : LoadingItem, ...rest):Boolean{ return item._isLoaded; }); } /** @private */ public function _onAllLoaded() : void { if(_isFinished){ return; } var eComplete : BulkProgressEvent = new BulkProgressEvent(COMPLETE); eComplete.setInfo(bytesLoaded, bytesTotal, bytesTotalCurrent, _itemsLoaded, itemsTotal, weightPercent); var eProgress : BulkProgressEvent = new BulkProgressEvent(PROGRESS); eProgress.setInfo(bytesLoaded, bytesTotal, bytesTotalCurrent, _itemsLoaded, itemsTotal, weightPercent); _isRunning = false; _endTIme = getTimer(); totalTime = BulkLoader.truncateNumber((_endTIme - _startTime) /1000); _updateStats(); _connections = {}; getStats(); _isFinished = true; log("Finished all", LOG_INFO); dispatchEvent(eProgress); dispatchEvent(eComplete); } /** If the logLevel if lower that LOG_ERRORS(3). Outputs a host of statistics about the loading operation * @return A formated string with loading statistics. * @see #LOG_ERRORS * @see #logLevel */ public function getStats() : String{ var stats : Array = []; stats.push("\n************************************"); stats.push("All items loaded(" + itemsTotal + ")"); stats.push("Total time(s): " + totalTime); stats.push("Average latency(s): " + truncateNumber(avgLatency)); stats.push("Average speed(kb/s): " + truncateNumber(speedAvg)); stats.push("Median speed(kb/s): " + truncateNumber(_speedTotal)); stats.push("KiloBytes total: " + truncateNumber(bytesTotal/1024)); var itemsInfo : Array = _items.map(function(item :LoadingItem, ...rest) : String{ return "\t" + item.getStats(); }); stats.push(itemsInfo.join("\n")) stats.push("************************************"); var statsString : String = stats.join("\n"); log(statsString, LOG_VERBOSE); return statsString; } /** @private * Outputs with a trace operation a message. * Depending on logLevel diferrent levels of messages will be outputed: *