splunk-sdk
Version:
SDK for usage with the Splunk REST API
1,555 lines (1,342 loc) • 332 kB
JavaScript
(function() {
var __exportName = 'splunkjs';
(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
// Copyright 2011 Splunk, Inc.
//
// 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.
// This file is the entry point for client-side code, so it "exports" the
// important functionality to the "window", such that others can easily
// include it.
(function(exportName) {
if (!window[exportName]) {
window[exportName] = {};
}
if (!window[exportName].UI) {
window[exportName].UI = {};
}
window[exportName].UI.Timeline = require('../ui/timeline.js');
})(__exportName);
},{"../ui/timeline.js":3}],2:[function(require,module,exports){
/*! Simple JavaScript Inheritance
* By John Resig http://ejohn.org/
* MIT Licensed.
* Inspired by base2 and Prototype
*/
(function(){
var root = exports || this;
var initializing = false;
var fnTest = (/xyz/.test(function() { return xyz; }) ? /\b_super\b/ : /.*/);
// The base Class implementation (does nothing)
root.Class = function(){};
// Create a new Class that inherits from this class
root.Class.extend = function(prop) {
var _super = this.prototype;
// Instantiate a base class (but only create the instance,
// don't run the init constructor)
initializing = true;
var prototype = new this();
initializing = false;
// Copy the properties over onto the new prototype
for (var name in prop) {
// Check if we're overwriting an existing function
prototype[name] = typeof prop[name] == "function" &&
typeof _super[name] == "function" && fnTest.test(prop[name]) ?
(function(name, fn){
return function() {
var tmp = this._super;
// Add a new ._super() method that is the same method
// but on the super-class
this._super = _super[name];
// The method only need to be bound temporarily, so we
// remove it when we're done executing
var ret = fn.apply(this, arguments);
this._super = tmp;
return ret;
};
})(name, prop[name]) :
prop[name];
}
// The dummy class constructor
function Class() {
// All construction is actually done in the init method
if ( !initializing && this.init )
this.init.apply(this, arguments);
}
// Populate our constructed prototype object
Class.prototype = prototype;
// Enforce the constructor to be what we expect
Class.constructor = Class;
// And make this class extendable
Class.extend = arguments.callee;
return Class;
};
})();
},{}],3:[function(require,module,exports){
// Copyright 2011 Splunk, Inc.
//
// 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.
(function() {
// Import the timeline code
var jg_global = require('./timeline/jg_global.js');
var time = require('./timeline/splunk_time.js');
var timeline = require('./timeline/splunk_timeline.js');
var format = require('./timeline/format.js');
var Class = require('../jquery.class').Class;
var utils = require('../utils');
var root = exports || this;
var SplunkTimeline = timeline.splunk.Timeline;
var DateTime = time.splunk.time.DateTime;
var SimpleTimeZone = time.splunk.time.SimpleTimeZone;
// Setup the exports and our timeline wrapper class
root.DateTime = DateTime;
root.SimpleTimeZone = SimpleTimeZone;
root.Timeline = Class.extend({
init: function(el) {
this.timeline = new SplunkTimeline();
this.timeline.setSeriesColor(0x73A550);
$(this.timeline.element).addClass("Timeline");
this.timeline.appendTo($(el).get(0));
// Add the external interface formatting functions
this.timeline.externalInterface.formatNumericString = format.formatNumericString;
this.timeline.externalInterface.formatNumber = format.formatNumber;
this.timeline.externalInterface.formatDate = format.formatDate;
this.timeline.externalInterface.formatTime = format.formatTime;
this.timeline.externalInterface.formatDateTime = format.formatDateTime;
this.timeline.externalInterface.formatTooltip = format.formatTooltip;
// We perform the bindings so that every function works
// properly when it is passed as a callback.
this.updateWithJSON = utils.bind(this, this.updateWithJSON);
this.updateWithXML = utils.bind(this, this.updateWithXML);
this.updateWithData = utils.bind(this, this.updateWithData);
},
updateWithJSON: function(timelineData) {
var data = {
buckets: [],
cursorTime: new DateTime(timelineData.cursor_time),
eventCount: timelineData.event_count,
earliestOffset: timelineData.earliestOffset || 0
};
if (data.cursorTime) {
data.cursorTime = data.cursorTime.toTimeZone(new SimpleTimeZone(data.earliestOffset));
}
for(var i = 0; i < timelineData.buckets.length; i++) {
var oldBucket = timelineData.buckets[i];
var newBucket = {
earliestTime: new DateTime(oldBucket.earliest_time),
duration: oldBucket.duration,
eventCount: oldBucket.total_count,
eventAvailableCount: oldBucket.available_count,
isComplete: oldBucket.is_finalized
};
if (isNaN(newBucket.duration)) {
newBucket.duration = 0;
}
if (isNaN(newBucket.earliestOffset)) {
newBucket.earliestOffset = 0;
}
if (isNaN(newBucket.latestOffset)) {
newBucket.latestOffset = 0;
}
if (newBucket.earliestTime) {
newBucket.latestTime = new DateTime(newBucket.earliestTime.getTime() + newBucket.duration);
}
if (newBucket.earliestTime) {
newBucket.earliestTime = newBucket.earliestTime.toTimeZone(new SimpleTimeZone(oldBucket.earliest_time_offset));
}
if (newBucket.latestTime) {
newBucket.latestTime = newBucket.latestTime.toTimeZone(new SimpleTimeZone(oldBucket.latest_time_offset));
}
data.buckets.push(newBucket);
}
this.timeline._updateTimelineData(data);
},
updateWithXML: function(xmlNode) {
this.timeline._parseTimelineData(xmlNode);
},
updateWithData: function(data) {
this.timeline._updateTimelineData(data);
}
});
})();
},{"../jquery.class":2,"../utils":8,"./timeline/format.js":4,"./timeline/jg_global.js":5,"./timeline/splunk_time.js":6,"./timeline/splunk_timeline.js":7}],4:[function(require,module,exports){
// Copyright 2011 Splunk, Inc.
//
// 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.
(function() {
var time = require('./splunk_time.js');
var DateTime = time.splunk.time.DateTime;
var SimpleTimeZone = time.splunk.time.SimpleTimeZone;
var formatNumber = exports.formatNumber = function(num) {
var pos = Math.abs(num);
if ((pos > 0) && ((pos < 1e-3) || (pos >= 1e9))) {
return num.toExponential(2).replace(/e/g, "E").replace(/\+/g, "");
}
var str = String(Number(num.toFixed(3)));
var dotIndex = str.indexOf(".");
if (dotIndex < 0) {
dotIndex = str.length;
}
var str2 = str.substring(dotIndex, str.length);
var i;
for (i = dotIndex - 3; i > 0; i -= 3) {
str2 = "," + str.substring(i, i + 3) + str2;
}
str2 = str.substring(0, i + 3) + str2;
return str2;
};
var formatNumericString = exports.formatNumericString = function(strSingular, strPlural, num) {
var str = (Math.abs(num) === 1) ? strSingular : strPlural;
str = str.split("%s").join(formatNumber(num));
return str;
};
var formatDate = exports.formatDate = function(time, timeZoneOffset, dateFormat) {
var date = new DateTime(time);
date = date.toTimeZone(new SimpleTimeZone(timeZoneOffset));
var monthNames = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ];
var monthShortNames = [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ];
var weekdayShortNames = [ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" ];
switch (dateFormat) {
case "EEE MMM d":
return weekdayShortNames[date.getWeekday()] + " " + monthShortNames[date.getMonth() - 1] + " " + date.getDay();
case "MMMM":
return monthNames[date.getMonth() - 1];
case "yyyy":
return String(date.getYear());
default:
return monthShortNames[date.getMonth() - 1] + " " + date.getDay() + ", " + date.getYear();
}
};
var formatTime = exports.formatTime = function(time, timeZoneOffset, timeFormat) {
var date = new DateTime(time);
date = date.toTimeZone(new SimpleTimeZone(timeZoneOffset));
var hours = date.getHours();
var minutes = date.getMinutes();
var seconds = Math.floor(date.getSeconds());
var milliseconds = Math.floor((date.getSeconds() - seconds) * 1000);
var ampm = (hours < 12) ? "AM" : "PM";
if (hours >= 12) {
hours -= 12;
}
if (hours === 0) {
hours = 12;
}
hours = ("" + hours);
minutes = (minutes < 10) ? ("0" + minutes) : ("" + minutes);
seconds = (seconds < 10) ? ("0" + seconds) : ("" + seconds);
milliseconds = (milliseconds < 100) ? (milliseconds < 10) ? ("00" + milliseconds) : ("0" + milliseconds) : ("" + milliseconds);
switch (timeFormat)
{
case "short":
return hours + ":" + minutes + " " + ampm;
case "medium":
return hours + ":" + minutes + ":" + seconds + " " + ampm;
case "long":
case "full":
return hours + ":" + minutes + ":" + seconds + "." + milliseconds + " " + ampm;
default:
if (milliseconds !== "000") {
return hours + ":" + minutes + ":" + seconds + "." + milliseconds + " " + ampm;
}
if (seconds !== "00") {
return hours + ":" + minutes + ":" + seconds + " " + ampm;
}
return hours + ":" + minutes + " " + ampm;
}
};
var formatDateTime = exports.formatDateTime = function(time, timeZoneOffset, dateFormat, timeFormat) {
return formatDate(time, timeZoneOffset, dateFormat) + " " + formatTime(time, timeZoneOffset, timeFormat);
};
var formatTooltip = exports.formatTooltip = function(earliestTime, latestTime, earliestOffset, latestOffset, eventCount) {
return formatNumericString("%s event", "%s events", eventCount) + " from " + formatDateTime(earliestTime, earliestOffset) + " to " + formatDateTime(latestTime, latestOffset);
};
})();
},{"./splunk_time.js":6}],5:[function(require,module,exports){
/**
* Global functions for defining classes and managing scope.
*
* The following functions are declared globally on the window object:
*
* jg_namespace
* jg_import
* jg_extend
* jg_static
* jg_mixin
* jg_has_mixin
* jg_delegate
*
* Copyright (c) 2011 Jason Gatt
*
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*/
(function()
{
// Private Variables
var _namespaces = {};
var _imported = {};
var _loading = {};
var _classPaths = {};
var _classInfo = {};
var _classDependencyList = [];
var _mixinCount = 0;
var _mixinDependencies = null;
var rootNamespace = exports;
var root = exports;
// Private Functions
/**
* Function for evaluating dynamically loaded scripts.
*/
var _evalScript = function(script)
{
// create local undefined vars so that script cannot access private vars
var _namespaces = undefined;
var _imported = undefined;
var _loading = undefined;
var _classPaths = undefined;
var _classInfo = undefined;
var _classDependencyList = undefined;
var _mixinCount = undefined;
var _mixinDependencies = undefined;
var _evalScript = undefined;
var _appendConstructor = undefined;
// set arguments to undefined so that script cannot access
arguments = undefined;
// eval script in context of window
eval.call(window, script);
};
/**
* Function for appending a mixin constructor to a base constructor.
*/
var _appendConstructor = function(baseConstructor, mixinConstructor)
{
var constructor = function()
{
baseConstructor.apply(this, arguments);
mixinConstructor.call(this);
};
return constructor;
};
// Global Functions
/**
* Returns a reference to the namespace corresponding to the given path. If the
* namespace doesn't exist, it is created.
*
* The optional closure function is intended to be used as a sandbox for
* defining members of the namespace. If provided, the closure function will be
* invoked in the scope of the namespace. The function will also be passed a
* reference to the namespace as a parameter. This parameter is not often
* needed, however, since it's equivalent to "this" within the closure. But for
* cases where an inner scope needs access to the namespace, it may come in
* handy.
*
* Example:
*
* <pre>
* // Declare the namespace we'll be working in.
* jg_namespace("my.stuff", function()
* {
*
* // Define a private variable only accessible within this closure.
* var myPrivateVariable = "private variable";
*
* // Define a public method at my.stuff.myPublicMethod.
* this.myPublicMethod = function()
* {
* ...
* };
*
* // Define a class at my.stuff.MyClass.
* this.MyClass = ...
*
* });
* </pre>
*
* @param path String. The dot delimited path to a namespace. An empty string
* corresponds to window. Must be non-null.
* @param closure Function. Optional. A function that will be invoked in the
* scope of the namespace.
* @return A reference to the namespace.
*/
var jg_namespace = root.jg_namespace = function(path, closure)
{
if (path == null)
throw new Error("Parameter path must be non-null.");
if (typeof path !== "string")
throw new Error("Parameter path must be a string.");
if ((closure != null) && (typeof closure !== "function"))
throw new Error("Parameter closure must be a function.");
var ns = _namespaces[path];
if (!ns)
{
var subPaths = path ? path.split(".") : [];
var subPath;
var scope;
ns = rootNamespace;
for (var i = 0, l = subPaths.length; i < l; i++)
{
subPath = subPaths[i];
scope = ns[subPath];
if (!scope)
scope = ns[subPath] = {};
ns = scope;
}
_namespaces[path] = ns;
}
if (closure)
closure.call(ns, ns);
return ns;
};
/**
* Returns a reference to the class corresponding to the given path. If the
* class is not found, it is dynamically loaded using a synchronous xhr request.
*
* By default, dynamically loaded classes must be defined in a js file located
* in a directory structure mirroring the class path. For example, the class
* definition for my.stuff.MyClass must be located in the file
* /my/stuff/MyClass.js. However, the jg_import.setClassPath method can be used
* to set different base directories for different namespaces. For example, you
* could locate the my.stuff library in a "libraries" subdirectory by calling
* jg_import.setClassPath("my.stuff", "libraries/my/stuff");
*
* Note: Some browsers do not allow local xhr requests. In order for dynamic
* class loading to function in these browsers, the files must be hosted from a
* web server.
*
* Example:
*
* <pre>
* // Set a class path for the my.stuff library.
* jg_import.setClassPath("my.stuff", "libraries/my/stuff");
*
* // Import my.stuff.MyClass as MyClass.
* var MyClass = jg_import("my.stuff.MyClass");
*
* // Create a new instance of MyClass.
* var myInstance = new MyClass();
* </pre>
*
* @param path String. The dot delimited path to a class. Must be non-null and
* non-empty.
* @return A reference to the class.
*/
var jg_import = root.jg_import = function(path)
{
if (path == null)
throw new Error("Parameter path must be non-null.");
if (typeof path !== "string")
throw new Error("Parameter path must be a string.");
if (!path)
throw new Error("Parameter path must be non-empty.");
var c = _imported[path];
if (!c)
{
if (_loading[path])
throw new Error("Recursive dependency on class " + path + ".");
var classInfo = {};
var nsIndex = path.lastIndexOf(".");
var nsPath = (nsIndex < 0) ? "" : path.substring(0, nsIndex);
var cPath = (nsIndex < 0) ? path : path.substring(nsIndex + 1);
var ns = jg_namespace(nsPath);
c = ns[cPath];
if (!c)
{
try
{
_loading[path] = true;
var filePath = jg_import.getClassPath(path) + ".js";
var script = null;
try
{
var xhr = window.ActiveXObject ? new window.ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();
xhr.open("GET", filePath, false);
xhr.send(null);
if ((xhr.status == 200) || (xhr.status == 0))
script = xhr.responseText;
}
catch (e)
{
}
if (script == null)
throw new Error("Failed to load class " + path + ".");
_evalScript(script);
c = ns[cPath];
if (!c)
throw new Error("Failed to initialize class " + path + ".");
classInfo.src = filePath;
classInfo.script = script;
}
finally
{
delete _loading[path];
}
}
classInfo.path = path;
classInfo.reference = c;
_classInfo[path] = classInfo;
_classDependencyList.push(path);
_imported[path] = c;
}
return c;
};
/**
* Sets a base directory from which to load classes for a given namespace.
*
* By default, dynamically loaded classes must be defined in a js file located
* in a directory structure mirroring the class path. For example, the class
* definition for my.stuff.MyClass must be located in the file
* /my/stuff/MyClass.js. However, the jg_import.setClassPath method can be used
* to set different base directories for different namespaces. For example, you
* could locate the my.stuff library in a "libraries" subdirectory by calling
* jg_import.setClassPath("my.stuff", "libraries/my/stuff");
*
* Note: Some browsers do not allow local xhr requests. In order for dynamic
* class loading to function in these browsers, the files must be hosted from a
* web server.
*
* Example:
*
* <pre>
* // Set a class path for the my.stuff library.
* jg_import.setClassPath("my.stuff", "libraries/my/stuff");
*
* // Import my.stuff.MyClass as MyClass.
* var MyClass = jg_import("my.stuff.MyClass");
*
* // Create a new instance of MyClass.
* var myInstance = new MyClass();
* </pre>
*
* @param path String. The dot delimited path to a namespace. An empty string
* will set a default directory for all namespaces that don't have an explicit
* directory assigned. Must be non-null.
* @param dir String. The uri path to a directory. An empty string corresponds
* to the current directory. Must be non-null.
*/
jg_import.setClassPath = function(path, dir)
{
if (path == null)
throw new Error("Parameter path must be non-null.");
if (typeof path !== "string")
throw new Error("Parameter path must be a string.");
if (dir == null)
throw new Error("Parameter dir must be non-null.");
if (typeof dir !== "string")
throw new Error("Parameter dir must be a string.");
_classPaths[path] = dir;
};
/**
* Gets the base directory from which classes are loaded for a given namespace.
* This reflects the class paths that have been set via jg_import.setClassPath.
*
* Example:
*
* <pre>
* // Set a class path for the my.stuff library.
* jg_import.setClassPath("my.stuff", "libraries/my/stuff");
*
* // Get the class path for the my.stuff.morestuff library.
* // This will be "libraries/my/stuff/morestuff".
* var dir = jg_import.getClassPath("my.stuff.morestuff");
* </pre>
*
* @param path String. The dot delimited path to a namespace. An empty string
* will get the default directory for all namespaces that don't have an explicit
* directory assigned. Must be non-null.
* @return A String corresponding to the base directory path.
*/
jg_import.getClassPath = function(path)
{
if (path == null)
throw new Error("Parameter path must be non-null.");
if (typeof path !== "string")
throw new Error("Parameter path must be a string.");
var classPathList = [];
var classPath;
for (classPath in _classPaths)
{
if (_classPaths.hasOwnProperty(classPath))
classPathList.push(classPath);
}
classPathList.sort();
for (var i = classPathList.length - 1; i >= 0; i--)
{
classPath = classPathList[i];
if (path.substring(0, classPath.length) === classPath)
return _classPaths[classPath] + path.substring(classPath.length).replace(/\./g, "/");
}
return path.replace(/\./g, "/");
};
/**
* Returns information for either an individual class or all classes imported
* with jg_import. If a path is given, returns information for the class
* corresponding to the given path. If the class is not found, returns null. If
* no path is given, returns a list of information for all imported classes. The
* list is ordered by class dependency, so that classes with dependencies on
* other classes appear after those classes in the list.
*
* The information returned for each class includes, at a minimum, the dot
* delimited path to the class and a reference to the class. If the class was
* dynamically loaded, the information also includes the src path to the loaded
* file and the raw script.
*
* Example:
*
* <pre>
* // Write a list of all imported classes to the console.
* var classInfoList = jg_import.getClassInfo();
* for (var i = 0, l = classInfoList.length; i < l; i++)
* console.log(classInfoList[i].path);
* </pre>
*
* @param path String. Optional. The dot delimited path to a class.
* @return An Object or an Array of Objects of the form
* { path, reference, src, script }.
*/
jg_import.getClassInfo = function(path)
{
if ((path != null) && (typeof path !== "string"))
throw new Error("Parameter path must be a string.");
if (!path)
{
var classInfoList = [];
for (var i = 0, l = _classDependencyList.length; i < l; i++)
classInfoList.push(jg_import.getClassInfo(_classDependencyList[i]));
return classInfoList;
}
var classInfo = _classInfo[path];
if (!classInfo)
return null;
var classInfo2 = {};
classInfo2.path = classInfo.path;
classInfo2.reference = classInfo.reference;
if (classInfo.src != null)
classInfo2.src = classInfo.src;
if (classInfo.script != null)
classInfo2.script = classInfo.script;
return classInfo2;
};
/**
* Creates a new class that derives from the given baseClass, using standard
* prototype inheritance.
*
* The optional closure function is intended to be used as a sandbox for
* defining members of the new class. If provided, the closure function will be
* invoked in the scope of the new class's prototype. The function will also be
* passed a reference to the new class, a reference to the baseClass's
* prototype, and a reference to the new class's prototype as parameters. The
* last parameter is not often needed, however, since it's equivalent to "this"
* within the closure. But for cases where an inner scope needs access to the
* new class's prototype, it may come in handy.
*
* Example:
*
* <pre>
* // Declare the namespace we'll be working in.
* jg_namespace("my.stuff", function()
* {
*
* // Import my.stuff.MyBaseClass as MyBaseClass.
* var MyBaseClass = jg_import("my.stuff.MyBaseClass");
*
* // Define a class at my.stuff.MyClass that derives from MyBaseClass. The
* // closure receives a reference to MyClass and a reference to
* // MyBaseClass.prototype. By convention, we name these "MyClass" (same
* // name as the class) and "base", respectively. The scope of the closure
* // is MyClass.prototype.
* this.MyClass = jg_extend(MyBaseClass, function(MyClass, base)
* {
*
* // Define a private static variable only accessible within this
* // closure.
* var myPrivateStaticVariable = "private static variable";
*
* // Define a public static method.
* MyClass.myPublicStaticMethod = function()
* {
* ...
* };
*
* // Define a public instance property. Avoid assigning mutable objects
* // to instance properties during definition. Initialize them in the
* // constructor instead.
* this.myPublicProperty = null;
*
* // Define a constructor for instances of MyClass, recursively calling
* // the base constructor. If a constructor is not defined, the base
* // constructor will be called automatically. Here, we also initialize
* // myPublicProperty.
* this.constructor = function(arg1, arg2)
* {
* base.constructor.call(this, arg1, arg2);
* this.myPublicProperty = [ 1, 2, 3 ];
* ...
* };
*
* // Define a public instance method.
* this.myPublicMethod = function()
* {
* ...
* };
*
* // Override an instance method defined in MyBaseClass, recursively
* // calling the base implementation.
* this.myBaseMethod = function(arg1, arg2)
* {
* base.myBaseMethod.call(this, arg1, arg2);
* ...
* };
*
* });
*
* });
* </pre>
*
* @param baseClass Function. The base class from which to derive a new class.
* Must be non-null.
* @param closure Function. Optional. A function that will be invoked in the
* scope of the new class's prototype.
* @return A reference to the new class.
*/
var jg_extend = root.jg_extend = function(baseClass, closure)
{
if (baseClass == null)
throw new Error("Parameter baseClass must be non-null.");
if (typeof baseClass !== "function")
throw new Error("Parameter baseClass must be a class.");
if ((closure != null) && (typeof closure !== "function"))
throw new Error("Parameter closure must be a function.");
var constructor = baseClass;
var base = baseClass.prototype;
baseClass = function(){};
baseClass.prototype = base;
var c = function()
{
constructor.apply(this, arguments);
};
var proto = c.prototype = new baseClass();
proto.constructor = c;
if (closure)
{
closure.call(proto, c, base, proto);
if (c.prototype !== proto)
throw new Error("Class member \"prototype\" cannot be overridden.");
if (proto.constructor !== c)
{
if (typeof proto.constructor !== "function")
throw new Error("Instance member \"constructor\" must be a function.");
constructor = proto.constructor;
proto.constructor = c;
}
}
return c;
};
/**
* Creates a new static or mixin class using the same conventions as jg_extend,
* but results in a simple Object instead of a Function with a prototype.
*
* The optional closure function is intended to be used as a sandbox for
* defining members of the new class. If provided, the closure function will be
* invoked in the scope of the new class. The function will also be passed a
* reference to the new class as a parameter.
*
* Example 1 - defining a static class:
*
* <pre>
* // Declare the namespace we'll be working in.
* jg_namespace("my.stuff", function()
* {
*
* // Define a static class at my.stuff.MyStaticClass.
* this.MyStaticClass = jg_static(function(MyStaticClass)
* {
*
* // Define a public static method. By convention, we define static
* // members using the class reference passed to the closure, since
* // this mirrors the way static members are defined when using
* // jg_extend.
* MyStaticClass.myPublicStaticMethod = function()
* {
* ...
* };
*
* });
*
* });
* </pre>
*
* Example 2 - defining a mixin class:
*
* <pre>
* // Declare the namespace we'll be working in.
* jg_namespace("my.stuff", function()
* {
*
* // Define a mixin class at my.stuff.MyMixin.
* this.MyMixin = jg_static(function(MyMixin)
* {
*
* // Define a public mixin method. By convention, we define mixin
* // members using "this", since this mirrors the way instance members
* // are defined when using jg_extend.
* this.myPublicMixinMethod = function()
* {
* ...
* };
*
* });
*
* });
* </pre>
*
* @param closure Function. Optional. A function that will be invoked in the
* scope of the new class.
* @return A reference to the new class.
*/
var jg_static = root.jg_static = function(closure)
{
if ((closure != null) && (typeof closure !== "function"))
throw new Error("Parameter closure must be a function.");
var c = {};
if (closure)
closure.call(c, c);
return c;
};
/**
* Copies members from a source object to a target object, returning a new
* prototype object that encapsulates the resulting state of the target. The
* source members "mixin" and "constructor" and members that begin with double
* underscore characters ("__") are not copied to the target object. Members
* that already exist in the target object are overwritten. Subsequent calls to
* this method with the same target and source objects will be ignored.
*
* This method is intended for copying mixin class members to a target class's
* prototype. The returned prototype object extends the target's base prototype
* and contains all the members that are currently mixed into the target. It can
* be used in place of references to the base prototype to override both
* inherited instance members and newly mixed in members.
*
* The source member "mixin" is intended to be a function for implementing more
* advanced mixin classes. It can be used to enforce a specific target type,
* intelligently override existing target members, or recursively apply other
* required mixin classes to the target. If present on the source object, the
* mixin function will be invoked in the scope of the target. The function will
* also be passed a base prototype object and a reference to the target as
* parameters. The last parameter is not often needed, however, since it's
* equivalent to "this" within the function. But for cases where an inner scope
* needs access to the target, it may come in handy. The mixin function is
* called before any other members are copied from the source to the target.
*
* The source member "constructor" is intended to be a function for initializing
* the mixin on an instance of the target class. If provided on the source
* object, it should be implemented as a default constructor that takes no
* arguments. The constructor function should not be called directly. Instead,
* the returned prototype object contains its own constructor function that
* automatically invokes the constructors for the source object, the given base
* prototype object, and any other objects that may have been recursively mixed
* into the target. The prototype constructor should be called from the
* constructor of a target class or manually invoked on a target instance. Any
* arguments passed to the prototype constructor are forwarded to the base
* prototype constructor.
*
* Example 1 - defining an advanced mixin class that implements the "mixin" and
* "constructor" members:
*
* <pre>
* // Declare the namespace we'll be working in.
* jg_namespace("my.stuff", function()
* {
*
* // Import MyBaseClass and MyBaseMixin.
* var MyBaseClass = jg_import("my.stuff.MyBaseClass");
* var MyBaseMixin = jg_import("my.stuff.MyBaseMixin");
*
* // Define a mixin class at my.stuff.MyMixin.
* this.MyMixin = jg_static(function(MyMixin)
* {
*
* // Define the mixin function to enforce a target type of MyBaseClass,
* // recursively apply MyBaseMixin to the target, and override a public
* // method of the base class.
* this.mixin = function(base)
* {
* if (!(this instanceof MyBaseClass))
* throw new Error("Mixin target must be an instance of my.stuff.MyBaseClass.");
*
* base = jg_mixin(this, MyBaseMixin, base);
*
* this.myPublicMethod = function()
* {
* base.myPublicMethod.call(this);
* ...
* };
* };
*
* // Define the constructor function to initialize MyMixin on the
* // target.
* this.constructor = function()
* {
* ...
* };
*
* });
*
* });
* </pre>
*
* Example 2 - applying the mixin defined above to a class:
*
* <pre>
* // Declare the namespace we'll be working in.
* jg_namespace("my.stuff", function()
* {
*
* // Import MyBaseClass and MyMixin.
* var MyBaseClass = jg_import("my.stuff.MyBaseClass");
* var MyMixin = jg_import("my.stuff.MyMixin");
*
* // Define a class at my.stuff.MyClass that derives from MyBaseClass.
* this.MyClass = jg_extend(MyBaseClass, function(MyClass, base)
* {
*
* // Copy members from MyMixin to this (MyClass.prototype).
* base = jg_mixin(this, MyMixin, base);
*
* // Define a constructor for instances of MyClass, recursively calling
* // the base constructor.
* this.constructor = function(arg1, arg2)
* {
* base.constructor.call(this, arg1, arg2);
* ...
* };
*
* });
*
* });
* </pre>
*
* Example 3 - applying the mixin defined above to an existing object instance:
*
* <pre>
* // Copy members from MyMixin to myInstance.
* var mixin = jg_mixin(myInstance, MyMixin);
*
* // Manually invoke the mixin constructor on myInstance.
* mixin.constructor.call(myInstance);
* </pre>
*
* @param target Object. The target object to copy members to. Must be non-null.
* @param source Object. The source object to copy members from. Must be
* non-null.
* @param base Object. Optional. A base prototype object whose constructor
* function should be called before the constructors of the source object or any
* recursively mixed in objects.
* @return The resulting prototype object. If the source object was already
* mixed into the target object via a previous call to jg_mixin, the given base
* prototype object is returned.
*/
var jg_mixin = root.jg_mixin = function(target, source, base)
{
if (target == null)
throw new Error("Parameter target must be non-null.");
if (source == null)
throw new Error("Parameter source must be non-null.");
var id = source.__jg_mixin_id;
if (!id)
id = source.__jg_mixin_id = "#" + (++_mixinCount);
id = "__jg_mixin_has_" + id;
if (target[id])
return base;
var baseConstructor = ((base != null) && base.hasOwnProperty("constructor") && (typeof base.constructor === "function")) ? base.constructor : function(){};
var baseClass = function(){};
baseClass.prototype = target.__proto__ || Object.prototype;
base = new baseClass();
base.constructor = baseConstructor;
var member;
var mixin = source.mixin;
if ((mixin != null) && (typeof mixin === "function"))
{
var mixinBase = new baseClass();
for (member in target)
{
if (target.hasOwnProperty(member))
mixinBase[member] = target[member];
}
mixinBase.constructor = baseConstructor;
try
{
if (!_mixinDependencies)
_mixinDependencies = [];
_mixinDependencies.push(base);
var constructor = target.constructor;
mixin.call(target, mixinBase, target);
if (target.constructor !== constructor)
throw new Error("Target member \"constructor\" cannot be overridden.");
}
finally
{
_mixinDependencies.pop();
if (_mixinDependencies.length == 0)
_mixinDependencies = null;
}
}
for (member in source)
{
if (source.hasOwnProperty(member) && (member !== "mixin") && (member !== "constructor") && (member.substring(0, 2) !== "__"))
target[member] = source[member];
}
for (member in target)
{
if (target.hasOwnProperty(member) && (member !== "constructor"))
base[member] = target[member];
}
var sourceConstructor = (source.hasOwnProperty("constructor") && (typeof source.constructor === "function")) ? source.constructor : null;
if (sourceConstructor)
{
base.constructor = _appendConstructor(base.constructor, sourceConstructor);
if (_mixinDependencies)
{
var dependentMixin;
for (var i = _mixinDependencies.length - 1; i >= 0; i--)
{
dependentMixin = _mixinDependencies[i];
dependentMixin.constructor = _appendConstructor(dependentMixin.constructor, sourceConstructor);
}
}
}
target[id] = true;
return base;
};
/**
* Tests whether a source object has been mixed into a target object using
* jg_mixin.
*
* Example:
*
* <pre>
* // Call a mixin method on myInstance only if it has the mixin MyMixin.
* if (jg_has_mixin(myInstance, MyMixin))
* myInstance.myMixinMethod();
* </pre>
*
* @param target Object. The target object to test on. Must be non-null.
* @param source Object. The source object to test for. Must be non-null.
* @return true if the source object is mixed into the target object; false
* otherwise.
*/
var jg_has_mixin = root.jg_has_mixin = function(target, source)
{
if (target == null)
throw new Error("Parameter target must be non-null.");
if (source == null)
throw new Error("Parameter source must be non-null.");
var id = source.__jg_mixin_id;
if (!id)
return false;
id = "__jg_mixin_has_" + id;
return (target[id] == true);
};
/**
* Creates a function that delegates to another function, preserving the given
* scope. The given method can be either a function object or the name of a
* function in the given scope. In the case of the later, the function name is
* resolved to a function object dynamically for each invocation of the
* delegate. This allows the underlying function to change without requiring a
* new delegate. If an underlying function is not found, the delegate function
* executes silently and returns undefined.
*
* Example:
*
* <pre>
* // Create a delegate function for this.myMethod.
* var myDelegate = jg_delegate(this, "myMethod");
*
* // The delegate can be passed around without losing scope. In this case, we
* // pass it to setTimeout.
* setTimeout(myDelegate, 1000);
* </pre>
*
* @param scope Object. The scope in which to invoke the method. Must be
* non-null if method is a function name.
* @param method Function or String. The function object or function name to
* invoke. Must be non-null.
* @return A function.
*/
var jg_delegate = root.jg_delegate = function(scope, method)
{
if (method == null)
throw new Error("Parameter method must be non-null.");
var isMethodName = (typeof method === "string");
if (isMethodName)
{
if (scope == null)
throw new Error("Parameter scope must be non-null.");
}
else
{
if (typeof method !== "function")
throw new Error("Parameter method must be a string or a function.");
}
var f = function()
{
if (!isMethodName)
return method.apply(scope, arguments);
var m = scope[method];
if (typeof m === "function")
return m.apply(scope, arguments);
return undefined;
};
return f;
};
})();
},{}],6:[function(require,module,exports){
/**
* Includes code from the jgatt library
* Copyright (c) 2011 Jason Gatt
* Dual licensed under the MIT and GPL licenses
*/
(function() {
var jg_global = require('./jg_global');
var jg_namespace = jg_global.jg_namespace;
var jg_import = jg_global.jg_import;
var jg_extend = jg_global.jg_extend;
var jg_static = jg_global.jg_static;
var jg_mixin = jg_global.jg_mixin;
var jg_has_mixin = jg_global.jg_has_mixin;
var jg_delegate = jg_global.jg_jg_delegate;
module.exports = jg_global;
/***** ONLY CHANGE THINGS UNDER THIS LINE *****/
jg_namespace("splunk.time", function()
{
this.ITimeZone = jg_extend(Object, function(ITimeZone, base)
{
// Public Methods
this.getStandardOffset = function()
{
};
this.getOffset = function(time)
{
};
});
});
jg_namespace("splunk.time", function()
{
var ITimeZone = jg_import("splunk.time.ITimeZone");
this.SimpleTimeZone = jg_extend(ITimeZone, function(SimpleTimeZone, base)
{
// Private Properties
this._offset = 0;
// Constructor
this.constructor = function(offset)
{
this._offset = (offset !== undefined) ? offset : 0;
};
// Public Methods
this.getStandardOffset = function()
{
return this._offset;
};
this.getOffset = function(time)
{
return this._offset;
};
});
});
jg_namespace("splunk.time", function()
{
var ITimeZone = jg_import("splunk.time.ITimeZone");
this.LocalTimeZone = jg_extend(ITimeZone, function(LocalTimeZone, base)
{
// Public Methods
this.getStandardOffset = function()
{
var date = new Date(0);
return -date.getTimezoneOffset() * 60;
};
this.getOffset = function(time)
{
var date = new Date(time * 1000);
return -date.getTimezoneOffset() * 60;
};
});
});
jg_namespace("splunk.time", function()
{
var LocalTimeZone = jg_import("splunk.time.LocalTimeZone");
var SimpleTimeZone = jg_import("splunk.time.SimpleTimeZone");
this.TimeZones = jg_static(function(TimeZones)
{
// Public Static Constants
TimeZones.LOCAL = new LocalTimeZone();
TimeZones.UTC = new SimpleTimeZone(0);
});
});
jg_namespace("splunk.time", function()
{
var ITimeZone = jg_import("splunk.time.ITimeZone");
var SimpleTimeZone = jg_import("splunk.time.SimpleTimeZone");
var TimeZones = jg_import("splunk.time.TimeZones");
this.DateTime = jg_extend(Object, function(DateTime, base)
{
// Private Static Constants
var _ISO_DATE_TIME_PATTERN = /([\+\-])?(\d{4,})(?:(?:\-(\d{2}))(?:(?:\-(\d{2}))(?:(?:[T ](\d{2}))(?:(?:\:(\d{2}))(?:(?:\:(\d{2}(?:\.\d+)?)))?)?(?:(Z)|([\+\-])(\d{2})(?:\:(\d{2}))?)?)?)?)?/;
// Private Static Methods
var _normalizePrecision = function(value)
{
return Number(value.toFixed(6));
};
var _pad = function(value, digits, fractionDigits)
{
if (value != value)
return "NaN";
if (value == Infinity)
return "Infinity";
if (value == -Infinity)
return "-Infinity";
digits = (digits !== undefined) ? digits : 0;
fractionDigits = (fractionDigits !== undefined) ? fractionDigits : 0;
var str = value.toFixed(20);
var decimalIndex = str.indexOf(".");
if (decimalIndex < 0)
decimalIndex = str.length;
else if (fractionDigits < 1)
str = str.substring(0, decimalIndex);
else
str = str.substring(0, decimalIndex) + "." + str.substring(decimalIndex + 1, decimalIndex + fractionDigits + 1);
for (var i = decimalIndex; i < digits; i++)
str = "0" + str;
return str;
};
// Private Properties
this._year = 0;
this._month = 1;
this._day = 1;
this._weekday = 0;
this._hours = 0;
this._minutes = 0;
this._seconds = 0;
this._timeZone = TimeZones.LOCAL;
this._timeZoneOffset = 0;
this._time = 0;
this._isValid = true;
// Constructor
this.constructor = function(yearOrTimevalue, month, day, hours, minutes, seconds, timeZone)
{
switch (arguments.length)
{
case 0:
var now = new Date();
this._time = now.getTime() / 1000;
this._updateProperties();
break;
case 1:
if (typeof yearOrTimevalue === "number")
{
this._time = yearOrTimevalue;
this._updateProperties();
}
else if (typeof yearOrTimevalue === "string")
{
var matches = _ISO_DATE_TIME_PATTERN.exec(yearOrTimevalue);
var numMatches = matches ? matches.length : 0;
var match;
match = (numMatches > 1) ? matches[1] : null;
var yearSign = (match == "-") ? -1 : 1;
match = (numMatches > 2) ? matches[2] : null;
this._year = match ? yearSign * Number(match) : 0;
match = (numMatches > 3) ? matches[3] : null;
this._month = match ? Number(match) : 1;
match = (numMatches > 4) ? matches[4] : null;
this._day = match ? Number(match) : 1;
match = (numMatches > 5) ? matches[5] : null;
this._hours = match ? Number(match) : 0;
match = (numMatches > 6) ? matches[6] : null;
this._minutes = match ? Number(match) : 0;
match = (numMatches > 7) ? matches[7] : null;
this._seconds = match ? Number(match) : 0;
match = (numMatches > 8) ? matches[8] : null;
var timeZoneUTC = (match == "Z");
match = (numMatches > 9) ? matches[9] : null;
var timeZoneSign = (match == "-") ? -1 : 1;
match = (numMatches > 10) ? matches[10] : null;
var timeZoneHours = match ? Number(match) : NaN;
match = (numMatches > 11) ? matches[11] : null;
var timeZoneMinutes = match ? Number(match) : NaN;
if (timeZoneUTC)
this._timeZone = TimeZones.UTC;
else if (!isNaN(timeZoneHours) && !isNaN(timeZoneMinutes))
this._timeZone = new SimpleTimeZone(timeZoneSign * (timeZoneHours * 60 + timeZoneMinutes) * 60);
else
this._timeZone = TimeZones.LOCAL;
this._updateTime();
}
else
{
this._time = NaN;
this._updateProperties();
}
break;
default:
if (typeof yearOrTimevalue === "number")
{
this._year = yearOrTimevalue;
this._month = (month !== undefined) ? month : 1;
this._day = (day !== undefined) ? day : 1;
this._hours = (hours !== undefined) ? hours : 0;
this._minutes = (minutes !== undefined) ? minutes : 0;
this._seconds = (seconds !== undefined) ? seconds : 0;
this._timeZone = (timeZone instanceof ITimeZone) ? timeZone : TimeZones.LOCAL;
this._updateTime();
}
else
{
this._time = NaN;
this._updateProperties();
}
break;
}
};
// Public Getters/Setters
this.getYear = function()
{
return this._year;
};
this.setYear = function(value)
{
this._year = value;
this._updateTime();
};
this.getMonth = function()
{
return this._month;
};