helper.js 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962
  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. /** @namespace Em **/
  225. Em.CoreObject.reopen({
  226. t:function (key, attrs) {
  227. return Em.I18n.t(key, attrs)
  228. }
  229. });
  230. Em.TextArea.reopen(Em.I18n.TranslateableAttributes);
  231. /** @namespace Em.Handlebars **/
  232. Em.Handlebars.registerHelper('log', function (variable) {
  233. console.log(variable);
  234. });
  235. Em.Handlebars.registerHelper('warn', function (variable) {
  236. console.warn(variable);
  237. });
  238. Em.Handlebars.registerHelper('highlight', function (property, words, fn) {
  239. var context = (fn.contexts && fn.contexts[0]) || this;
  240. property = Em.Handlebars.getPath(context, property, fn);
  241. words = words.split(";");
  242. // if (highlightTemplate == undefined) {
  243. var highlightTemplate = "<b>{0}</b>";
  244. // }
  245. words.forEach(function (word) {
  246. var searchRegExp = new RegExp("\\b" + word + "\\b", "gi");
  247. property = property.replace(searchRegExp, function (found) {
  248. return highlightTemplate.format(found);
  249. });
  250. });
  251. return new Em.Handlebars.SafeString(property);
  252. });
  253. Em.Handlebars.registerHelper('isAccessible', function (property, options) {
  254. var permission = Ember.Object.create({
  255. isAccessible: function() {
  256. return App.isAccessible(property);
  257. }.property('App.router.wizardWatcherController.isWizardRunning')
  258. });
  259. // wipe out contexts so boundIf uses `this` (the permission) as the context
  260. options.contexts = null;
  261. return Ember.Handlebars.helpers.boundIf.call(permission, "isAccessible", options);
  262. });
  263. /**
  264. * @namespace App
  265. */
  266. App = require('app');
  267. /**
  268. * Certain variables can have JSON in string
  269. * format, or in JSON format itself.
  270. *
  271. * @memberof App
  272. * @function parseJson
  273. * @param {string|object}
  274. * @return {object}
  275. */
  276. App.parseJSON = function (value) {
  277. if (typeof value == "string") {
  278. return jQuery.parseJSON(value);
  279. }
  280. return value;
  281. };
  282. /**
  283. * Check for empty <code>Object</code>, built in Em.isEmpty()
  284. * doesn't support <code>Object</code> type
  285. *
  286. * @memberof App
  287. * @method isEmptyObject
  288. * @param obj {Object}
  289. * @return {Boolean}
  290. */
  291. App.isEmptyObject = function(obj) {
  292. var empty = true;
  293. for (var prop in obj) { if (obj.hasOwnProperty(prop)) {empty = false; break;} }
  294. return empty;
  295. };
  296. /**
  297. * Convert object under_score keys to camelCase
  298. *
  299. * @param {Object} object
  300. * @return {Object}
  301. **/
  302. App.keysUnderscoreToCamelCase = function(object) {
  303. var tmp = {};
  304. for (var key in object) {
  305. tmp[stringUtils.underScoreToCamelCase(key)] = object[key];
  306. }
  307. return tmp;
  308. };
  309. /**
  310. * Convert dotted keys to camelcase
  311. *
  312. * @param {Object} object
  313. * @return {Object}
  314. **/
  315. App.keysDottedToCamelCase = function(object) {
  316. var tmp = {};
  317. for (var key in object) {
  318. tmp[key.split('.').reduce(function(p, c) { return p + c.capitalize()})] = object[key];
  319. }
  320. return tmp;
  321. };
  322. /**
  323. * Returns object with defined keys only.
  324. *
  325. * @memberof App
  326. * @method permit
  327. * @param {Object} obj - input object
  328. * @param {String|Array} keys - allowed keys
  329. * @return {Object}
  330. */
  331. App.permit = function(obj, keys) {
  332. var result = {};
  333. if (typeof obj !== 'object' || App.isEmptyObject(obj)) return result;
  334. if (typeof keys == 'string') keys = Array(keys);
  335. keys.forEach(function(key) {
  336. if (obj.hasOwnProperty(key))
  337. result[key] = obj[key];
  338. });
  339. return result;
  340. };
  341. /**
  342. *
  343. * @namespace App
  344. * @namespace App.format
  345. */
  346. App.format = {
  347. /**
  348. * @memberof App.format
  349. * @type {object}
  350. * @property components
  351. */
  352. components: {
  353. 'API': 'API',
  354. 'DECOMMISSION_DATANODE': 'Update Exclude File',
  355. 'DRPC': 'DRPC',
  356. 'FLUME_HANDLER': 'Flume',
  357. 'GLUSTERFS': 'GLUSTERFS',
  358. 'HBASE': 'HBase',
  359. 'HBASE_REGIONSERVER': 'RegionServer',
  360. 'HCAT': 'HCat Client',
  361. 'HDFS': 'HDFS',
  362. 'HISTORYSERVER': 'History Server',
  363. 'HIVE_SERVER': 'HiveServer2',
  364. 'JCE': 'JCE',
  365. 'MAPREDUCE2': 'MapReduce2',
  366. 'MYSQL': 'MySQL',
  367. 'REST': 'REST',
  368. 'SECONDARY_NAMENODE': 'SNameNode',
  369. 'STORM_REST_API': 'Storm REST API Server',
  370. 'WEBHCAT': 'WebHCat',
  371. 'YARN': 'YARN',
  372. 'UI': 'UI',
  373. 'ZKFC': 'ZKFailoverController',
  374. 'ZOOKEEPER': 'ZooKeeper',
  375. 'ZOOKEEPER_QUORUM_SERVICE_CHECK': 'ZK Quorum Service Check'
  376. },
  377. /**
  378. * @memberof App.format
  379. * @property command
  380. * @type {object}
  381. */
  382. command: {
  383. 'INSTALL': 'Install',
  384. 'UNINSTALL': 'Uninstall',
  385. 'START': 'Start',
  386. 'STOP': 'Stop',
  387. 'EXECUTE': 'Execute',
  388. 'ABORT': 'Abort',
  389. 'UPGRADE': 'Upgrade',
  390. 'RESTART': 'Restart',
  391. 'SERVICE_CHECK': 'Check',
  392. 'Excluded:': 'Decommission:',
  393. 'Included:': 'Recommission:'
  394. },
  395. /**
  396. * cached map of service and component names
  397. * @type {object}
  398. */
  399. stackRolesMap: {},
  400. /**
  401. * convert role to readable string
  402. *
  403. * @memberof App.format
  404. * @method role
  405. * @param {string} role
  406. * return {string}
  407. */
  408. role: function (role) {
  409. var models = [App.StackService, App.StackServiceComponent];
  410. if (App.isEmptyObject(this.stackRolesMap)) {
  411. models.forEach(function (model) {
  412. model.find().forEach(function (item) {
  413. this.stackRolesMap[item.get('id')] = item.get('displayName');
  414. }, this);
  415. }, this);
  416. }
  417. if (this.stackRolesMap[role]) {
  418. return this.stackRolesMap[role];
  419. }
  420. return this.normalizeName(role);
  421. },
  422. /**
  423. * Try to format non predefined names to readable format.
  424. *
  425. * @method normalizeName
  426. * @param name {String} - name to format
  427. * @return {String}
  428. */
  429. normalizeName: function(name) {
  430. if (!name || typeof name != 'string') return '';
  431. if (this.components[name]) return this.components[name];
  432. name = name.toLowerCase();
  433. var suffixNoSpaces = ['node','tracker','manager'];
  434. var suffixRegExp = new RegExp('(\\w+)(' + suffixNoSpaces.join('|') + ')', 'gi');
  435. if (/_/g.test(name)) {
  436. name = name.split('_').map(function(singleName) {
  437. return this.normalizeName(singleName.toUpperCase());
  438. }, this).join(' ');
  439. } else if(suffixRegExp.test(name)) {
  440. suffixRegExp.lastIndex = 0;
  441. var matches = suffixRegExp.exec(name);
  442. name = matches[1].capitalize() + matches[2].capitalize();
  443. }
  444. return name.capitalize();
  445. },
  446. /**
  447. * convert command_detail to readable string, show the string for all tasks name
  448. *
  449. * @memberof App.format
  450. * @method commandDetail
  451. * @param {string} command_detail
  452. * @param {string} request_inputs
  453. * @return {string}
  454. */
  455. commandDetail: function (command_detail, request_inputs) {
  456. var detailArr = command_detail.split(' ');
  457. var self = this;
  458. var result = '';
  459. detailArr.forEach( function(item) {
  460. // if the item has the pattern SERVICE/COMPONENT, drop the SERVICE part
  461. if (item.contains('/')) {
  462. item = item.split('/')[1];
  463. }
  464. if (item == 'DECOMMISSION,') {
  465. // ignore text 'DECOMMISSION,'( command came from 'excluded/included'), here get the component name from request_inputs
  466. item = (jQuery.parseJSON(request_inputs)) ? jQuery.parseJSON(request_inputs).slave_type : '';
  467. }
  468. if (self.components[item]) {
  469. result = result + ' ' + self.components[item];
  470. } else if (self.command[item]) {
  471. result = result + ' ' + self.command[item];
  472. } else {
  473. result = result + ' ' + self.role(item);
  474. }
  475. });
  476. if (result.indexOf('Decommission:') > -1 || result.indexOf('Recommission:') > -1) {
  477. // for Decommission command, make sure the hostname is in lower case
  478. result = result.split(':')[0] + ': ' + result.split(':')[1].toLowerCase();
  479. }
  480. //TODO check if UI use this
  481. if (result === ' Nagios Update Ignore Actionexecute') {
  482. result = Em.I18n.t('common.maintenance.task');
  483. }
  484. if (result.indexOf('Install Packages Actionexecute') != -1) {
  485. result = Em.I18n.t('common.installRepo.task');
  486. }
  487. if (result === ' Rebalancehdfs NameNode') {
  488. result = Em.I18n.t('services.service.actions.run.rebalanceHdfsNodes.title');
  489. }
  490. if (result === " Startdemoldap Knox Gateway") {
  491. result = Em.I18n.t('services.service.actions.run.startLdapKnox.title');
  492. }
  493. if (result === " Stopdemoldap Knox Gateway") {
  494. result = Em.I18n.t('services.service.actions.run.stopLdapKnox.title');
  495. }
  496. if (result === ' Refreshqueues ResourceManager') {
  497. result = Em.I18n.t('services.service.actions.run.yarnRefreshQueues.title');
  498. }
  499. return result;
  500. },
  501. /**
  502. * Convert uppercase status name to lowercase.
  503. * <br>
  504. * <br>PENDING - Not queued yet for a host
  505. * <br>QUEUED - Queued for a host
  506. * <br>IN_PROGRESS - Host reported it is working
  507. * <br>COMPLETED - Host reported success
  508. * <br>FAILED - Failed
  509. * <br>TIMEDOUT - Host did not respond in time
  510. * <br>ABORTED - Operation was abandoned
  511. *
  512. * @memberof App.format
  513. * @method taskStatus
  514. * @param {string} _taskStatus
  515. * @return {string}
  516. *
  517. */
  518. taskStatus:function (_taskStatus) {
  519. return _taskStatus.toLowerCase();
  520. },
  521. /**
  522. * simplify kdc error msg
  523. * @param {string} message
  524. * @param {boolean} strict if this flag is true ignore not defined msgs return null
  525. * else return input msg as is;
  526. * @returns {*}
  527. */
  528. kdcErrorMsg: function(message, strict) {
  529. /**
  530. * Error messages for KDC administrator credentials error
  531. * is used for checking if error message is caused by bad KDC credentials
  532. * @type {{missingKDC: string, invalidKDC: string}}
  533. */
  534. var specialMsg = {
  535. "missingKDC": "Missing KDC administrator credentials.",
  536. "invalidKDC": "Invalid KDC administrator credentials.",
  537. "missingRDCForRealm": "Failed to find a KDC for the specified realm - kadmin"
  538. };
  539. for (var m in specialMsg) {
  540. if (specialMsg.hasOwnProperty(m) && message.contains(specialMsg[m]))
  541. return specialMsg[m];
  542. }
  543. return strict ? null : message;
  544. }
  545. };
  546. /**
  547. * wrapper to bootstrap popover
  548. * fix issue when popover stuck on view routing
  549. *
  550. * @memberof App
  551. * @method popover
  552. * @param {DOMElement} self
  553. * @param {object} options
  554. */
  555. App.popover = function (self, options) {
  556. if (!self) return;
  557. self.popover(options);
  558. self.on("remove", function () {
  559. $(this).trigger('mouseleave').off().removeData('popover');
  560. });
  561. };
  562. /**
  563. * wrapper to bootstrap tooltip
  564. * fix issue when tooltip stuck on view routing
  565. * @memberof App
  566. * @method tooltip
  567. * @param {DOMElement} self
  568. * @param {object} options
  569. */
  570. App.tooltip = function (self, options) {
  571. if (!self) return;
  572. self.tooltip(options);
  573. /* istanbul ignore next */
  574. self.on("remove", function () {
  575. $(this).trigger('mouseleave').off().removeData('tooltip');
  576. });
  577. };
  578. /**
  579. * wrapper to Date().getTime()
  580. * fix issue when client clock and server clock not sync
  581. *
  582. * @memberof App
  583. * @method dateTime
  584. * @return {Number} timeStamp of current server clock
  585. */
  586. App.dateTime = function() {
  587. return new Date().getTime() + App.clockDistance;
  588. };
  589. /**
  590. *
  591. * @param {number} [x] timestamp
  592. * @returns {number}
  593. */
  594. App.dateTimeWithTimeZone = function (x) {
  595. var timezone = App.router.get('userSettingsController.userSettings.timezone');
  596. if (timezone) {
  597. var tz = Em.getWithDefault(timezone, 'zones.0.value', '');
  598. return moment(moment.tz(x ? new Date(x) : new Date(), tz).toArray()).toDate().getTime();
  599. }
  600. return x || new Date().getTime();
  601. };
  602. /**
  603. * Helper function for bound property helper registration
  604. * @memberof App
  605. * @method registerBoundHelper
  606. * @param name {String} name of helper
  607. * @param view {Em.View} view
  608. */
  609. App.registerBoundHelper = function(name, view) {
  610. Em.Handlebars.registerHelper(name, function(property, options) {
  611. options.hash.contentBinding = property;
  612. return Em.Handlebars.helpers.view.call(this, view, options);
  613. });
  614. };
  615. /*
  616. * Return singular or plural word based on Em.I18n, view|controller context property key.
  617. *
  618. * Example: {{pluralize hostsCount singular="t:host" plural="t:hosts"}}
  619. * {{pluralize hostsCount singular="@view.hostName"}}
  620. */
  621. App.registerBoundHelper('pluralize', Em.View.extend({
  622. tagName: 'span',
  623. template: Em.Handlebars.compile('{{view.wordOut}}'),
  624. wordOut: function() {
  625. var count, singular, plural;
  626. count = this.get('content');
  627. singular = this.get('singular');
  628. plural = this.get('plural');
  629. return this.getWord(count, singular, plural);
  630. }.property('content'),
  631. /**
  632. * Get computed word.
  633. *
  634. * @param {Number} count
  635. * @param {String} singular
  636. * @param {String} [plural]
  637. * @return {String}
  638. * @method getWord
  639. */
  640. getWord: function(count, singular, plural) {
  641. singular = this.parseValue(singular);
  642. // if plural not passed
  643. if (!plural) plural = singular + 's';
  644. else plural = this.parseValue(plural);
  645. if (singular && plural) {
  646. if (count == 1) {
  647. return singular;
  648. } else {
  649. return plural;
  650. }
  651. }
  652. return '';
  653. },
  654. /**
  655. * Detect and return value from its instance.
  656. *
  657. * @param {String} value
  658. * @return {*}
  659. * @method parseValue
  660. **/
  661. parseValue: function(value) {
  662. switch (value[0]) {
  663. case '@':
  664. value = this.getViewPropertyValue(value);
  665. break;
  666. case 't':
  667. value = this.tDetect(value);
  668. break;
  669. default:
  670. break;
  671. }
  672. return value;
  673. },
  674. /*
  675. * Detect for Em.I18n.t reference call
  676. * @params word {String}
  677. * return {String}
  678. */
  679. tDetect: function(word) {
  680. var splitted = word.split(':');
  681. if (splitted.length > 1 && splitted[0] == 't') {
  682. return Em.I18n.t(splitted[1]);
  683. } else {
  684. return splitted[0];
  685. }
  686. },
  687. /**
  688. * Get property value from view|controller by its key path.
  689. *
  690. * @param {String} value - key path
  691. * @return {*}
  692. * @method getViewPropertyValue
  693. **/
  694. getViewPropertyValue: function(value) {
  695. value = value.substr(1);
  696. var keyword = value.split('.')[0]; // return 'controller' or 'view'
  697. switch (keyword) {
  698. case 'controller':
  699. return Em.get(this, value);
  700. case 'view':
  701. return Em.get(this, value.replace(/^view/, 'parentView'));
  702. default:
  703. break;
  704. }
  705. }
  706. })
  707. );
  708. /**
  709. * Return defined string instead of empty if value is null/undefined
  710. * by default is `n/a`.
  711. *
  712. * @param empty {String} - value instead of empty string (not required)
  713. * can be used with Em.I18n pass value started with't:'
  714. *
  715. * Examples:
  716. *
  717. * default value will be returned
  718. * {{formatNull service.someValue}}
  719. *
  720. * <code>empty<code> will be returned
  721. * {{formatNull service.someValue empty="I'm empty"}}
  722. *
  723. * Em.I18n translation will be returned
  724. * {{formatNull service.someValue empty="t:my.key.to.translate"
  725. */
  726. App.registerBoundHelper('formatNull', Em.View.extend({
  727. tagName: 'span',
  728. template: Em.Handlebars.compile('{{view.result}}'),
  729. result: function() {
  730. var emptyValue = this.get('empty') ? this.get('empty') : Em.I18n.t('services.service.summary.notAvailable');
  731. emptyValue = emptyValue.startsWith('t:') ? Em.I18n.t(emptyValue.substr(2, emptyValue.length)) : emptyValue;
  732. return (this.get('content') || this.get('content') == 0) ? this.get('content') : emptyValue;
  733. }.property('content')
  734. }));
  735. /**
  736. * Return formatted string with inserted <code>wbr</code>-tag after each dot
  737. *
  738. * @param {String} content
  739. *
  740. * Examples:
  741. *
  742. * returns 'apple'
  743. * {{formatWordBreak 'apple'}}
  744. *
  745. * returns 'apple.<wbr />banana'
  746. * {{formatWordBreak 'apple.banana'}}
  747. *
  748. * returns 'apple.<wbr />banana.<wbr />uranium'
  749. * {{formatWordBreak 'apple.banana.uranium'}}
  750. */
  751. App.registerBoundHelper('formatWordBreak', Em.View.extend({
  752. attributeBindings: ["data-original-title"],
  753. tagName: 'span',
  754. template: Em.Handlebars.compile('{{{view.result}}}'),
  755. /**
  756. * @type {string}
  757. */
  758. result: function() {
  759. return this.get('content') && this.get('content').replace(/\./g, '.<wbr />');
  760. }.property('content')
  761. }));
  762. /**
  763. * Return <i></i> with class that correspond to status
  764. *
  765. * @param {string} content - status
  766. *
  767. * Examples:
  768. *
  769. * {{statusIcon view.status}}
  770. * returns 'icon-cog'
  771. *
  772. */
  773. App.registerBoundHelper('statusIcon', Em.View.extend({
  774. tagName: 'i',
  775. /**
  776. * relation map between status and icon class
  777. * @type {object}
  778. */
  779. statusIconMap: {
  780. 'COMPLETED': 'icon-ok completed',
  781. 'WARNING': 'icon-warning-sign',
  782. 'FAILED': 'icon-exclamation-sign failed',
  783. 'HOLDING_FAILED': 'icon-exclamation-sign failed',
  784. 'SKIPPED_FAILED': 'icon-share-alt failed',
  785. 'PENDING': 'icon-cog pending',
  786. 'QUEUED': 'icon-cog queued',
  787. 'IN_PROGRESS': 'icon-cogs in_progress',
  788. 'HOLDING': 'icon-pause',
  789. 'SUSPENDED': 'icon-pause',
  790. 'ABORTED': 'icon-minus aborted',
  791. 'TIMEDOUT': 'icon-time timedout',
  792. 'HOLDING_TIMEDOUT': 'icon-time timedout',
  793. 'SUBITEM_FAILED': 'icon-remove failed'
  794. },
  795. classNameBindings: ['iconClass'],
  796. attributeBindings: ['data-original-title'],
  797. didInsertElement: function () {
  798. App.tooltip($(this.get('element')));
  799. },
  800. 'data-original-title': function() {
  801. return this.get('content').toCapital();
  802. }.property('content'),
  803. /**
  804. * @type {string}
  805. */
  806. iconClass: function () {
  807. return this.get('statusIconMap')[this.get('content')] || 'icon-question-sign';
  808. }.property('content')
  809. }));
  810. /**
  811. * Ambari overrides the default date transformer.
  812. * This is done because of the non-standard data
  813. * sent. For example Nagios sends date as "12345678".
  814. * The problem is that it is a String and is represented
  815. * only in seconds whereas Javascript's Date needs
  816. * milliseconds representation.
  817. */
  818. DS.attr.transforms.date = {
  819. from: function (serialized) {
  820. var type = typeof serialized;
  821. if (type === Em.I18n.t('common.type.string')) {
  822. serialized = parseInt(serialized);
  823. type = typeof serialized;
  824. }
  825. if (type === Em.I18n.t('common.type.number')) {
  826. if (!serialized ){ //serialized timestamp = 0;
  827. return 0;
  828. }
  829. // The number could be seconds or milliseconds.
  830. // If seconds, then the length is 10
  831. // If milliseconds, the length is 13
  832. if (serialized.toString().length < 13) {
  833. serialized = serialized * 1000;
  834. }
  835. return new Date(serialized);
  836. } else if (serialized === null || serialized === undefined) {
  837. // if the value is not present in the data,
  838. // return undefined, not null.
  839. return serialized;
  840. } else {
  841. return null;
  842. }
  843. },
  844. to: function (deserialized) {
  845. if (deserialized instanceof Date) {
  846. return deserialized.getTime();
  847. } else if (deserialized === undefined) {
  848. return undefined;
  849. } else {
  850. return null;
  851. }
  852. }
  853. };
  854. DS.attr.transforms.object = {
  855. from: function(serialized) {
  856. return Ember.none(serialized) ? null : Object(serialized);
  857. },
  858. to: function(deserialized) {
  859. return Ember.none(deserialized) ? null : Object(deserialized);
  860. }
  861. };
  862. /**
  863. * Allows EmberData models to have array properties.
  864. *
  865. * Declare the property as <code>
  866. * operations: DS.attr('array'),
  867. * </code> and
  868. * during load provide a JSON array for value.
  869. *
  870. * This transform simply assigns the same array in both directions.
  871. */
  872. DS.attr.transforms.array = {
  873. from : function(serialized) {
  874. return serialized;
  875. },
  876. to : function(deserialized) {
  877. return deserialized;
  878. }
  879. };
  880. /**
  881. * Utility method to delete all existing records of a DS.Model type from the model's associated map and
  882. * store's persistence layer (recordCache)
  883. * @param type DS.Model Class
  884. */
  885. App.resetDsStoreTypeMap = function(type) {
  886. var allRecords = App.get('store.recordCache'); //This fetches all records in the ember-data persistence layer
  887. var typeMaps = App.get('store.typeMaps');
  888. var guidForType = Em.guidFor(type);
  889. var typeMap = typeMaps[guidForType];
  890. if (typeMap) {
  891. var idToClientIdMap = typeMap.idToCid;
  892. for (var id in idToClientIdMap) {
  893. if (idToClientIdMap.hasOwnProperty(id) && idToClientIdMap[id]) {
  894. delete allRecords[idToClientIdMap[id]]; // deletes the cached copy of the record from the store
  895. }
  896. }
  897. typeMaps[guidForType] = {
  898. idToCid: {},
  899. clientIds: [],
  900. cidToHash: {},
  901. recordArrays: []
  902. };
  903. }
  904. };