helper.js 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802
  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. /**
  20. * Remove spaces at beginning and ending of line.
  21. * @example
  22. * var str = " I'm a string "
  23. * str.trim() // return "I'm a string"
  24. * @method trim
  25. * @return {string}
  26. */
  27. String.prototype.trim = function () {
  28. return this.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
  29. };
  30. /**
  31. * Determines whether string end within another string.
  32. *
  33. * @method endsWith
  34. * @param suffix {string} substring for search
  35. * @return {boolean}
  36. */
  37. String.prototype.endsWith = function(suffix) {
  38. return this.indexOf(suffix, this.length - suffix.length) !== -1;
  39. };
  40. /**
  41. * Determines whether string start within another string.
  42. *
  43. * @method startsWith
  44. * @param prefix {string} substring for search
  45. * @return {boolean}
  46. */
  47. String.prototype.startsWith = function (prefix){
  48. return this.indexOf(prefix) == 0;
  49. };
  50. /**
  51. * Determines whether string founded within another string.
  52. *
  53. * @method contains
  54. * @param substring {string} substring for search
  55. * @return {boolean}
  56. */
  57. String.prototype.contains = function(substring) {
  58. return this.indexOf(substring) != -1;
  59. };
  60. /**
  61. * Capitalize the first letter of string.
  62. * @method capitalize
  63. * @return {string}
  64. */
  65. String.prototype.capitalize = function () {
  66. return this.charAt(0).toUpperCase() + this.slice(1);
  67. };
  68. /**
  69. * Capitalize the first letter of string.
  70. * And set to lowercase other part of string
  71. * @method toCapital
  72. * @return {string}
  73. */
  74. String.prototype.toCapital = function () {
  75. return this.charAt(0).toUpperCase() + this.slice(1).toLowerCase();
  76. };
  77. /**
  78. * Finds the value in an object where this string is a key.
  79. * Optionally, the index of the key can be provided where the
  80. * value of the nth key in the hierarchy is returned.
  81. *
  82. * Example:
  83. * var tofind = 'smart';
  84. * var person = {'name': 'Bob Bob', 'smart': 'no', 'age': '28', 'personality': {'smart': 'yes', 'funny': 'yes', 'emotion': 'happy'} };
  85. * tofind.findIn(person); // 'no'
  86. * tofind.findIn(person, 0); // 'no'
  87. * tofind.findIn(person, 1); // 'yes'
  88. * tofind.findIn(person, 2); // null
  89. *
  90. * @method findIn
  91. * @param multi {object}
  92. * @param index {number} Occurrence count of this key
  93. * @return {*} Value of key at given index
  94. */
  95. String.prototype.findIn = function(multi, index, _foundValues) {
  96. if (!index) {
  97. index = 0;
  98. }
  99. if (!_foundValues) {
  100. _foundValues = [];
  101. }
  102. multi = multi || '';
  103. var value = null;
  104. var str = this.valueOf();
  105. if (typeof multi == 'object') {
  106. for ( var key in multi) {
  107. if (value != null) {
  108. break;
  109. }
  110. if (key == str) {
  111. _foundValues.push(multi[key]);
  112. }
  113. if (_foundValues.length - 1 == index) {
  114. // Found the value
  115. return _foundValues[index];
  116. }
  117. if (typeof multi[key] == 'object') {
  118. value = value || this.findIn(multi[key], index, _foundValues);
  119. }
  120. }
  121. }
  122. return value;
  123. };
  124. /**
  125. * Replace {i} with argument. where i is number of argument to replace with.
  126. * @example
  127. * var str = "{0} world{1}";
  128. * str.format("Hello", "!") // return "Hello world!"
  129. *
  130. * @method format
  131. * @return {string}
  132. */
  133. String.prototype.format = function () {
  134. var args = arguments;
  135. return this.replace(/{(\d+)}/g, function (match, number) {
  136. return typeof args[number] != 'undefined' ? args[number] : match;
  137. });
  138. };
  139. /**
  140. * Wrap words in string within template.
  141. *
  142. * @method highlight
  143. * @param {string[]} words - words to wrap
  144. * @param {string} [highlightTemplate="<b>{0}</b>"] - template for wrapping
  145. * @return {string}
  146. */
  147. String.prototype.highlight = function (words, highlightTemplate) {
  148. var self = this;
  149. highlightTemplate = highlightTemplate ? highlightTemplate : "<b>{0}</b>";
  150. words.forEach(function (word) {
  151. var searchRegExp = new RegExp("\\b" + word + "\\b", "gi");
  152. self = self.replace(searchRegExp, function (found) {
  153. return highlightTemplate.format(found);
  154. });
  155. });
  156. return self;
  157. };
  158. /**
  159. * Convert time in milliseconds to object contained days, hours and minutes.
  160. * @typedef ConvertedTime
  161. * @type {Object}
  162. * @property {number} d - days
  163. * @property {number} h - hours
  164. * @property {string} m - minutes
  165. * @example
  166. * var time = 1000000000;
  167. * time.toDaysHoursMinutes() // {d: 11, h: 13, m: "46.67"}
  168. *
  169. * @method toDaysHoursMinutes
  170. * @return {object}
  171. */
  172. Number.prototype.toDaysHoursMinutes = function () {
  173. var formatted = {},
  174. dateDiff = this,
  175. secK = 1000, //ms
  176. minK = 60 * secK, // sec
  177. hourK = 60 * minK, // sec
  178. dayK = 24 * hourK;
  179. dateDiff = parseInt(dateDiff);
  180. formatted.d = Math.floor(dateDiff / dayK);
  181. dateDiff -= formatted.d * dayK;
  182. formatted.h = Math.floor(dateDiff / hourK);
  183. dateDiff -= formatted.h * hourK;
  184. formatted.m = (dateDiff / minK).toFixed(2);
  185. return formatted;
  186. };
  187. /**
  188. Sort an array by the key specified in the argument.
  189. Handle only native js objects as element of array, not the Ember's object.
  190. Can be used as alternative to sortProperty method of Ember library
  191. in order to speed up executing on large data volumes
  192. @method sortBy
  193. @param {String} path name(s) to sort on
  194. @return {Array} The sorted array.
  195. */
  196. Array.prototype.sortPropertyLight = function (path) {
  197. var realPath = (typeof path === "string") ? path.split('.') : [];
  198. this.sort(function (a, b) {
  199. var aProperty = a;
  200. var bProperty = b;
  201. realPath.forEach(function (key) {
  202. aProperty = aProperty[key];
  203. bProperty = bProperty[key];
  204. });
  205. if (aProperty > bProperty) return 1;
  206. if (aProperty < bProperty) return -1;
  207. return 0;
  208. });
  209. return this;
  210. };
  211. /** @namespace Em **/
  212. Em.CoreObject.reopen({
  213. t:function (key, attrs) {
  214. return Em.I18n.t(key, attrs)
  215. }
  216. });
  217. Em.TextArea.reopen(Em.I18n.TranslateableAttributes);
  218. /** @namespace Em.Handlebars **/
  219. Em.Handlebars.registerHelper('log', function (variable) {
  220. console.log(variable);
  221. });
  222. Em.Handlebars.registerHelper('warn', function (variable) {
  223. console.warn(variable);
  224. });
  225. Em.Handlebars.registerHelper('highlight', function (property, words, fn) {
  226. var context = (fn.contexts && fn.contexts[0]) || this;
  227. property = Em.Handlebars.getPath(context, property, fn);
  228. words = words.split(";");
  229. // if (highlightTemplate == undefined) {
  230. var highlightTemplate = "<b>{0}</b>";
  231. // }
  232. words.forEach(function (word) {
  233. var searchRegExp = new RegExp("\\b" + word + "\\b", "gi");
  234. property = property.replace(searchRegExp, function (found) {
  235. return highlightTemplate.format(found);
  236. });
  237. });
  238. return new Em.Handlebars.SafeString(property);
  239. });
  240. /**
  241. * @namespace App
  242. */
  243. App = require('app');
  244. /**
  245. * Certain variables can have JSON in string
  246. * format, or in JSON format itself.
  247. *
  248. * @memberof App
  249. * @function parseJson
  250. * @param {string|object}
  251. * @return {object}
  252. */
  253. App.parseJSON = function (value) {
  254. if (typeof value == "string") {
  255. return jQuery.parseJSON(value);
  256. }
  257. return value;
  258. };
  259. /**
  260. * Check for empty <code>Object</code>, built in Em.isEmpty()
  261. * doesn't support <code>Object</code> type
  262. *
  263. * @memberof App
  264. * @method isEmptyObject
  265. * @param obj {Object}
  266. * @return {Boolean}
  267. */
  268. App.isEmptyObject = function(obj) {
  269. var empty = true;
  270. for (var prop in obj) { if (obj.hasOwnProperty(prop)) {empty = false; break;} }
  271. return empty;
  272. }
  273. /**
  274. * Convert object under_score keys to camelCase
  275. *
  276. * @param {Object} object
  277. * @return {Object}
  278. **/
  279. App.keysUnderscoreToCamelCase = function(object) {
  280. var tmp = {};
  281. for (var key in object) {
  282. tmp[stringUtils.underScoreToCamelCase(key)] = object[key];
  283. }
  284. return tmp;
  285. };
  286. /**
  287. * Returns object with defined keys only.
  288. *
  289. * @memberof App
  290. * @method permit
  291. * @param {Object} obj - input object
  292. * @param {String|Array} keys - allowed keys
  293. * @return {Object}
  294. */
  295. App.permit = function(obj, keys) {
  296. var result = {};
  297. if (typeof obj !== 'object' || App.isEmptyObject(obj)) return result;
  298. if (typeof keys == 'string') keys = Array(keys);
  299. keys.forEach(function(key) {
  300. if (obj.hasOwnProperty(key))
  301. result[key] = obj[key];
  302. });
  303. return result;
  304. };
  305. /**
  306. *
  307. * @namespace App
  308. * @namespace App.format
  309. */
  310. App.format = {
  311. /**
  312. * @memberof App.format
  313. * @type {object}
  314. * @property components
  315. */
  316. components: {
  317. 'API': 'API',
  318. 'DECOMMISSION_DATANODE': 'Update Exclude File',
  319. 'DRPC': 'DRPC',
  320. 'FLUME_HANDLER': 'Flume',
  321. 'GLUSTERFS': 'GLUSTERFS',
  322. 'HBASE': 'HBase',
  323. 'HBASE_REGIONSERVER': 'RegionServer',
  324. 'HCAT': 'HCat Client',
  325. 'HDFS': 'HDFS',
  326. 'HISTORYSERVER': 'History Server',
  327. 'HIVE_SERVER': 'HiveServer2',
  328. 'JCE': 'JCE',
  329. 'MAPREDUCE': 'MapReduce',
  330. 'MAPREDUCE2': 'MapReduce2',
  331. 'MYSQL': 'MySQL',
  332. 'REST': 'REST',
  333. 'SECONDARY_NAMENODE': 'SNameNode',
  334. 'STORM_REST_API': 'Storm REST API Server',
  335. 'WEBHCAT': 'WebHCat',
  336. 'YARN': 'YARN',
  337. 'UI': 'UI',
  338. 'ZKFC': 'ZKFailoverController',
  339. 'ZOOKEEPER': 'ZooKeeper',
  340. 'ZOOKEEPER_QUORUM_SERVICE_CHECK': 'ZK Quorum Service Check'
  341. },
  342. /**
  343. * @memberof App.format
  344. * @property command
  345. * @type {object}
  346. */
  347. command: {
  348. 'INSTALL': 'Install',
  349. 'UNINSTALL': 'Uninstall',
  350. 'START': 'Start',
  351. 'STOP': 'Stop',
  352. 'EXECUTE': 'Execute',
  353. 'ABORT': 'Abort',
  354. 'UPGRADE': 'Upgrade',
  355. 'RESTART': 'Restart',
  356. 'SERVICE_CHECK': 'Check',
  357. 'Excluded:': 'Decommission:',
  358. 'Included:': 'Recommission:'
  359. },
  360. /**
  361. * convert role to readable string
  362. *
  363. * @memberof App.format
  364. * @method role
  365. * @param {string} role
  366. * return {string}
  367. */
  368. role:function (role) {
  369. var result;
  370. var models = [App.StackService, App.StackServiceComponent];
  371. models.forEach(function(model){
  372. var instance = model.find().findProperty('id',role);
  373. if (instance) {
  374. result = instance.get('displayName');
  375. }
  376. },this);
  377. if (!result) {
  378. result = this.normalizeName(role);
  379. }
  380. return result;
  381. },
  382. /**
  383. * Try to format non predefined names to readable format.
  384. *
  385. * @method normalizeName
  386. * @param name {String} - name to format
  387. * @return {String}
  388. */
  389. normalizeName: function(name) {
  390. if (!name || typeof name != 'string') return '';
  391. if (this.components[name]) return this.components[name];
  392. name = name.toLowerCase();
  393. var suffixNoSpaces = ['node','tracker','manager'];
  394. var suffixRegExp = new RegExp('(\\w+)(' + suffixNoSpaces.join('|') + ')', 'gi');
  395. if (/_/g.test(name)) {
  396. name = name.split('_').map(function(singleName) {
  397. return this.normalizeName(singleName.toUpperCase());
  398. }, this).join(' ');
  399. } else if(suffixRegExp.test(name)) {
  400. suffixRegExp.lastIndex = 0;
  401. var matches = suffixRegExp.exec(name);
  402. name = matches[1].capitalize() + matches[2].capitalize();
  403. }
  404. return name.capitalize();
  405. },
  406. /**
  407. * convert command_detail to readable string, show the string for all tasks name
  408. *
  409. * @memberof App.format
  410. * @method commandDetail
  411. * @param {string} command_detail
  412. * @param {string} request_inputs
  413. * @return {string}
  414. */
  415. commandDetail: function (command_detail, request_inputs) {
  416. var detailArr = command_detail.split(' ');
  417. var self = this;
  418. var result = '';
  419. detailArr.forEach( function(item) {
  420. // if the item has the pattern SERVICE/COMPONENT, drop the SERVICE part
  421. if (item.contains('/')) {
  422. item = item.split('/')[1];
  423. }
  424. if (item == 'DECOMMISSION,') {
  425. // ignore text 'DECOMMISSION,'( command came from 'excluded/included'), here get the component name from request_inputs
  426. item = (jQuery.parseJSON(request_inputs)) ? jQuery.parseJSON(request_inputs).slave_type : '';
  427. }
  428. if (self.components[item]) {
  429. result = result + ' ' + self.components[item];
  430. } else if (self.command[item]) {
  431. result = result + ' ' + self.command[item];
  432. } else {
  433. result = result + ' ' + self.role(item);
  434. }
  435. });
  436. if (result.indexOf('Decommission:') > -1 || result.indexOf('Recommission:') > -1) {
  437. // for Decommission command, make sure the hostname is in lower case
  438. result = result.split(':')[0] + ': ' + result.split(':')[1].toLowerCase();
  439. }
  440. if (result === ' Nagios Update Ignore Actionexecute') {
  441. result = Em.I18n.t('common.maintenance.task');
  442. }
  443. if (result === ' Rebalancehdfs NameNode') {
  444. result = Em.I18n.t('services.service.actions.run.rebalanceHdfsNodes.title');
  445. }
  446. return result;
  447. },
  448. /**
  449. * Convert uppercase status name to lowercase.
  450. * <br>
  451. * <br>PENDING - Not queued yet for a host
  452. * <br>QUEUED - Queued for a host
  453. * <br>IN_PROGRESS - Host reported it is working
  454. * <br>COMPLETED - Host reported success
  455. * <br>FAILED - Failed
  456. * <br>TIMEDOUT - Host did not respond in time
  457. * <br>ABORTED - Operation was abandoned
  458. *
  459. * @memberof App.format
  460. * @method taskStatus
  461. * @param {string} _taskStatus
  462. * @return {string}
  463. *
  464. */
  465. taskStatus:function (_taskStatus) {
  466. return _taskStatus.toLowerCase();
  467. }
  468. };
  469. /**
  470. * wrapper to bootstrap popover
  471. * fix issue when popover stuck on view routing
  472. *
  473. * @memberof App
  474. * @method popover
  475. * @param {DOMElement} self
  476. * @param {object} options
  477. */
  478. App.popover = function (self, options) {
  479. self.popover(options);
  480. self.on("remove DOMNodeRemoved", function () {
  481. $(this).trigger('mouseleave');
  482. });
  483. };
  484. /**
  485. * wrapper to bootstrap tooltip
  486. * fix issue when tooltip stuck on view routing
  487. * @memberof App
  488. * @method tooltip
  489. * @param {DOMElement} self
  490. * @param {object} options
  491. */
  492. App.tooltip = function (self, options) {
  493. self.tooltip(options);
  494. /* istanbul ignore next */
  495. self.on("remove DOMNodeRemoved", function () {
  496. $(this).trigger('mouseleave');
  497. });
  498. };
  499. /**
  500. * wrapper to Date().getTime()
  501. * fix issue when client clock and server clock not sync
  502. *
  503. * @memberof App
  504. * @method dateTime
  505. * @return {Number} timeStamp of current server clock
  506. */
  507. App.dateTime = function() {
  508. return new Date().getTime() + App.clockDistance;
  509. };
  510. /**
  511. * Helper function for bound property helper registration
  512. * @memberof App
  513. * @method registerBoundHelper
  514. * @param name {String} name of helper
  515. * @param view {Em.View} view
  516. */
  517. App.registerBoundHelper = function(name, view) {
  518. Em.Handlebars.registerHelper(name, function(property, options) {
  519. options.hash.contentBinding = property;
  520. return Em.Handlebars.helpers.view.call(this, view, options);
  521. });
  522. };
  523. /*
  524. * Return singular or plural word based on Em.I18n, view|controller context property key.
  525. *
  526. * Example: {{pluralize hostsCount singular="t:host" plural="t:hosts"}}
  527. * {{pluralize hostsCount singular="@view.hostName"}}
  528. */
  529. App.registerBoundHelper('pluralize', Em.View.extend({
  530. tagName: 'span',
  531. template: Em.Handlebars.compile('{{view.wordOut}}'),
  532. wordOut: function() {
  533. var count, singular, plural;
  534. count = this.get('content');
  535. singular = this.get('singular');
  536. plural = this.get('plural');
  537. return this.getWord(count, singular, plural);
  538. }.property('content'),
  539. /**
  540. * Get computed word.
  541. *
  542. * @param {Number} count
  543. * @param {String} singular
  544. * @param {String} [plural]
  545. * @return {String}
  546. * @method getWord
  547. */
  548. getWord: function(count, singular, plural) {
  549. singular = this.parseValue(singular);
  550. // if plural not passed
  551. if (!plural) plural = singular + 's';
  552. else plural = this.parseValue(plural);
  553. if (singular && plural) {
  554. if (count > 1) {
  555. return plural;
  556. } else {
  557. return singular;
  558. }
  559. }
  560. return '';
  561. },
  562. /**
  563. * Detect and return value from its instance.
  564. *
  565. * @param {String} value
  566. * @return {*}
  567. * @method parseValue
  568. **/
  569. parseValue: function(value) {
  570. switch (value[0]) {
  571. case '@':
  572. value = this.getViewPropertyValue(value);
  573. break;
  574. case 't':
  575. value = this.tDetect(value);
  576. break;
  577. default:
  578. break;
  579. }
  580. return value;
  581. },
  582. /*
  583. * Detect for Em.I18n.t reference call
  584. * @params word {String}
  585. * return {String}
  586. */
  587. tDetect: function(word) {
  588. var splitted = word.split(':');
  589. if (splitted.length > 1 && splitted[0] == 't') {
  590. return Em.I18n.t(splitted[1]);
  591. } else {
  592. return splitted[0];
  593. }
  594. },
  595. /**
  596. * Get property value from view|controller by its key path.
  597. *
  598. * @param {String} value - key path
  599. * @return {*}
  600. * @method getViewPropertyValue
  601. **/
  602. getViewPropertyValue: function(value) {
  603. value = value.substr(1);
  604. var keyword = value.split('.')[0]; // return 'controller' or 'view'
  605. switch (keyword) {
  606. case 'controller':
  607. return Em.get(this, value);
  608. case 'view':
  609. return Em.get(this, value.replace(/^view/, 'parentView'))
  610. default:
  611. break;
  612. }
  613. }
  614. })
  615. );
  616. /**
  617. * Return defined string instead of empty if value is null/undefined
  618. * by default is `n/a`.
  619. *
  620. * @param empty {String} - value instead of empty string (not required)
  621. * can be used with Em.I18n pass value started with't:'
  622. *
  623. * Examples:
  624. *
  625. * default value will be returned
  626. * {{formatNull service.someValue}}
  627. *
  628. * <code>empty<code> will be returned
  629. * {{formatNull service.someValue empty="I'm empty"}}
  630. *
  631. * Em.I18n translation will be returned
  632. * {{formatNull service.someValue empty="t:my.key.to.translate"
  633. */
  634. App.registerBoundHelper('formatNull', Em.View.extend({
  635. tagName: 'span',
  636. template: Em.Handlebars.compile('{{view.result}}'),
  637. result: function() {
  638. var emptyValue = this.get('empty') ? this.get('empty') : Em.I18n.t('services.service.summary.notAvailable');
  639. emptyValue = emptyValue.startsWith('t:') ? Em.I18n.t(emptyValue.substr(2, emptyValue.length)) : emptyValue;
  640. return (this.get('content') || this.get('content') == 0) ? this.get('content') : emptyValue;
  641. }.property('content')
  642. }));
  643. /**
  644. * Return formatted string with inserted <code>wbr</code>-tag after each dot
  645. *
  646. * @param {String} content
  647. *
  648. * Examples:
  649. *
  650. * returns 'apple'
  651. * {{formatWordBreak 'apple'}}
  652. *
  653. * returns 'apple.<wbr />banana'
  654. * {{formatWordBreak 'apple.banana'}}
  655. *
  656. * returns 'apple.<wbr />banana.<wbr />uranium'
  657. * {{formatWordBreak 'apple.banana.uranium'}}
  658. */
  659. App.registerBoundHelper('formatWordBreak', Em.View.extend({
  660. tagName: 'span',
  661. template: Em.Handlebars.compile('{{{view.result}}}'),
  662. /**
  663. * @type {string}
  664. */
  665. result: function() {
  666. return this.get('content') && this.get('content').replace(/\./g, '.<wbr />');
  667. }.property('content')
  668. }));
  669. /**
  670. * Ambari overrides the default date transformer.
  671. * This is done because of the non-standard data
  672. * sent. For example Nagios sends date as "12345678".
  673. * The problem is that it is a String and is represented
  674. * only in seconds whereas Javascript's Date needs
  675. * milliseconds representation.
  676. */
  677. DS.attr.transforms.date = {
  678. from: function (serialized) {
  679. var type = typeof serialized;
  680. if (type === Em.I18n.t('common.type.string')) {
  681. serialized = parseInt(serialized);
  682. type = typeof serialized;
  683. }
  684. if (type === Em.I18n.t('common.type.number')) {
  685. if (!serialized ){ //serialized timestamp = 0;
  686. return 0;
  687. }
  688. // The number could be seconds or milliseconds.
  689. // If seconds, then the length is 10
  690. // If milliseconds, the length is 13
  691. if (serialized.toString().length < 13) {
  692. serialized = serialized * 1000;
  693. }
  694. return new Date(serialized);
  695. } else if (serialized === null || serialized === undefined) {
  696. // if the value is not present in the data,
  697. // return undefined, not null.
  698. return serialized;
  699. } else {
  700. return null;
  701. }
  702. },
  703. to: function (deserialized) {
  704. if (deserialized instanceof Date) {
  705. return deserialized.getTime();
  706. } else if (deserialized === undefined) {
  707. return undefined;
  708. } else {
  709. return null;
  710. }
  711. }
  712. };
  713. DS.attr.transforms.object = {
  714. from: function(serialized) {
  715. return Ember.none(serialized) ? null : Object(serialized);
  716. },
  717. to: function(deserialized) {
  718. return Ember.none(deserialized) ? null : Object(deserialized);
  719. }
  720. };
  721. /**
  722. * Allows EmberData models to have array properties.
  723. *
  724. * Declare the property as <code>
  725. * operations: DS.attr('array'),
  726. * </code> and
  727. * during load provide a JSON array for value.
  728. *
  729. * This transform simply assigns the same array in both directions.
  730. */
  731. DS.attr.transforms.array = {
  732. from : function(serialized) {
  733. return serialized;
  734. },
  735. to : function(deserialized) {
  736. return deserialized;
  737. }
  738. };
  739. /**
  740. * Utility method to delete all existing records of a DS.Model type from the model's associated map and
  741. * store's persistence layer (recordCache)
  742. * @param type DS.Model Class
  743. */
  744. App.resetDsStoreTypeMap = function(type) {
  745. var allRecords = App.get('store.recordCache'); //This fetches all records in the ember-data persistence layer
  746. var typeMaps = App.get('store.typeMaps');
  747. var guidForType = Em.guidFor(type);
  748. var typeMap = typeMaps[guidForType];
  749. if (typeMap) {
  750. var idToClientIdMap = typeMap.idToCid;
  751. for (var id in idToClientIdMap) {
  752. if (idToClientIdMap.hasOwnProperty(id) && idToClientIdMap[id]) {
  753. delete allRecords[idToClientIdMap[id]]; // deletes the cached copy of the record from the store
  754. }
  755. }
  756. typeMaps[guidForType] = {
  757. idToCid: {},
  758. clientIds: [],
  759. cidToHash: {},
  760. recordArrays: []
  761. };
  762. }
  763. };