capturing all dom manipulation events - javascript

I'm trying to create a proxy JS so every request to external resource will be proxied like XHR or any other resource.
so for XHR request i manage to do it with this code:
if(window.XMLHttpRequest)
{
var XMLHttpRequest = window.XMLHttpRequest;
var startTracing = function () {
XMLHttpRequest.prototype.uniqueID = function() {
// each XMLHttpRequest gets assigned a unique ID and memorizes it
// in the "uniqueIDMemo" property
if (!this.uniqueIDMemo) {
this.uniqueIDMemo = Math.floor(Math.random() * 1000);
}
return this.uniqueIDMemo;
}
// backup original "open" function reference
XMLHttpRequest.prototype.oldOpen = XMLHttpRequest.prototype.open;
var newOpen = function(method, url, async, user, password) {
//console.log(url);//new
if (url.includes("somesample")) {
//Debug Only
/*console.log("[" + this.uniqueID() + "] intercepted open (" +
method + " , " +
url + " , " +
async + " , " +
user + " , " +
password + ")");*/
urlParts = /^(?:\w+\:\/\/)?([^\/]+)(.*)$/.exec(url);
hostname = urlParts[1]; // www.example.com
path = urlParts[2]; // /path/to/somwhere
proxyprefix = "http://myproxy.com/xhr.php?url="
fullurl = "http://" + hostname + path;
rewrittenUrl = proxyprefix + btoa(encodeURIComponent(fullurl));
url = rewrittenUrl;
}
this.oldOpen(method, url, async, user, password);
}
XMLHttpRequest.prototype.open = newOpen;
// backup original "send" function reference
XMLHttpRequest.prototype.oldSend = XMLHttpRequest.prototype.send;
var newSend = function(a) {
//console.log("[" + this.uniqueID() + "] intercepted send (" + a + ")");
var xhr = this;
var onload = function() {
/*console.log("[" + xhr.uniqueID() + "] intercepted load: " +
xhr.status +
" " + xhr.responseText);*/
};
var onerror = function() {
/* console.log("[" + xhr.uniqueID() + "] intercepted error: " +
xhr.status);*/
};
xhr.addEventListener("load", onload, false);
xhr.addEventListener("error", onerror, false);
this.oldSend(a);
}
XMLHttpRequest.prototype.send = newSend;
}
startTracing();
}
else if (window.ActiveXObject) {
var ActualActiveXObject = ActiveXObject;
var ActiveXObject = function(progid) {
var ax = new ActualActiveXObject(progid);
if (progid.toLowerCase() == "msxml2.xmlhttp") {
var o = {
_ax: ax,
_status: "fake",
responseText: "",
responseXml: null,
readyState: 0,
status: 0,
statusText: 0,
onReadyStateChange: null
};
o._onReadyStateChange = function() {
var self = o;
return function() {
self.readyState = self._ax.readyState;
if (self.readyState == 4) {
self.responseText = self._ax.responseText;
self.responseXml = self._ax.responseXml;
self.status = self._ax.status;
self.statusText = self._ax.statusText;
}
if (self.onReadyStateChange) self.onReadyStateChange();
}
}();
o.open = function(bstrMethod, bstrUrl, varAsync, bstrUser, bstrPassword) {
/*console.log("intercepted open (" +
bstrMethod + " , " +
bstrUrl + " , " +
varAsync + " , " +
bstrUser + " , " +
bstrPassword + ")");*/
varAsync = (varAsync !== false);
this._ax.onReadyStateChange = this._onReadyStateChange
return this._ax.open(bstrMethod, bstrUrl, varAsync, bstrUser, bstrPassword);
};
o.send = function(varBody) {
return this._ax.send(varBody);
};
}
else
var o = ax;
return o;
}
}
and its working fine.
and because i have got some js that manipulate the dom and adds elements i need to intercept that to.
so i started by rewriting appendChild with that code:
window.callbackFunc = function(elem, args) {
//console.log(elem);
for (var key in elem) {
if (elem.hasOwnProperty(key) && elem[key].src)
{
elem[key].src = "http://myptoxy/proxy.php?u=" +encodeURIComponent(elem[key].src);
}
}
}
window.f = Element.prototype.appendChild;
Element.prototype.appendChild = function() {
window.callbackFunc.call(this, arguments);
return window.f.apply(this, arguments);
};
and thats also working well but i encounter a problem with createlement.
some js code on my site creates an iframe with src that i'm unable to intercept with this code:
document.createElement = function(create) {
return function() {
var ret = create.apply(this, arguments);
//console.log(ret);
for (var key in ret) {
if (ret.hasOwnProperty(key) && ret[key].src) {
ret[key].src = "http://myproxy.com/proxy.php?u=" + encodeURIComponent(elem[key].src);
}
}
return ret;
};
}(document.createElement)
I mean I can intercept the creation but the attributes are empty obviously the script adds the attribute after the element creation)
I tried to use MutationObserver but with no luck...
Any help?
Another approach to the entire problem will be great!

Related

ServiceNow - Change a file name in Midserver

