through this discussion, I knew how to call an external function of javascript via Java : Call external javascript functions from java code
I tried the same thing with my script and it did not work
metar.js :
(function() {
// http://www.met.tamu.edu/class/metar/metar-pg10-sky.html
// https://ww8.fltplan.com/AreaForecast/abbreviations.htm
// http://en.wikipedia.org/wiki/METAR
// http://www.unc.edu/~haines/metar.html
var CLOUDS = {
NCD: "no clouds",
SKC: "sky clear",
CLR: "no clouds under 12,000 ft",
NSC: "no significant",
FEW: "few",
SCT: "scattered",
BKN: "broken",
OVC: "overcast",
VV: "vertical visibility"
};
var WEATHER = {
// Intensity
"-": "light intensity",
"+": "heavy intensity",
VC: "in the vicinity",
// Descriptor
MI: "shallow",
PR: "partial",
BC: "patches",
DR: "low drifting",
BL: "blowing",
SH: "showers",
TS: "thunderstorm",
FZ: "freezing",
// Precipitation
RA: "rain",
DZ: "drizzle",
SN: "snow",
SG: "snow grains",
IC: "ice crystals",
PL: "ice pellets",
GR: "hail",
GS: "small hail",
UP: "unknown precipitation",
// Obscuration
FG: "fog",
VA: "volcanic ash",
BR: "mist",
HZ: "haze",
DU: "widespread dust",
FU: "smoke",
SA: "sand",
PY: "spray",
// Other
SQ: "squall",
PO: "dust or sand whirls",
DS: "duststorm",
SS: "sandstorm",
FC: "funnel cloud"
};
function parseAbbreviation(s, map) {
var abbreviation, meaning, length = 3;
if (!s) return;
while (length && !meaning) {
abbreviation = s.slice(0, length);
meaning = map[abbreviation];
length--;
}
if (meaning) {
return {
abbreviation: abbreviation,
meaning: meaning
};
}
}
function asInt(s) {
return parseInt(s, 10);
}
function METAR(metarString) {
this.fields = metarString.split(" ").map(function(f) {
return f.trim();
}).filter(function(f) {
return !!f;
});
this.i = -1;
this.current = null;
this.result = {};
}
METAR.prototype.next = function() {
this.i++;
return this.current = this.fields[this.i];
};
METAR.prototype.peek = function() {
return this.fields[this.i+1];
};
METAR.prototype.parseStation = function() {
this.next();
this.result.station = this.current;
};
METAR.prototype.parseDate = function() {
this.next();
var d = new Date();
d.setUTCDate(asInt(this.current.slice(0,2)));
d.setUTCHours(asInt(this.current.slice(2,4)));
d.setUTCMinutes(asInt(this.current.slice(4,6)));
this.result.time = d;
};
METAR.prototype.parseAuto = function() {
this.result.auto = this.peek() === "AUTO";
if (this.result.auto) this.next();
};
METAR.prototype.parseCorrection = function() {
var token = this.peek();
this.result.correction = false;
if (token.lastIndexOf('CC', 0) == 0) {
this.result.correction = token.substr(2,1);
this.next();
}
};
var variableWind = /^([0-9]{3})V([0-9]{3})$/;
METAR.prototype.parseWind = function() {
this.next();
this.result.wind = {
speed: null,
gust: null,
direction: null,
variation: null
};
var direction = this.current.slice(0,3);
if (direction === "VRB") {
this.result.wind.direction = "VRB";
this.result.wind.variation = true;
}
else {
this.result.wind.direction = asInt(direction);
}
var gust = this.current.slice(5,8);
if (gust[0] === "G") {
this.result.wind.gust = asInt(gust.slice(1));
}
this.result.wind.speed = asInt(this.current.slice(3,5));
var unitMatch;
if (unitMatch = this.current.match(/KT|MPS|KPH$/)) {
this.result.wind.unit = unitMatch[0];
}
else {
throw new Error("Bad wind unit: " + this.current);
}
var varMatch;
if (varMatch = this.peek().match(variableWind)) {
this.next();
this.result.wind.variation = {
min: asInt(varMatch[1]),
max: asInt(varMatch[2])
};
}
};
METAR.prototype.parseCavok = function() {
this.result.cavok = this.peek() === "CAVOK";
if (this.result.cavok) this.next();
};
METAR.prototype.parseVisibility = function() {
this.result.visibility = null;
if (this.result.cavok) return;
this.next();
if (this.current === "////") return;
this.result.visibility = asInt(this.current.slice(0,4));
// TODO: Direction too. I've not seen it in finnish METARs...
};
METAR.prototype.parseRunwayVisibility = function() {
if (this.result.cavok) return;
if (this.peek().match(/^R[0-9]+/)) {
this.next();
// TODO: Parse it!
}
};
function parseWeatherAbbrv(s, res) {
var weather = parseAbbreviation(s, WEATHER);
if (weather) {
res = res || [];
res.push(weather);
return parseWeatherAbbrv(s.slice(weather.abbreviation.length), res);
}
return res;
}
METAR.prototype.parseWeather = function() {
if (this.result.weather === undefined) this.result.weather = null;
if (this.result.cavok) return;
var weather = parseWeatherAbbrv(this.peek());
if (!weather) return;
if (!this.result.weather) this.result.weather = [];
this.result.weather = this.result.weather.concat(weather);
this.next();
this.parseWeather();
};
METAR.prototype.parseClouds = function() {
if (!this.result.clouds) this.result.clouds = null;
if (this.result.cavok) return;
var cloud = parseAbbreviation(this.peek(), CLOUDS);
if (!cloud) return;
this.next();
cloud.altitude = asInt(this.current.slice(cloud.abbreviation.length))*100 || null;
cloud.cumulonimbus = /CB$/.test(this.current);
this.result.clouds = (this.result.clouds || []);
this.result.clouds.push(cloud);
this.parseClouds();
};
METAR.prototype.parseTempDewpoint = function() {
this.next();
var replaced = this.current.replace(/M/g, "-");
var a = replaced.split("/");
if( 2 !== a.length ) return; // expecting XX/XX
this.result.temperature = asInt( a[0] );
this.result.dewpoint = asInt( a[1] );
};
METAR.prototype.parseAltimeter = function() {
var temp;
this.next();
if (this.current === undefined || this.current === null) return;
// inches of mercury if AXXXX
if (this.current.length === 5 && "A" === this.current[0]) {
temp = this.current.substr(1, 2);
temp += ".";
temp += this.current.substr(3, 5);
this.result.altimeter_in_hg = parseFloat(temp, 10);
}
else if (this.current.length && "Q" === this.current[0]) {
temp = this.current.substr(1);
this.result.altimeter_hpa = parseInt(temp, 10);
}
};
METAR.prototype.parse = function() {
this.parseStation();
this.parseDate();
this.parseAuto();
this.parseCorrection();
this.parseWind();
this.parseCavok();
this.parseVisibility();
this.parseRunwayVisibility();
this.parseWeather();
this.parseClouds();
this.parseTempDewpoint();
this.parseAltimeter();
};
function parseMETAR(metarString) {
var m = new METAR(metarString);
m.parse();
return m.result;
}
if (typeof module !== "undefined") {
module.exports = parseMETAR;
}
else if (typeof window !== "undefined") {
window.parseMETAR = parseMETAR;
}
}());
Code java :
package testjavascript;
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import java.io.FileReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
public class testjavascript
{
public static void main(String[] args) throws Exception {
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("JavaScript");
engine.eval(new FileReader("C:\\metar.js"));
Invocable inv = (Invocable) engine;
System.out.println(inv.invokeFunction("parseMETAR","EFJY 171950Z AUTO 27006KT 220V310 9999 FEW012 SCT015 BKN060 13/12 Q1006"));
}
}
error :
Exception in thread "main" java.lang.NoSuchMethodException: No such function parseMETAR
at jdk.nashorn.api.scripting.ScriptObjectMirror.callMember(ScriptObjectMirror.java:197)
at jdk.nashorn.api.scripting.NashornScriptEngine.invokeImpl(NashornScriptEngine.java:381)
at jdk.nashorn.api.scripting.NashornScriptEngine.invokeFunction(NashornScriptEngine.java:187)
at testjavascript.testjavascript.main(testjavascript.java:18)
Can someone help me please
Related
Image Here
Hello! I am trying to add a search bar that acts like a proxy at the top of my website. Whenever I input a website like https://stackoverflow.com I receive an error on the website. RangeError: Failed to construct 'Response': The status provided (0) is outside the range [200, 599] (Note: I am using the ultraviolet service) If you'd like to test yourself the website is https://lun.netlify.app also no errors seem to appear in the console log.
importScripts('/uv/uv.bundle.js');
importScripts('/uv/uv.config.js');
class UVServiceWorker extends EventEmitter {
constructor(config = __uv$config) {
super();
if (!config.bare) config.bare = '/bare/';
this.addresses = typeof config.bare === 'string' ? [ new URL(config.bare, location) ] : config.bare.map(str => new URL(str, location));
this.headers = {
csp: [
'cross-origin-embedder-policy',
'cross-origin-opener-policy',
'cross-origin-resource-policy',
'content-security-policy',
'content-security-policy-report-only',
'expect-ct',
'feature-policy',
'origin-isolation',
'strict-transport-security',
'upgrade-insecure-requests',
'x-content-type-options',
'x-download-options',
'x-frame-options',
'x-permitted-cross-domain-policies',
'x-powered-by',
'x-xss-protection',
],
forward: [
'accept-encoding',
'connection',
'content-length',
'content-type',
'user-agent',
],
};
this.method = {
empty: [
'GET',
'HEAD'
]
};
this.statusCode = {
empty: [
204,
304,
],
};
this.config = config;
};
async fetch({ request }) {
if (!request.url.startsWith(location.origin + (this.config.prefix || '/service/'))) {
return fetch(request);
};
try {
const ultraviolet = new Ultraviolet(this.config);
if (typeof this.config.construct === 'function') {
this.config.construct(ultraviolet, 'service');
};
const db = await ultraviolet.cookie.db();
ultraviolet.meta.origin = location.origin;
ultraviolet.meta.base = ultraviolet.meta.url = new URL(ultraviolet.sourceUrl(request.url));
const requestCtx = new RequestContext(
request,
this,
ultraviolet,
!this.method.empty.includes(request.method.toUpperCase()) ? await request.blob() : null
);
if (ultraviolet.meta.url.protocol === 'blob:') {
requestCtx.blob = true;
requestCtx.base = requestCtx.url = new URL(requestCtx.url.pathname);
};
if (request.referrer && request.referrer.startsWith(location.origin)) {
const referer = new URL(ultraviolet.sourceUrl(request.referrer));
if (ultraviolet.meta.url.origin !== referer.origin && request.mode === 'cors') {
requestCtx.headers.origin = referer.origin;
};
requestCtx.headers.referer = referer.href;
};
const cookies = await ultraviolet.cookie.getCookies(db) || [];
const cookieStr = ultraviolet.cookie.serialize(cookies, ultraviolet.meta, false);
const browser = Ultraviolet.Bowser.getParser(self.navigator.userAgent).getBrowserName();
if (browser === 'Firefox' && !(request.destination === 'iframe' || request.destination === 'document')) {
requestCtx.forward.shift();
};
if (cookieStr) requestCtx.headers.cookie = cookieStr;
const reqEvent = new HookEvent(requestCtx, null, null);
this.emit('request', reqEvent);
if (reqEvent.intercepted) return reqEvent.returnValue;
const response = await fetch(requestCtx.send);
if (response.status === 500) {
return Promise.reject('');
};
const responseCtx = new ResponseContext(requestCtx, response, this);
const resEvent = new HookEvent(responseCtx, null, null);
this.emit('beforemod', resEvent);
if (resEvent.intercepted) return resEvent.returnValue;
for (const name of this.headers.csp) {
if (responseCtx.headers[name]) delete responseCtx.headers[name];
};
if (responseCtx.headers.location) {
responseCtx.headers.location = ultraviolet.rewriteUrl(responseCtx.headers.location);
};
if (responseCtx.headers['set-cookie']) {
Promise.resolve(ultraviolet.cookie.setCookies(responseCtx.headers['set-cookie'], db, ultraviolet.meta)).then(() => {
self.clients.matchAll().then(function (clients){
clients.forEach(function(client){
client.postMessage({
msg: 'updateCookies',
url: ultraviolet.meta.url.href,
});
});
});
});
delete responseCtx.headers['set-cookie'];
};
if (responseCtx.body) {
switch(request.destination) {
case 'script':
case 'worker':
responseCtx.body = `if (!self.__uv && self.importScripts) importScripts('${__uv$config.bundle}', '${__uv$config.config}', '${__uv$config.handler}');\n`;
responseCtx.body += ultraviolet.js.rewrite(
await response.text()
);
break;
case 'style':
responseCtx.body = ultraviolet.rewriteCSS(
await response.text()
);
break;
case 'iframe':
case 'document':
if (isHtml(ultraviolet.meta.url, (responseCtx.headers['content-type'] || ''))) {
responseCtx.body = ultraviolet.rewriteHtml(
await response.text(),
{
document: true ,
injectHead: ultraviolet.createHtmlInject(
this.config.handler,
this.config.bundle,
this.config.config,
ultraviolet.cookie.serialize(cookies, ultraviolet.meta, true),
request.referrer
)
}
);
};
};
};
if (requestCtx.headers.accept === 'text/event-stream') {
responseCtx.headers['content-type'] = 'text/event-stream';
};
this.emit('response', resEvent);
if (resEvent.intercepted) return resEvent.returnValue;
return new Response(responseCtx.body, {
headers: responseCtx.headers,
status: responseCtx.status,
statusText: responseCtx.statusText,
});
} catch(err) {
return new Response(err.toString(), {
status: 500,
});
};
};
getBarerResponse(response) {
const headers = {};
const raw = JSON.parse(response.headers.get('x-bare-headers'));
for (const key in raw) {
headers[key.toLowerCase()] = raw[key];
};
return {
headers,
status: +response.headers.get('x-bare-status'),
statusText: response.headers.get('x-bare-status-text'),
body: !this.statusCode.empty.includes(+response.headers.get('x-bare-status')) ? response.body : null,
};
};
get address() {
return this.addresses[Math.floor(Math.random() * this.addresses.length)];
};
static Ultraviolet = Ultraviolet;
};
self.UVServiceWorker = UVServiceWorker;
class ResponseContext {
constructor(request, response, worker) {
const { headers, status, statusText, body } = !request.blob ? worker.getBarerResponse(response) : {
status: response.status,
statusText: response.statusText,
headers: Object.fromEntries([...response.headers.entries()]),
body: response.body,
};
this.request = request;
this.raw = response;
this.ultraviolet = request.ultraviolet;
this.headers = headers;
this.status = status;
this.statusText = statusText;
this.body = body;
};
get url() {
return this.request.url;
}
get base() {
return this.request.base;
};
set base(val) {
this.request.base = val;
};
};
class RequestContext {
constructor(request, worker, ultraviolet, body = null) {
this.ultraviolet = ultraviolet;
this.request = request;
this.headers = Object.fromEntries([...request.headers.entries()]);
this.method = request.method;
this.forward = [...worker.headers.forward];
this.address = worker.address;
this.body = body || null;
this.redirect = request.redirect;
this.credentials = 'omit';
this.mode = request.mode === 'cors' ? request.mode : 'same-origin';
this.blob = false;
};
get send() {
return new Request((!this.blob ? this.address.href + 'v1/' : 'blob:' + location.origin + this.url.pathname), {
method: this.method,
headers: {
'x-bare-protocol': this.url.protocol,
'x-bare-host': this.url.hostname,
'x-bare-path': this.url.pathname + this.url.search,
'x-bare-port': this.url.port || (this.url.protocol === 'https:' ? '443' : '80'),
'x-bare-headers': JSON.stringify(this.headers),
'x-bare-forward-headers': JSON.stringify(this.forward),
},
redirect: this.redirect,
credentials: this.credentials,
mode: location.origin !== this.address.origin ? 'cors' : this.mode,
body: this.body
});
};
get url() {
return this.ultraviolet.meta.url;
};
set url(val) {
this.ultraviolet.meta.url = val;
};
get base() {
return this.ultraviolet.meta.base;
};
set base(val) {
this.ultraviolet.meta.base = val;
};
}
function isHtml(url, contentType = '') {
return (Ultraviolet.mime.contentType((contentType || url.pathname)) || 'text/html').split(';')[0] === 'text/html';
};
class HookEvent {
#intercepted;
#returnValue;
constructor(data = {}, target = null, that = null) {
this.#intercepted = false;
this.#returnValue = null;
this.data = data;
this.target = target;
this.that = that;
};
get intercepted() {
return this.#intercepted;
};
get returnValue() {
return this.#returnValue;
};
respondWith(input) {
this.#returnValue = input;
this.#intercepted = true;
};
};
var R = typeof Reflect === 'object' ? Reflect : null
var ReflectApply = R && typeof R.apply === 'function'
? R.apply
: function ReflectApply(target, receiver, args) {
return Function.prototype.apply.call(target, receiver, args);
}
var ReflectOwnKeys
if (R && typeof R.ownKeys === 'function') {
ReflectOwnKeys = R.ownKeys
} else if (Object.getOwnPropertySymbols) {
ReflectOwnKeys = function ReflectOwnKeys(target) {
return Object.getOwnPropertyNames(target)
.concat(Object.getOwnPropertySymbols(target));
};
} else {
ReflectOwnKeys = function ReflectOwnKeys(target) {
return Object.getOwnPropertyNames(target);
};
}
function ProcessEmitWarning(warning) {
if (console && console.warn) console.warn(warning);
}
var NumberIsNaN = Number.isNaN || function NumberIsNaN(value) {
return value !== value;
}
function EventEmitter() {
EventEmitter.init.call(this);
}
EventEmitter.EventEmitter = EventEmitter;
EventEmitter.prototype._events = undefined;
EventEmitter.prototype._eventsCount = 0;
EventEmitter.prototype._maxListeners = undefined;
var defaultMaxListeners = 10;
function checkListener(listener) {
if (typeof listener !== 'function') {
throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener);
}
}
Object.defineProperty(EventEmitter, 'defaultMaxListeners', {
enumerable: true,
get: function() {
return defaultMaxListeners;
},
set: function(arg) {
if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) {
throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + '.');
}
defaultMaxListeners = arg;
}
});
EventEmitter.init = function() {
if (this._events === undefined ||
this._events === Object.getPrototypeOf(this)._events) {
this._events = Object.create(null);
this._eventsCount = 0;
}
this._maxListeners = this._maxListeners || undefined;
};
EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {
if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) {
throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + '.');
}
this._maxListeners = n;
return this;
};
function _getMaxListeners(that) {
if (that._maxListeners === undefined)
return EventEmitter.defaultMaxListeners;
return that._maxListeners;
}
EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
return _getMaxListeners(this);
};
EventEmitter.prototype.emit = function emit(type) {
var args = [];
for (var i = 1; i < arguments.length; i++) args.push(arguments[i]);
var doError = (type === 'error');
var events = this._events;
if (events !== undefined)
doError = (doError && events.error === undefined);
else if (!doError)
return false;
if (doError) {
var er;
if (args.length > 0)
er = args[0];
if (er instanceof Error) {
throw er;
}
var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : ''));
err.context = er;
throw err;
}
var handler = events[type];
if (handler === undefined)
return false;
if (typeof handler === 'function') {
ReflectApply(handler, this, args);
} else {
var len = handler.length;
var listeners = arrayClone(handler, len);
for (var i = 0; i < len; ++i)
ReflectApply(listeners[i], this, args);
}
return true;
};
function _addListener(target, type, listener, prepend) {
var m;
var events;
var existing;
checkListener(listener);
events = target._events;
if (events === undefined) {
events = target._events = Object.create(null);
target._eventsCount = 0;
} else {
if (events.newListener !== undefined) {
target.emit('newListener', type,
listener.listener ? listener.listener : listener);
events = target._events;
}
existing = events[type];
}
if (existing === undefined) {
existing = events[type] = listener;
++target._eventsCount;
} else {
if (typeof existing === 'function') {
existing = events[type] =
prepend ? [listener, existing] : [existing, listener];
} else if (prepend) {
existing.unshift(listener);
} else {
existing.push(listener);
}
// Check for listener leak
m = _getMaxListeners(target);
if (m > 0 && existing.length > m && !existing.warned) {
existing.warned = true;
var w = new Error('Possible EventEmitter memory leak detected. ' +
existing.length + ' ' + String(type) + ' listeners ' +
'added. Use emitter.setMaxListeners() to ' +
'increase limit');
w.name = 'MaxListenersExceededWarning';
w.emitter = target;
w.type = type;
w.count = existing.length;
ProcessEmitWarning(w);
}
}
return target;
}
EventEmitter.prototype.addListener = function addListener(type, listener) {
return _addListener(this, type, listener, false);
};
EventEmitter.prototype.on = EventEmitter.prototype.addListener;
EventEmitter.prototype.prependListener =
function prependListener(type, listener) {
return _addListener(this, type, listener, true);
};
function onceWrapper() {
if (!this.fired) {
this.target.removeListener(this.type, this.wrapFn);
this.fired = true;
if (arguments.length === 0)
return this.listener.call(this.target);
return this.listener.apply(this.target, arguments);
}
}
function _onceWrap(target, type, listener) {
var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener };
var wrapped = onceWrapper.bind(state);
wrapped.listener = listener;
state.wrapFn = wrapped;
return wrapped;
}
EventEmitter.prototype.once = function once(type, listener) {
checkListener(listener);
this.on(type, _onceWrap(this, type, listener));
return this;
};
EventEmitter.prototype.prependOnceListener =
function prependOnceListener(type, listener) {
checkListener(listener);
this.prependListener(type, _onceWrap(this, type, listener));
return this;
};
EventEmitter.prototype.removeListener =
function removeListener(type, listener) {
var list, events, position, i, originalListener;
checkListener(listener);
events = this._events;
if (events === undefined)
return this;
list = events[type];
if (list === undefined)
return this;
if (list === listener || list.listener === listener) {
if (--this._eventsCount === 0)
this._events = Object.create(null);
else {
delete events[type];
if (events.removeListener)
this.emit('removeListener', type, list.listener || listener);
}
} else if (typeof list !== 'function') {
position = -1;
for (i = list.length - 1; i >= 0; i--) {
if (list[i] === listener || list[i].listener === listener) {
originalListener = list[i].listener;
position = i;
break;
}
}
if (position < 0)
return this;
if (position === 0)
list.shift();
else {
spliceOne(list, position);
}
if (list.length === 1)
events[type] = list[0];
if (events.removeListener !== undefined)
this.emit('removeListener', type, originalListener || listener);
}
return this;
};
EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
EventEmitter.prototype.removeAllListeners =
function removeAllListeners(type) {
var listeners, events, i;
events = this._events;
if (events === undefined)
return this;
if (events.removeListener === undefined) {
if (arguments.length === 0) {
this._events = Object.create(null);
this._eventsCount = 0;
} else if (events[type] !== undefined) {
if (--this._eventsCount === 0)
this._events = Object.create(null);
else
delete events[type];
}
return this;
}
if (arguments.length === 0) {
var keys = Object.keys(events);
var key;
for (i = 0; i < keys.length; ++i) {
key = keys[i];
if (key === 'removeListener') continue;
this.removeAllListeners(key);
}
this.removeAllListeners('removeListener');
this._events = Object.create(null);
this._eventsCount = 0;
return this;
}
listeners = events[type];
if (typeof listeners === 'function') {
this.removeListener(type, listeners);
} else if (listeners !== undefined) {
// LIFO order
for (i = listeners.length - 1; i >= 0; i--) {
this.removeListener(type, listeners[i]);
}
}
return this;
};
function _listeners(target, type, unwrap) {
var events = target._events;
if (events === undefined)
return [];
var evlistener = events[type];
if (evlistener === undefined)
return [];
if (typeof evlistener === 'function')
return unwrap ? [evlistener.listener || evlistener] : [evlistener];
return unwrap ?
unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);
}
EventEmitter.prototype.listeners = function listeners(type) {
return _listeners(this, type, true);
};
EventEmitter.prototype.rawListeners = function rawListeners(type) {
return _listeners(this, type, false);
};
EventEmitter.listenerCount = function(emitter, type) {
if (typeof emitter.listenerCount === 'function') {
return emitter.listenerCount(type);
} else {
return listenerCount.call(emitter, type);
}
};
EventEmitter.prototype.listenerCount = listenerCount;
function listenerCount(type) {
var events = this._events;
if (events !== undefined) {
var evlistener = events[type];
if (typeof evlistener === 'function') {
return 1;
} else if (evlistener !== undefined) {
return evlistener.length;
}
}
return 0;
}
EventEmitter.prototype.eventNames = function eventNames() {
return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : [];
};
function arrayClone(arr, n) {
var copy = new Array(n);
for (var i = 0; i < n; ++i)
copy[i] = arr[i];
return copy;
}
function spliceOne(list, index) {
for (; index + 1 < list.length; index++)
list[index] = list[index + 1];
list.pop();
}
function unwrapListeners(arr) {
var ret = new Array(arr.length);
for (var i = 0; i < ret.length; ++i) {
ret[i] = arr[i].listener || arr[i];
}
return ret;
}
function once(emitter, name) {
return new Promise(function (resolve, reject) {
function errorListener(err) {
emitter.removeListener(name, resolver);
reject(err);
}
function resolver() {
if (typeof emitter.removeListener === 'function') {
emitter.removeListener('error', errorListener);
}
resolve([].slice.call(arguments));
};
eventTargetAgnosticAddListener(emitter, name, resolver, { once: true });
if (name !== 'error') {
addErrorHandlerIfEventEmitter(emitter, errorListener, { once: true });
}
});
}
function addErrorHandlerIfEventEmitter(emitter, handler, flags) {
if (typeof emitter.on === 'function') {
eventTargetAgnosticAddListener(emitter, 'error', handler, flags);
}
}
function eventTargetAgnosticAddListener(emitter, name, listener, flags) {
if (typeof emitter.on === 'function') {
if (flags.once) {
emitter.once(name, listener);
} else {
emitter.on(name, listener);
}
} else if (typeof emitter.addEventListener === 'function') {
emitter.addEventListener(name, function wrapListener(arg) {
if (flags.once) {
emitter.removeEventListener(name, wrapListener);
}
listener(arg);
});
} else {
throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type ' + typeof emitter);
}
}
i made a module for odoo 12 to lock the pos screen the code works fine in odoo 10, but gives error this.pos is null or this.pos.currency is undefined. in the models.js, i want to switch the orders of different cashiers but this.pos is not initialized, what should i do so that it becomes initialized?
here is my code:
odoo.define('pos_user_lock.models',
//['point_of_sale.models','point_of_sale.screens','point_of_sale.chrome'
//,'web.ajax','web.core'],
function (require) {
"use strict";
var ajax = require('web.ajax');
var screens = require('point_of_sale.screens');
var models = require('point_of_sale.models');
var chrome = require('point_of_sale.chrome');
var core = require('web.core');
var QWeb = core.qweb;
var _t = core._t;
models.Order = models.Order.extend({
initialize: function(attributes,options){
var order = models.Order.__super__.initialize.call(this,attributes,options);
if (!this.cashier)
{
this.cashier = this.pos.cashier || this.pos.user;
}
this.is_last_selected = (this.is_last_selected === undefined) ? false:this.is_last_selected;
return order;
},
finalize: function() {
var res = models.Order.__super__.finalize.call(this);
this.pos.lock_user_screen();
},
init_from_JSON: function(json) {
var user = this.get_user_by_id(json.user_id);
if (user)
this.cashier = user;
this.is_last_selected = json.is_last_selected;
models.Order.__super__.init_from_JSON.call(this, json);
},
export_as_JSON: function() {
var res = models.Order.__super__.export_as_JSON.call(this);
if (this.cashier)
res.user_id = this.cashier.id ;
if(this.pos && this.pos.get_cashier())
res.user_id = this.pos.get_cashier().id ;
res.is_last_selected = this.is_last_selected;
return res;
},
get_user_by_id: function(id) {
var users = this.pos.users;
for (var i = 0; i < users.length; i++) {
var user = users[i];
if (user.id == id)
return user;
}
},
});
models.PosModel = models.PosModel.extend({
initialize: function(session, attributes) {
models.PosModel.__super__.initialize.call(this, session, attributes);
var self = this;
alert(JSON.stringify(attributes.pos));
this.ready.then(function(){
if (self.config.auto_push_order)
self.config.iface_precompute_cash = true;
});
},
is_locked: function(){
if (
this.gui.current_popup
&& this.gui.current_popup.template == 'PasswordPinPopupWidget'
){
return true;
}
return false;
},
unlock: function(){
if (this.is_locked()){
this.gui.close_popup();
}
},
lock_user_screen: function(){
var self = this;
if (!this.config.lock_users) return;
this.gui.show_popup('passwordPin',{
'title': _t('Insert password or scan your barcode'),
});
},
get_last_order: function(){
var orders = this.get_order_list();
for (var i = 0; i < orders.length; i++) {
if (orders[i].is_last_selected) {
return orders[i];
}
}
return null;
},
set_last_order: function(order){
var orders = this.get_order_list();
for (var i = 0; i < orders.length; i++) {
if (orders[i].uid == order.uid) {
orders[i].is_last_selected = true;
}else{
orders[i].is_last_selected = false;
}
}
return null;
},
set_order: function(order){
models.PosModel.__super__.set_order.call(this, order);
this.set_last_order(order);
},
get_order_list: function(){
var orders = models.PosModel.__super__.get_order_list.call(this);
var c_orders = [];
var cashier = this.cashier || this.user;
for (var i = 0; i < orders.length; i++) {
if (cashier && orders[i].cashier.id === cashier.id) {
c_orders.push(orders[i]);
}
}
return c_orders;
},
switch_order: function(){
var self = this;
if(self.pos)
{
}
else
{
alert("self.pos is null");
}
if(self !== undefined && self != null && self.pos !== undefined && self.pos.currency != null)
{
alert("in switch order");
//console.log(this.pos.currency);
if (!self.config.lock_users) return;
var user = self.pos.get_cashier() || self.user;
var orders = self.get_order_list();
var last_order = self.get_last_order() || orders[0];
if (orders.length) {
self.set_order(last_order);
}
else {
self.add_new_order();
}
}
},
set_cashier: function(user){
models.PosModel.__super__.set_cashier.call(this,user);
if(this.pos)
{
alert("this.pos is not null in set_cashier");
}
else
{
alert("this.pos is null in set_cashier");
}
this.switch_order(this);
if (!this.table && this.config.iface_floorplan)
this.set_table(null);
},
});
return models;
});
the web page shows this.pos is null. and this.currency is null.
i found the solution by adding:
this.pos = this;
inside initialize function of PosModel.
I have noticed that when using google.maps location you can track the location of your car or walking very closely. Yet when I try this of code in javascript:
navigator.geolocation.getCurrentPosition(
success,
error, {
maximumAge: 600000,
timeout: 10000,
enableHighAccuracy: true
});
It returns success with an accuracy of 800m --> 1200m (meters) I must be totally wrong on how to accurately track location in javascript. I will be using window.setInterval( to update the position continuously! Thanks everyone.
Use watchPosition() instead of repeatedly calling getCurrentPosition().
You can also use position.coords.accuracy to decide if the reading is accurate enough for you to use. The value is in meters and can be thought of as a radius of a circle and you're in there somewhere.
If you want to spend the time/effort you can also provide a sophisticated filter and sanity checker such as: -
'use strict';
/* identification division.
* program-id. TravelManagerPolyfill.
* author. Richard Maher.
* version. 1.0
*/
// Simple polyfill paper-tiger
ServiceWorkerRegistration.prototype.travelManager
= new BackgroundGeolocation();
/*
* This module simulates the work that needs to be done by the UA or
* SW daemon in order to facilitate background geolocation on the web.
*
* Each client even in the same scope will have their own TravelManager
* object/registration. With individual "options" configuration.
*
* TODO: Ask someone why registrations just can't be done in Ultimate
* Web App manifests?
*
* NB: Please treat this as a black-box and concentrate on what it does
* and not how it does it. Most of the magic will be in the UA. Some of
* the proposed throttle functionality may be duplicating existing UA
* functionality and therefore be redundant.
*/
function BackgroundGeolocation()
{
const EARTH_RADIUS = 6371000;
const SHUSH = 60000;
const NUMBER = "number";
const STRING = "string";
const BOOLEAN = "boolean";
const DATE = "date";
const MIN_DATE = -864*Math.pow(10,13);
const MAX_DATE = 864*Math.pow(10,13);
const MSECS = 1000;
const TIMEOUT_IS_USELESS
= Number.POSITIVE_INFINITY;
const toRad = function(num){return num*Math.PI/180};
const DEFAULT_OPTIONS =
{
"maxSilence" : 900000,
"minSilence" : 4000,
"maxSnail" : 15000,
"minProgress": 15,
"maxAge" : 0,
"accurate" : true,
"dropDodgy" : false
}
var options = DEFAULT_OPTIONS;
var lastOptions = options;
var seqNum = 0;
var lastPos, trackerId, loiterTimer, deltaMetres, lastDrop,
replayTimer, timeDetent, spaceDetent, loiterDetent,
maxLocAge, accurate, maxSilence, watchCnt, acceptCnt,
lastUpdate, kept, broken, currActive, regId, subscription,
dropDodgy, mostConfident, leastConfident, recalibrateTimer
;
var OptionElem = function(name,valType,minValue,maxValue,shift)
{
this.name = name;
this.type = valType;
this.minValue = minValue;
this.maxValue = maxValue;
this.shift = shift;
return this;
}
var optionRules =
[
new OptionElem("maxSilence", NUMBER, 0,Number.POSITIVE_INFINITY,MSECS),
new OptionElem("minSilence", NUMBER, 0,SHUSH,MSECS),
new OptionElem("maxSnail", NUMBER, 0,Number.POSITIVE_INFINITY,MSECS),
new OptionElem("maxAge", NUMBER, 0,Number.POSITIVE_INFINITY,MSECS),
new OptionElem("minProgress",NUMBER, 0,Number.POSITIVE_INFINITY,1),
new OptionElem("accurate", BOOLEAN,0,1,0),
new OptionElem("dropDodgy", BOOLEAN,0,1,0),
];
var subscribe =
function(userOptions)
{
if(!navigator.geolocation)
return Promise.reject(new Error("Unsupported browser - No Geolocation support"));
if (regId) return Promise.resolve(subscription);
if (userOptions != undefined) {
parseOptions(userOptions);
lastOptions = options;
}
regId = ++seqNum;
subscription =
{
getId: function(){return regId},
setOptions: setOptions,
unsubscribe: unsubscribe
}
return new Promise((resolve, reject) =>
{
kept = resolve;
broken = reject;
getCurrent(startPosition, startError);
});
}
var getCurrent =
function(currentSuccess, currentFailure)
{
navigator.geolocation.getCurrentPosition(currentSuccess, currentFailure ,{
maximumAge: Number.POSITIVE_INFINITY,
timeout: TIMEOUT_IS_USELESS
});
}
var startPosition =
function(position)
{
kept(subscription);
kept = null;
broken = null;
fireTravelEvent({
"cmd":"start",
"position": pos4Net(position)
},function(){
lastPos = position;
watchCnt = 1;
acceptCnt = 0;
mostConfident = position.coords.accuracy.toFixed();
leastConfident = mostConfident;
startWatch();
loiterTimer = setTimeout(loiterLimit, loiterDetent);
})
}
var startError =
function(positionError){
regId = null;
broken(positionError);
broken = null;
kept = null;
}
var startWatch =
function()
{
trackerId = navigator.geolocation.watchPosition(filterLocation, locError, {
enableHighAccuracy: accurate,
maximumAge: maxLocAge,
timeout: TIMEOUT_IS_USELESS
});
recalibrateTimer = setTimeout(recalibrate, maxSilence);
}
var stopWatch =
function()
{
navigator.geolocation.clearWatch(trackerId);
clearTimeout(recalibrateTimer);
trackerId = null;
recalibrateTimer = null;
}
var fireTravelEvent =
function(msg,callback)
{
try {
currActive.postMessage(msg);
console.log("Msg Sent to SW");
if (callback) callback();
} catch (e) {
if (e.name == "InvalidStateError" || e.name == "TypeError") {
navigator.serviceWorker.ready
.then(reg => {
currActive = reg.active;
fireTravelEvent(msg, callback)})
} else {
throw e;
}
}
}
var vetOption = function(userOption,rule)
{
var result;
switch(rule.type){
case NUMBER:
case DATE:
result = Number(userOption*rule.shift);
if (Number.isNaN(result) || result < rule.minValue || result > rule.maxValue) {
result = null;
}
break;
case STRING:
result = String(userOption);
if (typeof result != STRING){
result = null;
}
break;
case BOOLEAN:
result = Boolean(userOption);
if (typeof result != BOOLEAN){
result = null;
}
break;
default:
console.log("Invalid data type '"+rule.type+"'")
}
if (result == null) {
console.log("Invalid parameter '"+rule.name+"'")
}
return result;
}
var setOptions =
function(userOptions)
{
parseOptions(userOptions);
for (var x in options) {
if (options[x] != lastOptions[x]){
stopWatch();
startWatch();
break;
}
}
lastOptions = options;
}
var parseOptions =
function(userOptions)
{
var rawOptions = userOptions || {};
for (var i=0; i<optionRules.length; i++){
var currOption = optionRules[i].name;
if ((currOption in rawOptions)){
var currentTarget = vetOption(rawOptions[currOption], optionRules[i]);
if (currentTarget){
options[currOption] = currentTarget;
} else {
console.log("Invalid option "+optionRules[i].name+" value = " + rawOptions[currOption])
}
}
}
for (var opt in rawOptions){
if (!optionRules.some(function(rule){return rule.name==this},opt)){
console.log("Unknown option '"+opt+"'")
}
}
timeDetent = options.minSilence;
maxSilence = options.maxSilence;
spaceDetent = options.minProgress;
loiterDetent = options.maxSnail;
maxLocAge = options.maxAge;
accurate = options.accurate;
dropDodgy = options.dropDodgy;
if (timeDetent > maxSilence){
timeDetent = maxSilence;
console.log("Minimum Silence overridden by Maximum Silence");
}
if (loiterDetent > maxSilence){
loiterDetent = maxSilence;
console.log("Maximum Snail overridden by Maximum Silence");
}
if (loiterDetent < timeDetent) {
loiterDetent = timeDetent;
console.log("Maximum Snail overridden by Minimum Silence");
}
return;
}
var locError =
function(error)
{
fireTravelEvent({"cmd":"error","error": {
"code": error.code,
"message": error.message
}});
}
var recalibrate =
function()
{
console.log("recalibrating");
stopWatch();
startWatch();
mostConfident = leastConfident;
}
var filterLocation =
function(position)
{
watchCnt++;
if (position.timestamp <= lastPos.timestamp) return;
var currTime = Date.now();
var updateDelta = currTime - lastUpdate;
var dropping = (updateDelta < timeDetent);
deltaMetres = calculateDistance(
position.coords.latitude,
position.coords.longitude,
lastPos.coords.latitude,
lastPos.coords.longitude)
if (deltaMetres.toFixed() < spaceDetent) return;
if (dropping) {
lastDrop = position;
if (!replayTimer)
replayTimer = setTimeout(moveReplay, (timeDetent - updateDelta));
return;
}
var giveOrTake = position.coords.accuracy.toFixed();
if (giveOrTake > leastConfident) leastConfident = giveOrTake;
if (giveOrTake < mostConfident ) mostConfident = giveOrTake;
if (dropDodgy &&
giveOrTake > spaceDetent &&
giveOrTake > deltaMetres &&
giveOrTake > (2*mostConfident)) {
return; // Not legit. Dicky phone tower or access point?
}
acceptCnt++;
clearTimeout(recalibrateTimer);
recalibrateTimer = setTimeout(recalibrate, maxSilence);
clearTimeout(loiterTimer);
loiterTimer = setTimeout(loiterLimit, loiterDetent);
fireTravelEvent({
"cmd":"travel",
"position":pos4Net(position)
})
lastPos = position;
lastUpdate = currTime;
}
var loiterLimit =
function()
{
loiterTimer = null;
fireTravelEvent({"cmd":"loiter","position":pos4Net(lastPos)})
}
var moveReplay =
function()
{
replayTimer = null;
if ((lastDrop.timestamp > lastPos.timestamp)) {
filterLocation(lastDrop);
}
}
var calculateDistance =
function(lat1, lon1, lat2, lon2){
var dLat = toRad(lat2 - lat1);
var dLon = toRad(lon2 - lon1);
var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(toRad(lat1)) *
Math.cos(toRad(lat2)) * Math.sin(dLon / 2) * Math.sin(dLon / 2);
var distance = EARTH_RADIUS * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
return distance;
}
var unsubscribe =
function(cancel)
{
if (!regId) return Promise.resolve(false);
stopWatch();
if (loiterTimer) {
clearTimeout(loiterTimer);
loiterTimer = null;
}
if (replayTimer) {
clearTimeout(replayTimer);
replayTimer = null;
}
regId = null;
lastUpdate = 0;
if (cancel) {
return Promise.resolve(true);
} else {
return new Promise((resolve, reject) =>
{
kept = resolve;
broken = reject;
getCurrent(endPosition, endError);
});
}
}
var endPosition =
function(position)
{
fireTravelEvent({
"cmd":"end",
"position":pos4Net(position)
})
kept(true);
kept = null;
broken = null;
}
var endError =
function(error)
{
fireTravelEvent({"cmd":"error","error": {
"code": error.code,
"message": error.message
}});
broken(false);
broken = null;
kept = null;
}
var pos4Net =
function(pos)
{
return {
coords: {
latitude: pos.coords.latitude,
longitude: pos.coords.longitude,
accuracy: pos.coords.accuracy.toFixed()
},
timestamp: pos.timestamp
}
}
return {subscribe: subscribe};
}
I would like to send an XML string as POST from javascript to server. The XML has this structure:
<?xml version="1.0" encoding="UTF-8"?>
<Devices>
<Device>
<Id>212121</Id>
<Accuracy>3</Accuracy>
<BatteryVolts>12.34</BatteryVolts>
</Device>
<Device>
<Id>212122</Id>
<Accuracy>5</Accuracy>
<BatteryVolts>12.14</BatteryVolts>
</Device>
</Devices>
In javascript I use:
var dd = '<?xml version="1.0" encoding="UTF-8"?>< ... all xml goes here '
$.ajax({
async: true,
type: "POST",
data: dd,
contentType: "application/x-www-form-urlencoded",
dataType: "xml",
url: 'api/deviceapi',
success: function (data) { var ok= 1; },
error: function (xhr) { var ok = 0; }
});
In the controller:
public int Post(object message)
{//parse message ...
return 1;
}
Once I get the xml into the controller I can parse it, no problem. Please help, thank you!
var defineClass = function () {
var inheritance = function inheritance() { };
return function defineClass(data) {
var classname = data.name,
superclass = data.extend || Object,
constructor = data.construct || function () { },
methods = data.methods || {},
statics = data.statics || {},
borrows,
provides;
if (!data.borrows) {
borrows = [];
}
else {
if (data.borrows instanceof Array) {
borrows = data.borrows;
}
else {
borrows = [data.borrows];
};
};
if (!data.provides) {
provides = [];
}
else {
if (data.provides instanceof Array) {
provides = data.provides;
}
else {
provides = [data.provides];
};
};
inheritance.prototype = superclass.prototype;
var proto = new inheritance();
for (var i = 0; i < borrows.length; i++) {
var c = borrows[i];
for (var p in c.prototype) {
if (typeof c.prototype[p] != "function") continue;
proto[p] = c.prototype[p];
}
}
for (var p in methods) {
proto[p] = methods[p];
};
proto.constructor = constructor;
constructor.superclass = superclass.prototype;
if (classname) {
proto.classname = classname;
};
for (var i = 0; i < provides.length; i++) {
var c = provides[i];
for (var p in c.prototype) {
if (typeof c.prototype[p] != "function") {
continue;
};
if (p == "constructor" || p == "superclass") {
continue;
};
if (p in proto && typeof proto[p] == "function" && proto[p].length == c.prototype[p].length) {
continue;
};
throw new Error("Class " + classname + " are not provided method " + c.classname + "." + p);
};
};
constructor.prototype = proto;
for (var p in statics) {
constructor[p] = statics[p];
};
return constructor;
}
}();
var EndPoint = (function () {
return defineClass({
name: "EndPoint",
construct: function (urlObj) {
var myUrl,
myScheme,
myDefaultScheme = "http",
myLogin,
myPassword,
myHost,
myDefaultHost = "localhost",
myIP,
myDefaultIP = "127.0.0.1",
myPort,
myDefaultPort = "80",
myPath,
myDefaultPath = "/",
myOptions,
myAnchor;
var self = this;
var parse_url = /^(?:([A-Za-z]+):)?(\/{0,3})(?:([A-Za-z]+):([A-Za-z]+)#)?([0-9.\-A-Za-z]+)(?::(\d+))?(?:\/([^?#]*))?(?:\?([^#]*))?(?:#(.*))?$/;
var result = parse_url.exec(urlObj);
var names = ['url', 'scheme', 'slash', 'login', 'password', 'host', 'port', 'path', 'query', 'hash'];
var i;
for (i = 0; i < names.length; i += 1) {
switch (names[i]) {
case 'url':
myUrl = result[i];
break;
case 'scheme':
myScheme = result[i];
break;
case 'slash':
break;
case 'login':
myLogin = result[i];
break;
case 'password':
myPassword = result[i];
break;
case 'host':
myHost = result[i];
break;
case 'port':
myPort = result[i];
break;
case 'path':
myPath = result[i];
break;
case 'query':
myOptions = result[i];
break;
case 'hash':
myAnchor = result[i];
break;
}
}
this.scheme = myScheme;
this.login = myLogin;
this.password = myPassword;
this.host = myHost;
this.ip = myIP;
this.port = myPort;
this.path = myPath;
this.options = myOptions;
this.anchor = myAnchor;
this.url = myUrl;
},
methods: {
ValidateIP: function (ip) {
return /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/.test(ip);
},
ValidateUrl: function (url) {
return /^(http|ftp|https):\/\/[\w-]+(\.[\w-]+)+([\w.,#?^=%&:\/~+#-]*[\w#?^=%&\/~+#-])?/.test(url);
},
ValidateShortUrl: function (url) {
if (/^\/\/[\w-]+(\.[\w-]+)+([\w.,#?^=%&:\/~+#-]*[\w#?^=%&\/~+#-])?/.test(url)) {
return true;
};
if (/^[\w-]+(\.[\w-]+)+([\w.,#?^=%&:\/~+#-]*[\w#?^=%&\/~+#-])?/.test(url)) {
return true;
}
return false;
}
}
})
}());
var QueryType = function QueryType() {
if (!(this instanceof QueryType)) {
return new QueryType(arguments[0]);
};
this.endPoint = arguments[0]["endPoint"];
this.envelope = arguments[0]["envelope"];
this.type = arguments[0]["type"];
this.headers = arguments[0]["headers"];
this.callback_success = arguments[0]["callback_success"];
this.callback_failure = arguments[0]["callback_failure"];
this.timeout = arguments[0]["timeout"];
this.username = arguments[0]["username"];
this.password = arguments[0]["password"];
};
var TaskManager = function () {
if (!(this instanceof TaskManager)) {
return new TaskManager();
};
var instance;
TaskManager = function () {
return instance;
};
TaskManager.prototype = this;
instance = new TaskManager();
instance.constructor = TaskManager;
function Request() {
if (!(this instanceof Request)) {
return new Request();
};
var instance;
Request = function () {
return instance;
};
Request.prototype = this;
instance = new Request();
instance.constructor = Request;
var httpRequest = new XMLHttpRequest();
instance.send = function (query, callback, errorHandler) {
try { netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead"); } catch (e) { };
httpRequest.abort();
if ((query.username == undefined) || (query.password == undefined)) {
httpRequest.open(query.type, query.endPoint.url, true);
}
else {
httpRequest.open(query.type, query.endPoint.url, true, query.username, query.password);
};
if (query.headers != null) {
for (var i = 0; i < query.headers.length; ++i) {
httpRequest.setRequestHeader(query.headers[i][0], query.headers[i][1]);
}
}
else {
httpRequest.setRequestHeader("SOAPAction", '""');
httpRequest.setRequestHeader("Content-Type", "text/xml");
};
httpRequest.onreadystatechange = function () {
if (httpRequest.readyState == 4) {
if (httpRequest.status == 200) {
callback(httpRequest.responseText);
}
else {
if (errorHandler) {
errorHandler(httpRequest.status, httpRequest.statusText);
}
else {
callback(null);
};
};
};
};
switch (query.type) {
case "POST":
httpRequest.send(query.envelope);
break;
case "GET":
httpRequest.send(null);
break;
}
};
instance.cancel = function () {
httpRequest.abort();
};
return instance;
};
var httpHandler = Request();
var queryQueue = [];
var timeoutID = -1;
var startedFlag = false;
var currentQuery = null;
var start = function () {
if (queryQueue.length > 0) {
startedFlag = true;
currentQuery = queryQueue.shift();
httpHandler.send(currentQuery,
function (resp) {
if (timeoutID >= 0) {
clearTimeout(timeoutID);
timeoutID = -1;
};
currentQuery.callback_success(resp);
start();
},
function (resp) {
if (timeoutID >= 0) {
clearTimeout(timeoutID);
timeoutID = -1;
};
currentQuery.callback_failure(resp);
start();
}
);
}
else {
startedFlag = false;
};
};
instance.add = function (req) {
if (req instanceof QueryType) {
queryQueue.push(req);
if (!startedFlag) {
start();
};
return true;
}
else {
return false;
};
};
instance.stopCurrent = function () {
httpHandler.cancel();
timeoutID = -1;
if ((currentQuery.callback_failure != undefined) && (currentQuery.callback_failure != null)) {
currentQuery.callback_failure("<comm_error>COMM TIMEOUT</comm_error>");
};
start();
};
return instance;
};
//to send a request it must be
TaskManager().add(
new QueryType({
"endPoint": new EndPoint("http://***.***.***.***/api/deviceapi"),
"type": "POST",
"envelope": '<?xml version="1.0" encoding="UTF-8"?>< ... all xml goes here ',
"callback_success": function (wResponse) { /* here we get a response from the server */ },
"callback_failure": function (status, statusText) { },
"timeout": 60
})
);
I cannot figure out why I keep getting this error:
Uncaught TypeError: Cannot read property 'options' of null
getFSREPlist
(anonymous function)
The error is referencing this line of code (21):
document.getElementById(elementidupdate).options.length=0;
What is weird is that it was working prior to this new google map api I just put on. Also, it is pulling the country code "1" and putting it in the drop down, but not the province code "19".
Here is the on page script:
getFSREPlist('1', 'fsrep-search-province', 'CountryID', '19');getFSREPlist('19', 'fsrep-search-city', 'ProvinceID', '3'); request.send(null);
Here is the full file:
function sack(file) {
this.xmlhttp = null;
this.resetData = function () {
this.method = "POST";
this.queryStringSeparator = "?";
this.argumentSeparator = "&";
this.URLString = "";
this.encodeURIString = true;
this.execute = false;
this.element = null;
this.elementObj = null;
this.requestFile = file;
this.vars = new Object();
this.responseStatus = new Array(2);
};
this.resetFunctions = function () {
this.onLoading = function () {};
this.onLoaded = function () {};
this.onInteractive = function () {};
this.onCompletion = function () {};
this.onError = function () {};
this.onFail = function () {};
};
this.reset = function () {
this.resetFunctions();
this.resetData();
};
this.createAJAX = function () {
try {
this.xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e1) {
try {
this.xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e2) {
this.xmlhttp = null;
}
}
if (!this.xmlhttp) {
if (typeof XMLHttpRequest != "undefined") {
this.xmlhttp = new XMLHttpRequest();
} else {
this.failed = true;
}
}
};
this.setVar = function (name, value) {
this.vars[name] = Array(value, false);
};
this.encVar = function (name, value, returnvars) {
if (true == returnvars) {
return Array(encodeURIComponent(name), encodeURIComponent(value));
} else {
this.vars[encodeURIComponent(name)] = Array(encodeURIComponent(value), true);
}
}
this.processURLString = function (string, encode) {
encoded = encodeURIComponent(this.argumentSeparator);
regexp = new RegExp(this.argumentSeparator + "|" + encoded);
varArray = string.split(regexp);
for (i = 0; i < varArray.length; i++) {
urlVars = varArray[i].split("=");
if (true == encode) {
this.encVar(urlVars[0], urlVars[1]);
} else {
this.setVar(urlVars[0], urlVars[1]);
}
}
}
this.createURLString = function (urlstring) {
if (this.encodeURIString && this.URLString.length) {
this.processURLString(this.URLString, true);
}
if (urlstring) {
if (this.URLString.length) {
this.URLString += this.argumentSeparator + urlstring;
} else {
this.URLString = urlstring;
}
}
this.setVar("rndval", new Date().getTime());
urlstringtemp = new Array();
for (key in this.vars) {
if (false == this.vars[key][1] && true == this.encodeURIString) {
encoded = this.encVar(key, this.vars[key][0], true);
delete this.vars[key];
this.vars[encoded[0]] = Array(encoded[1], true);
key = encoded[0];
}
urlstringtemp[urlstringtemp.length] = key + "=" + this.vars[key][0];
}
if (urlstring) {
this.URLString += this.argumentSeparator + urlstringtemp.join(this.argumentSeparator);
} else {
this.URLString += urlstringtemp.join(this.argumentSeparator);
}
}
this.runResponse = function () {
eval(this.response);
}
this.runAJAX = function (urlstring) {
if (this.failed) {
this.onFail();
} else {
this.createURLString(urlstring);
if (this.element) {
this.elementObj = document.getElementById(this.element);
}
if (this.xmlhttp) {
var self = this;
if (this.method == "GET") {
totalurlstring = this.requestFile + this.queryStringSeparator + this.URLString;
this.xmlhttp.open(this.method, totalurlstring, true);
} else {
this.xmlhttp.open(this.method, this.requestFile, true);
try {
this.xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")
} catch (e) {}
}
this.xmlhttp.onreadystatechange = function () {
switch (self.xmlhttp.readyState) {
case 1:
self.onLoading();
break;
case 2:
self.onLoaded();
break;
case 3:
self.onInteractive();
break;
case 4:
self.response = self.xmlhttp.responseText;
self.responseXML = self.xmlhttp.responseXML;
self.responseStatus[0] = self.xmlhttp.status;
self.responseStatus[1] = self.xmlhttp.statusText;
if (self.execute) {
self.runResponse();
}
if (self.elementObj) {
elemNodeName = self.elementObj.nodeName;
elemNodeName.toLowerCase();
if (elemNodeName == "input" || elemNodeName == "select" || elemNodeName == "option" || elemNodeName == "textarea") {
self.elementObj.value = self.response;
} else {
self.elementObj.innerHTML = self.response;
}
}
if (self.responseStatus[0] == "200") {
self.onCompletion();
} else {
self.onError();
}
self.URLString = "";
break;
}
};
this.xmlhttp.send(this.URLString);
}
}
};
this.reset();
this.createAJAX();
}
var ajax = new Array();
function getFSREPlist(sel, elementidupdate, fsrepvariable, currentvalue) {
if (sel == '[object]' || sel == '[object HTMLSelectElement]') {
var FSREPID = sel.options[sel.selectedIndex].value;
} else {
var FSREPID = sel;
}
document.getElementById(elementidupdate).options.length = 0;
var index = ajax.length;
ajax[index] = new sack();
ajax[index].requestFile = 'http://www.cabcot.com/wp-content/plugins/firestorm-real-estate-plugin/search.php?' + fsrepvariable + '=' + FSREPID + '&cvalue=' + currentvalue;
ajax[index].onCompletion = function () {
ElementUpdate(index, elementidupdate)
};
ajax[index].runAJAX();
}
function ElementUpdate(index, elementidupdate) {
var obj = document.getElementById(elementidupdate);
eval(ajax[index].response);
}
You should call getFSREPlist when DOM is loaded. I ran
document.getElementById('fsrep-search-province').options.length=0
from chrome´s console. while page was still loading and caused that same error.
http://i.imgur.com/GBFizq1.png