helper.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  1. /**
  2. * Licensed to the Apache Software Foundation (ASF) under one
  3. * or more contributor license agreements. See the NOTICE file
  4. * distributed with this work for additional information
  5. * regarding copyright ownership. The ASF licenses this file
  6. * to you under the Apache License, Version 2.0 (the
  7. * "License"); you may not use this file except in compliance
  8. * with the License. You may obtain a copy of the License at
  9. *
  10. * http://www.apache.org/licenses/LICENSE-2.0
  11. *
  12. * Unless required by applicable law or agreed to in writing, software
  13. * distributed under the License is distributed on an "AS IS" BASIS,
  14. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. * See the License for the specific language governing permissions and
  16. * limitations under the License.
  17. */
  18. String.prototype.trim = function () {
  19. return this.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
  20. };
  21. /**
  22. * convert ip address string to long int
  23. * @return {*}
  24. */
  25. String.prototype.ip2long = function () {
  26. // * example 1: ip2long('192.0.34.166');
  27. // * returns 1: 3221234342
  28. // * example 2: ip2long('0.0xABCDEF');
  29. // * returns 2: 11259375
  30. // * example 3: ip2long('255.255.255.256');
  31. // * returns 3: false
  32. var i = 0;
  33. // PHP allows decimal, octal, and hexadecimal IP components.
  34. // PHP allows between 1 (e.g. 127) to 4 (e.g 127.0.0.1) components.
  35. var IP = this.match(/^([1-9]\d*|0[0-7]*|0x[\da-f]+)(?:\.([1-9]\d*|0[0-7]*|0x[\da-f]+))?(?:\.([1-9]\d*|0[0-7]*|0x[\da-f]+))?(?:\.([1-9]\d*|0[0-7]*|0x[\da-f]+))?$/i); // Verify IP format.
  36. if (!IP) {
  37. return false; // Invalid format.
  38. }
  39. // Reuse IP variable for component counter.
  40. IP[0] = 0;
  41. for (i = 1; i < 5; i += 1) {
  42. IP[0] += !!((IP[i] || '').length);
  43. IP[i] = parseInt(IP[i]) || 0;
  44. }
  45. // Continue to use IP for overflow values.
  46. // PHP does not allow any component to overflow.
  47. IP.push(256, 256, 256, 256);
  48. // Recalculate overflow of last component supplied to make up for missing components.
  49. IP[4 + IP[0]] *= Math.pow(256, 4 - IP[0]);
  50. if (IP[1] >= IP[5] || IP[2] >= IP[6] || IP[3] >= IP[7] || IP[4] >= IP[8]) {
  51. return false;
  52. }
  53. return IP[1] * (IP[0] === 1 || 16777216) + IP[2] * (IP[0] <= 2 || 65536) + IP[3] * (IP[0] <= 3 || 256) + IP[4] * 1;
  54. };
  55. String.prototype.capitalize = function () {
  56. return this.charAt(0).toUpperCase() + this.slice(1);
  57. }
  58. Em.CoreObject.reopen({
  59. t:function (key, attrs) {
  60. return Em.I18n.t(key, attrs)
  61. }
  62. });
  63. Em.Handlebars.registerHelper('log', function (variable) {
  64. console.log(variable);
  65. });
  66. Em.Handlebars.registerHelper('warn', function (variable) {
  67. console.warn(variable);
  68. });
  69. Em.Handlebars.registerHelper('highlight', function (property, words, fn) {
  70. var context = (fn.contexts && fn.contexts[0]) || this;
  71. property = Em.Handlebars.getPath(context, property, fn);
  72. words = words.split(";");
  73. // if (highlightTemplate == undefined) {
  74. var highlightTemplate = "<b>{0}</b>";
  75. // }
  76. words.forEach(function (word) {
  77. var searchRegExp = new RegExp("\\b" + word + "\\b", "gi");
  78. property = property.replace(searchRegExp, function (found) {
  79. return highlightTemplate.format(found);
  80. });
  81. });
  82. return new Em.Handlebars.SafeString(property);
  83. })
  84. /**
  85. * Replace {i} with argument. where i is number of argument to replace with
  86. * @return {String}
  87. */
  88. String.prototype.format = function () {
  89. var args = arguments;
  90. return this.replace(/{(\d+)}/g, function (match, number) {
  91. return typeof args[number] != 'undefined' ? args[number] : match;
  92. });
  93. };
  94. String.prototype.highlight = function (words, highlightTemplate) {
  95. var self = this;
  96. if (highlightTemplate == undefined) {
  97. var highlightTemplate = "<b>{0}</b>";
  98. }
  99. words.forEach(function (word) {
  100. var searchRegExp = new RegExp("\\b" + word + "\\b", "gi");
  101. self = self.replace(searchRegExp, function (found) {
  102. return highlightTemplate.format(found);
  103. });
  104. });
  105. return self;
  106. };
  107. /**
  108. * Convert byte size to other metrics.
  109. * @param {Number} precision Number to adjust precision of return value. Default is 0.
  110. * @param {String} parseType JS method name for parse string to number. Default is "parseInt".
  111. * @remarks The parseType argument can be "parseInt" or "parseFloat".
  112. * @return {String) Returns converted value with abbreviation.
  113. */
  114. Number.prototype.bytesToSize = function (precision, parseType/* = 'parseInt' */) {
  115. if (arguments[1] === undefined) {
  116. parseType = 'parseInt';
  117. }
  118. var value = this;
  119. var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
  120. var posttxt = 0;
  121. if (this == 0) return 'n/a';
  122. while (value >= 1024) {
  123. posttxt++;
  124. value = value / 1024;
  125. }
  126. var parsedValue = window[parseType](value);
  127. return parsedValue.toFixed(precision) + " " + sizes[posttxt];
  128. }
  129. Number.prototype.toDaysHoursMinutes = function () {
  130. var formatted = {},
  131. dateDiff = this,
  132. secK = 1000, //ms
  133. minK = 60 * secK, // sec
  134. hourK = 60 * minK, // sec
  135. dayK = 24 * hourK;
  136. dateDiff = parseInt(dateDiff);
  137. formatted.d = Math.floor(dateDiff / dayK);
  138. dateDiff -= formatted.d * dayK;
  139. formatted.h = Math.floor(dateDiff / hourK);
  140. dateDiff -= formatted.h * hourK;
  141. formatted.m = (dateDiff / minK).toFixed(2);
  142. return formatted;
  143. }
  144. Number.prototype.countPercentageRatio = function (maxValue) {
  145. var usedValue = this;
  146. return Math.round((usedValue / maxValue) * 100) + "%";
  147. }
  148. Number.prototype.long2ip = function () {
  149. // http://kevin.vanzonneveld.net
  150. // + original by: Waldo Malqui Silva
  151. // * example 1: long2ip( 3221234342 );
  152. // * returns 1: '192.0.34.166'
  153. if (!isFinite(this))
  154. return false;
  155. return [this >>> 24, this >>> 16 & 0xFF, this >>> 8 & 0xFF, this & 0xFF].join('.');
  156. }
  157. /**
  158. * Formats the given URL template by replacing keys in 'substitutes'
  159. * with their values. If not in App.testMode, the testUrl is used.
  160. *
  161. * The substitution points in urlTemplate should be of format "...{key}..."
  162. * For example "http://apache.org/{projectName}".
  163. * The substitutes can then be{projectName: "Ambari"}.
  164. *
  165. * Keys which will be automatically taken care of are:
  166. * {
  167. * hostName: App.test_hostname,
  168. * fromSeconds: ..., // 1 hour back from now
  169. * toSeconds: ..., // now
  170. * stepSeconds: ..., // 15 seconds by default
  171. * }
  172. *
  173. * @param {String} urlTemplate URL template on which substitutions are to be made
  174. * @param substitutes Object containing keys to be replaced with respective values
  175. * @param {String} testUrl URL to be used if app is not in test mode (!App.testMode)
  176. * @return {String} Formatted URL
  177. */
  178. App.formatUrl = function (urlTemplate, substitutes, testUrl) {
  179. var formatted = urlTemplate;
  180. if (urlTemplate) {
  181. if (!App.testMode) {
  182. var toSeconds = Math.round(new Date().getTime() / 1000);
  183. var allSubstitutes = {
  184. toSeconds:toSeconds,
  185. fromSeconds:toSeconds - 3600, // 1 hour back
  186. stepSeconds:15, // 15 seconds
  187. hostName:App.test_hostname
  188. };
  189. jQuery.extend(allSubstitutes, substitutes);
  190. for (key in allSubstitutes) {
  191. var useKey = '{' + key + '}';
  192. formatted = formatted.replace(new RegExp(useKey, 'g'), allSubstitutes[key]);
  193. }
  194. } else {
  195. formatted = testUrl;
  196. }
  197. }
  198. return formatted;
  199. }
  200. /**
  201. * Certain variables can have JSON in string
  202. * format, or in JSON format itself.
  203. */
  204. App.parseJSON = function (value) {
  205. if (typeof value == "string") {
  206. return jQuery.parseJSON(value);
  207. }
  208. return value;
  209. };
  210. App.format = {
  211. role:function (role) {
  212. switch (role) {
  213. case 'ZOOKEEPER_SERVER':
  214. return 'ZooKeeper Server';
  215. case 'ZOOKEEPER_CLIENT':
  216. return 'ZooKeeper Client';
  217. case 'NAMENODE':
  218. return 'NameNode';
  219. case 'NAMENODE_SERVICE_CHECK':
  220. return 'NameNode Check';
  221. case 'DATANODE':
  222. return 'DataNode';
  223. case 'HDFS_SERVICE_CHECK':
  224. return 'HDFS Check';
  225. case 'SECONDARY_NAMENODE':
  226. return 'SNameNode';
  227. case 'HDFS_CLIENT':
  228. return 'HDFS Client';
  229. case 'HBASE_MASTER':
  230. return 'HBase Master';
  231. case 'HBASE_REGIONSERVER':
  232. return 'HBase RegionServer';
  233. case 'HBASE_CLIENT':
  234. return 'HBase Client';
  235. case 'JOBTRACKER':
  236. return 'JobTracker';
  237. case 'TASKTRACKER':
  238. return 'TaskTracker';
  239. case 'MAPREDUCE_CLIENT':
  240. return 'MapReduce Client';
  241. case 'JAVA_JCE':
  242. return 'Java JCE';
  243. case 'KERBEROS_SERVER':
  244. return 'Kerberos Server';
  245. case 'KERBEROS_CLIENT':
  246. return 'Kerberos Client';
  247. case 'KERBEROS_ADMIN_CLIENT':
  248. return 'Kerberos Admin Client';
  249. case 'HADOOP_CLIENT':
  250. return 'Hadoop Client';
  251. case 'JOBTRACKER_SERVICE_CHECK':
  252. return 'JobTracker Check';
  253. case 'MAPREDUCE_SERVICE_CHECK':
  254. return 'MapReduce Check';
  255. case 'ZOOKEEPER_SERVICE_CHECK':
  256. return 'ZooKeeper Check';
  257. case 'ZOOKEEPER_QUORUM_SERVICE_CHECK':
  258. return 'ZK Quorum Check';
  259. case 'HBASE_SERVICE_CHECK':
  260. return 'HBase Check';
  261. case 'MYSQL_SERVER':
  262. return 'MySQL Server';
  263. case 'HIVE_SERVER':
  264. return 'HiveServer2';
  265. case 'HIVE_METASTORE':
  266. return 'Hive Metastore';
  267. case 'HIVE_CLIENT':
  268. return 'Hive Client';
  269. case 'HIVE_SERVICE_CHECK':
  270. return 'Hive Check';
  271. case 'HCAT':
  272. return 'HCat';
  273. case 'HCAT_SERVICE_CHECK':
  274. return 'HCat Check';
  275. case 'OOZIE_CLIENT':
  276. return 'Oozie Client';
  277. case 'OOZIE_SERVER':
  278. return 'Oozie Server';
  279. case 'OOZIE_SERVICE_CHECK':
  280. return 'Oozie Check';
  281. case 'PIG':
  282. return 'Pig';
  283. case 'PIG_SERVICE_CHECK':
  284. return 'Pig Check';
  285. case 'SQOOP':
  286. return 'Sqoop';
  287. case 'SQOOP_SERVICE_CHECK':
  288. return 'Sqoop Check';
  289. case 'WEBHCAT_SERVER':
  290. return 'WebHCat Server';
  291. case 'WEBHCAT_SERVICE_CHECK':
  292. return 'WebHCat Check';
  293. case 'NAGIOS_SERVER':
  294. return 'Nagios Server';
  295. case 'GANGLIA_SERVER':
  296. return 'Ganglia Server';
  297. case 'GANGLIA_MONITOR':
  298. return 'Ganglia Monitor';
  299. case 'GMOND_SERVICE_CHECK':
  300. return 'Gmond Check'
  301. case 'GMETAD_SERVICE_CHECK':
  302. return 'Gmetad Check';
  303. case 'DECOMMISSION_DATANODE':
  304. return 'Decommission DataNode';
  305. }
  306. },
  307. /**
  308. * PENDING - Not queued yet for a host
  309. * QUEUED - Queued for a host
  310. * IN_PROGRESS - Host reported it is working
  311. * COMPLETED - Host reported success
  312. * FAILED - Failed
  313. * TIMEDOUT - Host did not respond in time
  314. * ABORTED - Operation was abandoned
  315. */
  316. taskStatus:function (_taskStatus) {
  317. return _taskStatus.toLowerCase();
  318. }
  319. };
  320. Array.prototype.removeAll = function(array){
  321. var temp = array;
  322. for(var i = 0 ; i < array.length ; i++ ){
  323. temp = temp.without(array[i]);
  324. }
  325. return temp;
  326. };