I am currently trying to replace the name of a file in the Mid Server after a scheduled export.
The idea here is that the file goes with the name in the format "file_name_datetime" and the customer needs "datetime_file_name" for the file to be correctly read by another system.
My main idea was to rename the file after the export to the correct format, but if there is a way of changing the file name to the required one I could do that also.
I would love to hear from you guys as I have no idea how can I do this.
Thanks in advance.
If anyone is interested in the answer, see below:
Script include:
initialize: function() {
this.filePath = gs.getProperty('directory_path');
this.midServer = gs.getProperty('midserver');
this.authMidServerBase64 = gs.getProperty('authmidserver');
},
nameChange: function(exportSetName) {
var exportGr = new GlideRecord("sys_export_set_run");
exportGr.addEncodedQuery("set.nameSTARTSWITH" + exportSetName);
exportGr.orderByDesc("completed");
exportGr.query();
if (exportGr.next()) {
var attachSysID = exportGr.ecc_agent_attachment.sys_id;
}
var attachGr = new GlideRecord("sys_attachment");
attachGr.addEncodedQuery("table_sys_idSTARTSWITH" + attachSysID);
attachGr.query();
if (attachGr.next()) {
var attachName = attachGr.file_name;
var attachDate = attachName.match((/\d+/));
var newName = attachDate + '_' + exportSetName + '.csv';
}
var jspr = new JavascriptProbe(this.midServer);
jspr.setName('FileNameChange'); // This can be any name
jspr.setJavascript('var ddr = new MidServer_script_include(); res = ddr.execute();');
jspr.addParameter("verbose", "true");
jspr.addParameter("skip_sensor", "true"); // prevent Discovery sensors running for the ECC input
jspr.addParameter("filename", this.filePath + "\\" + attachName);
jspr.addParameter("filePath", this.filePath);
jspr.addParameter("newName", this.filePath + "\\" + newName);
jspr.addParameter("operation", "rename");
return jspr.create();
},
Mid Server Script include:
initialize: function() {
/**
*** Set up the Packages references
**/
this.File = Packages.java.io.File;
this.FileOutputStream = Packages.java.io.FileOutputStream;
this.FileInputStream = Packages.java.io.FileInputStream;
this.Path = Packages.java.nio.file.Path;
this.Paths = Packages.java.nio.file.Paths;
this.Files = Packages.java.nio.file.Files;
this.StandardCopyOption = Packages.java.nio.file.StandardCopyOption;
/**
/* Set up the parameters
**/
this.verbose = probe.getParameter("verbose");
this.filePath = probe.getParameter("filePath");
this.filename = probe.getParameter("filename");
this.operation = probe.getParameter("operation");
this.newName = probe.getParameter("newName");
result = "initialize complete";
},
execute: function() {
if (this.operation == 'rename') {
this.fileRename(this.filename, this.newName);
}
return result;
},
fileRename: function(fileName, newName) {
result+= "\r\n Renaming file.";
this._debug(result);
try {
var res = this._moveFile(fileName, newName);
} catch (e) {
result += "\r\n Erro no renomeamento do ficheiro: " + e;
this._debug(result);
}
},
_moveFile: function(initialPath, targetPath) {
try {
this._debug("Initiating file move function");
var inPath = this.Paths.get(initialPath);
var tgPath = this.Paths.get(targetPath);
var res = this.Files.move(inPath, tgPath, this.StandardCopyOption.REPLACE_EXISTING);
result += "File successfully moved from: " + initialPath + " to: " + targetPath + " \r\n Result: " + res;
this._debug(result);
} catch (e) {
this._debug('Error:' + e);
}
},
_debug: function(m) {
if (this.verbose == "true") {
ms.log("::: Mid Server script include logger ::: " + m);
}
},
https://community.servicenow.com/community?id=community_question&sys_id=a56b38a6db326490fa192183ca961987

How can I use the Eclipse Paho JavaScript Client to connect to test.mosquitto.org?

