Created
June 27, 2012 06:02
-
-
Save rpgmaker/3001802 to your computer and use it in GitHub Desktop.
JS API (Kinda Final)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
if (!JSON) { | |
throw new Error("JSON library is required to load PSERVICEBUS. Please reference json2.js"); | |
} | |
if (!jQuery) { | |
throw new Error("jQuery library is required to load PSERVICEBUS"); | |
} | |
String.format = function (text) { | |
'use strict'; | |
if (arguments.length <= 1) return text; | |
var length = arguments.length - 2, token; | |
for (token = 0; token <= length; token++) { | |
text = text.replace(new RegExp("\\{" + token + "\\}", "gi"), arguments[token + 1]); | |
} | |
return text; | |
}; | |
//Enable cross domain request | |
jQuery.support.cors = true; | |
var PSERVICEBUS; | |
if (!PSERVICEBUS) PSERVICEBUS = {}; | |
(function (fn) { | |
'use strict'; | |
var hubcounter = 0, | |
hubconnections = {}; | |
fn.protocols = { | |
httpstreaming: 1, | |
serversent: 4, | |
ieforeverframe: 2, | |
foreverframe: 3, | |
longpolling: 5 | |
}; | |
fn.hub = function () { | |
var self = this, | |
interval = 500, | |
transport = null, | |
active = false, | |
msgID = 0, | |
hubID = ++hubcounter, | |
name = "hub" + hubID, | |
url = null, | |
protocol = fn.setting.protocol() || | |
($.browser.msie ? fn.protocols.ieforeverframe : | |
$.browser.opera ? fn.protocols.serversent : | |
$.browser.safari || $.browser.webkit || $.browser.mozilla ? | |
fn.protocols.httpstreaming : fn.protocols.foreverframe), | |
transportType = ( | |
protocol === fn.protocols.ieforeverframe || protocol === fn.protocols.foreverframe ? "foreverframe" : | |
protocol === fn.protocols.httpstreaming ? "httpstreaming" : | |
protocol === fn.protocols.serversent ? "serversent" : ""), | |
scope = function (f, context) { | |
return function () { return f.apply(context); }; | |
}, | |
xhrcallback = function () { | |
if (transport.readyState === 4) { self.close(); return; } | |
var messages = transport.responseText.match(/<comet>(.+?)<\/comet>/g); | |
while (messages && messages[msgID]) { | |
var message = messages[msgID].substring(7, messages[msgID].length - 8), | |
msg = JSON.parse(message); | |
self.onmessage(msg); | |
msgID++; | |
} | |
}, | |
checkframe = function () { | |
var iframe = transport.getElementById(name); | |
if (!iframe) return; | |
if (iframe.readyState === 'complete') { self.close(); return; } | |
setTimeout(scope(checkframe, self), interval); | |
}; | |
hubconnections[hubID] = self; | |
var _open = function () { | |
if (active) return; | |
active = true; | |
switch (protocol) { | |
case fn.protocols.httpstreaming: | |
transport = ("XDomainRequest" in window) ? new XDomainRequest() : | |
new XMLHttpRequest(); | |
transport.open("GET", url, true); | |
transport.onreadystatechange = scope(xhrcallback, self); | |
transport.send(null); | |
break; | |
case fn.protocols.ieforeverframe: | |
var p = document.location.protocol; | |
transport = new ActiveXObject("htmlfile"); | |
transport.open(); | |
transport.write(String.format("<html><script>{0}</script></html>", | |
p.indexOf("file") >= 0 || document.domain.indexOf("localhost") >= 0 ? "" : | |
String.format("document.domain='{0}//{1}';", p, document.domain))); | |
transport.close(); | |
transport.parentWindow.push = self.onmessage; | |
var div = transport.createElement("div"); | |
div.id = name + "div"; | |
transport.body.appendChild(div); | |
div.innerHTML = String.format("<iframe id='{0}' src='{1}'></iframe>", name, url); | |
setTimeout(scope(checkframe, self), interval); | |
break; | |
case fn.protocols.foreverframe: | |
var frameid = name + "frame"; | |
transport = document.createElement("iframe"); | |
transport.id = frameid; | |
transport.style.display = "none"; | |
document.body.appendChild(transport); | |
transport.onload = scope(self.close, self); | |
transport.push = self.onmessage; | |
transport.src = url + "&frameid=" + frameid; | |
break; | |
case fn.protocols.serversent: | |
transport = new EventSource(url); | |
transport.onmessage = function (response) { | |
var msg = JSON.parse(response.data); | |
self.onmessage(msg); | |
}; | |
break; | |
} | |
}; | |
this.onclose = function () { }; | |
this.onmessage = function (msg) { }; | |
this.open = function (uri) { | |
url = uri + "&transport=" + transportType; | |
setTimeout(function () { _open(); }, 10); | |
}; | |
this.close = function () { | |
if (!active) return; | |
active = false; | |
delete hubconnections[hubID]; | |
switch (protocol) { | |
case fn.protocols.httpstreaming: | |
if (transport.readyState !== 4) transport.abort(); | |
break; | |
case fn.protocols.ieforeverframe: | |
var transportdiv = transport.getElementById(name + "div"), | |
transportframe = transport.getElementById(name); | |
transportframe.contentWindow.document.location.replace("about:blank"); | |
$(transportdiv).remove(transportframe); | |
$(transport.body).remove(transportdiv); | |
transport.parentWindow.push = null; | |
break; | |
case fn.protocols.foreverframe: | |
var content = transport.contentWindow || transport.contentDocument; | |
content.document.location.replace("about:blank"); | |
transport.push = null; | |
$(document.body).remove(transport); | |
break; | |
case fn.protocols.serversent: | |
transport.close(); | |
break; | |
} | |
transport = null; | |
if($.browser.msie) CollectGarbage(); | |
self.onclose(); | |
}; | |
}; | |
} (PSERVICEBUS)); | |
(function (fn) { | |
'use strict'; | |
var endpointAddress = "http://localhost:8087/ESBRestService/", | |
websocketAddress = "", | |
websocketPort = "8081", | |
rethrow = false, | |
apikey = "demo", | |
passcode = "demo", | |
includeIdentity = false, | |
protocol = undefined, | |
usernamecookie = "pservicebus_username", | |
apikeytoken = "pservicebus_apikey_key", | |
passcodetoken = "pservicebus_passcode_key", | |
username = "", | |
durable = false, | |
handlers = {}, | |
longpolling = false, | |
invalidstate = 1, | |
getcookie = function (c_name) { | |
var i, x, y, ARRcookies = document.cookie.split(";"); | |
for (i = 0; i < ARRcookies.length; i++) { | |
x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("=")); | |
y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1); | |
x = x.replace(/^\s+|\s+$/g, ""); | |
if (x === c_name) { | |
return unescape(y); | |
} | |
} | |
}, | |
setcookie = function (c_name, value, exdays) { | |
var exdate = new Date(); | |
exdate.setDate(exdate.getDate() + exdays); | |
var c_value = escape(value) + ((!exdays) ? "" : "; expires=" + exdate.toUTCString()); | |
document.cookie = c_name + "=" + c_value; | |
}, | |
getusername = function () { | |
if (username) return username; | |
username = getcookie(usernamecookie); | |
if (!username){ | |
var date = new Date(); | |
username = String.format("js{0}{1}{2}", date.getTime(), date.getMonth(), date.getFullYear()); | |
} | |
if (durable) setcookie(usernamecookie, username, 30); | |
return username; | |
}; | |
fn.ondisconnect = function () { }; | |
fn.transport = { | |
msmq: 0, | |
rabbitmq: 1, | |
ravendb: 2, | |
tcp: 3, | |
redis: 7 | |
}; | |
fn.format = { | |
json: 1, | |
xml: 0 | |
}; | |
fn.timespan = function (day, hour, min, sec, ms) { | |
sec = sec || 0; | |
ms = ms || 0; | |
min = min || 0; | |
hour = hour || 0; | |
day = day || 0; | |
var date = new Date(); | |
date.setDate(date.getDate() + day); | |
date.setMinutes(date.getMinutes() + min); | |
date.setSeconds(date.getSeconds() + sec); | |
date.setMilliseconds(date.getMilliseconds() + ms); | |
date.setHours(date.getHours() + hour); | |
return date.getTime() - (new Date().getTime()); | |
}; | |
var ajax = (function () { | |
return { | |
helper: (function () { | |
var usejsonp = false, | |
fail = function (e) { | |
if (typeof (e) !== "string") return; | |
throw e; | |
}, | |
jsonp = function (method, data, success) { | |
data.ReThrowException = rethrow.toString(); | |
data.ESBUserName = apikey; | |
data.ESBPassword = passcode; | |
var url = String.format("{0}{1}?callback=?", endpointAddress, method); | |
$.ajax({ | |
url: url, | |
data: data, | |
dataType: 'jsonp', | |
crossDomain: true, | |
contentType: 'application/json; charset=utf-8', | |
success: function (result) { | |
if (success) success(JSON.parse(result)); | |
}, | |
error: function (e) { | |
if (fail) fail(e); | |
} | |
}); | |
}, | |
json = function (method, data, success, async) { | |
async = async || false; | |
var url = String.format("{0}{1}?ReThrowException={2}&ESBUserName={3}&ESBPassword={4}", | |
endpointAddress, method, rethrow, apikey, passcode); | |
$.ajax({ | |
type: 'POST', | |
url: url, | |
data: data, | |
traditional: true, | |
dataType: 'json', | |
async: async, | |
success: function (result, status, xhr) { | |
if (result) { | |
var d = result.d || result; | |
if (d) { | |
var evald = JSON.parse(d); | |
if (success) success(evald); | |
} | |
} | |
}, | |
error: function (xhr, e, msg) { | |
if (!usejsonp) { | |
usejsonp = true; | |
jsonp(method, data, success); | |
return; | |
} | |
if (fail) fail(xhr.responseText); | |
} | |
}); | |
}; | |
return { | |
invoke: function(method, data, success, async){ | |
data = data || {}; | |
if(usejsonp) jsonp(method, data, success); | |
else json(method, data, success, async); | |
} | |
}; | |
})() | |
}; | |
})(); | |
var messagehandler = function (username, _transport, _dto, _interval, _batchsize, _action) { | |
var subscriber = username, | |
transport = _transport, | |
dto = _dto, | |
interval = _interval, | |
batchsize = _batchsize, | |
action = _action, | |
handle = null, | |
hub = null, | |
websocket = null, | |
running = false, | |
self = this, | |
xhr = null, | |
huburl = (endpointAddress + String.format("StreamSubscriberMessages/?subscriberName={0}&transportName={1}&messageTypeInfo={2}&batchSize={3}&interval={4}", | |
subscriber, transport, JSON.stringify(dto), batchsize, interval)), | |
handlemessage = function () { | |
if (!running) return; | |
xhr = ajax.helper.invoke("GetSubscriberMessages", | |
{ subscriberName: subscriber, transportName: transport, | |
messageTypeInfo: JSON.stringify(dto), | |
batchSize: batchsize | |
}, function (msgs) { | |
for (var i = 0; i < msgs.length; i++) { | |
action(msgs[i]); | |
} | |
handle = setTimeout(handlemessage, interval); | |
}, true); | |
}; | |
longpolling = $.browser.opera && parseInt($.browser.version) < 12 && document.location.protocol.indexOf("file://") >= 0 ? true : longpolling; | |
longpolling = $.browser.opera && parseInt($.browser.version) < 12 && (huburl.indexOf("localhost") >= 0 || huburl.indexOf(String.format("{0}.", document.domain)) < 0) ? true : longpolling; | |
this.start = function () { | |
if (running) return; | |
running = true; | |
if (!fn.setting.protocol() && ("WebSocket" in window)) { | |
websocket = new WebSocket(fn.setting.websocket()); | |
websocket.onopen = function () { | |
websocket.send(JSON.stringify({ SubscriberName: subscriber, TransportName: transport, | |
BatchSize: batchsize, MessageTypeInfo: JSON.stringify(dto), Interval: interval | |
})); | |
}; | |
websocket.onmessage = function (e) { | |
var msg = JSON.parse(e.data); | |
action(msg); | |
}; | |
} | |
else if (!longpolling) { | |
hub = new fn.hub(); | |
hub.onmessage = action; | |
hub.onclose = function () { /*stream closing*/ }; | |
hub.open(huburl); | |
} | |
else { | |
handle = setTimeout(handlemessage, interval); | |
} | |
}; | |
this.stop = function () { | |
running = false; | |
if (longpolling) handle = clearTimeout(handle); | |
try { | |
if (websocket) websocket.close(); | |
else if (hub) hub.close(); | |
else if (xhr) xhr.abort(); | |
} catch (e) { } | |
xhr = null; | |
hub = null; | |
websocket = null; | |
}; | |
}; | |
fn.setting = (function () { | |
return { | |
apikey: function (value) { apikey = value; }, | |
passcode: function (value) { passcode = value; }, | |
rethrow: function (value) { rethrow = value; }, | |
websocketport: function (port) { websocketPort = port; }, | |
endpoint: function (value) { endpointAddress = value; }, | |
includeIdentity: function (value) { includeIdentity = value; }, | |
durable: function (value) { durable = value; }, | |
longpolling: function (value) { longpolling = value; }, | |
protocol: function(value){ | |
longpolling = value === fn.protocols.longpolling ? true : longpolling; | |
if(value){ | |
protocol = value; | |
} else { | |
return protocol; | |
} | |
}, | |
logging: false, | |
websocket: function () { | |
if (websocketAddress) return websocketAddress; | |
var url = endpointAddress.replace("//", "\\").split("/")[0], | |
tokens = url.split(":"); | |
tokens[tokens.length - 1] = websocketPort; | |
tokens[0] = "ws"; | |
url = tokens.join(":"); | |
return url.replace("\\", "//"); | |
}, | |
transport: (function () { | |
var address = "localhost:5672;userID=guest;password=guest", | |
parseEndpoint = function (topicName, subscriberName) { | |
return address + ";queue=" + topicName + subscriberName; | |
}, | |
transporttype = fn.transport.rabbitmq, | |
transportformat = fn.format.xml; | |
return { | |
address: function (value) { address = value; }, | |
format: function(value) { transportformat = value; }, | |
transporttype: function() { return transporttype; }, | |
type: function(value) { transporttype = value; }, | |
info: function (topicName, subscriberName) { | |
switch (transporttype) { | |
case fn.transport.msmq: | |
case fn.transport.rabbitmq: | |
case fn.transport.redis: | |
return { | |
Format: transportformat, | |
Path: parseEndpoint(topicName, subscriberName) | |
}; | |
case fn.transport.ravendb: | |
return { | |
Format: transportformat, | |
ConnectionString: parseEndpoint(topicName, subscriberName) | |
}; | |
case fn.transport.tcp: | |
var tokens = address.split(':'), | |
useSSL = tokens.length > 2 ? | |
("true" === tokens[2].toLowerCase) : false, | |
ipAddress = tokens[0], | |
port = parseInt(tokens[1]); | |
return { | |
Format: transportformat, | |
IPAddress: ipAddress, Port: port, | |
UseSSL: useSSL | |
}; | |
} | |
} | |
}; | |
})() | |
}; | |
})(); | |
fn.register = function (data) { | |
if (!data.topic) | |
throw "topic need to be set for register method"; | |
ajax.helper.invoke("RegisterTopic", { | |
topicData: | |
JSON.stringify({ | |
ContractDict: (data.info || {}), | |
TopicName: data.topic, | |
TopicDescription: data.description || data.topic}) | |
}); | |
}; | |
fn.unregister = function (data) { | |
}; | |
fn.publish = function (data) { | |
if (!data.topic || !data.message) | |
throw "topic and message property need to be set for publish method"; | |
var groupid = data.groupid, | |
sequenceid = data.sequenceid, | |
message = data.message, | |
headers = data.headers || {}, | |
expiration = data.expiration || fn.timespan(30)/*30 days*/; | |
if (includeIdentity) { | |
message[apikeytoken] = apikey; | |
message[passcodetoken] = passcode; | |
} | |
if(groupid && sequenceid){ | |
headers["ESB_GROUP_ID"] = groupid; | |
headers["ESB_SEQUENCE_ID"] = sequenceid; | |
} | |
ajax.helper.invoke("PublishTopic", | |
{ topicName: data.topic, | |
topicData: JSON.stringify({ Headers: headers, ExpiresIn: expiration }), | |
publishData: JSON.stringify([message]) | |
}, null, true); | |
}; | |
fn.unsubscribe = function (data) { | |
if (!data.topic) | |
throw "topic property need to be set for unsubscribe method"; | |
var topicname = data.topic, | |
name = getusername(); | |
ajax.helper.invoke("UnSubscribeFrom", | |
{ subscriber: name, topicName: topicname }); | |
ajax.helper.invoke("DeleteTransport", | |
{ subscriber: name, transportName: topicname }); | |
if (handlers[topicname]) | |
handlers[topicname].stop(); | |
}; | |
fn.subscribe = function (data) { | |
if (!data.topic || !data.callback) | |
throw "topic and callback property need to be set for subscribe method"; | |
if (typeof (data.callback) !== "function") | |
throw "callback must be a function"; | |
if(!data.info) throw "info is required to deserialize received messages"; | |
var topicname = data.topic, | |
callback = data.callback, | |
username = getusername(), | |
filter = data.filter || "", | |
batchsize = data.batchsize || 1, | |
contract = data.info, | |
interval = data.interval || fn.timespan(0, 0, 0, 0, 5) /*5 millisecond*/, | |
handler; | |
ajax.helper.invoke("SelectSubscriber", { name: username }, function (s) { | |
var filters = filter.split(','), | |
topics = s.Topics, | |
state = s.State, | |
actions = [], i; | |
if (includeIdentity) { | |
filters.push(String.format(" {0} = {1}", apikeytoken, apikey)); | |
filters.push(String.format(" {0} = {1}", passcodetoken, passcode)); | |
} | |
filter = filters.join(","); | |
if (state === invalidstate) | |
actions.push(function () { | |
ajax.helper.invoke("CreateSubscriber", { subscriber: username }); | |
}); | |
if (!topics[topicname]) { | |
actions.push(function () { | |
ajax.helper.invoke("SubscribeTo", | |
{ subscriber: username, topicName: topicname, filter: filter }); | |
}); | |
actions.push(function () { | |
ajax.helper.invoke("AddTransport", | |
{ subscriber: username, transportName: topicname, | |
transportType: fn.setting.transport.transporttype(), | |
transportData: | |
JSON.stringify(fn.setting.transport.info(topicname, username)), | |
topicName: topicname | |
}); | |
}); | |
} | |
for (i = 0; i < actions.length; i++) actions[i](); | |
if (includeIdentity) { | |
contract[apikeytoken] = ""; | |
contract[passcodetoken] = ""; | |
} | |
handler = new messagehandler(username, topicname, contract, interval, 1, callback); | |
handler.start(); | |
handlers[topicname] = handler; | |
}); | |
}; | |
$(window).bind("beforeunload", function () { | |
var username = getusername(); | |
if (!durable) ajax.helper.invoke("DeleteSubscriber", { name: username }); | |
for (var key in handlers){ | |
var handler = handlers[key]; | |
if(!handler) continue; | |
handler.stop(); | |
delete handlers[key]; | |
} | |
handlers = {}; | |
if (fn.ondisconnect) fn.ondisconnect(); | |
//Disconnect connection to esb server and any streaming connections | |
ajax.helper.invoke("Disconnect", {subscriberName: username}); | |
}); | |
} (PSERVICEBUS)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment