helper.js 30 KB

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