I am new to the IOT world and have been confused why I have not been able to use the Eclipse Paho JavaScript Client to connect to test.mosquitto.org.
I have used Port: 8080 and Path: /mqtt as has been suggested in other paho-mqtt questions, but am met with a Failed to connect: AMQJS0007E Socket error:undefined when using this Eclipse web client.
I have used the HiveMQ WebClient and have been able to connect, publish and subscribe to both test.mosquitto.org (Port 8080) and iot.eclipse.org (Port 443).
I have noticed that HiveMQ sources mqttws31.js compared to Paho Eclipse's paho-mqtt.js, but am unsure of the significance.
I would say there are two parts to this question:
What am I missing to get the Eclipse Paho JavaScript Client to connect to test.mosquitto.org ?
What is the difference between mqttws31.js and paho-mqtt.js that allows one to connect to test.mosquitto.org relatively painlessly compared to the other?
Thanks !
Relevant Code:
The code below is taken directly from the page source of https://www.eclipse.org/paho/clients/js/utility/
paho-mqtt.js: https://www.eclipse.org/paho/js/paho-mqtt.js
utility.js (handles button callbacks):
/*******************************************************************************
* Copyright (c) 2015 IBM Corp.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* and Eclipse Distribution License v1.0 which accompany this distribution.
*
* The Eclipse Public License is available at
* http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* James Sutton - Initial Contribution
*******************************************************************************/
/*
Eclipse Paho MQTT-JS Utility
This utility can be used to test the Eclipse Paho MQTT Javascript client.
*/
// Create a client instance
var client = null;
var connected = false;
logMessage("INFO", "Starting Eclipse Paho JavaScript Utility.");
// Things to do as soon as the page loads
document.getElementById("clientIdInput").value = "js-utility-" + makeid();
// called when the client connects
function onConnect(context) {
// Once a connection has been made, make a subscription and send a message.
var connectionString = context.invocationContext.host + ":" + context.invocationContext.port + context.invocationContext.path;
logMessage("INFO", "Connection Success ", "[URI: ", connectionString, ", ID: ", context.invocationContext.clientId, "]");
var statusSpan = document.getElementById("connectionStatus");
statusSpan.innerHTML = "Connected to: " + connectionString + " as " + context.invocationContext.clientId;
connected = true;
setFormEnabledState(true);
}
function onConnected(reconnect, uri) {
// Once a connection has been made, make a subscription and send a message.
logMessage("INFO", "Client Has now connected: [Reconnected: ", reconnect, ", URI: ", uri, "]");
connected = true;
}
function onFail(context) {
logMessage("ERROR", "Failed to connect. [Error Message: ", context.errorMessage, "]");
var statusSpan = document.getElementById("connectionStatus");
statusSpan.innerHTML = "Failed to connect: " + context.errorMessage;
connected = false;
setFormEnabledState(false);
}
// called when the client loses its connection
function onConnectionLost(responseObject) {
if (responseObject.errorCode !== 0) {
logMessage("INFO", "Connection Lost. [Error Message: ", responseObject.errorMessage, "]");
}
connected = false;
}
// called when a message arrives
function onMessageArrived(message) {
logMessage("INFO", "Message Recieved: [Topic: ", message.destinationName, ", Payload: ", message.payloadString, ", QoS: ", message.qos, ", Retained: ", message.retained, ", Duplicate: ", message.duplicate, "]");
var messageTime = new Date().toISOString();
// Insert into History Table
var table = document.getElementById("incomingMessageTable").getElementsByTagName("tbody")[0];
var row = table.insertRow(0);
row.insertCell(0).innerHTML = message.destinationName;
row.insertCell(1).innerHTML = safeTagsRegex(message.payloadString);
row.insertCell(2).innerHTML = messageTime;
row.insertCell(3).innerHTML = message.qos;
if (!document.getElementById(message.destinationName)) {
var lastMessageTable = document.getElementById("lastMessageTable").getElementsByTagName("tbody")[0];
var newlastMessageRow = lastMessageTable.insertRow(0);
newlastMessageRow.id = message.destinationName;
newlastMessageRow.insertCell(0).innerHTML = message.destinationName;
newlastMessageRow.insertCell(1).innerHTML = safeTagsRegex(message.payloadString);
newlastMessageRow.insertCell(2).innerHTML = messageTime;
newlastMessageRow.insertCell(3).innerHTML = message.qos;
} else {
// Update Last Message Table
var lastMessageRow = document.getElementById(message.destinationName);
lastMessageRow.id = message.destinationName;
lastMessageRow.cells[0].innerHTML = message.destinationName;
lastMessageRow.cells[1].innerHTML = safeTagsRegex(message.payloadString);
lastMessageRow.cells[2].innerHTML = messageTime;
lastMessageRow.cells[3].innerHTML = message.qos;
}
}
function connectionToggle() {
if (connected) {
disconnect();
} else {
connect();
}
}
function connect() {
var hostname = document.getElementById("hostInput").value;
var port = document.getElementById("portInput").value;
var clientId = document.getElementById("clientIdInput").value;
var path = document.getElementById("pathInput").value;
var user = document.getElementById("userInput").value;
var pass = document.getElementById("passInput").value;
var keepAlive = Number(document.getElementById("keepAliveInput").value);
var timeout = Number(document.getElementById("timeoutInput").value);
var tls = document.getElementById("tlsInput").checked;
var automaticReconnect = document.getElementById("automaticReconnectInput").checked;
var cleanSession = document.getElementById("cleanSessionInput").checked;
var lastWillTopic = document.getElementById("lwtInput").value;
var lastWillQos = Number(document.getElementById("lwQosInput").value);
var lastWillRetain = document.getElementById("lwRetainInput").checked;
var lastWillMessageVal = document.getElementById("lwMInput").value;
if (path.length > 0) {
client = new Paho.Client(hostname, Number(port), path, clientId);
} else {
client = new Paho.Client(hostname, Number(port), clientId);
}
logMessage("INFO", "Connecting to Server: [Host: ", hostname, ", Port: ", port, ", Path: ", client.path, ", ID: ", clientId, "]");
// set callback handlers
client.onConnectionLost = onConnectionLost;
client.onMessageArrived = onMessageArrived;
client.onConnected = onConnected;
var options = {
invocationContext: { host: hostname, port: port, path: client.path, clientId: clientId },
timeout: timeout,
keepAliveInterval: keepAlive,
cleanSession: cleanSession,
useSSL: tls,
reconnect: automaticReconnect,
onSuccess: onConnect,
onFailure: onFail
};
if (user.length > 0) {
options.userName = user;
}
if (pass.length > 0) {
options.password = pass;
}
if (lastWillTopic.length > 0) {
var lastWillMessage = new Paho.Message(lastWillMessageVal);
lastWillMessage.destinationName = lastWillTopic;
lastWillMessage.qos = lastWillQos;
lastWillMessage.retained = lastWillRetain;
options.willMessage = lastWillMessage;
}
// connect the client
client.connect(options);
var statusSpan = document.getElementById("connectionStatus");
statusSpan.innerHTML = "Connecting...";
}
function disconnect() {
logMessage("INFO", "Disconnecting from Server.");
client.disconnect();
var statusSpan = document.getElementById("connectionStatus");
statusSpan.innerHTML = "Connection - Disconnected.";
connected = false;
setFormEnabledState(false);
}
// Sets various form controls to either enabled or disabled
function setFormEnabledState(enabled) {
// Connection Panel Elements
if (enabled) {
document.getElementById("clientConnectButton").innerHTML = "Disconnect";
} else {
document.getElementById("clientConnectButton").innerHTML = "Connect";
}
document.getElementById("hostInput").disabled = enabled;
document.getElementById("portInput").disabled = enabled;
document.getElementById("clientIdInput").disabled = enabled;
document.getElementById("pathInput").disabled = enabled;
document.getElementById("userInput").disabled = enabled;
document.getElementById("passInput").disabled = enabled;
document.getElementById("keepAliveInput").disabled = enabled;
document.getElementById("timeoutInput").disabled = enabled;
document.getElementById("tlsInput").disabled = enabled;
document.getElementById("automaticReconnectInput").disabled = enabled;
document.getElementById("cleanSessionInput").disabled = enabled;
document.getElementById("lwtInput").disabled = enabled;
document.getElementById("lwQosInput").disabled = enabled;
document.getElementById("lwRetainInput").disabled = enabled;
document.getElementById("lwMInput").disabled = enabled;
// Publish Panel Elements
document.getElementById("publishTopicInput").disabled = !enabled;
document.getElementById("publishQosInput").disabled = !enabled;
document.getElementById("publishMessageInput").disabled = !enabled;
document.getElementById("publishButton").disabled = !enabled;
document.getElementById("publishRetainInput").disabled = !enabled;
// Subscription Panel Elements
document.getElementById("subscribeTopicInput").disabled = !enabled;
document.getElementById("subscribeQosInput").disabled = !enabled;
document.getElementById("subscribeButton").disabled = !enabled;
document.getElementById("unsubscribeButton").disabled = !enabled;
}
function publish() {
var topic = document.getElementById("publishTopicInput").value;
var qos = document.getElementById("publishQosInput").value;
var message = document.getElementById("publishMessageInput").value;
var retain = document.getElementById("publishRetainInput").checked;
logMessage("INFO", "Publishing Message: [Topic: ", topic, ", Payload: ", message, ", QoS: ", qos, ", Retain: ", retain, "]");
message = new Paho.Message(message);
message.destinationName = topic;
message.qos = Number(qos);
message.retained = retain;
client.send(message);
}
function subscribe() {
var topic = document.getElementById("subscribeTopicInput").value;
var qos = document.getElementById("subscribeQosInput").value;
logMessage("INFO", "Subscribing to: [Topic: ", topic, ", QoS: ", qos, "]");
client.subscribe(topic, { qos: Number(qos) });
}
function unsubscribe() {
var topic = document.getElementById("subscribeTopicInput").value;
logMessage("INFO", "Unsubscribing: [Topic: ", topic, "]");
client.unsubscribe(topic, {
onSuccess: unsubscribeSuccess,
onFailure: unsubscribeFailure,
invocationContext: { topic: topic }
});
}
function unsubscribeSuccess(context) {
logMessage("INFO", "Unsubscribed. [Topic: ", context.invocationContext.topic, "]");
}
function unsubscribeFailure(context) {
logMessage("ERROR", "Failed to unsubscribe. [Topic: ", context.invocationContext.topic, ", Error: ", context.errorMessage, "]");
}
function clearHistory() {
var table = document.getElementById("incomingMessageTable");
//or use : var table = document.all.tableid;
for (var i = table.rows.length - 1; i > 0; i--) {
table.deleteRow(i);
}
}
// Just in case someone sends html
function safeTagsRegex(str) {
return str.replace(/&/g, "&").replace(/</g, "<").
replace(/>/g, ">");
}
function makeid() {
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (var i = 0; i < 5; i++)
text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;
}
function logMessage(type, ...content) {
var consolePre = document.getElementById("consolePre");
var date = new Date();
var timeString = date.toUTCString();
var logMessage = timeString + " - " + type + " - " + content.join("");
consolePre.innerHTML += logMessage + "\n";
if (type === "INFO") {
console.info(logMessage);
} else if (type === "ERROR") {
console.error(logMessage);
} else {
console.log(logMessage);
}
}
The code below is taken directly from the page source of http://www.hivemq.com/demos/websocket-client/
mqttws31.js: http://www.hivemq.com/demos/websocket-client/js/mqttws31.js
app.js (handles app callbacks):
/**
* Copyright 2013 dc-square GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* #author: Christoph Schäbel
*/
var websocketclient = {
'client': null,
'lastMessageId': 1,
'lastSubId': 1,
'subscriptions': [],
'messages': [],
'connected': false,
'connect': function () {
var host = $('#urlInput').val();
var port = parseInt($('#portInput').val(), 10);
var clientId = $('#clientIdInput').val();
var username = $('#userInput').val();
var password = $('#pwInput').val();
var keepAlive = parseInt($('#keepAliveInput').val());
var cleanSession = $('#cleanSessionInput').is(':checked');
var lwTopic = $('#lwTopicInput').val();
var lwQos = parseInt($('#lwQosInput').val());
var lwRetain = $('#LWRInput').is(':checked');
var lwMessage = $('#LWMInput').val();
var ssl = $('#sslInput').is(':checked');
this.client = new Messaging.Client(host, port, clientId);
this.client.onConnectionLost = this.onConnectionLost;
this.client.onMessageArrived = this.onMessageArrived;
var options = {
timeout: 3,
keepAliveInterval: keepAlive,
cleanSession: cleanSession,
useSSL: ssl,
onSuccess: this.onConnect,
onFailure: this.onFail
};
if (username.length > 0) {
options.userName = username;
}
if (password.length > 0) {
options.password = password;
}
if (lwTopic.length > 0) {
var willmsg = new Messaging.Message(lwMessage);
willmsg.qos = lwQos;
willmsg.destinationName = lwTopic;
willmsg.retained = lwRetain;
options.willMessage = willmsg;
}
this.client.connect(options);
},
'onConnect': function () {
websocketclient.connected = true;
console.log("connected");
var body = $('body').addClass('connected').removeClass('notconnected').removeClass('connectionbroke');
websocketclient.render.hide('conni');
websocketclient.render.show('publish');
websocketclient.render.show('sub');
websocketclient.render.show('messages');
},
'onFail': function (message) {
websocketclient.connected = false;
console.log("error: " + message.errorMessage);
websocketclient.render.showError('Connect failed: ' + message.errorMessage);
},
'onConnectionLost': function (responseObject) {
websocketclient.connected = false;
if (responseObject.errorCode !== 0) {
console.log("onConnectionLost:" + responseObject.errorMessage);
}
$('body.connected').removeClass('connected').addClass('notconnected').addClass('connectionbroke');
websocketclient.render.show('conni');
websocketclient.render.hide('publish');
websocketclient.render.hide('sub');
websocketclient.render.hide('messages');
//Cleanup messages
websocketclient.messages = [];
websocketclient.render.clearMessages();
//Cleanup subscriptions
websocketclient.subscriptions = [];
websocketclient.render.clearSubscriptions();
},
'onMessageArrived': function (message) {
// console.log("onMessageArrived:" + message.payloadString + " qos: " + message.qos);
var subscription = websocketclient.getSubscriptionForTopic(message.destinationName);
var messageObj = {
'topic': message.destinationName,
'retained': message.retained,
'qos': message.qos,
'payload': message.payloadString,
'timestamp': moment(),
'subscriptionId': subscription.id,
'color': websocketclient.getColorForSubscription(subscription.id)
};
console.log(messageObj);
messageObj.id = websocketclient.render.message(messageObj);
websocketclient.messages.push(messageObj);
},
'disconnect': function () {
this.client.disconnect();
},
'publish': function (topic, payload, qos, retain) {
if (!websocketclient.connected) {
websocketclient.render.showError("Not connected");
return false;
}
var message = new Messaging.Message(payload);
message.destinationName = topic;
message.qos = qos;
message.retained = retain;
this.client.send(message);
},
'subscribe': function (topic, qosNr, color) {
if (!websocketclient.connected) {
websocketclient.render.showError("Not connected");
return false;
}
if (topic.length < 1) {
websocketclient.render.showError("Topic cannot be empty");
return false;
}
if (_.find(this.subscriptions, { 'topic': topic })) {
websocketclient.render.showError('You are already subscribed to this topic');
return false;
}
this.client.subscribe(topic, {qos: qosNr});
if (color.length < 1) {
color = '999999';
}
var subscription = {'topic': topic, 'qos': qosNr, 'color': color};
subscription.id = websocketclient.render.subscription(subscription);
this.subscriptions.push(subscription);
return true;
},
'unsubscribe': function (id) {
var subs = _.find(websocketclient.subscriptions, {'id': id});
this.client.unsubscribe(subs.topic);
websocketclient.subscriptions = _.filter(websocketclient.subscriptions, function (item) {
return item.id != id;
});
websocketclient.render.removeSubscriptionsMessages(id);
},
'deleteSubscription': function (id) {
var elem = $("#sub" + id);
if (confirm('Are you sure ?')) {
elem.remove();
this.unsubscribe(id);
}
},
'getRandomColor': function () {
var r = (Math.round(Math.random() * 255)).toString(16);
var g = (Math.round(Math.random() * 255)).toString(16);
var b = (Math.round(Math.random() * 255)).toString(16);
return r + g + b;
},
'getSubscriptionForTopic': function (topic) {
var i;
for (i = 0; i < this.subscriptions.length; i++) {
if (this.compareTopics(topic, this.subscriptions[i].topic)) {
return this.subscriptions[i];
}
}
return false;
},
'getColorForPublishTopic': function (topic) {
var id = this.getSubscriptionForTopic(topic);
return this.getColorForSubscription(id);
},
'getColorForSubscription': function (id) {
try {
if (!id) {
return '99999';
}
var sub = _.find(this.subscriptions, { 'id': id });
if (!sub) {
return '999999';
} else {
return sub.color;
}
} catch (e) {
return '999999';
}
},
'compareTopics': function (topic, subTopic) {
var pattern = subTopic.replace("+", "(.*?)").replace("#", "(.*)");
var regex = new RegExp("^" + pattern + "$");
return regex.test(topic);
},
'render': {
'showError': function (message) {
alert(message);
},
'messages': function () {
websocketclient.render.clearMessages();
_.forEach(websocketclient.messages, function (message) {
message.id = websocketclient.render.message(message);
});
},
'message': function (message) {
var largest = websocketclient.lastMessageId++;
var html = '<li class="messLine id="' + largest + '">' +
' <div class="row large-12 mess' + largest + '" style="border-left: solid 10px #' + message.color + '; ">' +
' <div class="large-12 columns messageText">' +
' <div class="large-3 columns date">' + message.timestamp.format("YYYY-MM-DD HH:mm:ss") + '</div>' +
' <div class="large-5 columns topicM truncate" id="topicM' + largest + '" title="' + Encoder.htmlEncode(message.topic, 0) + '">Topic: ' + Encoder.htmlEncode(message.topic) + '</div>' +
' <div class="large-2 columns qos">Qos: ' + message.qos + '</div>' +
' <div class="large-2 columns retain">';
if (message.retained) {
html += 'Retained';
}
html += ' </div>' +
' <div class="large-12 columns message break-words">' + Encoder.htmlEncode(message.payload) + '</div>' +
' </div>' +
' </div>' +
'</li>';
$("#messEdit").prepend(html);
return largest;
},
'subscriptions': function () {
websocketclient.render.clearSubscriptions();
_.forEach(websocketclient.subscriptions, function (subs) {
subs.id = websocketclient.render.subscription(subs);
});
},
'subscription': function (subscription) {
var largest = websocketclient.lastSubId++;
$("#innerEdit").append(
'<li class="subLine" id="sub' + largest + '">' +
' <div class="row large-12 subs' + largest + '" style="border-left: solid 10px #' + subscription.color + '; background-color: #ffffff">' +
' <div class="large-12 columns subText">' +
' <div class="large-1 columns right closer">' +
' x' +
' </div>' +
' <div class="qos">Qos: ' + subscription.qos + '</div>' +
' <div class="topic truncate" id="topic' + largest + '" title="' + Encoder.htmlEncode(subscription.topic, 0) + '">' + Encoder.htmlEncode(subscription.topic) + '</div>' +
' </div>' +
' </div>' +
'</li>');
return largest;
},
'toggleAll': function () {
websocketclient.render.toggle('conni');
websocketclient.render.toggle('publish');
websocketclient.render.toggle('messages');
websocketclient.render.toggle('sub');
},
'toggle': function (name) {
$('.' + name + 'Arrow').toggleClass("closed");
$('.' + name + 'Top').toggleClass("closed");
var elem = $('#' + name + 'Main');
elem.slideToggle();
},
'hide': function (name) {
$('.' + name + 'Arrow').addClass("closed");
$('.' + name + 'Top').addClass("closed");
var elem = $('#' + name + 'Main');
elem.slideUp();
},
'show': function (name) {
$('.' + name + 'Arrow').removeClass("closed");
$('.' + name + 'Top').removeClass("closed");
var elem = $('#' + name + 'Main');
elem.slideDown();
},
'removeSubscriptionsMessages': function (id) {
websocketclient.messages = _.filter(websocketclient.messages, function (item) {
return item.subscriptionId != id;
});
websocketclient.render.messages();
},
'clearMessages': function () {
$("#messEdit").empty();
},
'clearSubscriptions': function () {
$("#innerEdit").empty();
}
}
};
I think I am a bit late...but I leave here for posterity.
The Paho JS library has undergo a series of changes before release 1.0.3 and the last one 1.1.0.
If you refer to a mqttws31.js probably you was using a version earlier than 1.0.3, because from 1.0.3 the main js file was renamed to paho-mqtt.js.
Can be the reason why something in your code was working differently from HiveMQ version.
I tried to sum the situation here

