helper.js 28 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051
  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. var stringUtils = require('utils/string_utils');
  19. var timezoneUtils = require('utils/date/timezone');
  20. /**
  21. * Remove spaces at beginning and ending of line.
  22. * @example
  23. * var str = " I'm a string "
  24. * str.trim() // return "I'm a string"
  25. * @method trim
  26. * @return {string}
  27. */
  28. String.prototype.trim = function () {
  29. return this.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
  30. };
  31. /**
  32. * Determines whether string end within another string.
  33. *
  34. * @method endsWith
  35. * @param suffix {string} substring for search
  36. * @return {boolean}
  37. */
  38. String.prototype.endsWith = function(suffix) {
  39. return this.indexOf(suffix, this.length - suffix.length) !== -1;
  40. };
  41. /**
  42. * Determines whether string start within another string.
  43. *
  44. * @method startsWith
  45. * @param prefix {string} substring for search
  46. * @return {boolean}
  47. */
  48. String.prototype.startsWith = function (prefix){
  49. return this.indexOf(prefix) == 0;
  50. };
  51. /**
  52. * Determines whether string founded within another string.
  53. *
  54. * @method contains
  55. * @param substring {string} substring for search
  56. * @return {boolean}
  57. */
  58. String.prototype.contains = function(substring) {
  59. return this.indexOf(substring) != -1;
  60. };
  61. /**
  62. * Capitalize the first letter of string.
  63. * @method capitalize
  64. * @return {string}
  65. */
  66. String.prototype.capitalize = function () {
  67. return this.charAt(0).toUpperCase() + this.slice(1);
  68. };
  69. /**
  70. * Capitalize the first letter of string.
  71. * And set to lowercase other part of string
  72. * @method toCapital
  73. * @return {string}
  74. */
  75. String.prototype.toCapital = function () {
  76. return this.charAt(0).toUpperCase() + this.slice(1).toLowerCase();
  77. };
  78. /**
  79. * Finds the value in an object where this string is a key.
  80. * Optionally, the index of the key can be provided where the
  81. * value of the nth key in the hierarchy is returned.
  82. *
  83. * Example:
  84. * var tofind = 'smart';
  85. * var person = {'name': 'Bob Bob', 'smart': 'no', 'age': '28', 'personality': {'smart': 'yes', 'funny': 'yes', 'emotion': 'happy'} };
  86. * tofind.findIn(person); // 'no'
  87. * tofind.findIn(person, 0); // 'no'
  88. * tofind.findIn(person, 1); // 'yes'
  89. * tofind.findIn(person, 2); // null
  90. *
  91. * @method findIn
  92. * @param multi {object}
  93. * @param index {number} Occurrence count of this key
  94. * @return {*} Value of key at given index
  95. */
  96. String.prototype.findIn = function(multi, index, _foundValues) {
  97. if (!index) {
  98. index = 0;
  99. }
  100. if (!_foundValues) {
  101. _foundValues = [];
  102. }
  103. multi = multi || '';
  104. var value = null;
  105. var str = this.valueOf();
  106. if (typeof multi == 'object') {
  107. for ( var key in multi) {
  108. if (value != null) {
  109. break;
  110. }
  111. if (key == str) {
  112. _foundValues.push(multi[key]);
  113. }
  114. if (_foundValues.length - 1 == index) {
  115. // Found the value
  116. return _foundValues[index];
  117. }
  118. if (typeof multi[key] == 'object') {
  119. value = value || this.findIn(multi[key], index, _foundValues);
  120. }
  121. }
  122. }
  123. return value;
  124. };
  125. /**
  126. * Replace {i} with argument. where i is number of argument to replace with.
  127. * @example
  128. * var str = "{0} world{1}";
  129. * str.format("Hello", "!") // return "Hello world!"
  130. *
  131. * @method format
  132. * @return {string}
  133. */
  134. String.prototype.format = function () {
  135. var args = arguments;
  136. return this.replace(/{(\d+)}/g, function (match, number) {
  137. return typeof args[number] != 'undefined' ? args[number] : match;
  138. });
  139. };
  140. /**
  141. * Wrap words in string within template.
  142. *
  143. * @method highlight
  144. * @param {string[]} words - words to wrap
  145. * @param {string} [highlightTemplate="<b>{0}</b>"] - template for wrapping
  146. * @return {string}
  147. */
  148. String.prototype.highlight = function (words, highlightTemplate) {
  149. var self = this;
  150. highlightTemplate = highlightTemplate ? highlightTemplate : "<b>{0}</b>";
  151. words.forEach(function (word) {
  152. var searchRegExp = new RegExp("\\b" + word + "\\b", "gi");
  153. self = self.replace(searchRegExp, function (found) {
  154. return highlightTemplate.format(found);
  155. });
  156. });
  157. return self;
  158. };
  159. /**
  160. * Convert time in milliseconds to object contained days, hours and minutes.
  161. * @typedef ConvertedTime
  162. * @type {Object}
  163. * @property {number} d - days
  164. * @property {number} h - hours
  165. * @property {string} m - minutes
  166. * @example
  167. * var time = 1000000000;
  168. * time.toDaysHoursMinutes() // {d: 11, h: 13, m: "46.67"}
  169. *
  170. * @method toDaysHoursMinutes
  171. * @return {object}
  172. */
  173. Number.prototype.toDaysHoursMinutes = function () {
  174. var formatted = {},
  175. dateDiff = this,
  176. secK = 1000, //ms
  177. minK = 60 * secK, // sec
  178. hourK = 60 * minK, // sec
  179. dayK = 24 * hourK;
  180. dateDiff = parseInt(dateDiff);
  181. formatted.d = Math.floor(dateDiff / dayK);
  182. dateDiff -= formatted.d * dayK;
  183. formatted.h = Math.floor(dateDiff / hourK);
  184. dateDiff -= formatted.h * hourK;
  185. formatted.m = (dateDiff / minK).toFixed(2);
  186. return formatted;
  187. };
  188. /**
  189. *
  190. * @param bound1 {Number}
  191. * @param bound2 {Number}
  192. * @return {boolean}
  193. */
  194. Number.prototype.isInRange = function (bound1, bound2) {
  195. var upperBound, lowerBound;
  196. upperBound = bound1 > bound2 ? bound1: bound2;
  197. lowerBound = bound1 < bound2 ? bound1: bound2;
  198. return this > lowerBound && this < upperBound;
  199. };
  200. /**
  201. Sort an array by the key specified in the argument.
  202. Handle only native js objects as element of array, not the Ember's object.
  203. Can be used as alternative to sortProperty method of Ember library
  204. in order to speed up executing on large data volumes
  205. @method sortBy
  206. @param {String} path name(s) to sort on
  207. @return {Array} The sorted array.
  208. */
  209. Array.prototype.sortPropertyLight = function (path) {
  210. var realPath = (typeof path === "string") ? path.split('.') : [];
  211. this.sort(function (a, b) {
  212. var aProperty = a;
  213. var bProperty = b;
  214. realPath.forEach(function (key) {
  215. aProperty = aProperty[key];
  216. bProperty = bProperty[key];
  217. });
  218. if (aProperty > bProperty) return 1;
  219. if (aProperty < bProperty) return -1;
  220. return 0;
  221. });
  222. return this;
  223. };
  224. /**
  225. * Create map from array with executing provided callback for each array's item
  226. * Example:
  227. * <pre>
  228. * var array = [{a: 1, b: 3}, {a: 2, b: 2}, {a: 3, b: 1}];
  229. * var map = array.toMapByCallback('a', function (item) {
  230. * return Em.get(item, 'b');
  231. * });
  232. * console.log(map); // {1: 3, 2: 2, 3: 1}
  233. * </pre>
  234. * <code>map[1]</code> is much more faster than <code>array.findProperty('a', 1).get('b')</code>
  235. *
  236. * @param {string} property
  237. * @param {Function} callback
  238. * @returns {object}
  239. * @method toMapByCallback
  240. */
  241. Array.prototype.toMapByCallback = function (property, callback) {
  242. var ret = {};
  243. Em.assert('`property` can\'t be empty string', property.length);
  244. Em.assert('`callback` should be a function', 'function' === Em.typeOf(callback));
  245. this.forEach(function (item) {
  246. var key = Em.get(item, property);
  247. ret[key] = callback(item, property);
  248. });
  249. return ret;
  250. };
  251. /**
  252. * Create map from array
  253. * Example:
  254. * <pre>
  255. * var array = [{a: 1}, {a: 2}, {a: 3}];
  256. * var map = array.toMapByProperty('a'); // {1: {a: 1}, 2: {a: 2}, 3: {a: 3}}
  257. * </pre>
  258. * <code>map[1]</code> is much more faster than <code>array.findProperty('a', 1)</code>
  259. *
  260. * @param {string} property
  261. * @return {object}
  262. * @method toMapByProperty
  263. * @see toMapByCallback
  264. */
  265. Array.prototype.toMapByProperty = function (property) {
  266. return this.toMapByCallback(property, function (item) {
  267. return item;
  268. });
  269. };
  270. /**
  271. * Create wick map from array
  272. * Example:
  273. * <pre>
  274. * var array = [{a: 1}, {a: 2}, {a: 3}];
  275. * var map = array.toWickMapByProperty('a'); // {1: true, 2: true, 3: true}
  276. * </pre>
  277. * <code>map[1]</code> works faster than <code>array.someProperty('a', 1)</code>
  278. *
  279. * @param {string} property
  280. * @return {object}
  281. * @method toWickMapByProperty
  282. * @see toMapByCallback
  283. */
  284. Array.prototype.toWickMapByProperty = function (property) {
  285. return this.toMapByCallback(property, function () {
  286. return true;
  287. });
  288. };
  289. /**
  290. * Create wick map from array of primitives
  291. * Example:
  292. * <pre>
  293. * var array = [1, 2, 3];
  294. * var map = array.toWickMap(); // {1: true, 2: true, 3: true}
  295. * </pre>
  296. * <code>map[1]</code> works faster than <code>array.contains(1)</code>
  297. *
  298. * @returns {object}
  299. * @method toWickMap
  300. */
  301. Array.prototype.toWickMap = function () {
  302. var ret = {};
  303. this.forEach(function (item) {
  304. ret[item] = true;
  305. });
  306. return ret;
  307. };
  308. /** @namespace Em **/
  309. Em.CoreObject.reopen({
  310. t:function (key, attrs) {
  311. return Em.I18n.t(key, attrs)
  312. }
  313. });
  314. Em.TextArea.reopen(Em.I18n.TranslateableAttributes);
  315. /** @namespace Em.Handlebars **/
  316. Em.Handlebars.registerHelper('log', function (variable) {
  317. console.log(variable);
  318. });
  319. Em.Handlebars.registerHelper('warn', function (variable) {
  320. console.warn(variable);
  321. });
  322. Em.Handlebars.registerHelper('highlight', function (property, words, fn) {
  323. var context = (fn.contexts && fn.contexts[0]) || this;
  324. property = Em.Handlebars.getPath(context, property, fn);
  325. words = words.split(";");
  326. // if (highlightTemplate == undefined) {
  327. var highlightTemplate = "<b>{0}</b>";
  328. // }
  329. words.forEach(function (word) {
  330. var searchRegExp = new RegExp("\\b" + word + "\\b", "gi");
  331. property = property.replace(searchRegExp, function (found) {
  332. return highlightTemplate.format(found);
  333. });
  334. });
  335. return new Em.Handlebars.SafeString(property);
  336. });
  337. Em.Handlebars.registerHelper('isAccessible', function (property, options) {
  338. var permission = Ember.Object.create({
  339. isAccessible: function() {
  340. return App.isAccessible(property);
  341. }.property('App.router.wizardWatcherController.isWizardRunning')
  342. });
  343. // wipe out contexts so boundIf uses `this` (the permission) as the context
  344. options.contexts = null;
  345. return Ember.Handlebars.helpers.boundIf.call(permission, "isAccessible", options);
  346. });
  347. /**
  348. * @namespace App
  349. */
  350. App = require('app');
  351. /**
  352. * Certain variables can have JSON in string
  353. * format, or in JSON format itself.
  354. *
  355. * @memberof App
  356. * @function parseJson
  357. * @param {string|object}
  358. * @return {object}
  359. */
  360. App.parseJSON = function (value) {
  361. if (typeof value == "string") {
  362. return jQuery.parseJSON(value);
  363. }
  364. return value;
  365. };
  366. /**
  367. * Check for empty <code>Object</code>, built in Em.isEmpty()
  368. * doesn't support <code>Object</code> type
  369. *
  370. * @memberof App
  371. * @method isEmptyObject
  372. * @param obj {Object}
  373. * @return {Boolean}
  374. */
  375. App.isEmptyObject = function(obj) {
  376. var empty = true;
  377. for (var prop in obj) { if (obj.hasOwnProperty(prop)) {empty = false; break;} }
  378. return empty;
  379. };
  380. /**
  381. * Convert object under_score keys to camelCase
  382. *
  383. * @param {Object} object
  384. * @return {Object}
  385. **/
  386. App.keysUnderscoreToCamelCase = function(object) {
  387. var tmp = {};
  388. for (var key in object) {
  389. tmp[stringUtils.underScoreToCamelCase(key)] = object[key];
  390. }
  391. return tmp;
  392. };
  393. /**
  394. * Convert dotted keys to camelcase
  395. *
  396. * @param {Object} object
  397. * @return {Object}
  398. **/
  399. App.keysDottedToCamelCase = function(object) {
  400. var tmp = {};
  401. for (var key in object) {
  402. tmp[key.split('.').reduce(function(p, c) { return p + c.capitalize()})] = object[key];
  403. }
  404. return tmp;
  405. };
  406. /**
  407. * Returns object with defined keys only.
  408. *
  409. * @memberof App
  410. * @method permit
  411. * @param {Object} obj - input object
  412. * @param {String|Array} keys - allowed keys
  413. * @return {Object}
  414. */
  415. App.permit = function(obj, keys) {
  416. var result = {};
  417. if (typeof obj !== 'object' || App.isEmptyObject(obj)) return result;
  418. if (typeof keys == 'string') keys = Array(keys);
  419. keys.forEach(function(key) {
  420. if (obj.hasOwnProperty(key))
  421. result[key] = obj[key];
  422. });
  423. return result;
  424. };
  425. /**
  426. *
  427. * @namespace App
  428. * @namespace App.format
  429. */
  430. App.format = {
  431. /**
  432. * @memberof App.format
  433. * @type {object}
  434. * @property components
  435. */
  436. components: {
  437. 'API': 'API',
  438. 'DECOMMISSION_DATANODE': 'Update Exclude File',
  439. 'DRPC': 'DRPC',
  440. 'FLUME_HANDLER': 'Flume',
  441. 'GLUSTERFS': 'GLUSTERFS',
  442. 'HBASE': 'HBase',
  443. 'HBASE_REGIONSERVER': 'RegionServer',
  444. 'HCAT': 'HCat Client',
  445. 'HDFS': 'HDFS',
  446. 'HISTORYSERVER': 'History Server',
  447. 'HIVE_SERVER': 'HiveServer2',
  448. 'JCE': 'JCE',
  449. 'MAPREDUCE2': 'MapReduce2',
  450. 'MYSQL': 'MySQL',
  451. 'REST': 'REST',
  452. 'SECONDARY_NAMENODE': 'SNameNode',
  453. 'STORM_REST_API': 'Storm REST API Server',
  454. 'WEBHCAT': 'WebHCat',
  455. 'YARN': 'YARN',
  456. 'UI': 'UI',
  457. 'ZKFC': 'ZKFailoverController',
  458. 'ZOOKEEPER': 'ZooKeeper',
  459. 'ZOOKEEPER_QUORUM_SERVICE_CHECK': 'ZK Quorum Service Check'
  460. },
  461. /**
  462. * @memberof App.format
  463. * @property command
  464. * @type {object}
  465. */
  466. command: {
  467. 'INSTALL': 'Install',
  468. 'UNINSTALL': 'Uninstall',
  469. 'START': 'Start',
  470. 'STOP': 'Stop',
  471. 'EXECUTE': 'Execute',
  472. 'ABORT': 'Abort',
  473. 'UPGRADE': 'Upgrade',
  474. 'RESTART': 'Restart',
  475. 'SERVICE_CHECK': 'Check',
  476. 'Excluded:': 'Decommission:',
  477. 'Included:': 'Recommission:'
  478. },
  479. /**
  480. * cached map of service and component names
  481. * @type {object}
  482. */
  483. stackRolesMap: {},
  484. /**
  485. * convert role to readable string
  486. *
  487. * @memberof App.format
  488. * @method role
  489. * @param {string} role
  490. * return {string}
  491. */
  492. role: function (role) {
  493. var models = [App.StackService, App.StackServiceComponent];
  494. if (App.isEmptyObject(this.stackRolesMap)) {
  495. models.forEach(function (model) {
  496. model.find().forEach(function (item) {
  497. this.stackRolesMap[item.get('id')] = item.get('displayName');
  498. }, this);
  499. }, this);
  500. }
  501. if (this.stackRolesMap[role]) {
  502. return this.stackRolesMap[role];
  503. }
  504. return this.normalizeName(role);
  505. },
  506. /**
  507. * Try to format non predefined names to readable format.
  508. *
  509. * @method normalizeName
  510. * @param name {String} - name to format
  511. * @return {String}
  512. */
  513. normalizeName: function(name) {
  514. if (!name || typeof name != 'string') return '';
  515. if (this.components[name]) return this.components[name];
  516. name = name.toLowerCase();
  517. var suffixNoSpaces = ['node','tracker','manager'];
  518. var suffixRegExp = new RegExp('(\\w+)(' + suffixNoSpaces.join('|') + ')', 'gi');
  519. if (/_/g.test(name)) {
  520. name = name.split('_').map(function(singleName) {
  521. return this.normalizeName(singleName.toUpperCase());
  522. }, this).join(' ');
  523. } else if(suffixRegExp.test(name)) {
  524. suffixRegExp.lastIndex = 0;
  525. var matches = suffixRegExp.exec(name);
  526. name = matches[1].capitalize() + matches[2].capitalize();
  527. }
  528. return name.capitalize();
  529. },
  530. /**
  531. * convert command_detail to readable string, show the string for all tasks name
  532. *
  533. * @memberof App.format
  534. * @method commandDetail
  535. * @param {string} command_detail
  536. * @param {string} request_inputs
  537. * @return {string}
  538. */
  539. commandDetail: function (command_detail, request_inputs) {
  540. var detailArr = command_detail.split(' ');
  541. var self = this;
  542. var result = '';
  543. detailArr.forEach( function(item) {
  544. // if the item has the pattern SERVICE/COMPONENT, drop the SERVICE part
  545. if (item.contains('/')) {
  546. item = item.split('/')[1];
  547. }
  548. if (item == 'DECOMMISSION,') {
  549. // ignore text 'DECOMMISSION,'( command came from 'excluded/included'), here get the component name from request_inputs
  550. item = (jQuery.parseJSON(request_inputs)) ? jQuery.parseJSON(request_inputs).slave_type : '';
  551. }
  552. if (self.components[item]) {
  553. result = result + ' ' + self.components[item];
  554. } else if (self.command[item]) {
  555. result = result + ' ' + self.command[item];
  556. } else {
  557. result = result + ' ' + self.role(item);
  558. }
  559. });
  560. if (result.indexOf('Decommission:') > -1 || result.indexOf('Recommission:') > -1) {
  561. // for Decommission command, make sure the hostname is in lower case
  562. result = result.split(':')[0] + ': ' + result.split(':')[1].toLowerCase();
  563. }
  564. //TODO check if UI use this
  565. if (result === ' Nagios Update Ignore Actionexecute') {
  566. result = Em.I18n.t('common.maintenance.task');
  567. }
  568. if (result.indexOf('Install Packages Actionexecute') != -1) {
  569. result = Em.I18n.t('common.installRepo.task');
  570. }
  571. if (result === ' Rebalancehdfs NameNode') {
  572. result = Em.I18n.t('services.service.actions.run.rebalanceHdfsNodes.title');
  573. }
  574. if (result === " Startdemoldap Knox Gateway") {
  575. result = Em.I18n.t('services.service.actions.run.startLdapKnox.title');
  576. }
  577. if (result === " Stopdemoldap Knox Gateway") {
  578. result = Em.I18n.t('services.service.actions.run.stopLdapKnox.title');
  579. }
  580. if (result === ' Refreshqueues ResourceManager') {
  581. result = Em.I18n.t('services.service.actions.run.yarnRefreshQueues.title');
  582. }
  583. return result;
  584. },
  585. /**
  586. * Convert uppercase status name to lowercase.
  587. * <br>
  588. * <br>PENDING - Not queued yet for a host
  589. * <br>QUEUED - Queued for a host
  590. * <br>IN_PROGRESS - Host reported it is working
  591. * <br>COMPLETED - Host reported success
  592. * <br>FAILED - Failed
  593. * <br>TIMEDOUT - Host did not respond in time
  594. * <br>ABORTED - Operation was abandoned
  595. *
  596. * @memberof App.format
  597. * @method taskStatus
  598. * @param {string} _taskStatus
  599. * @return {string}
  600. *
  601. */
  602. taskStatus:function (_taskStatus) {
  603. return _taskStatus.toLowerCase();
  604. },
  605. /**
  606. * simplify kdc error msg
  607. * @param {string} message
  608. * @param {boolean} strict if this flag is true ignore not defined msgs return null
  609. * else return input msg as is;
  610. * @returns {*}
  611. */
  612. kdcErrorMsg: function(message, strict) {
  613. /**
  614. * Error messages for KDC administrator credentials error
  615. * is used for checking if error message is caused by bad KDC credentials
  616. * @type {{missingKDC: string, invalidKDC: string}}
  617. */
  618. var specialMsg = {
  619. "missingKDC": "Missing KDC administrator credentials.",
  620. "invalidKDC": "Invalid KDC administrator credentials.",
  621. "missingRDCForRealm": "Failed to find a KDC for the specified realm - kadmin"
  622. };
  623. for (var m in specialMsg) {
  624. if (specialMsg.hasOwnProperty(m) && message.contains(specialMsg[m]))
  625. return specialMsg[m];
  626. }
  627. return strict ? null : message;
  628. }
  629. };
  630. /**
  631. * wrapper to bootstrap popover
  632. * fix issue when popover stuck on view routing
  633. *
  634. * @memberof App
  635. * @method popover
  636. * @param {DOMElement} self
  637. * @param {object} options
  638. */
  639. App.popover = function (self, options) {
  640. if (!self) return;
  641. self.popover(options);
  642. self.on("remove", function () {
  643. $(this).trigger('mouseleave').off().removeData('popover');
  644. });
  645. };
  646. /**
  647. * wrapper to bootstrap tooltip
  648. * fix issue when tooltip stuck on view routing
  649. * @memberof App
  650. * @method tooltip
  651. * @param {DOMElement} self
  652. * @param {object} options
  653. */
  654. App.tooltip = function (self, options) {
  655. if (!self) return;
  656. self.tooltip(options);
  657. /* istanbul ignore next */
  658. self.on("remove", function () {
  659. $(this).trigger('mouseleave').off().removeData('tooltip');
  660. });
  661. };
  662. /**
  663. * wrapper to Date().getTime()
  664. * fix issue when client clock and server clock not sync
  665. *
  666. * @memberof App
  667. * @method dateTime
  668. * @return {Number} timeStamp of current server clock
  669. */
  670. App.dateTime = function() {
  671. return new Date().getTime() + App.clockDistance;
  672. };
  673. /**
  674. *
  675. * @param {number} [x] timestamp
  676. * @returns {number}
  677. */
  678. App.dateTimeWithTimeZone = function (x) {
  679. var timezone = App.router.get('userSettingsController.userSettings.timezone');
  680. if (timezone) {
  681. var tz = Em.getWithDefault(timezone, 'zones.0.value', '');
  682. return moment(moment.tz(x ? new Date(x) : new Date(), tz).toArray()).toDate().getTime();
  683. }
  684. return x || new Date().getTime();
  685. };
  686. /**
  687. * Helper function for bound property helper registration
  688. * @memberof App
  689. * @method registerBoundHelper
  690. * @param name {String} name of helper
  691. * @param view {Em.View} view
  692. */
  693. App.registerBoundHelper = function(name, view) {
  694. Em.Handlebars.registerHelper(name, function(property, options) {
  695. options.hash.contentBinding = property;
  696. return Em.Handlebars.helpers.view.call(this, view, options);
  697. });
  698. };
  699. /*
  700. * Return singular or plural word based on Em.I18n, view|controller context property key.
  701. *
  702. * Example: {{pluralize hostsCount singular="t:host" plural="t:hosts"}}
  703. * {{pluralize hostsCount singular="@view.hostName"}}
  704. */
  705. App.registerBoundHelper('pluralize', Em.View.extend({
  706. tagName: 'span',
  707. template: Em.Handlebars.compile('{{view.wordOut}}'),
  708. wordOut: function() {
  709. var count, singular, plural;
  710. count = this.get('content');
  711. singular = this.get('singular');
  712. plural = this.get('plural');
  713. return this.getWord(count, singular, plural);
  714. }.property('content'),
  715. /**
  716. * Get computed word.
  717. *
  718. * @param {Number} count
  719. * @param {String} singular
  720. * @param {String} [plural]
  721. * @return {String}
  722. * @method getWord
  723. */
  724. getWord: function(count, singular, plural) {
  725. singular = this.parseValue(singular);
  726. // if plural not passed
  727. if (!plural) plural = singular + 's';
  728. else plural = this.parseValue(plural);
  729. if (singular && plural) {
  730. if (count == 1) {
  731. return singular;
  732. } else {
  733. return plural;
  734. }
  735. }
  736. return '';
  737. },
  738. /**
  739. * Detect and return value from its instance.
  740. *
  741. * @param {String} value
  742. * @return {*}
  743. * @method parseValue
  744. **/
  745. parseValue: function(value) {
  746. switch (value[0]) {
  747. case '@':
  748. value = this.getViewPropertyValue(value);
  749. break;
  750. case 't':
  751. value = this.tDetect(value);
  752. break;
  753. default:
  754. break;
  755. }
  756. return value;
  757. },
  758. /*
  759. * Detect for Em.I18n.t reference call
  760. * @params word {String}
  761. * return {String}
  762. */
  763. tDetect: function(word) {
  764. var splitted = word.split(':');
  765. if (splitted.length > 1 && splitted[0] == 't') {
  766. return Em.I18n.t(splitted[1]);
  767. } else {
  768. return splitted[0];
  769. }
  770. },
  771. /**
  772. * Get property value from view|controller by its key path.
  773. *
  774. * @param {String} value - key path
  775. * @return {*}
  776. * @method getViewPropertyValue
  777. **/
  778. getViewPropertyValue: function(value) {
  779. value = value.substr(1);
  780. var keyword = value.split('.')[0]; // return 'controller' or 'view'
  781. switch (keyword) {
  782. case 'controller':
  783. return Em.get(this, value);
  784. case 'view':
  785. return Em.get(this, value.replace(/^view/, 'parentView'));
  786. default:
  787. break;
  788. }
  789. }
  790. })
  791. );
  792. /**
  793. * Return defined string instead of empty if value is null/undefined
  794. * by default is `n/a`.
  795. *
  796. * @param empty {String} - value instead of empty string (not required)
  797. * can be used with Em.I18n pass value started with't:'
  798. *
  799. * Examples:
  800. *
  801. * default value will be returned
  802. * {{formatNull service.someValue}}
  803. *
  804. * <code>empty<code> will be returned
  805. * {{formatNull service.someValue empty="I'm empty"}}
  806. *
  807. * Em.I18n translation will be returned
  808. * {{formatNull service.someValue empty="t:my.key.to.translate"
  809. */
  810. App.registerBoundHelper('formatNull', Em.View.extend({
  811. tagName: 'span',
  812. template: Em.Handlebars.compile('{{view.result}}'),
  813. result: function() {
  814. var emptyValue = this.get('empty') ? this.get('empty') : Em.I18n.t('services.service.summary.notAvailable');
  815. emptyValue = emptyValue.startsWith('t:') ? Em.I18n.t(emptyValue.substr(2, emptyValue.length)) : emptyValue;
  816. return (this.get('content') || this.get('content') == 0) ? this.get('content') : emptyValue;
  817. }.property('content')
  818. }));
  819. /**
  820. * Return formatted string with inserted <code>wbr</code>-tag after each dot
  821. *
  822. * @param {String} content
  823. *
  824. * Examples:
  825. *
  826. * returns 'apple'
  827. * {{formatWordBreak 'apple'}}
  828. *
  829. * returns 'apple.<wbr />banana'
  830. * {{formatWordBreak 'apple.banana'}}
  831. *
  832. * returns 'apple.<wbr />banana.<wbr />uranium'
  833. * {{formatWordBreak 'apple.banana.uranium'}}
  834. */
  835. App.registerBoundHelper('formatWordBreak', Em.View.extend({
  836. attributeBindings: ["data-original-title"],
  837. tagName: 'span',
  838. template: Em.Handlebars.compile('{{{view.result}}}'),
  839. /**
  840. * @type {string}
  841. */
  842. result: function() {
  843. return this.get('content') && this.get('content').replace(/\./g, '.<wbr />');
  844. }.property('content')
  845. }));
  846. /**
  847. * Return <i></i> with class that correspond to status
  848. *
  849. * @param {string} content - status
  850. *
  851. * Examples:
  852. *
  853. * {{statusIcon view.status}}
  854. * returns 'icon-cog'
  855. *
  856. */
  857. App.registerBoundHelper('statusIcon', Em.View.extend({
  858. tagName: 'i',
  859. /**
  860. * relation map between status and icon class
  861. * @type {object}
  862. */
  863. statusIconMap: {
  864. 'COMPLETED': 'icon-ok completed',
  865. 'WARNING': 'icon-warning-sign',
  866. 'FAILED': 'icon-exclamation-sign failed',
  867. 'HOLDING_FAILED': 'icon-exclamation-sign failed',
  868. 'SKIPPED_FAILED': 'icon-share-alt failed',
  869. 'PENDING': 'icon-cog pending',
  870. 'QUEUED': 'icon-cog queued',
  871. 'IN_PROGRESS': 'icon-cogs in_progress',
  872. 'HOLDING': 'icon-pause',
  873. 'SUSPENDED': 'icon-pause',
  874. 'ABORTED': 'icon-minus aborted',
  875. 'TIMEDOUT': 'icon-time timedout',
  876. 'HOLDING_TIMEDOUT': 'icon-time timedout',
  877. 'SUBITEM_FAILED': 'icon-remove failed'
  878. },
  879. classNameBindings: ['iconClass'],
  880. attributeBindings: ['data-original-title'],
  881. didInsertElement: function () {
  882. App.tooltip($(this.get('element')));
  883. },
  884. 'data-original-title': function() {
  885. return this.get('content').toCapital();
  886. }.property('content'),
  887. /**
  888. * @type {string}
  889. */
  890. iconClass: function () {
  891. return this.get('statusIconMap')[this.get('content')] || 'icon-question-sign';
  892. }.property('content')
  893. }));
  894. /**
  895. * Ambari overrides the default date transformer.
  896. * This is done because of the non-standard data
  897. * sent. For example Nagios sends date as "12345678".
  898. * The problem is that it is a String and is represented
  899. * only in seconds whereas Javascript's Date needs
  900. * milliseconds representation.
  901. */
  902. DS.attr.transforms.date = {
  903. from: function (serialized) {
  904. var type = typeof serialized;
  905. if (type === Em.I18n.t('common.type.string')) {
  906. serialized = parseInt(serialized);
  907. type = typeof serialized;
  908. }
  909. if (type === Em.I18n.t('common.type.number')) {
  910. if (!serialized ){ //serialized timestamp = 0;
  911. return 0;
  912. }
  913. // The number could be seconds or milliseconds.
  914. // If seconds, then the length is 10
  915. // If milliseconds, the length is 13
  916. if (serialized.toString().length < 13) {
  917. serialized = serialized * 1000;
  918. }
  919. return new Date(serialized);
  920. } else if (serialized === null || serialized === undefined) {
  921. // if the value is not present in the data,
  922. // return undefined, not null.
  923. return serialized;
  924. } else {
  925. return null;
  926. }
  927. },
  928. to: function (deserialized) {
  929. if (deserialized instanceof Date) {
  930. return deserialized.getTime();
  931. } else if (deserialized === undefined) {
  932. return undefined;
  933. } else {
  934. return null;
  935. }
  936. }
  937. };
  938. DS.attr.transforms.object = {
  939. from: function(serialized) {
  940. return Ember.none(serialized) ? null : Object(serialized);
  941. },
  942. to: function(deserialized) {
  943. return Ember.none(deserialized) ? null : Object(deserialized);
  944. }
  945. };
  946. /**
  947. * Allows EmberData models to have array properties.
  948. *
  949. * Declare the property as <code>
  950. * operations: DS.attr('array'),
  951. * </code> and
  952. * during load provide a JSON array for value.
  953. *
  954. * This transform simply assigns the same array in both directions.
  955. */
  956. DS.attr.transforms.array = {
  957. from : function(serialized) {
  958. return serialized;
  959. },
  960. to : function(deserialized) {
  961. return deserialized;
  962. }
  963. };
  964. /**
  965. * Utility method to delete all existing records of a DS.Model type from the model's associated map and
  966. * store's persistence layer (recordCache)
  967. * @param type DS.Model Class
  968. */
  969. App.resetDsStoreTypeMap = function(type) {
  970. var allRecords = App.get('store.recordCache'); //This fetches all records in the ember-data persistence layer
  971. var typeMaps = App.get('store.typeMaps');
  972. var guidForType = Em.guidFor(type);
  973. var typeMap = typeMaps[guidForType];
  974. if (typeMap) {
  975. var idToClientIdMap = typeMap.idToCid;
  976. for (var id in idToClientIdMap) {
  977. if (idToClientIdMap.hasOwnProperty(id) && idToClientIdMap[id]) {
  978. delete allRecords[idToClientIdMap[id]]; // deletes the cached copy of the record from the store
  979. }
  980. }
  981. typeMaps[guidForType] = {
  982. idToCid: {},
  983. clientIds: [],
  984. cidToHash: {},
  985. recordArrays: []
  986. };
  987. }
  988. };