You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@metron.apache.org by ce...@apache.org on 2016/06/17 14:37:07 UTC
[02/46] incubator-metron git commit: METRON-237 Remove metron-ui from
the code base. (mmiklavcic via cestella) closes apache/incubator-metron#159
http://git-wip-us.apache.org/repos/asf/incubator-metron/blob/40aadab8/metron-ui/lib/public/vendor/require/text.js
----------------------------------------------------------------------
diff --git a/metron-ui/lib/public/vendor/require/text.js b/metron-ui/lib/public/vendor/require/text.js
deleted file mode 100755
index 3c31b6f..0000000
--- a/metron-ui/lib/public/vendor/require/text.js
+++ /dev/null
@@ -1,386 +0,0 @@
-/**
- * @license RequireJS text 2.0.10 Copyright (c) 2010-2012, The Dojo Foundation All Rights Reserved.
- * Available via the MIT or new BSD license.
- * see: http://github.com/requirejs/text for details
- */
-/*jslint regexp: true */
-/*global require, XMLHttpRequest, ActiveXObject,
- define, window, process, Packages,
- java, location, Components, FileUtils */
-
-define(['module'], function (module) {
- 'use strict';
-
- var text, fs, Cc, Ci, xpcIsWindows,
- progIds = ['Msxml2.XMLHTTP', 'Microsoft.XMLHTTP', 'Msxml2.XMLHTTP.4.0'],
- xmlRegExp = /^\s*<\?xml(\s)+version=[\'\"](\d)*.(\d)*[\'\"](\s)*\?>/im,
- bodyRegExp = /<body[^>]*>\s*([\s\S]+)\s*<\/body>/im,
- hasLocation = typeof location !== 'undefined' && location.href,
- defaultProtocol = hasLocation && location.protocol && location.protocol.replace(/\:/, ''),
- defaultHostName = hasLocation && location.hostname,
- defaultPort = hasLocation && (location.port || undefined),
- buildMap = {},
- masterConfig = (module.config && module.config()) || {};
-
- text = {
- version: '2.0.10',
-
- strip: function (content) {
- //Strips <?xml ...?> declarations so that external SVG and XML
- //documents can be added to a document without worry. Also, if the string
- //is an HTML document, only the part inside the body tag is returned.
- if (content) {
- content = content.replace(xmlRegExp, "");
- var matches = content.match(bodyRegExp);
- if (matches) {
- content = matches[1];
- }
- } else {
- content = "";
- }
- return content;
- },
-
- jsEscape: function (content) {
- return content.replace(/(['\\])/g, '\\$1')
- .replace(/[\f]/g, "\\f")
- .replace(/[\b]/g, "\\b")
- .replace(/[\n]/g, "\\n")
- .replace(/[\t]/g, "\\t")
- .replace(/[\r]/g, "\\r")
- .replace(/[\u2028]/g, "\\u2028")
- .replace(/[\u2029]/g, "\\u2029");
- },
-
- createXhr: masterConfig.createXhr || function () {
- //Would love to dump the ActiveX crap in here. Need IE 6 to die first.
- var xhr, i, progId;
- if (typeof XMLHttpRequest !== "undefined") {
- return new XMLHttpRequest();
- } else if (typeof ActiveXObject !== "undefined") {
- for (i = 0; i < 3; i += 1) {
- progId = progIds[i];
- try {
- xhr = new ActiveXObject(progId);
- } catch (e) {}
-
- if (xhr) {
- progIds = [progId]; // so faster next time
- break;
- }
- }
- }
-
- return xhr;
- },
-
- /**
- * Parses a resource name into its component parts. Resource names
- * look like: module/name.ext!strip, where the !strip part is
- * optional.
- * @param {String} name the resource name
- * @returns {Object} with properties "moduleName", "ext" and "strip"
- * where strip is a boolean.
- */
- parseName: function (name) {
- var modName, ext, temp,
- strip = false,
- index = name.indexOf("."),
- isRelative = name.indexOf('./') === 0 ||
- name.indexOf('../') === 0;
-
- if (index !== -1 && (!isRelative || index > 1)) {
- modName = name.substring(0, index);
- ext = name.substring(index + 1, name.length);
- } else {
- modName = name;
- }
-
- temp = ext || modName;
- index = temp.indexOf("!");
- if (index !== -1) {
- //Pull off the strip arg.
- strip = temp.substring(index + 1) === "strip";
- temp = temp.substring(0, index);
- if (ext) {
- ext = temp;
- } else {
- modName = temp;
- }
- }
-
- return {
- moduleName: modName,
- ext: ext,
- strip: strip
- };
- },
-
- xdRegExp: /^((\w+)\:)?\/\/([^\/\\]+)/,
-
- /**
- * Is an URL on another domain. Only works for browser use, returns
- * false in non-browser environments. Only used to know if an
- * optimized .js version of a text resource should be loaded
- * instead.
- * @param {String} url
- * @returns Boolean
- */
- useXhr: function (url, protocol, hostname, port) {
- var uProtocol, uHostName, uPort,
- match = text.xdRegExp.exec(url);
- if (!match) {
- return true;
- }
- uProtocol = match[2];
- uHostName = match[3];
-
- uHostName = uHostName.split(':');
- uPort = uHostName[1];
- uHostName = uHostName[0];
-
- return (!uProtocol || uProtocol === protocol) &&
- (!uHostName || uHostName.toLowerCase() === hostname.toLowerCase()) &&
- ((!uPort && !uHostName) || uPort === port);
- },
-
- finishLoad: function (name, strip, content, onLoad) {
- content = strip ? text.strip(content) : content;
- if (masterConfig.isBuild) {
- buildMap[name] = content;
- }
- onLoad(content);
- },
-
- load: function (name, req, onLoad, config) {
- //Name has format: some.module.filext!strip
- //The strip part is optional.
- //if strip is present, then that means only get the string contents
- //inside a body tag in an HTML string. For XML/SVG content it means
- //removing the <?xml ...?> declarations so the content can be inserted
- //into the current doc without problems.
-
- // Do not bother with the work if a build and text will
- // not be inlined.
- if (config.isBuild && !config.inlineText) {
- onLoad();
- return;
- }
-
- masterConfig.isBuild = config.isBuild;
-
- var parsed = text.parseName(name),
- nonStripName = parsed.moduleName +
- (parsed.ext ? '.' + parsed.ext : ''),
- url = req.toUrl(nonStripName),
- useXhr = (masterConfig.useXhr) ||
- text.useXhr;
-
- // Do not load if it is an empty: url
- if (url.indexOf('empty:') === 0) {
- onLoad();
- return;
- }
-
- //Load the text. Use XHR if possible and in a browser.
- if (!hasLocation || useXhr(url, defaultProtocol, defaultHostName, defaultPort)) {
- text.get(url, function (content) {
- text.finishLoad(name, parsed.strip, content, onLoad);
- }, function (err) {
- if (onLoad.error) {
- onLoad.error(err);
- }
- });
- } else {
- //Need to fetch the resource across domains. Assume
- //the resource has been optimized into a JS module. Fetch
- //by the module name + extension, but do not include the
- //!strip part to avoid file system issues.
- req([nonStripName], function (content) {
- text.finishLoad(parsed.moduleName + '.' + parsed.ext,
- parsed.strip, content, onLoad);
- });
- }
- },
-
- write: function (pluginName, moduleName, write, config) {
- if (buildMap.hasOwnProperty(moduleName)) {
- var content = text.jsEscape(buildMap[moduleName]);
- write.asModule(pluginName + "!" + moduleName,
- "define(function () { return '" +
- content +
- "';});\n");
- }
- },
-
- writeFile: function (pluginName, moduleName, req, write, config) {
- var parsed = text.parseName(moduleName),
- extPart = parsed.ext ? '.' + parsed.ext : '',
- nonStripName = parsed.moduleName + extPart,
- //Use a '.js' file name so that it indicates it is a
- //script that can be loaded across domains.
- fileName = req.toUrl(parsed.moduleName + extPart) + '.js';
-
- //Leverage own load() method to load plugin value, but only
- //write out values that do not have the strip argument,
- //to avoid any potential issues with ! in file names.
- text.load(nonStripName, req, function (value) {
- //Use own write() method to construct full module value.
- //But need to create shell that translates writeFile's
- //write() to the right interface.
- var textWrite = function (contents) {
- return write(fileName, contents);
- };
- textWrite.asModule = function (moduleName, contents) {
- return write.asModule(moduleName, fileName, contents);
- };
-
- text.write(pluginName, nonStripName, textWrite, config);
- }, config);
- }
- };
-
- if (masterConfig.env === 'node' || (!masterConfig.env &&
- typeof process !== "undefined" &&
- process.versions &&
- !!process.versions.node &&
- !process.versions['node-webkit'])) {
- //Using special require.nodeRequire, something added by r.js.
- fs = require.nodeRequire('fs');
-
- text.get = function (url, callback, errback) {
- try {
- var file = fs.readFileSync(url, 'utf8');
- //Remove BOM (Byte Mark Order) from utf8 files if it is there.
- if (file.indexOf('\uFEFF') === 0) {
- file = file.substring(1);
- }
- callback(file);
- } catch (e) {
- errback(e);
- }
- };
- } else if (masterConfig.env === 'xhr' || (!masterConfig.env &&
- text.createXhr())) {
- text.get = function (url, callback, errback, headers) {
- var xhr = text.createXhr(), header;
- xhr.open('GET', url, true);
-
- //Allow plugins direct access to xhr headers
- if (headers) {
- for (header in headers) {
- if (headers.hasOwnProperty(header)) {
- xhr.setRequestHeader(header.toLowerCase(), headers[header]);
- }
- }
- }
-
- //Allow overrides specified in config
- if (masterConfig.onXhr) {
- masterConfig.onXhr(xhr, url);
- }
-
- xhr.onreadystatechange = function (evt) {
- var status, err;
- //Do not explicitly handle errors, those should be
- //visible via console output in the browser.
- if (xhr.readyState === 4) {
- status = xhr.status;
- if (status > 399 && status < 600) {
- //An http 4xx or 5xx error. Signal an error.
- err = new Error(url + ' HTTP status: ' + status);
- err.xhr = xhr;
- errback(err);
- } else {
- callback(xhr.responseText);
- }
-
- if (masterConfig.onXhrComplete) {
- masterConfig.onXhrComplete(xhr, url);
- }
- }
- };
- xhr.send(null);
- };
- } else if (masterConfig.env === 'rhino' || (!masterConfig.env &&
- typeof Packages !== 'undefined' && typeof java !== 'undefined')) {
- //Why Java, why is this so awkward?
- text.get = function (url, callback) {
- var stringBuffer, line,
- encoding = "utf-8",
- file = new java.io.File(url),
- lineSeparator = java.lang.System.getProperty("line.separator"),
- input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(file), encoding)),
- content = '';
- try {
- stringBuffer = new java.lang.StringBuffer();
- line = input.readLine();
-
- // Byte Order Mark (BOM) - The Unicode Standard, version 3.0, page 324
- // http://www.unicode.org/faq/utf_bom.html
-
- // Note that when we use utf-8, the BOM should appear as "EF BB BF", but it doesn't due to this bug in the JDK:
- // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4508058
- if (line && line.length() && line.charAt(0) === 0xfeff) {
- // Eat the BOM, since we've already found the encoding on this file,
- // and we plan to concatenating this buffer with others; the BOM should
- // only appear at the top of a file.
- line = line.substring(1);
- }
-
- if (line !== null) {
- stringBuffer.append(line);
- }
-
- while ((line = input.readLine()) !== null) {
- stringBuffer.append(lineSeparator);
- stringBuffer.append(line);
- }
- //Make sure we return a JavaScript string and not a Java string.
- content = String(stringBuffer.toString()); //String
- } finally {
- input.close();
- }
- callback(content);
- };
- } else if (masterConfig.env === 'xpconnect' || (!masterConfig.env &&
- typeof Components !== 'undefined' && Components.classes &&
- Components.interfaces)) {
- //Avert your gaze!
- Cc = Components.classes,
- Ci = Components.interfaces;
- Components.utils['import']('resource://gre/modules/FileUtils.jsm');
- xpcIsWindows = ('@mozilla.org/windows-registry-key;1' in Cc);
-
- text.get = function (url, callback) {
- var inStream, convertStream, fileObj,
- readData = {};
-
- if (xpcIsWindows) {
- url = url.replace(/\//g, '\\');
- }
-
- fileObj = new FileUtils.File(url);
-
- //XPCOM, you so crazy
- try {
- inStream = Cc['@mozilla.org/network/file-input-stream;1']
- .createInstance(Ci.nsIFileInputStream);
- inStream.init(fileObj, 1, 0, false);
-
- convertStream = Cc['@mozilla.org/intl/converter-input-stream;1']
- .createInstance(Ci.nsIConverterInputStream);
- convertStream.init(inStream, "utf-8", inStream.available(),
- Ci.nsIConverterInputStream.DEFAULT_REPLACEMENT_CHARACTER);
-
- convertStream.readString(inStream.available(), readData);
- convertStream.close();
- inStream.close();
- callback(readData.value);
- } catch (e) {
- throw new Error((fileObj && fileObj.path || '') + ': ' + e);
- }
- };
- }
- return text;
-});
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-metron/blob/40aadab8/metron-ui/lib/public/vendor/require/tmpl.js
----------------------------------------------------------------------
diff --git a/metron-ui/lib/public/vendor/require/tmpl.js b/metron-ui/lib/public/vendor/require/tmpl.js
deleted file mode 100755
index c5bce80..0000000
--- a/metron-ui/lib/public/vendor/require/tmpl.js
+++ /dev/null
@@ -1,17 +0,0 @@
-/*jshint unused:false */
-define(['module'], function (module) {
- 'use strict';
-
- var masterConfig = (module.config && module.config()) || {};
-
- return {
- load: function (name, require, onLoad, config) {
- var url = require.toUrl(name);
- require(['text!'+name], function (text) {
- masterConfig.registerTemplate && masterConfig.registerTemplate(url, text);
- onLoad(text);
- });
- }
- };
-
-});
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-metron/blob/40aadab8/metron-ui/lib/public/vendor/timezone.js
----------------------------------------------------------------------
diff --git a/metron-ui/lib/public/vendor/timezone.js b/metron-ui/lib/public/vendor/timezone.js
deleted file mode 100755
index 8b8478a..0000000
--- a/metron-ui/lib/public/vendor/timezone.js
+++ /dev/null
@@ -1,993 +0,0 @@
-// -----
-// The `timezoneJS.Date` object gives you full-blown timezone support, independent from the timezone set on the end-user's machine running the browser. It uses the Olson zoneinfo files for its timezone data.
-//
-// The constructor function and setter methods use proxy JavaScript Date objects behind the scenes, so you can use strings like '10/22/2006' with the constructor. You also get the same sensible wraparound behavior with numeric parameters (like setting a value of 14 for the month wraps around to the next March).
-//
-// The other significant difference from the built-in JavaScript Date is that `timezoneJS.Date` also has named properties that store the values of year, month, date, etc., so it can be directly serialized to JSON and used for data transfer.
-
-/*
- * Copyright 2010 Matthew Eernisse (mde@fleegix.org)
- * and Open Source Applications Foundation
- *
- * 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.
- *
- * Credits: Ideas included from incomplete JS implementation of Olson
- * parser, "XMLDAte" by Philippe Goetz (philippe.goetz@wanadoo.fr)
- *
- * Contributions:
- * Jan Niehusmann
- * Ricky Romero
- * Preston Hunt (prestonhunt@gmail.com)
- * Dov. B Katz (dov.katz@morganstanley.com)
- * Peter Bergstr�m (pbergstr@mac.com)
- * Long Ho
- */
-(function () {
- // Standard initialization stuff to make sure the library is
- // usable on both client and server (node) side.
- "use strict";
- var root = this;
-
- var timezoneJS;
- if (typeof exports !== 'undefined') {
- timezoneJS = exports;
- } else {
- timezoneJS = root.timezoneJS = {};
- }
-
- timezoneJS.VERSION = '0.4.4';
-
- // Grab the ajax library from global context.
- // This can be jQuery, Zepto or fleegix.
- // You can also specify your own transport mechanism by declaring
- // `timezoneJS.timezone.transport` to a `function`. More details will follow
- var $ = root.$ || root.jQuery || root.Zepto
- , fleegix = root.fleegix
- , _arrIndexOf
- // Declare constant list of days and months. Unfortunately this doesn't leave room for i18n due to the Olson data being in English itself
- , DAYS = timezoneJS.Days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
- , MONTHS = timezoneJS.Months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
- , SHORT_MONTHS = {}
- , SHORT_DAYS = {}
- , EXACT_DATE_TIME = {}
- , TZ_REGEXP = new RegExp('^[a-zA-Z]+/');
-
- //`{ "Jan": 0, "Feb": 1, "Mar": 2, "Apr": 3, "May": 4, "Jun": 5, "Jul": 6, "Aug": 7, "Sep": 8, "Oct": 9, "Nov": 10, "Dec": 11 }`
- for (var i = 0; i < MONTHS.length; i++) {
- SHORT_MONTHS[MONTHS[i].substr(0, 3)] = i;
- }
-
- //`{ "Sun": 0, "Mon": 1, "Tue": 2, "Wed": 3, "Thu": 4, "Fri": 5, "Sat": 6 }`
- for (i = 0; i < DAYS.length; i++) {
- SHORT_DAYS[DAYS[i].substr(0, 3)] = i;
- }
-
-
- //Handle array indexOf in IE
- //From https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/indexOf
- //Extending Array prototype causes IE to iterate thru extra element
- _arrIndexOf = Array.prototype.indexOf || function (el) {
- if (this === null) {
- throw new TypeError();
- }
- var t = Object(this);
- var len = t.length >>> 0;
- if (len === 0) {
- return -1;
- }
- var n = 0;
- if (arguments.length > 1) {
- n = Number(arguments[1]);
- if (n != n) { // shortcut for verifying if it's NaN
- n = 0;
- } else if (n !== 0 && n !== Infinity && n !== -Infinity) {
- n = (n > 0 || -1) * Math.floor(Math.abs(n));
- }
- }
- if (n >= len) {
- return -1;
- }
- var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
- for (; k < len; k++) {
- if (k in t && t[k] === el) {
- return k;
- }
- }
- return -1;
- };
-
-
- // Format a number to the length = digits. For ex:
- //
- // `_fixWidth(2, 2) = '02'`
- //
- // `_fixWidth(1998, 2) = '98'`
- //
- // This is used to pad numbers in converting date to string in ISO standard.
- var _fixWidth = function (number, digits) {
- if (typeof number !== "number") { throw "not a number: " + number; }
- var s = number.toString();
- if (number.length > digits) {
- return number.substr(number.length - digits, number.length);
- }
- while (s.length < digits) {
- s = '0' + s;
- }
- return s;
- };
-
- // Abstraction layer for different transport layers, including fleegix/jQuery/Zepto
- //
- // Object `opts` include
- //
- // - `url`: url to ajax query
- //
- // - `async`: true for asynchronous, false otherwise. If false, return value will be response from URL. This is true by default
- //
- // - `success`: success callback function
- //
- // - `error`: error callback function
- // Returns response from URL if async is false, otherwise the AJAX request object itself
- var _transport = function (opts) {
- if ((!fleegix || typeof fleegix.xhr === 'undefined') && (!$ || typeof $.ajax === 'undefined')) {
- throw new Error('Please use the Fleegix.js XHR module, jQuery ajax, Zepto ajax, or define your own transport mechanism for downloading zone files.');
- }
- if (!opts) return;
- if (!opts.url) throw new Error ('URL must be specified');
- if (!('async' in opts)) opts.async = true;
- if (!opts.async) {
- return fleegix && fleegix.xhr
- ? fleegix.xhr.doReq({ url: opts.url, async: false })
- : $.ajax({ url : opts.url, async : false }).responseText;
- }
- return fleegix && fleegix.xhr
- ? fleegix.xhr.send({
- url : opts.url,
- method : 'get',
- handleSuccess : opts.success,
- handleErr : opts.error
- })
- : $.ajax({
- url : opts.url,
- dataType: 'text',
- method : 'GET',
- error : opts.error,
- success : opts.success
- });
- };
-
- // Constructor, which is similar to that of the native Date object itself
- timezoneJS.Date = function () {
- var args = Array.prototype.slice.apply(arguments)
- , dt = null
- , tz = null
- , arr = [];
-
-
- //We support several different constructors, including all the ones from `Date` object
- // with a timezone string at the end.
- //
- //- `[tz]`: Returns object with time in `tz` specified.
- //
- // - `utcMillis`, `[tz]`: Return object with UTC time = `utcMillis`, in `tz`.
- //
- // - `Date`, `[tz]`: Returns object with UTC time = `Date.getTime()`, in `tz`.
- //
- // - `year, month, [date,] [hours,] [minutes,] [seconds,] [millis,] [tz]: Same as `Date` object
- // with tz.
- //
- // - `Array`: Can be any combo of the above.
- //
- //If 1st argument is an array, we can use it as a list of arguments itself
- if (Object.prototype.toString.call(args[0]) === '[object Array]') {
- args = args[0];
- }
- if (typeof args[args.length - 1] === 'string' && TZ_REGEXP.test(args[args.length - 1])) {
- tz = args.pop();
- }
- switch (args.length) {
- case 0:
- dt = new Date();
- break;
- case 1:
- dt = new Date(args[0]);
- break;
- default:
- for (var i = 0; i < 7; i++) {
- arr[i] = args[i] || 0;
- }
- dt = new Date(arr[0], arr[1], arr[2], arr[3], arr[4], arr[5], arr[6]);
- break;
- }
-
- this._useCache = false;
- this._tzInfo = {};
- this._day = 0;
- this.year = 0;
- this.month = 0;
- this.date = 0;
- this.hours = 0;
- this.minutes = 0;
- this.seconds = 0;
- this.milliseconds = 0;
- this.timezone = tz || null;
- //Tricky part:
- // For the cases where there are 1/2 arguments: `timezoneJS.Date(millis, [tz])` and `timezoneJS.Date(Date, [tz])`. The
- // Date `dt` created should be in UTC. Thus the way I detect such cases is to determine if `arr` is not populated & `tz`
- // is specified. Because if `tz` is not specified, `dt` can be in local time.
- if (arr.length) {
- this.setFromDateObjProxy(dt);
- } else {
- this.setFromTimeProxy(dt.getTime(), tz);
- }
- };
-
- // Implements most of the native Date object
- timezoneJS.Date.prototype = {
- getDate: function () { return this.date; },
- getDay: function () { return this._day; },
- getFullYear: function () { return this.year; },
- getMonth: function () { return this.month; },
- getYear: function () { return this.year - 1900; },
- getHours: function () { return this.hours; },
- getMilliseconds: function () { return this.milliseconds; },
- getMinutes: function () { return this.minutes; },
- getSeconds: function () { return this.seconds; },
- getUTCDate: function () { return this.getUTCDateProxy().getUTCDate(); },
- getUTCDay: function () { return this.getUTCDateProxy().getUTCDay(); },
- getUTCFullYear: function () { return this.getUTCDateProxy().getUTCFullYear(); },
- getUTCHours: function () { return this.getUTCDateProxy().getUTCHours(); },
- getUTCMilliseconds: function () { return this.getUTCDateProxy().getUTCMilliseconds(); },
- getUTCMinutes: function () { return this.getUTCDateProxy().getUTCMinutes(); },
- getUTCMonth: function () { return this.getUTCDateProxy().getUTCMonth(); },
- getUTCSeconds: function () { return this.getUTCDateProxy().getUTCSeconds(); },
- // Time adjusted to user-specified timezone
- getTime: function () {
- return this._timeProxy + (this.getTimezoneOffset() * 60 * 1000);
- },
- getTimezone: function () { return this.timezone; },
- getTimezoneOffset: function () { return this.getTimezoneInfo().tzOffset; },
- getTimezoneAbbreviation: function () { return this.getTimezoneInfo().tzAbbr; },
- getTimezoneInfo: function () {
- if (this._useCache) return this._tzInfo;
- var res;
- // If timezone is specified, get the correct timezone info based on the Date given
- if (this.timezone) {
- res = this.timezone === 'Etc/UTC' || this.timezone === 'Etc/GMT'
- ? { tzOffset: 0, tzAbbr: 'UTC' }
- : timezoneJS.timezone.getTzInfo(this._timeProxy, this.timezone);
- }
- // If no timezone was specified, use the local browser offset
- else {
- res = { tzOffset: this.getLocalOffset(), tzAbbr: null };
- }
- this._tzInfo = res;
- this._useCache = true;
- return res;
- },
- getUTCDateProxy: function () {
- var dt = new Date(this._timeProxy);
- dt.setUTCMinutes(dt.getUTCMinutes() + this.getTimezoneOffset());
- return dt;
- },
- setDate: function (date) {
- this.setAttribute('date', date);
- return this.getTime();
- },
- setFullYear: function (year, month, date) {
- if (date !== undefined) { this.setAttribute('date', 1); }
- this.setAttribute('year', year);
- if (month !== undefined) { this.setAttribute('month', month); }
- if (date !== undefined) { this.setAttribute('date', date); }
- return this.getTime();
- },
- setMonth: function (month, date) {
- this.setAttribute('month', month);
- if (date !== undefined) { this.setAttribute('date', date); }
- return this.getTime();
- },
- setYear: function (year) {
- year = Number(year);
- if (0 <= year && year <= 99) { year += 1900; }
- this.setUTCAttribute('year', year);
- return this.getTime();
- },
- setHours: function (hours, minutes, seconds, milliseconds) {
- this.setAttribute('hours', hours);
- if (minutes !== undefined) { this.setAttribute('minutes', minutes); }
- if (seconds !== undefined) { this.setAttribute('seconds', seconds); }
- if (milliseconds !== undefined) { this.setAttribute('milliseconds', milliseconds); }
- return this.getTime();
- },
- setMinutes: function (minutes, seconds, milliseconds) {
- this.setAttribute('minutes', minutes);
- if (seconds !== undefined) { this.setAttribute('seconds', seconds); }
- if (milliseconds !== undefined) { this.setAttribute('milliseconds', milliseconds); }
- return this.getTime();
- },
- setSeconds: function (seconds, milliseconds) {
- this.setAttribute('seconds', seconds);
- if (milliseconds !== undefined) { this.setAttribute('milliseconds', milliseconds); }
- return this.getTime();
- },
- setMilliseconds: function (milliseconds) {
- this.setAttribute('milliseconds', milliseconds);
- return this.getTime();
- },
- setTime: function (n) {
- if (isNaN(n)) { throw new Error('Units must be a number.'); }
- this.setFromTimeProxy(n, this.timezone);
- return this.getTime();
- },
- setUTCFullYear: function (year, month, date) {
- if (date !== undefined) { this.setUTCAttribute('date', 1); }
- this.setUTCAttribute('year', year);
- if (month !== undefined) { this.setUTCAttribute('month', month); }
- if (date !== undefined) { this.setUTCAttribute('date', date); }
- return this.getTime();
- },
- setUTCMonth: function (month, date) {
- this.setUTCAttribute('month', month);
- if (date !== undefined) { this.setUTCAttribute('date', date); }
- return this.getTime();
- },
- setUTCDate: function (date) {
- this.setUTCAttribute('date', date);
- return this.getTime();
- },
- setUTCHours: function (hours, minutes, seconds, milliseconds) {
- this.setUTCAttribute('hours', hours);
- if (minutes !== undefined) { this.setUTCAttribute('minutes', minutes); }
- if (seconds !== undefined) { this.setUTCAttribute('seconds', seconds); }
- if (milliseconds !== undefined) { this.setUTCAttribute('milliseconds', milliseconds); }
- return this.getTime();
- },
- setUTCMinutes: function (minutes, seconds, milliseconds) {
- this.setUTCAttribute('minutes', minutes);
- if (seconds !== undefined) { this.setUTCAttribute('seconds', seconds); }
- if (milliseconds !== undefined) { this.setUTCAttribute('milliseconds', milliseconds); }
- return this.getTime();
- },
- setUTCSeconds: function (seconds, milliseconds) {
- this.setUTCAttribute('seconds', seconds);
- if (milliseconds !== undefined) { this.setUTCAttribute('milliseconds', milliseconds); }
- return this.getTime();
- },
- setUTCMilliseconds: function (milliseconds) {
- this.setUTCAttribute('milliseconds', milliseconds);
- return this.getTime();
- },
- setFromDateObjProxy: function (dt) {
- this.year = dt.getFullYear();
- this.month = dt.getMonth();
- this.date = dt.getDate();
- this.hours = dt.getHours();
- this.minutes = dt.getMinutes();
- this.seconds = dt.getSeconds();
- this.milliseconds = dt.getMilliseconds();
- this._day = dt.getDay();
- this._dateProxy = dt;
- this._timeProxy = Date.UTC(this.year, this.month, this.date, this.hours, this.minutes, this.seconds, this.milliseconds);
- this._useCache = false;
- },
- setFromTimeProxy: function (utcMillis, tz) {
- var dt = new Date(utcMillis);
- var tzOffset;
- tzOffset = tz ? timezoneJS.timezone.getTzInfo(dt, tz).tzOffset : dt.getTimezoneOffset();
- dt.setTime(utcMillis + (dt.getTimezoneOffset() - tzOffset) * 60000);
- this.setFromDateObjProxy(dt);
- },
- setAttribute: function (unit, n) {
- if (isNaN(n)) { throw new Error('Units must be a number.'); }
- var dt = this._dateProxy;
- var meth = unit === 'year' ? 'FullYear' : unit.substr(0, 1).toUpperCase() + unit.substr(1);
- dt['set' + meth](n);
- this.setFromDateObjProxy(dt);
- },
- setUTCAttribute: function (unit, n) {
- if (isNaN(n)) { throw new Error('Units must be a number.'); }
- var meth = unit === 'year' ? 'FullYear' : unit.substr(0, 1).toUpperCase() + unit.substr(1);
- var dt = this.getUTCDateProxy();
- dt['setUTC' + meth](n);
- dt.setUTCMinutes(dt.getUTCMinutes() - this.getTimezoneOffset());
- this.setFromTimeProxy(dt.getTime() + this.getTimezoneOffset() * 60000, this.timezone);
- },
- setTimezone: function (tz) {
- var previousOffset = this.getTimezoneInfo().tzOffset;
- this.timezone = tz;
- this._useCache = false;
- // Set UTC minutes offsets by the delta of the two timezones
- this.setUTCMinutes(this.getUTCMinutes() - this.getTimezoneInfo().tzOffset + previousOffset);
- },
- removeTimezone: function () {
- this.timezone = null;
- this._useCache = false;
- },
- valueOf: function () { return this.getTime(); },
- clone: function () {
- return this.timezone ? new timezoneJS.Date(this.getTime(), this.timezone) : new timezoneJS.Date(this.getTime());
- },
- toGMTString: function () { return this.toString('EEE, dd MMM yyyy HH:mm:ss Z', 'Etc/GMT'); },
- toLocaleString: function () {},
- toLocaleDateString: function () {},
- toLocaleTimeString: function () {},
- toSource: function () {},
- toISOString: function () { return this.toString('yyyy-MM-ddTHH:mm:ss.SSS', 'Etc/UTC') + 'Z'; },
- toJSON: function () { return this.toISOString(); },
- // Allows different format following ISO8601 format:
- toString: function (format, tz) {
- // Default format is the same as toISOString
- if (!format) format = 'yyyy-MM-dd HH:mm:ss';
- var result = format;
- var tzInfo = tz ? timezoneJS.timezone.getTzInfo(this.getTime(), tz) : this.getTimezoneInfo();
- var _this = this;
- // If timezone is specified, get a clone of the current Date object and modify it
- if (tz) {
- _this = this.clone();
- _this.setTimezone(tz);
- }
- var hours = _this.getHours();
- return result
- // fix the same characters in Month names
- .replace(/a+/g, function () { return 'k'; })
- // `y`: year
- .replace(/y+/g, function (token) { return _fixWidth(_this.getFullYear(), token.length); })
- // `d`: date
- .replace(/d+/g, function (token) { return _fixWidth(_this.getDate(), token.length); })
- // `m`: minute
- .replace(/m+/g, function (token) { return _fixWidth(_this.getMinutes(), token.length); })
- // `s`: second
- .replace(/s+/g, function (token) { return _fixWidth(_this.getSeconds(), token.length); })
- // `S`: millisecond
- .replace(/S+/g, function (token) { return _fixWidth(_this.getMilliseconds(), token.length); })
- // `M`: month. Note: `MM` will be the numeric representation (e.g February is 02) but `MMM` will be text representation (e.g February is Feb)
- .replace(/M+/g, function (token) {
- var _month = _this.getMonth(),
- _len = token.length;
- if (_len > 3) {
- return timezoneJS.Months[_month];
- } else if (_len > 2) {
- return timezoneJS.Months[_month].substring(0, _len);
- }
- return _fixWidth(_month + 1, _len);
- })
- // `k`: AM/PM
- .replace(/k+/g, function () {
- if (hours >= 12) {
- if (hours > 12) {
- hours -= 12;
- }
- return 'PM';
- }
- return 'AM';
- })
- // `H`: hour
- .replace(/H+/g, function (token) { return _fixWidth(hours, token.length); })
- // `E`: day
- .replace(/E+/g, function (token) { return DAYS[_this.getDay()].substring(0, token.length); })
- // `Z`: timezone abbreviation
- .replace(/Z+/gi, function () { return tzInfo.tzAbbr; });
- },
- toUTCString: function () { return this.toGMTString(); },
- civilToJulianDayNumber: function (y, m, d) {
- var a;
- // Adjust for zero-based JS-style array
- m++;
- if (m > 12) {
- a = parseInt(m/12, 10);
- m = m % 12;
- y += a;
- }
- if (m <= 2) {
- y -= 1;
- m += 12;
- }
- a = Math.floor(y / 100);
- var b = 2 - a + Math.floor(a / 4)
- , jDt = Math.floor(365.25 * (y + 4716)) + Math.floor(30.6001 * (m + 1)) + d + b - 1524;
- return jDt;
- },
- getLocalOffset: function () {
- return this._dateProxy.getTimezoneOffset();
- }
- };
-
-
- timezoneJS.timezone = new function () {
- var _this = this
- , regionMap = {'Etc':'etcetera','EST':'northamerica','MST':'northamerica','HST':'northamerica','EST5EDT':'northamerica','CST6CDT':'northamerica','MST7MDT':'northamerica','PST8PDT':'northamerica','America':'northamerica','Pacific':'australasia','Atlantic':'europe','Africa':'africa','Indian':'africa','Antarctica':'antarctica','Asia':'asia','Australia':'australasia','Europe':'europe','WET':'europe','CET':'europe','MET':'europe','EET':'europe'}
- , regionExceptions = {'Pacific/Honolulu':'northamerica','Atlantic/Bermuda':'northamerica','Atlantic/Cape_Verde':'africa','Atlantic/St_Helena':'africa','Indian/Kerguelen':'antarctica','Indian/Chagos':'asia','Indian/Maldives':'asia','Indian/Christmas':'australasia','Indian/Cocos':'australasia','America/Danmarkshavn':'europe','America/Scoresbysund':'europe','America/Godthab':'europe','America/Thule':'europe','Asia/Yekaterinburg':'europe','Asia/Omsk':'europe','Asia/Novosibirsk':'europe','Asia/Krasnoyarsk':'europe','Asia/Irkutsk':'europe','Asia/Yakutsk':'europe','Asia/Vladivostok':'europe','Asia/Sakhalin':'europe','Asia/Magadan':'europe','Asia/Kamchatka':'europe','Asia/Anadyr':'europe','Africa/Ceuta':'europe','America/Argentina/Buenos_Aires':'southamerica','America/Argentina/Cordoba':'southamerica','America/Argentina/Tucuman':'southamerica','America/Argentina/La_Rioja':'southamerica','America/Argentina/San_Juan':'southamerica','America/Argentina/Jujuy':'southamerica','America/Argen
tina/Catamarca':'southamerica','America/Argentina/Mendoza':'southamerica','America/Argentina/Rio_Gallegos':'southamerica','America/Argentina/Ushuaia':'southamerica','America/Aruba':'southamerica','America/La_Paz':'southamerica','America/Noronha':'southamerica','America/Belem':'southamerica','America/Fortaleza':'southamerica','America/Recife':'southamerica','America/Araguaina':'southamerica','America/Maceio':'southamerica','America/Bahia':'southamerica','America/Sao_Paulo':'southamerica','America/Campo_Grande':'southamerica','America/Cuiaba':'southamerica','America/Porto_Velho':'southamerica','America/Boa_Vista':'southamerica','America/Manaus':'southamerica','America/Eirunepe':'southamerica','America/Rio_Branco':'southamerica','America/Santiago':'southamerica','Pacific/Easter':'southamerica','America/Bogota':'southamerica','America/Curacao':'southamerica','America/Guayaquil':'southamerica','Pacific/Galapagos':'southamerica','Atlantic/Stanley':'southamerica','America/Cayenne':'southam
erica','America/Guyana':'southamerica','America/Asuncion':'southamerica','America/Lima':'southamerica','Atlantic/South_Georgia':'southamerica','America/Paramaribo':'southamerica','America/Port_of_Spain':'southamerica','America/Montevideo':'southamerica','America/Caracas':'southamerica'};
- function invalidTZError(t) { throw new Error('Timezone "' + t + '" is either incorrect, or not loaded in the timezone registry.'); }
- function builtInLoadZoneFile(fileName, opts) {
- var url = _this.zoneFileBasePath + '/' + fileName;
- return !opts || !opts.async
- ? _this.parseZones(_this.transport({ url : url, async : false }))
- : _this.transport({
- async: true,
- url : url,
- success : function (str) {
- if (_this.parseZones(str) && typeof opts.callback === 'function') {
- opts.callback();
- }
- return true;
- },
- error : function () {
- throw new Error('Error retrieving "' + url + '" zoneinfo files');
- }
- });
- }
- function getRegionForTimezone(tz) {
- var exc = regionExceptions[tz]
- , reg
- , ret;
- if (exc) return exc;
- reg = tz.split('/')[0];
- ret = regionMap[reg];
- // If there's nothing listed in the main regions for this TZ, check the 'backward' links
- if (ret) return ret;
- var link = _this.zones[tz];
- if (typeof link === 'string') {
- return getRegionForTimezone(link);
- }
- // Backward-compat file hasn't loaded yet, try looking in there
- if (!_this.loadedZones.backward) {
- // This is for obvious legacy zones (e.g., Iceland) that don't even have a prefix like "America/" that look like normal zones
- _this.loadZoneFile('backward');
- return getRegionForTimezone(tz);
- }
- invalidTZError(tz);
- }
- function parseTimeString(str) {
- var pat = /(\d+)(?::0*(\d*))?(?::0*(\d*))?([wsugz])?$/;
- var hms = str.match(pat);
- hms[1] = parseInt(hms[1], 10);
- hms[2] = hms[2] ? parseInt(hms[2], 10) : 0;
- hms[3] = hms[3] ? parseInt(hms[3], 10) : 0;
-
- return hms;
- }
- function processZone(z) {
- if (!z[3]) { return; }
- var yea = parseInt(z[3], 10);
- var mon = 11;
- var dat = 31;
- if (z[4]) {
- mon = SHORT_MONTHS[z[4].substr(0, 3)];
- dat = parseInt(z[5], 10) || 1;
- }
- var string = z[6] ? z[6] : '00:00:00'
- , t = parseTimeString(string);
- return [yea, mon, dat, t[1], t[2], t[3]];
- }
- function getZone(dt, tz) {
- var utcMillis = typeof dt === 'number' ? dt : new Date(dt).getTime();
- var t = tz;
- var zoneList = _this.zones[t];
- // Follow links to get to an actual zone
- while (typeof zoneList === "string") {
- t = zoneList;
- zoneList = _this.zones[t];
- }
- if (!zoneList) {
- // Backward-compat file hasn't loaded yet, try looking in there
- if (!_this.loadedZones.backward) {
- //This is for backward entries like "America/Fort_Wayne" that
- // getRegionForTimezone *thinks* it has a region file and zone
- // for (e.g., America => 'northamerica'), but in reality it's a
- // legacy zone we need the backward file for.
- _this.loadZoneFile('backward');
- return getZone(dt, tz);
- }
- invalidTZError(t);
- }
- if (zoneList.length === 0) {
- throw new Error('No Zone found for "' + tz + '" on ' + dt);
- }
- //Do backwards lookup since most use cases deal with newer dates.
- for (var i = zoneList.length - 1; i >= 0; i--) {
- var z = zoneList[i];
- if (z[3] && utcMillis > z[3]) break;
- }
- return zoneList[i+1];
- }
- function getBasicOffset(time) {
- var off = parseTimeString(time)
- , adj = time.charAt(0) === '-' ? -1 : 1;
- off = adj * (((off[1] * 60 + off[2]) * 60 + off[3]) * 1000);
- return off/60/1000;
- }
-
- //if isUTC is true, date is given in UTC, otherwise it's given
- // in local time (ie. date.getUTC*() returns local time components)
- function getRule(dt, zone, isUTC) {
- var date = typeof dt === 'number' ? new Date(dt) : dt;
- var ruleset = zone[1];
- var basicOffset = zone[0];
-
- // If the zone has a DST rule like '1:00', create a rule and return it
- // instead of looking it up in the parsed rules
- var staticDstMatch = ruleset.match(/^([0-9]):([0-9][0-9])$/);
- if (staticDstMatch) {
- return [-1000000,'max','-','Jan',1,parseTimeString('0:00'),parseInt(staticDstMatch[1]) * 60 + parseInt(staticDstMatch[2]), '-'];
- }
-
- //Convert a date to UTC. Depending on the 'type' parameter, the date
- // parameter may be:
- //
- // - `u`, `g`, `z`: already UTC (no adjustment).
- //
- // - `s`: standard time (adjust for time zone offset but not for DST)
- //
- // - `w`: wall clock time (adjust for both time zone and DST offset).
- //
- // DST adjustment is done using the rule given as third argument.
- var convertDateToUTC = function (date, type, rule) {
- var offset = 0;
-
- if (type === 'u' || type === 'g' || type === 'z') { // UTC
- offset = 0;
- } else if (type === 's') { // Standard Time
- offset = basicOffset;
- } else if (type === 'w' || !type) { // Wall Clock Time
- offset = getAdjustedOffset(basicOffset, rule);
- } else {
- throw("unknown type " + type);
- }
- offset *= 60 * 1000; // to millis
-
- return new Date(date.getTime() + offset);
- };
-
- //Step 1: Find applicable rules for this year.
- //
- //Step 2: Sort the rules by effective date.
- //
- //Step 3: Check requested date to see if a rule has yet taken effect this year. If not,
- //
- //Step 4: Get the rules for the previous year. If there isn't an applicable rule for last year, then
- // there probably is no current time offset since they seem to explicitly turn off the offset
- // when someone stops observing DST.
- //
- // FIXME if this is not the case and we'll walk all the way back (ugh).
- //
- //Step 5: Sort the rules by effective date.
- //Step 6: Apply the most recent rule before the current time.
- var convertRuleToExactDateAndTime = function (yearAndRule, prevRule) {
- var year = yearAndRule[0]
- , rule = yearAndRule[1];
- // Assume that the rule applies to the year of the given date.
-
- var hms = rule[5];
- var effectiveDate;
-
- if (!EXACT_DATE_TIME[year])
- EXACT_DATE_TIME[year] = {};
-
- // Result for given parameters is already stored
- if (EXACT_DATE_TIME[year][rule])
- effectiveDate = EXACT_DATE_TIME[year][rule];
- else {
- //If we have a specific date, use that!
- if (!isNaN(rule[4])) {
- effectiveDate = new Date(Date.UTC(year, SHORT_MONTHS[rule[3]], rule[4], hms[1], hms[2], hms[3], 0));
- }
- //Let's hunt for the date.
- else {
- var targetDay
- , operator;
- //Example: `lastThu`
- if (rule[4].substr(0, 4) === "last") {
- // Start at the last day of the month and work backward.
- effectiveDate = new Date(Date.UTC(year, SHORT_MONTHS[rule[3]] + 1, 1, hms[1] - 24, hms[2], hms[3], 0));
- targetDay = SHORT_DAYS[rule[4].substr(4, 3)];
- operator = "<=";
- }
- //Example: `Sun>=15`
- else {
- //Start at the specified date.
- effectiveDate = new Date(Date.UTC(year, SHORT_MONTHS[rule[3]], rule[4].substr(5), hms[1], hms[2], hms[3], 0));
- targetDay = SHORT_DAYS[rule[4].substr(0, 3)];
- operator = rule[4].substr(3, 2);
- }
- var ourDay = effectiveDate.getUTCDay();
- //Go forwards.
- if (operator === ">=") {
- effectiveDate.setUTCDate(effectiveDate.getUTCDate() + (targetDay - ourDay + ((targetDay < ourDay) ? 7 : 0)));
- }
- //Go backwards. Looking for the last of a certain day, or operator is "<=" (less likely).
- else {
- effectiveDate.setUTCDate(effectiveDate.getUTCDate() + (targetDay - ourDay - ((targetDay > ourDay) ? 7 : 0)));
- }
- }
- EXACT_DATE_TIME[year][rule] = effectiveDate;
- }
-
-
- //If previous rule is given, correct for the fact that the starting time of the current
- // rule may be specified in local time.
- if (prevRule) {
- effectiveDate = convertDateToUTC(effectiveDate, hms[4], prevRule);
- }
- return effectiveDate;
- };
-
- var findApplicableRules = function (year, ruleset) {
- var applicableRules = [];
- for (var i = 0; ruleset && i < ruleset.length; i++) {
- //Exclude future rules.
- if (ruleset[i][0] <= year &&
- (
- // Date is in a set range.
- ruleset[i][1] >= year ||
- // Date is in an "only" year.
- (ruleset[i][0] === year && ruleset[i][1] === "only") ||
- //We're in a range from the start year to infinity.
- ruleset[i][1] === "max"
- )
- ) {
- //It's completely okay to have any number of matches here.
- // Normally we should only see two, but that doesn't preclude other numbers of matches.
- // These matches are applicable to this year.
- applicableRules.push([year, ruleset[i]]);
- }
- }
- return applicableRules;
- };
-
- var compareDates = function (a, b, prev) {
- var year, rule;
- if (a.constructor !== Date) {
- year = a[0];
- rule = a[1];
- a = (!prev && EXACT_DATE_TIME[year] && EXACT_DATE_TIME[year][rule])
- ? EXACT_DATE_TIME[year][rule]
- : convertRuleToExactDateAndTime(a, prev);
- } else if (prev) {
- a = convertDateToUTC(a, isUTC ? 'u' : 'w', prev);
- }
- if (b.constructor !== Date) {
- year = b[0];
- rule = b[1];
- b = (!prev && EXACT_DATE_TIME[year] && EXACT_DATE_TIME[year][rule]) ? EXACT_DATE_TIME[year][rule]
- : convertRuleToExactDateAndTime(b, prev);
- } else if (prev) {
- b = convertDateToUTC(b, isUTC ? 'u' : 'w', prev);
- }
- a = Number(a);
- b = Number(b);
- return a - b;
- };
-
- var year = date.getUTCFullYear();
- var applicableRules;
-
- applicableRules = findApplicableRules(year, _this.rules[ruleset]);
- applicableRules.push(date);
- //While sorting, the time zone in which the rule starting time is specified
- // is ignored. This is ok as long as the timespan between two DST changes is
- // larger than the DST offset, which is probably always true.
- // As the given date may indeed be close to a DST change, it may get sorted
- // to a wrong position (off by one), which is corrected below.
- applicableRules.sort(compareDates);
-
- //If there are not enough past DST rules...
- if (_arrIndexOf.call(applicableRules, date) < 2) {
- applicableRules = applicableRules.concat(findApplicableRules(year-1, _this.rules[ruleset]));
- applicableRules.sort(compareDates);
- }
- var pinpoint = _arrIndexOf.call(applicableRules, date);
- if (pinpoint > 1 && compareDates(date, applicableRules[pinpoint-1], applicableRules[pinpoint-2][1]) < 0) {
- //The previous rule does not really apply, take the one before that.
- return applicableRules[pinpoint - 2][1];
- } else if (pinpoint > 0 && pinpoint < applicableRules.length - 1 && compareDates(date, applicableRules[pinpoint+1], applicableRules[pinpoint-1][1]) > 0) {
-
- //The next rule does already apply, take that one.
- return applicableRules[pinpoint + 1][1];
- } else if (pinpoint === 0) {
- //No applicable rule found in this and in previous year.
- return null;
- }
- return applicableRules[pinpoint - 1][1];
- }
- function getAdjustedOffset(off, rule) {
- return -Math.ceil(rule[6] - off);
- }
- function getAbbreviation(zone, rule) {
- var res;
- var base = zone[2];
- if (base.indexOf('%s') > -1) {
- var repl;
- if (rule) {
- repl = rule[7] === '-' ? '' : rule[7];
- }
- //FIXME: Right now just falling back to Standard --
- // apparently ought to use the last valid rule,
- // although in practice that always ought to be Standard
- else {
- repl = 'S';
- }
- res = base.replace('%s', repl);
- }
- else if (base.indexOf('/') > -1) {
- //Chose one of two alternative strings.
- res = base.split("/", 2)[rule[6] ? 1 : 0];
- } else {
- res = base;
- }
- return res;
- }
-
- this.zoneFileBasePath = null;
- this.zoneFiles = ['africa', 'antarctica', 'asia', 'australasia', 'backward', 'etcetera', 'europe', 'northamerica', 'pacificnew', 'southamerica'];
- this.loadingSchemes = {
- PRELOAD_ALL: 'preloadAll',
- LAZY_LOAD: 'lazyLoad',
- MANUAL_LOAD: 'manualLoad'
- };
- this.loadingScheme = this.loadingSchemes.LAZY_LOAD;
- this.loadedZones = {};
- this.zones = {};
- this.rules = {};
-
- this.init = function (o) {
- var opts = { async: true }
- , def = this.loadingScheme === this.loadingSchemes.PRELOAD_ALL
- ? this.zoneFiles
- : (this.defaultZoneFile || 'northamerica')
- , done = 0
- , callbackFn;
- //Override default with any passed-in opts
- for (var p in o) {
- opts[p] = o[p];
- }
- if (typeof def === 'string') {
- return this.loadZoneFile(def, opts);
- }
- //Wraps callback function in another one that makes
- // sure all files have been loaded.
- callbackFn = opts.callback;
- opts.callback = function () {
- done++;
- (done === def.length) && typeof callbackFn === 'function' && callbackFn();
- };
- for (var i = 0; i < def.length; i++) {
- this.loadZoneFile(def[i], opts);
- }
- };
-
- //Get the zone files via XHR -- if the sync flag
- // is set to true, it's being called by the lazy-loading
- // mechanism, so the result needs to be returned inline.
- this.loadZoneFile = function (fileName, opts) {
- if (typeof this.zoneFileBasePath === 'undefined') {
- throw new Error('Please define a base path to your zone file directory -- timezoneJS.timezone.zoneFileBasePath.');
- }
- //Ignore already loaded zones.
- if (this.loadedZones[fileName]) {
- return;
- }
- this.loadedZones[fileName] = true;
- return builtInLoadZoneFile(fileName, opts);
- };
- this.loadZoneJSONData = function (url, sync) {
- var processData = function (data) {
- data = eval('('+ data +')');
- for (var z in data.zones) {
- _this.zones[z] = data.zones[z];
- }
- for (var r in data.rules) {
- _this.rules[r] = data.rules[r];
- }
- };
- return sync
- ? processData(_this.transport({ url : url, async : false }))
- : _this.transport({ url : url, success : processData });
- };
- this.loadZoneDataFromObject = function (data) {
- if (!data) { return; }
- for (var z in data.zones) {
- _this.zones[z] = data.zones[z];
- }
- for (var r in data.rules) {
- _this.rules[r] = data.rules[r];
- }
- };
- this.getAllZones = function () {
- var arr = [];
- for (var z in this.zones) { arr.push(z); }
- return arr.sort();
- };
- this.parseZones = function (str) {
- var lines = str.split('\n')
- , arr = []
- , chunk = ''
- , l
- , zone = null
- , rule = null;
- for (var i = 0; i < lines.length; i++) {
- l = lines[i];
- if (l.match(/^\s/)) {
- l = "Zone " + zone + l;
- }
- l = l.split("#")[0];
- if (l.length > 3) {
- arr = l.split(/\s+/);
- chunk = arr.shift();
- //Ignore Leap.
- switch (chunk) {
- case 'Zone':
- zone = arr.shift();
- if (!_this.zones[zone]) {
- _this.zones[zone] = [];
- }
- if (arr.length < 3) break;
- //Process zone right here and replace 3rd element with the processed array.
- arr.splice(3, arr.length, processZone(arr));
- if (arr[3]) arr[3] = Date.UTC.apply(null, arr[3]);
- arr[0] = -getBasicOffset(arr[0]);
- _this.zones[zone].push(arr);
- break;
- case 'Rule':
- rule = arr.shift();
- if (!_this.rules[rule]) {
- _this.rules[rule] = [];
- }
- //Parse int FROM year and TO year
- arr[0] = parseInt(arr[0], 10);
- arr[1] = parseInt(arr[1], 10) || arr[1];
- //Parse time string AT
- arr[5] = parseTimeString(arr[5]);
- //Parse offset SAVE
- arr[6] = getBasicOffset(arr[6]);
- _this.rules[rule].push(arr);
- break;
- case 'Link':
- //No zones for these should already exist.
- if (_this.zones[arr[1]]) {
- throw new Error('Error with Link ' + arr[1] + '. Cannot create link of a preexisted zone.');
- }
- //Create the link.
- _this.zones[arr[1]] = arr[0];
- break;
- }
- }
- }
- return true;
- };
- //Expose transport mechanism and allow overwrite.
- this.transport = _transport;
- this.getTzInfo = function (dt, tz, isUTC) {
- //Lazy-load any zones not yet loaded.
- if (this.loadingScheme === this.loadingSchemes.LAZY_LOAD) {
- //Get the correct region for the zone.
- var zoneFile = getRegionForTimezone(tz);
- if (!zoneFile) {
- throw new Error('Not a valid timezone ID.');
- }
- if (!this.loadedZones[zoneFile]) {
- //Get the file and parse it -- use synchronous XHR.
- this.loadZoneFile(zoneFile);
- }
- }
- var z = getZone(dt, tz);
- var off = z[0];
- //See if the offset needs adjustment.
- var rule = getRule(dt, z, isUTC);
- if (rule) {
- off = getAdjustedOffset(off, rule);
- }
- var abbr = getAbbreviation(z, rule);
- return { tzOffset: off, tzAbbr: abbr };
- };
- };
-}).call(this);
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-metron/blob/40aadab8/metron-ui/lib/views/alerts.jade
----------------------------------------------------------------------
diff --git a/metron-ui/lib/views/alerts.jade b/metron-ui/lib/views/alerts.jade
deleted file mode 100644
index 758e3b5..0000000
--- a/metron-ui/lib/views/alerts.jade
+++ /dev/null
@@ -1,79 +0,0 @@
-//
- Licensed to the Apache Software Foundation (ASF) under one
- or more contributor license agreements. See the NOTICE file
- distributed with this work for additional information
- regarding copyright ownership. The ASF licenses this file
- to you 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.
-//
-
-doctype html
-html
- head
- meta(charset='utf-8')
- meta(http-equiv='X-UA-Compatible', content='IE=edge,chrome=1')
- meta(name='viewport', content='width=device-width')
- title Kibana 3 - Alerts
- link(rel='stylesheet', href='css/bootstrap.dark.min.css', title='Dark')
- link(rel='stylesheet', href='css/timepicker.css')
- link(rel='stylesheet', href='css/animate.min.css')
- link(rel='stylesheet', href='css/normalize.min.css')
- link(rel='stylesheet', href='css/metron.css')
- script(src='vendor/require/require.js')
- script(src='app/components/require.config.js')
- script.
- require(['app'], function () {
- function updateAlerts(alert) {
- if (alerts[alert.title]) {
- alerts[alert.title].count++;
- jQuery('#' + alerts[alert.title].id).html(alerts[alert.title].count);
- } else {
- var id = 'alert-' + Math.floor((Math.random() * 1000000) + 1);
- alerts[alert.title] = { count: 1, id: id, title: alert.title };
- console.log(alerts[alert.title]);
- jQuery('#realtime-alerts tbody').append(
- '<tr><td class="count" id="' + id + '">' + alerts[alert.title].count + '</td><td>' + alerts[alert.title].title + '</td><td>' + (new Date()) + '</td></tr>'
- );
- }
- }
-
- var host = window.document.location.host.replace(/:.*/, '');
- var port = window.document.location.port;
- var ws = new WebSocket('ws://' + host + ':' + port + '/alert');
- var alerts = {};
- ws.onmessage = function (event) {
- console.log(event);
- updateAlerts(JSON.parse(event.data));
- };
- })
- style
- body
- noscript
- .container
- center
- h3 You must enable javascript to use Kibana
- link(rel='stylesheet', href='css/bootstrap.dark.min.css')
- link(rel='stylesheet', href='css/bootstrap-responsive.min.css')
- link(rel='stylesheet', href='css/font-awesome.min.css')
- .container-fluid
- .row-fluid
- .span6.offset3
- table#realtime-alerts.table
- caption Dashboard Alerts
- thead
- tr
- th Count
- th Dashboard Name
- th Last Alert
- tbody
- //
- <div ng-cloak ng-view></div>
http://git-wip-us.apache.org/repos/asf/incubator-metron/blob/40aadab8/metron-ui/lib/views/index.jade
----------------------------------------------------------------------
diff --git a/metron-ui/lib/views/index.jade b/metron-ui/lib/views/index.jade
deleted file mode 100644
index 4246b58..0000000
--- a/metron-ui/lib/views/index.jade
+++ /dev/null
@@ -1,60 +0,0 @@
-//
- Licensed to the Apache Software Foundation (ASF) under one
- or more contributor license agreements. See the NOTICE file
- distributed with this work for additional information
- regarding copyright ownership. The ASF licenses this file
- to you 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.
-//
-
-doctype html
-html
- head
- meta(charset='utf-8')
- meta(http-equiv='X-UA-Compatible', content='IE=edge,chrome=1')
- meta(name='viewport', content='width=device-width')
- title Kibana 3{{dashboard.current.title ? " - "+dashboard.current.title : ""}}
- link(rel='stylesheet', href='css/bootstrap.light.min.css', title='Light')
- link(rel='stylesheet', href='css/timepicker.css')
- link(rel='stylesheet', href='css/animate.min.css')
- link(rel='stylesheet', href='css/normalize.min.css')
- link(rel='stylesheet', href='css/metron.css')
- //
- load the root require context
- script(src='vendor/require/require.js')
- script(src='app/components/require.config.js')
- script.
- user=!{user}
- config=!{config}
- require(['app'], function () {})
- style
- body
- noscript
- .container
- center
- h3 You must enable javascript to use Kibana
- link(rel='stylesheet', ng-href='css/bootstrap.{{dashboard.current.style||\'dark\'}}.min.css')
- link(rel='stylesheet', href='css/bootstrap-responsive.min.css')
- link(rel='stylesheet', href='css/font-awesome.min.css')
- div(class='alert-{{alert.severity}} dashboard-notice', ng-cloak='ng-cloak', ng-repeat='alert in dashAlerts.list', ng-show='$last')
- button.close(type='button', ng-click='dashAlerts.clear(alert)', style='padding-right: 50px;') �
- strong {{alert.title}}
- span(ng-bind-html='alert.text')
- .pull-right.small(style='padding-right: 10px;') {{$index + 1}} alert(s)
- .navbar.navbar-static-top(ng-cloak='ng-cloak')
- .navbar-inner
- .container-fluid
- span.brand
- img(src='img/small.png', bs-tooltip='\'Kibana \'+(kbnVersion==\'@REV@\'?\'master\':kbnVersion)', data-placement='bottom')
- | {{dashboard.current.title}}
- ul.nav.pull-right(ng-controller='dashLoader', ng-init='init()', ng-include='\'app/partials/dashLoader.html\'')
- div(ng-cloak='ng-cloak', ng-view='ng-view')
http://git-wip-us.apache.org/repos/asf/incubator-metron/blob/40aadab8/metron-ui/lib/views/login.jade
----------------------------------------------------------------------
diff --git a/metron-ui/lib/views/login.jade b/metron-ui/lib/views/login.jade
deleted file mode 100644
index d2da35c..0000000
--- a/metron-ui/lib/views/login.jade
+++ /dev/null
@@ -1,61 +0,0 @@
-//
- Licensed to the Apache Software Foundation (ASF) under one
- or more contributor license agreements. See the NOTICE file
- distributed with this work for additional information
- regarding copyright ownership. The ASF licenses this file
- to you 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.
-//
-
-doctype html
-html
- head
- meta(charset='utf-8')
- meta(http-equiv='X-UA-Compatible', content='IE=edge,chrome=1')
- meta(name='viewport', content='width=device-width')
- title Metron - Login
- link(rel='stylesheet', href='css/bootstrap.dark.min.css', title='Dark')
- link(rel='stylesheet', href='css/timepicker.css')
- link(rel='stylesheet', href='css/animate.min.css')
- link(rel='stylesheet', href='css/normalize.min.css')
- link(rel='stylesheet', href='css/metron.css')
- style
- body
- noscript
- .container
- center
- h3 You must enable javascript to use Kibana
- link(rel='stylesheet', href='css/bootstrap.dark.min.css')
- link(rel='stylesheet', href='css/bootstrap-responsive.min.css')
- link(rel='stylesheet', href='css/font-awesome.min.css')
- .container-fluid
- .row-fluid
- .span6.offset3
- form.form-horizontal.login-form(action='/login', method='POST')
- fieldset
- legend Login
- if flash.error
- .alert.alert-error=flash.error
- div(class="#{flash.error ? 'control-group error' : 'control-group'}")
- label.control-label(for='inputEmail') Email
- .controls
- input#inputEmail(type='text', name='email', placeholder='Email')
-
- div(class="#{flash.error ? 'control-group error' : 'control-group'}")
- label.control-label(for='inputPassword') Password
- .controls
- input#inputPassword(type='password', name='password', placeholder='Password')
- .control-group
- .controls
- button.btn(type='submit') Sign in
- //
- <div ng-cloak ng-view></div>
http://git-wip-us.apache.org/repos/asf/incubator-metron/blob/40aadab8/metron-ui/package.json
----------------------------------------------------------------------
diff --git a/metron-ui/package.json b/metron-ui/package.json
deleted file mode 100644
index d142489..0000000
--- a/metron-ui/package.json
+++ /dev/null
@@ -1,26 +0,0 @@
-{
- "name": "metron-ui",
- "version": "0.0.0",
- "private": true,
- "scripts": {
- "start": "node ./bin/www"
- },
- "dependencies": {
- "body-parser": "~1.13.2",
- "cookie-parser": "~1.3.5",
- "debug": "~2.2.0",
- "express": "~4.13.1",
- "jade": "~1.11.0",
- "morgan": "~1.6.1",
- "serve-favicon": "~2.3.0",
- "lodash": "~4.6.1",
- "connect": "3.4.1",
- "connect-flash": "~0.1.1",
- "cookie-session": "~2.0.0-alpha.1",
- "passport": "~0.3.2",
- "passport-ldapauth": "~0.5.0",
- "http-proxy": "~1.13.2",
- "xml-stream": "~0.4.5",
- "serve-static": "~1.10.2"
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-metron/blob/40aadab8/metron-ui/script/es_fetch
----------------------------------------------------------------------
diff --git a/metron-ui/script/es_fetch b/metron-ui/script/es_fetch
deleted file mode 100755
index 54c2c5a..0000000
--- a/metron-ui/script/es_fetch
+++ /dev/null
@@ -1,81 +0,0 @@
-#!/usr/bin/env node
-
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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.
- */
-
-/*
- * fetch.js
- * A small utility to fetch records from Elasticsearch and save as JSON
- *
- */
-
-var http = require('http')
- , fs = require('fs')
- , _ = require('lodash');
-
-var options = {
- host: process.env.ES_HOST || 'localhost',
- port: 9200
-};
-
-var size = 1000;
-var fields = [ '_source' ];
-
-// indices to pull test data from
-var indices = [
- 'sourcefire',
- 'qosmos',
- 'qradar',
- 'fireeye',
- 'bro-201405050800'
-];
-
-var retrieve = function (index, i) {
- options.path =
- '/' + index + '/_search?size=' + size + '&fields=' + fields.join(',');
-
- http.get(options, function (response) {
- var data = [];
-
- response.on('data', function (chunk) {
- data.push(chunk);
- });
-
- response.on('end', function () {
- var filePath = 'seed/es/' + index + '.json'
- , results = _.pluck(JSON.parse(data.join('')).hits.hits, '_source');
-
- var output = results.map(function (v) {
- return JSON.stringify(v);
- });
-
- // ES-friendly bulk format
- var fmt = "{\"index\": { \"_index\": \"" + index +
- "\", \"_type\": \"" + index + "\"}}\n";
- var toWrite = fmt + output.join("\n" + fmt) + "\n";
-
- fs.writeFile(filePath, toWrite, function (err) {
- if (err) {
- throw err;
- }
- });
- });
- });
-};
-
-indices.forEach(retrieve);
http://git-wip-us.apache.org/repos/asf/incubator-metron/blob/40aadab8/metron-ui/script/es_gen.js
----------------------------------------------------------------------
diff --git a/metron-ui/script/es_gen.js b/metron-ui/script/es_gen.js
deleted file mode 100755
index 2da17fa..0000000
--- a/metron-ui/script/es_gen.js
+++ /dev/null
@@ -1,191 +0,0 @@
-#!/usr/bin/env node
-
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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.
- */
-
-/*
- * es_gen.js
- * A small utility that generates json seed data for Elasticsearch
- *
- */
-
-var _ = require('lodash');
-var Chance = require('chance');
-var fs = require('fs');
-
-var chance = new Chance();
-var documentsPerIndex = 1000;
-var numEnrichedMachines = 100;
-var numOtherMachines = 200;
-
-var oneMonthAgo = new Date();
-oneMonthAgo.setMonth(oneMonthAgo.getMonth() - 1);
-
-var startTimestamp = oneMonthAgo.getTime();
-var endTimestamp = startTimestamp + (90 * 24 * 60 * 60 * 1000);
-var sources = [
- 'bro',
- 'fireeye',
- 'lancope',
- 'qosmos',
- 'qradar',
- 'sourcefire'
-];
-
-
-var inventory = [];
-var assetValues = ['important', 'mundane'];
-var assetTypes = ['printer', 'server', 'router'];
-var alertType = ['error', 'warning', 'alert'];
-var clusters = ['preprod', 'cluster A', 'cluster B'];
-var protocols = ['tcp', 'udp'];
-var protocolMap = {tcp: 6, udp: 17};
-
-function pad(n, width, z) {
- z = z || '0';
- n = n + '';
- return n.length >= width ? n : new Array(width - n.length + 1).join(z) + n;
-}
-
-function ipToHex(ip) {
- var parts = ip.split('.');
- for (var i = 0; i < parts.length; i++) {
- parts[i] = parseInt(parts[i]).toString(16);
- }
- return parts.join('');
-}
-
-function choice(arr) {
- return arr[Math.floor(Math.random() * arr.length)];
-}
-
-function randomAlert(source) {
- var dst = choice(inventory);
- var src = choice(inventory);
- var protocol = choice(protocols);
- var instance = pad(chance.integer({min: 1, max: 3}), 3);
- var triggered = [];
-
- for(var i = 0; i < chance.integer({min: 1, max: 1}); i++) {
- triggered.push({
- body: chance.sentence(),
- title: chance.word(),
- type: choice(alertType),
- priority: chance.integer({min: 1, max: 3})
- });
- }
-
- return {
- alerts: {
- identifier: {
- topology: {
- topology: source,
- topology_instance: source[0].toUpperCase() + instance
- },
- environment: {
- customer: 'mtd',
- instance: 'dev',
- datacenter: choice(clusters)
- }
- },
- triggered: triggered[0]
- },
- message: {
- ip_dst_addr: dst.ip,
- ip_src_addr: src.ip,
- ip_dst_port: chance.integer({min: 22, max: 65535}),
- ip_src_port: chance.integer({min: 22, max: 65535}),
- protocol: protocol,
- original_string: chance.paragraph(),
- timestamp: chance.integer({min: startTimestamp, max: endTimestamp})
- },
- enrichment: {
- geo: {
- ip_dst_addr: dst.geo,
- ip_src_addr: src.geo
- },
- host: {
- ip_dst_addr: dst.host,
- ip_src_addr: src.host
- }
- }
- };
-}
-
-for (var i = 0; i < numEnrichedMachines; i++) {
- inventory.push({
- ip: chance.ip(),
- geo: {
- country: 'US',
- dmaCode: chance.integer({min: 500, max: 700}),
- city: chance.city(),
- postalCode: chance.zip(),
- latitude: chance.latitude({fixed: 4}),
- longitude: chance.longitude({fixed: 4}),
- locID: chance.integer({min: 10000, max: 30000})
- },
- host: {
- known_info: {
- asset_value: choice(assetValues),
- type: choice(assetTypes),
- local: choice(['YES', 'NO'])
- }
- }
- });
-}
-
-for (var i = 0; i < numOtherMachines; i++) {
- inventory.push({ip: chance.ip()});
-}
-
-for (var i = 0; i < sources.length; i++) {
- var source = sources[i];
- var filename = source + '.json';
- var json = fs.createWriteStream('seed/es/' + filename);
- var objects = [];
-
- for (var j = 0; j < documentsPerIndex; j++) {
- var index = source + '_index';
- var type = source + '_type';
- objects.push(JSON.stringify({index: {_index: index, _type: type}}));
-
- var alertData = randomAlert(source);
- objects.push(JSON.stringify(alertData));
-
- objects.push(JSON.stringify({index: {_index: 'pcap_all', _type: 'pcap'}}));
- objects.push(JSON.stringify({
- ip_src_addr: alertData.message.ip_src_addr,
- ip_dst_addr: alertData.message.ip_dst_addr,
- ip_src_port: alertData.message.ip_src_port,
- ip_dst_port: alertData.message.ip_dst_port,
- protocol: protocolMap[alertData.message.protocol],
- pcap_id: [
- ipToHex(alertData.message.ip_src_addr),
- ipToHex(alertData.message.ip_dst_addr),
- protocolMap[alertData.message.protocol],
- alertData.message.ip_src_port,
- alertData.message.ip_dst_port,
- pad(chance.integer({min: 0, max: 99999}), 5),
- pad(chance.integer({min: 0, max: 99999}), 5)
- ].join('-')
- }));
- }
-
- json.write(objects.join('\n'));
- json.close();
-}
http://git-wip-us.apache.org/repos/asf/incubator-metron/blob/40aadab8/metron-ui/script/es_seed
----------------------------------------------------------------------
diff --git a/metron-ui/script/es_seed b/metron-ui/script/es_seed
deleted file mode 100755
index 3fd1ea8..0000000
--- a/metron-ui/script/es_seed
+++ /dev/null
@@ -1,87 +0,0 @@
-#!/usr/bin/env sh
-#
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements. See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership. The ASF licenses this file
-# to you 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.
-#
-
-
-# Delete all existing indices.
-curl -XDELETE 'http://localhost:9200/_all/'
-
-# Create the PCAP index.
-curl -XPUT 'http://localhost:9200/pcap_all/' -d '{
- "settings": {
- "index.codec.bloom.load": false,
- "index.compound_on_flush": false,
- "index.compound_format": false,
- "index.merge.policy.use_compound_file": false,
- "index.refresh_interval": 120,
- "index.action.write_consistency": false,
- "index.translog.flush_threshold_ops": 100000,
- "index.compound_on_flush": false,
- "index.compound_format": false,
- "index.merge.policy.use_compound_file": false,
- "index.merge.policy.segments_per_tier": 50,
- "index.merge.policy.max_merge_at_once_explicit": 50,
- "index.merge.policy.max_merge_at_once": 30,
- "index.merge.policy.floor_segment": 1
- },
- "mappings": {
- "pcap": {
- "_all": {
- "enabled": false
- },
- "_source": {
- "includes": ["pcap_id"]
- },
- "properties": {
- "pcap_id": {
- "type": "string",
- "index": "no",
- "postings_format": "Lucene41"
- },
- "ip_protocol": {
- "type": "long",
- "precision_step" : 64
- },
- "src_addr": {
- "type": "string",
- "index": "not_analyzed",
- "postings_format": "Lucene41"
- },
- "src_port": {
- "type": "long",
- "precision_step" : 64
- },
- "dst_addr": {
- "type": "string",
- "index": "not_analyzed",
- "postings_format": "Lucene41"
- },
- "dst_port": {
- "type": "long",
- "precision_step" : 64
- }
- }
- }
- }
-}'
-
-# Seed Elasticsearch.
-for file in seed/es/*.json
-do
- curl -s -XPOST --data-binary @$file 'http://localhost:9200/_bulk'
-done
http://git-wip-us.apache.org/repos/asf/incubator-metron/blob/40aadab8/metron-ui/script/generate_alert
----------------------------------------------------------------------
diff --git a/metron-ui/script/generate_alert b/metron-ui/script/generate_alert
deleted file mode 100755
index 74d3228..0000000
--- a/metron-ui/script/generate_alert
+++ /dev/null
@@ -1,56 +0,0 @@
-#!/usr/bin/env node
-
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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.
- */
-
-// Script to generate sample alerts
-
-var kafka = require('../lib/modules/kafka')
- , Chance = require('chance')
- , chance = new Chance()
-
- // Number of randomly-generated messages per second
- , mps = 5
- , topic = 'metron'
- , dashboardCount = 10;
-
-var dashboards = [];
-
-for (var i = 0; i < dashboardCount; i++) {
- dashboards.push({
- title: chance.sentence({
- words: chance.integer({ min: 1, max: 7 })
- }).replace(/\./, '')
- });
-}
-
-
-// Fire off random text
-setInterval(function () {
- var message = dashboards[chance.integer({ min: 0, max: dashboardCount-1 })];
-
- kafka.produce(topic, JSON.stringify(message), function (err, result) {
- console.log('Sending Text:');
- console.log(message);
- console.log();
- console.log('Reply from kafka server:');
- console.log(result);
- console.log();
- console.log();
- });
-}, 1000 / mps);
http://git-wip-us.apache.org/repos/asf/incubator-metron/blob/40aadab8/metron-ui/script/ldap_seed
----------------------------------------------------------------------
diff --git a/metron-ui/script/ldap_seed b/metron-ui/script/ldap_seed
deleted file mode 100755
index b64fd54..0000000
--- a/metron-ui/script/ldap_seed
+++ /dev/null
@@ -1,22 +0,0 @@
-#!/usr/bin/env sh
-#
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements. See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership. The ASF licenses this file
-# to you 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.
-#
-
-cd /vagrant/seed/ldap
-sudo ldapadd -h localhost -p 389 -D 'cn=admin,dc=metron,dc=dev' -w metron -f content.ldif
-cd -
http://git-wip-us.apache.org/repos/asf/incubator-metron/blob/40aadab8/metron-ui/script/migrate
----------------------------------------------------------------------
diff --git a/metron-ui/script/migrate b/metron-ui/script/migrate
deleted file mode 100755
index ac41f13..0000000
--- a/metron-ui/script/migrate
+++ /dev/null
@@ -1,20 +0,0 @@
-#!/usr/bin/env sh
-#
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements. See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership. The ASF licenses this file
-# to you 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.
-#
-
-./node_modules/db-migrate/bin/db-migrate $@
http://git-wip-us.apache.org/repos/asf/incubator-metron/blob/40aadab8/metron-ui/script/parse
----------------------------------------------------------------------
diff --git a/metron-ui/script/parse b/metron-ui/script/parse
deleted file mode 100755
index 1aab1fe..0000000
--- a/metron-ui/script/parse
+++ /dev/null
@@ -1,66 +0,0 @@
-#!/usr/bin/env node
-
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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.
- */
-
-var spawn = require('child_process').spawn
- , sax = require('sax')
- , saxpath = require('saxpath')
- , xml2js = require('xml2js')
- , url = process.argv[2];
-
-if (process.argv.length !== 3) {
- console.log('Usage: script/parse [URL of pcap]');
- process.exit(1);
-}
-
-// reset all sax entities
-for (var entity in sax.ENTITIES) {
- sax.ENTITIES[entity] = '&' + entity + ';';
-}
-
-var PCAPToJSON = function (pcapUrl, cb) {
- var saxParser = sax.createStream(true)
- , streamer = new saxpath.SaXPath(saxParser, '/pdml/packet')
- , parser = new xml2js.Parser()
- , curl = spawn('curl', ['-s', pcapUrl])
- , tshark = spawn('tshark', ['-i', '-', '-T', 'pdml']);
-
- streamer.on('match', function (xml) {
- parser.parseString(xml, function (err, result) {
- if (err) {
- console.log('problem with xml chunk:');
- console.log(xml);
- throw err;
- } else {
- cb(result);
- }
- });
- });
-
- curl.stdout.pipe(tshark.stdin);
- tshark.stdout.pipe(saxParser);
-};
-
-PCAPToJSON(url, function (json) {
- // uncomment to output formatted JSON
- console.log(JSON.stringify(json, null, 2));
-
- // uncomment to output condensed JSON
- // console.log(JSON.stringify(json));
-});