How to refresh image by setTimeout, when url is getting by ajax?

I am writing a REST client to remote api. And I am using xmlHTTPRequest to get information about images.I need to refresh my images in every 30 seconds. My implementation of setTimeout function doesn't work. Anyone can help me? Thank you in advance.
Here is my code: Image.js
function Camera(id, name, ip, port) {
var button = document.createElement("button");
button.classList.add("camera");
button.innerHTML += "<h3>" + name + "</h3><br>";
var ismin = true;
this.id = id;
this.name = name;
this.ip = ip;
this.port = port;
this.getURL = function getURL(min) {
var url = 'http://' + ip + ":8080/api";
return min ? url + '/miniature/' + id + '?t=' + new Date().getTime() : url + '/image/' + id + '?t=' + new Date().getTime();
};
this.appendImg = function appendImg(url) {
button.innerHTML = "<h3>" + name + '</h3><br><img src="' + url + '"/>';
setTimeout(appendImg(url),30000);
};
this.showElement = function showElement(url) {
this.appendImg(url);
var that = this;
document.querySelector('#camera-section').appendChild(button);
button.addEventListener('click', function () {
ismin = !ismin;
that.appendImg(that.getURL(ismin), false);
});
};}
And a part of main.js:
function showImage(response) {
response = JSON.parse(sessionStorage.getItem('camera'));
console.log(response);
for (var i = 0; i < response.length; i++) {
var a = response[i];
var camera = new Camera(a.cameraId, a.name, ip, port, true);
var curl = camera.getURL(true);
camera.showElement(curl);
}
}
xml.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
var response = JSON.parse(this.responseText);
sessionStorage.setItem('camera',JSON.stringify(response));
//console.log(sessionStorage.getItem('camera'));
showImage(sessionStorage.getItem('camera'));
}
};
xml.open('GET', mainUrl);
xml.send(null);
Regarding the comment of Pranay Kumar, first part of your code could be like this::
function Camera(id, name, ip, port) {
var button = document.createElement("button");
button.classList.add("camera");
button.innerHTML += "<h3>" + name + "</h3><br>";
var ismin = true;
this.id = id;
this.name = name;
this.ip = ip;
this.port = port;
this.getURL = function getURL(min) {
var url = 'http://' + ip + ":8080/api";
return min ? url + '/miniature/' + id + '?t=' + new Date().getTime() : url + '/image/' + id + '?t=' + new Date().getTime();
};
this._appendImg = function(url) {
return function() {
button.innerHTML = "<h3>" + name + '</h3><br><img src="' + url + '"/>';
}
};
this._timerHandle = 0;
this.appendImg = function(url) {
if (this._timerHandle) {
clearInterval(this._timerHandle);
}
this._timerHandle = setInterval(this._appendImg(url),30000);
}
this.showElement = function showElement(url) {
this.appendImg(url);
var that = this;
document.querySelector('#camera-section').appendChild(button);
button.addEventListener('click', function () {
ismin = !ismin;
that.appendImg(that.getURL(ismin), false);
});
}
}
You want refresh image every 30 seconds.
So use setInterval instead of setTimeout

