webglade

JavaScript library to dynamically create XUL GUI from Glade XML files
git clone https://logand.com/git/webglade.git/
Log | Files | Refs | README | LICENSE

Connection.js (6744B)


      1 /**
      2  * Contain the Connection class
      3  *
      4  * @filename Connection.js
      5  * @$LastChangedDate$
      6  * @author Fabio Serra <faser@faser.net>
      7  * @copyright Fabio Serra (The Initial Developer of the Original Code)
      8  * @license Mozilla Public License Version 1.1
      9  *
     10 */
     11 
     12 /**
     13  * Construct a new Connection object
     14  * @class Used to send GET or POST request to a server. The object provide a timeout and
     15  * return a connectionID that can be used to track multiple request made at the same time
     16  * @constructor
     17  * @param {string} targetUrl The URL to make a connection
     18  * @param {bool} permission Ask permission in case of MAB is not running as an extension
     19  * @throws XMLHttpRequest exception when unable to create an XMLHttpRequest object
     20  * @return A new Connection
     21  *
     22 */
     23 function Connection(targetUrl,permission) {
     24 	/**
     25 	 * The target URL
     26 	 * @type string
     27 	*/
     28 	this.url = targetUrl;
     29 
     30 	/**
     31 	 * Need permission
     32      * @type bool
     33 	*/
     34 	this.blPermission = false;
     35 	if(permission) {this.blPermission = true;}
     36 
     37 	/**
     38 	 * How long I have to wait for an answer before aborting. Default 1 minute
     39      * @type int
     40 	*/
     41 	this.timeout = 60000;
     42 
     43 	/**
     44 	 * The interval id returned by the setInterval
     45      * @private
     46      * @type int
     47 	*/
     48 	this.intervalID = null;
     49 
     50 	/**
     51 	 * Connection ID to use with the callback function.
     52      * The caller have to know from which obj receive the result.
     53      * @private
     54      * @type int
     55 	*/
     56 	this.connectionID = Math.round(Math.random()*(10000000-1))+1;
     57 
     58 	/**
     59 	 * The server answer has been loaded?
     60      * @const
     61      * @type int
     62 	*/
     63 	this.COMPLETED = 4;
     64 
     65 	/**
     66 	 * This object contain all fields that should be returned after a connection
     67      * @type object
     68 	*/
     69 	this.retParams = {};
     70 		/** Unique identifier */
     71 		this.retParams.connectionID = this.connectionID;
     72 		/**
     73 		 * Returned status code. 0 means everything is OK
     74          * @type int
     75 		*/
     76 		this.retParams.status = 0;
     77 		/**
     78 		 * Associated text message
     79          * @type string
     80 		*/
     81 		this.retParams.message = "";
     82 		/**
     83 		 * Full response content as requested (XML or TXT)
     84     	*/
     85 		this.retParams.content = "";
     86 		/**
     87 		 * The URL that generated the response
     88 		*/
     89 		this.retParams.requestedURL = "";
     90 
     91 
     92 	//Create XMLHttpRequest object
     93 	try {
     94 		/**
     95 		 * The XMLHttpRequest object
     96          * @type XMLHttpRequest
     97 		*/
     98 		this.req = new XMLHttpRequest();
     99 	}catch(e){
    100 		throw("Creating XMLHttpRequest:" + e);
    101 	}
    102 }
    103 
    104 /**
    105  * Send a request to the target url
    106  * @param {string} string The query string
    107  * @param {string} method The HTTP request method (GET | POST)
    108  * @param {string} responseType The requested response type (txt | xml)
    109  * @return void
    110  * @throw netscape.security
    111  * @throw XMLHttpRequest open or send exceptions
    112 */
    113 Connection.prototype.send = function(string,method,responseType) {
    114 	//Request permission for remote application
    115 	if(this.blPermission) {
    116 		try {
    117 			netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
    118 		}catch (e){
    119 			throw(e);
    120 		}
    121 	}
    122 
    123 	//encode string
    124 	var params = encodeURI(string);
    125 
    126 	var me = this;
    127 	var lambda = function myScopeFunction(){
    128 		me.getResponse(responseType);
    129 	}
    130 
    131 	//Abort current connection
    132 	var timedOut = function() {
    133 		me.abortConnection(10);
    134 	}
    135 
    136 	if(responseType == "xml") {this.req.overrideMimeType("text/xml");}
    137 
    138 	switch(method) {
    139 		case "GET":
    140 			var qString = this.url + '?' + params;
    141 			try {
    142 				//Check for timeout
    143 				this.intervalID =  setInterval(timedOut,this.timeout);
    144 				this.req.open("GET",qString,true);
    145 				//Save the request url
    146 				this.retParams.requestedURL = qString;
    147 				this.req.send(null);
    148 			}catch(e){
    149 				throw(e);
    150 			}
    151 
    152 			break;
    153 		case "POST":
    154 			try {
    155 				//Check for timeout
    156 				this.intervalID =  setInterval(timedOut,this.timeout);
    157 				this.req.open("POST",this.url,true);
    158 				this.req.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
    159 				this.req.send(params);
    160 			}catch(e){
    161 				throw(e);
    162 			}
    163 			break;
    164 		default:
    165 			throw("Connection Exception: method not supported");
    166 
    167 	}
    168 
    169 
    170 	this.req.onload = lambda;
    171 }
    172 
    173 /**
    174  * Handle the server response and send the result to the defined callback function
    175  * @param {string} responseType The requested response type (txt | xml)
    176  * @return void
    177 */
    178 
    179 Connection.prototype.getResponse = function(responseType) {
    180 	if(this.req.readyState == this.COMPLETED) {
    181 	//Clear Inteval for timeout checking
    182 	clearInterval(this.intervalID);
    183 		if(this.req.status !=200) {
    184 			this.connectionException(20);
    185 			this.errorCallback(this.retParams);
    186 		} else {
    187 			if(responseType == "txt") {
    188 				this.retParams.content = this.req.responseText;
    189 				this.callBack(this.retParams);
    190 			}else{
    191 				var responseXML = new DOMParser().parseFromString(this.req.responseText, 'text/xml');
    192 				this.retParams.content = this.req.responseXML;
    193 				this.callBack(this.retParams);
    194 			}
    195 		}
    196 	}
    197 }
    198 
    199 /**
    200  * To pass the reference to the function to be called when the data is available.
    201  * @param {string} fRef function name
    202  * @return void
    203 */
    204 Connection.prototype.setCallback= function (fRef) {
    205 	this.callBack=fRef;
    206 }
    207 
    208 /**
    209  * To pass the reference to the function in case of errors
    210  * @param {string} fRef function name
    211  * @return void
    212 */
    213 Connection.prototype.setErrorCallback= function (fRef) {
    214 	this.errorCallback=fRef;
    215 }
    216 
    217 /**
    218  * Abort in progress connection
    219  * @param {int} errorCode provide a properly error code
    220  * @return void
    221  * @throw exception
    222 */
    223 Connection.prototype.abortConnection = function(errorCode) {
    224 	try {
    225 		this.req.abort();
    226 		clearInterval(this.intervalID);
    227 		this.connectionException(errorCode);
    228 		this.errorCallback(this.retParams);
    229 	}catch(e){
    230 		throw(e);
    231 	}
    232 }
    233 
    234 /**
    235  * Set the status code and a message in case of error
    236  * @param {int} errorCode An error code
    237  * @return void
    238 */
    239 Connection.prototype.connectionException = function (errorCode) {
    240 	switch(errorCode) {
    241 		//TimeOut
    242 		case 10:
    243 			this.retParams.status = errorCode;
    244 			this.retParams.message = "Connection has timed out";
    245 			break;
    246 		case 20:
    247 			this.retParams.status = errorCode;
    248 			this.retParams.message = "The server respond with a bad status code: " + this.req.status;
    249 			//check if the response have some more info in html format
    250 			if(this.req.responseText) {
    251 				//TODO - LIMIT TEXT
    252 				this.retParams.message += "\n" + stripHTML(this.req.responseText);
    253 			}
    254 			break;
    255 		case 30:
    256 			this.retParams.status = errorCode;
    257 			this.retParams.message = "Connection cancelled by user";
    258 			break;
    259 		case 40:
    260 			this.retParams.status = errorCode;
    261 			this.retParams.message = "General connection failure";
    262 			break;
    263 
    264 	}
    265 
    266 }