How to save the parameters value between functions call?

I'm trying to create a weather app, sending Ajax requests to OpenWeatherMap. I've got an error in w.getWeatherFunc, when I'm giving the function sendRequest the parameter of w.weather and then giving the same parameter to the function displayFunc, which I'm calling next.
Here is what I've got in the console:
Uncaught TypeError: Cannot read property 'weather' of undefined
at displayFunc (weather.js:46)
at weather.js:78
How can I fix this and make it work?
function Weather () {
var w = this;
var weatherUrl = 'http://api.openweathermap.org/data/2.5/weather?';
var appid = '&appid=c0a7816b2acba9dbfb70977a1e537369';
var googleUrl = 'https://maps.googleapis.com/maps/api/geocode/json?address=';
var googleKey = '&key=AIzaSyBHBjF5lDpw2tSXVJ6A1ra-RKT90ek5bvQ';
w.demo = document.getElementById('demo');
w.place = document.getElementById('place');
w.description = document.getElementById('description');
w.temp = document.getElementById('temp');
w.humidity = document.getElementById('humidity');
w.getWeather = document.getElementById('getWeather');
w.addCityBtn = document.getElementById('addCity');
w.rmCityBtn = document.getElementById('rmCity');
w.icon = document.getElementById('icon');
w.wind = document.getElementById('wind');
w.time = document.getElementById('time');
w.lat = null;
w.lon = null;
w.cityArray = [];
w.weather = null;
function sendRequest (url, data) {
var request = new XMLHttpRequest();
request.open('GET', url, true);
request.send();
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
data = JSON.parse(request.responseText);
console.log(data);
return data;
} else {
console.log(request.status + ': ' + request.statusText);
}
}
}
function displayFunc (obj) {
console.log('obj ' + obj);
w.icon.src = 'http://openweathermap.org/img/w/' + obj.weather[0].icon + '.png';
var timeNow = new Date();
var hours = timeNow.getHours();
var minutes = timeNow.getMinutes() < 10 ? '0' + timeNow.getMinutes() : timeNow.getMinutes();
w.time.innerHTML = hours + ':' + minutes;
w.place.innerHTML = 'Place: ' + obj.name;
w.description.innerHTML = "Weather: " + obj.weather[0].description;
w.temp.innerHTML = "Temperature: " + w.convertToCels(obj.main.temp) + "°C";
w.humidity.innerHTML = "Humidity: " + obj.main.humidity + '%';
w.wind.innerHTML = 'Wind: ' + obj.wind.speed + ' meter/sec';
}
w.convertToCels = function(temp) {
var tempC = Math.round(temp - 273.15);
return tempC;
}
w.getWeatherFunc = function() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(location){
w.lat = location.coords.latitude;
w.lon = location.coords.longitude;
var url = weatherUrl + 'lat=' + w.lat + '&lon=' + w.lon + appid;
var result = sendRequest(url, w.weather);
console.log(result);
displayFunc(result);
});
} else {
alert('Browser could not find your current location');
}
}
w.addCityBtn.onclick = function() {
var newCity = prompt('Please insert city', 'Kiev');
var gUrl = googleUrl + newCity + googleKey;
var newCityWeather = null;
sendRequest(url, newCityWeather);
var location = newCityWeather.results[0].geometry.location;
var newUrl = weatherUrl + 'lat=' + location.lat + '&lon=' + location.lng + appid;
sendRequest(newUrl, w.weather);
displayFunc(newCity);
w.cityArray.push(newCity);
}
window.onload = w.getWeatherFunc;
setInterval(function() {
w.getWeatherFunc();
}, 900000);
}
Your ajax return returns into the browsers engine. As its async you need to create a callback:
function sendRequest(url,data,callback){
//if the data was received
callback(data);
}
Use like this
sendRequest("yoururl",data,function(data){
displayFunc(data);
});
The first time you pass the obj to the function it will save it one scope higher. after that, if you don;t pass the object the one you saved earlier will be used.
var objBkp;
function displayFunc (obj) {
if(undefined === obj) obj = objBkp;
else objBkp = obj;
// rest of code here
}
In your sendRequest you are passing only the value of w.weather, not its reference. JavaScript doesn't pass variables by value or by reference, but by sharing. So if you want to give the value to your variable you should do this inside your function sendRequest:
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
w.weather = JSON.parse(request.responseText);
console.log(data);
return data;
} else {
console.log(request.status + ': ' + request.statusText);
}
}
Also, if you are using the attributes, you don't have to pass them in the function as arguments. Besides that fact, it would be good if you also create get() and set()
What does the console.log(result); in getWeatherFunc gives you?
The problem as I see it is that in the displayFunc the parameter passed is undefined.

Significance of '&' Symbol in JavaScript

I am currently working on a form that posts data to SAP. I am using JavaScript to invoke a Web Service to do this. I am running into an issue where one of the fields in the form has the value of 'GT&N' and I only get an error when the '&' symbol is present. I have looked on Google but have found nothing in relation the the & Symbol and JavaScript.
Error Message I'm receiving from the Web Page:
Unexpected end of file. Following elements are not closed: Characteristic_Value, RunParameter, Run, Body, Envelope. Line 1, position 2520
**The 'Characteristic_Value' is my field within the form.
Error I see when I debug:
Whenever I do not use the '&' Symbol, everything works great. I also tried using other special charecters and it posts just fine.
There is quite a bit of code to this so I am not going to post all of it unless requested as this is just a general question in regards to the '&' Symbol and JavaScript.
The JavaScript Code
//Create
var WebServer = "http://webserver";
var WebServiceName = "CreateIngredient";
var ScriptType = "Transaction";
var RepeatingTableXMLPath = "/my:myFields/my:CreateIngredient/my:CreateIngredient_Repeat";
// To Call Web service from infopath
function CreateIngredient(theXmlNode) {
//Add parameter into the request
var addBatchRequest = new SOAPClientParameters();
var Addresses = new Array();
var AddressXmlNodes = theXmlNode.selectNodes(RepeatingTableXMLPath);
// Loop for Input Field from Repeating Table
for (var i = 0; i < AddressXmlNodes.length; i++) {
var xPath = AddressXmlNodes[i].getXPath();
// Input field, It can be n number of fields
addBatchRequest.add("Material_description", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Material_description").getValue());
addBatchRequest.add("Base_Unit_of_Measure", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Base_Unit_of_Measure").getValue());
addBatchRequest.add("Material_group", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Material_group").getValue());
addBatchRequest.add("External_Material_Group", AddressXmlNodes[i].selectSingleNode(xPath + "/my:External_Material_Group").getValue());
addBatchRequest.add("Division", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Division").getValue());
addBatchRequest.add("Authorization_Group", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Authorization_Group").getValue());
addBatchRequest.add("Gross_weight", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Gross_weight").getValue());
addBatchRequest.add("Weight_Unit", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Weight_Unit").getValue());
addBatchRequest.add("Net_weight", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Net_weight").getValue());
addBatchRequest.add("Dangerous_Goods_Indicator_Profile", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Dangerous_Goods_Indicator_Profile").getValue());
addBatchRequest.add("Class_number", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Class_number").getValue());
addBatchRequest.add("Characteristic_Value", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Characteristic_Value").getValue().toString());
addBatchRequest.add("Class_number1", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Class_number1").getValue());
addBatchRequest.add("Plant", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Plant").getValue());
addBatchRequest.add("Checking_Group_for_Availability_Check", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Checking_Group_for_Availability_Check").getValue());
addBatchRequest.add("Batch_management_requirement_indicator", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Batch_management_requirement_indicator").getValue());
addBatchRequest.add("Transportation_group", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Transportation_group").getValue());
addBatchRequest.add("Loading_group", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Loading_group").getValue());
addBatchRequest.add("Profit_Center", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Profit_Center").getValue());
addBatchRequest.add("Purchasing_group", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Purchasing_group").getValue());
addBatchRequest.add("Plant-Specific_Material_Status", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Plant-Specific_Material_Status").getValue());
addBatchRequest.add("Tax_indicator_for_material__Purchasing_", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Tax_indicator_for_material__Purchasing_").getValue());
addBatchRequest.add("Indicator___automatic_purchase_order_allowed_", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Indicator___automatic_purchase_order_allowed_").getValue());
addBatchRequest.add("Purchasing_Value_Key", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Purchasing_Value_Key").getValue());
addBatchRequest.add("Storage_location", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Storage_location").getValue());
addBatchRequest.add("Temperature_conditions_indicator", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Temperature_conditions_indicator").getValue());
addBatchRequest.add("Label_type", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Label_type").getValue());
addBatchRequest.add("Label_form", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Label_form").getValue());
addBatchRequest.add("Minimum_remaining_shelf_life", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Minimum_remaining_shelf_life").getValue());
addBatchRequest.add("Total_shelf_life", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Total_shelf_life").getValue());
addBatchRequest.add("Storage_percentage", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Storage_percentage").getValue());
addBatchRequest.add("Documentation_required_indicator", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Documentation_required_indicator").getValue());
addBatchRequest.add("QM_in_Procurement_is_Active", AddressXmlNodes[i].selectSingleNode(xPath + "/my:QM_in_Procurement_is_Active").getValue());
addBatchRequest.add("Control_Key_for_Quality_Management_in_Procurement", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Control_Key_for_Quality_Management_in_Procurement").getValue());
addBatchRequest.add("Valuation_Class", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Valuation_Class").getValue());
addBatchRequest.add("Price_control_indicator", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Price_control_indicator").getValue());
addBatchRequest.add("Price_unit", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Price_unit").getValue());
addBatchRequest.add("Standard_price", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Standard_price").getValue());
addBatchRequest.add("Price_unit_for_valuation_prices_based_on_tax_commercial_law", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Price_unit_for_valuation_prices_based_on_tax_commercial_law").getValue());
addBatchRequest.add("Material-related_origin", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Material-related_origin").getValue());
addBatchRequest.add("Variance_Key", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Variance_Key").getValue());
addBatchRequest.add("Lot_Size_for_Product_Costing", AddressXmlNodes[i].selectSingleNode(xPath + "/my:Lot_Size_for_Product_Costing").getValue());
// Output field has been field with text Retrieving... in Gray color for presentation purpose only
var LogFieldNode = AddressXmlNodes[i].selectSingleNode(xPath + "/my:LogField");
var txtLog = document.getElementById("SV_" + LogFieldNode.getAttribute("SVFormElementId"));
txtLog.value = "Retrieving...";
txtLog.style.color = 'Gray';
// Final web service call parameter
var pl = new SOAPClientParameters();
pl.add("RunParameter", addBatchRequest.toXml());
pl.toXml();
SOAPClient.invoke(WebServer + "/formsservice.svc/basic", "Run", pl, true, CreateIngredient_callBack, i);
}
}
// To display the retrieved result in the proper output fields
function CreateIngredient_callBack(u, xmlresponse, RowNumber) {
var theXmlNode1 = SVFormInternalGetProperXmlNode(SVForms[0]);
var AddressXmlNodes1 = theXmlNode1.selectNodes(RepeatingTableXMLPath);
var xPath = AddressXmlNodes1[RowNumber].getXPath();
var LogFieldNode = AddressXmlNodes1[RowNumber].selectSingleNode(xPath + "/my:LogField");
var txtLog = document.getElementById("SV_" + LogFieldNode.getAttribute("SVFormElementId"));
txtLog.style.color = "";
txtLog.value = "";
if (u == null)
alert("No data retrieved for Row Number " + (RowNumber + 1) + ".");
else {
//Display result in repeating table
if (u.LogField) {
LogFieldNode.setValue(u.LogField);
document.getElementById("SV_" + LogFieldNode.getAttribute("SVFormElementId")).value = u.LogField;
}
}
}
///////////////////// Do not modify below this line ///////////////////////////////
var WsdlResult = null;
//Helping method: To build xml
function SOAPClientParameters() {
var _pl = new Array();
this.add = function (name, value) {
_pl[name] = value;
return _pl;
}
this.toXml = function () {
var xml = "";
for (var p in _pl) {
if (typeof (_pl[p]) != "function")
xml += "<" + p + ">" + _pl[p].toString() + "</" + p + ">";
}
return xml;
}
}
function SOAPClientRepeatingParametersXml(name, values) {
var xml = "";
for (var i = 0; i < values.length; i++) {
xml += "<" + name + ">" + values[i].toString() + "</" + name + ">";
}
return xml;
}
function SOAPClient() { }
SOAPClient.invoke = function (url, method, parameters, async, callback, RowNumber) {
if (async)
SOAPClient._loadWsdl(url, method, parameters, async, callback, RowNumber);
else
return SOAPClient._loadWsdl(url, method, parameters, async, callback, RowNumber);
}
// private: wsdl cache
SOAPClient_cacheWsdl = new Array();
// private: invoke async
SOAPClient._loadWsdl = function (url, method, parameters, async, callback, RowNumber) {
// load from cache?
var wsdl = SOAPClient_cacheWsdl[url];
if (wsdl + "" != "" && wsdl + "" != "undefined")
return SOAPClient._sendSoapRequest(url, method, parameters, async, callback, wsdl, RowNumber);
// get wsdl
var xmlHttp = SOAPClient._getXmlHttp();
xmlHttp.open("GET", url + "?wsdl", async);
if (async) {
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState == 4)
SOAPClient._onLoadWsdl(url, method, parameters, async, callback, xmlHttp, RowNumber);
}
}
xmlHttp.send(null);
if (!async)
return SOAPClient._onLoadWsdl(url, method, parameters, async, callback, xmlHttp, RowNumber);
}
SOAPClient._onLoadWsdl = function (url, method, parameters, async, callback, req, RowNumber) {
var wsdl = req.responseXML;
SOAPClient_cacheWsdl[url] = wsdl; // save a copy in cache
return SOAPClient._sendSoapRequest(url, method, parameters, async, callback, wsdl, RowNumber);
}
SOAPClient._sendSoapRequest = function (url, method, parameters, async, callback, wsdl, RowNumber) {
// get namespace
try {
var ns = "http://servername.com/server/";
// build SOAP request
var sr =
"<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<soap:Envelope " +
"xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" " +
'xmlns:api="http://IPAddress/Integrics/Enswitch/API" ' +
"xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" " +
"xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">" +
"<soap:Body>" +
"<" + method + " xmlns=\"" + ns + "\">" +
parameters.toXml() +
"</" + method + "></soap:Body></soap:Envelope>";
// send request
var xmlHttp = SOAPClient._getXmlHttp();
xmlHttp.open("POST", url, async);
var soapaction = ((ns.lastIndexOf("/") != ns.length - 1) ? ns + "/" : ns) + method;
xmlHttp.setRequestHeader("SOAPAction", "http://servername.com/server/I" + ScriptType + "Service/Process(" + WebServiceName + ")");
xmlHttp.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
if (async) {
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState == 4)
SOAPClient._onSendSoapRequest(method, async, callback, wsdl, xmlHttp, RowNumber);
}
}
xmlHttp.send(sr);
}
catch (ex) { }
if (!async)
return SOAPClient._onSendSoapRequest(method, async, callback, wsdl, xmlHttp, RowNumber);
}
SOAPClient._onSendSoapRequest = function (method, async, callback, wsdl, req, RowNumber) {
var o = null;
var nd = SOAPClient._getElementsByTagName(req.responseXML, method + "Result");
if (nd.length == 0) {
if (req.responseXML.getElementsByTagName("faultcode").length > 0);
alert(req.responseXML.getElementsByTagName("faultstring") [0].childNodes[0].nodeValue);
}
else
o = SOAPClient._soapresult2object(nd[0], wsdl);
if (callback)
callback(o, req.responseXML, RowNumber);
if (!async)
return o;
}
// private: utils
SOAPClient._getElementsByTagName = function (document, tagName) {
try {
// trying to get node omitting any namespaces (latest versions of MSXML.XMLDocument)
return document.selectNodes(".//*[local-name()=\"" + tagName + "\"]");
}
catch (ex) { }
// old XML parser support
return document.getElementsByTagName(tagName);
}
SOAPClient._soapresult2object = function (node, wsdl) {
return SOAPClient._node2object(node, wsdl);
}
SOAPClient._node2object = function (node, wsdl) {
// null node
if (node == null)
return null;
// text node
if (node.nodeType == 3 || node.nodeType == 4)
return SOAPClient._extractValue(node, wsdl);
// leaf node
if (node.childNodes.length == 1 && (node.childNodes[0].nodeType == 3 || node.childNodes[0].nodeType == 4))
return SOAPClient._node2object(node.childNodes[0], wsdl);
var isarray = SOAPClient._getTypeFromWsdl(node.nodeName, wsdl).toLowerCase().indexOf("arrayof") != -1;
// object node
if (!isarray) {
var obj = null;
if (node.hasChildNodes())
obj = new Object();
for (var i = 0; i < node.childNodes.length; i++) {
var p = SOAPClient._node2object(node.childNodes[i], wsdl);
obj[node.childNodes[i].nodeName] = p;
}
return obj;
}
// list node
else {
// create node ref
var l = new Array();
for (var i = 0; i < node.childNodes.length; i++)
l[l.length] = SOAPClient._node2object(node.childNodes[i], wsdl);
return l;
}
return null;
}
SOAPClient._extractValue = function (node, wsdl) {
var value = node.nodeValue;
switch (SOAPClient._getTypeFromWsdl(node.parentNode.nodeName, wsdl).toLowerCase()) {
default:
case "s:string":
return (value != null) ? value + "" : "";
case "s:boolean":
return value + "" == "true";
case "s:int":
case "s:long":
return (value != null) ? parseInt(value + "", 10) : 0;
case "s:double":
return (value != null) ? parseFloat(value + "") : 0;
case "s:datetime":
if (value == null)
return null;
else {
value = value + "";
value = value.substring(0, value.lastIndexOf("."));
value = value.replace(/T/gi, " ");
value = value.replace(/-/gi, "/");
var d = new Date();
d.setTime(Date.parse(value));
return d;
}
}
}
SOAPClient._getTypeFromWsdl = function (elementname, wsdl) {
var ell = wsdl.getElementsByTagName("s:element"); // IE
if (ell.length == 0)
ell = wsdl.getElementsByTagName("element"); // MOZ
for (var i = 0; i < ell.length; i++) {
if (ell[i].attributes["name"] + "" == "undefined") // IE
{
if (ell[i].attributes.getNamedItem("name") != null && ell[i].attributes.getNamedItem("name").nodeValue == elementname && ell[i].attributes.getNamedItem("type") != null)
return ell[i].attributes.getNamedItem("type").nodeValue;
}
else // MOZ
{
if (ell[i].attributes["name"] != null && ell[i].attributes["name"].value == elementname && ell[i].attributes["type"] != null)
return ell[i].attributes["type"].value;
}
}
return "";
}
// private: xmlhttp factory
SOAPClient._getXmlHttp = function () {
try {
if (window.XDomainRequest) {
var req = new window.XDomainRequest();
if (req.readyState == null) {
req.readyState = 1;
req.addEventListener("load",
function () {
req.readyState = 4;
if (typeof req.onreadystatechange == "function")
req.onreadystatechange();
},
false);
}
return req;
}
}
catch (ex) {
try {
if (window.XMLHttpRequest) {
var req = new XMLHttpRequest();
// some versions of Moz do not support the readyState property and the onreadystate event so we patch it!
if (req.readyState == null) {
req.readyState = 1;
req.addEventListener("load",
function () {
req.readyState = 4;
if (typeof req.onreadystatechange == "function")
req.onreadystatechange();
},
false);
}
return req;
}
}
catch (ex) {
try {
// Internet Explorer
if (window.ActiveXObject)
return new ActiveXObject("Msxml2.XMLHTTP"); //ActiveXObject(SOAPClient._getXmlHttpProgID());
} catch (e) {
// Firefox, Opera 8.0+, Safari
try {
return new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
try {
return new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
alert("Your browser does not support AJAX!");
return false;
}
}
}
}
}
}
SOAPClient._getXmlHttpProgID = function () {
if (SOAPClient._getXmlHttpProgID.progid)
return SOAPClient._getXmlHttpProgID.progid;
var progids = ["Msxml2.XMLHTTP.5.0", "Msxml2.XMLHTTP.4.0", "MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP", "Microsoft.XMLHTTP"];
var o;
for (var i = 0; i < progids.length; i++) {
try {
o = new ActiveXObject(progids[i]);
return SOAPClient._getXmlHttpProgID.progid = progids[i];
}
catch (ex) { };
}
throw new Error("Could not find an installed XML parser");
}
Thanks in advance for any helpful input.
Cheers
Try &#38 instead of & sign.

Categories

Resources