helper.js 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931
  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. /**
  338. * Usage:
  339. *
  340. * <pre>
  341. * {{#isAuthorized "SERVICE.TOGGLE_ALERTS"}}
  342. * {{! some truly code }}
  343. * {{else}}
  344. * {{! some falsy code }}
  345. * {{/isAuthorized}}
  346. * </pre>
  347. */
  348. Em.Handlebars.registerHelper('isAuthorized', function (property, options) {
  349. var permission = Ember.Object.create({
  350. isAuthorized: function() {
  351. return App.isAuthorized(property);
  352. }.property('App.router.wizardWatcherController.isWizardRunning')
  353. });
  354. // wipe out contexts so boundIf uses `this` (the permission) as the context
  355. options.contexts = null;
  356. return Ember.Handlebars.helpers.boundIf.call(permission, "isAuthorized", options);
  357. });
  358. /**
  359. * @namespace App
  360. */
  361. App = require('app');
  362. /**
  363. * Certain variables can have JSON in string
  364. * format, or in JSON format itself.
  365. *
  366. * @memberof App
  367. * @function parseJson
  368. * @param {string|object}
  369. * @return {object}
  370. */
  371. App.parseJSON = function (value) {
  372. if (typeof value == "string") {
  373. return jQuery.parseJSON(value);
  374. }
  375. return value;
  376. };
  377. /**
  378. * Check for empty <code>Object</code>, built in Em.isEmpty()
  379. * doesn't support <code>Object</code> type
  380. *
  381. * @memberof App
  382. * @method isEmptyObject
  383. * @param obj {Object}
  384. * @return {Boolean}
  385. */
  386. App.isEmptyObject = function(obj) {
  387. var empty = true;
  388. for (var prop in obj) { if (obj.hasOwnProperty(prop)) {empty = false; break;} }
  389. return empty;
  390. };
  391. /**
  392. * Convert object under_score keys to camelCase
  393. *
  394. * @param {Object} object
  395. * @return {Object}
  396. **/
  397. App.keysUnderscoreToCamelCase = function(object) {
  398. var tmp = {};
  399. for (var key in object) {
  400. tmp[stringUtils.underScoreToCamelCase(key)] = object[key];
  401. }
  402. return tmp;
  403. };
  404. /**
  405. * Convert dotted keys to camelcase
  406. *
  407. * @param {Object} object
  408. * @return {Object}
  409. **/
  410. App.keysDottedToCamelCase = function(object) {
  411. var tmp = {};
  412. for (var key in object) {
  413. tmp[key.split('.').reduce(function(p, c) { return p + c.capitalize()})] = object[key];
  414. }
  415. return tmp;
  416. };
  417. /**
  418. * Returns object with defined keys only.
  419. *
  420. * @memberof App
  421. * @method permit
  422. * @param {Object} obj - input object
  423. * @param {String|Array} keys - allowed keys
  424. * @return {Object}
  425. */
  426. App.permit = function(obj, keys) {
  427. var result = {};
  428. if (typeof obj !== 'object' || App.isEmptyObject(obj)) return result;
  429. if (typeof keys == 'string') keys = Array(keys);
  430. keys.forEach(function(key) {
  431. if (obj.hasOwnProperty(key))
  432. result[key] = obj[key];
  433. });
  434. return result;
  435. };
  436. /**
  437. *
  438. * @namespace App
  439. * @namespace App.format
  440. */
  441. App.format = {
  442. /**
  443. * @memberof App.format
  444. * @type {object}
  445. * @property components
  446. */
  447. components: {
  448. 'API': 'API',
  449. 'DECOMMISSION_DATANODE': 'Update Exclude File',
  450. 'DRPC': 'DRPC',
  451. 'FLUME_HANDLER': 'Flume',
  452. 'GLUSTERFS': 'GLUSTERFS',
  453. 'HBASE': 'HBase',
  454. 'HBASE_REGIONSERVER': 'RegionServer',
  455. 'HCAT': 'HCat Client',
  456. 'HDFS': 'HDFS',
  457. 'HISTORYSERVER': 'History Server',
  458. 'HIVE_SERVER': 'HiveServer2',
  459. 'JCE': 'JCE',
  460. 'MAPREDUCE2': 'MapReduce2',
  461. 'MYSQL': 'MySQL',
  462. 'REST': 'REST',
  463. 'SECONDARY_NAMENODE': 'SNameNode',
  464. 'STORM_REST_API': 'Storm REST API Server',
  465. 'WEBHCAT': 'WebHCat',
  466. 'YARN': 'YARN',
  467. 'UI': 'UI',
  468. 'ZKFC': 'ZKFailoverController',
  469. 'ZOOKEEPER': 'ZooKeeper',
  470. 'ZOOKEEPER_QUORUM_SERVICE_CHECK': 'ZK Quorum Service Check',
  471. 'HAWQ': 'HAWQ',
  472. 'PXF': 'PXF'
  473. },
  474. /**
  475. * @memberof App.format
  476. * @property command
  477. * @type {object}
  478. */
  479. command: {
  480. 'INSTALL': 'Install',
  481. 'UNINSTALL': 'Uninstall',
  482. 'START': 'Start',
  483. 'STOP': 'Stop',
  484. 'EXECUTE': 'Execute',
  485. 'ABORT': 'Abort',
  486. 'UPGRADE': 'Upgrade',
  487. 'RESTART': 'Restart',
  488. 'SERVICE_CHECK': 'Check',
  489. 'Excluded:': 'Decommission:',
  490. 'Included:': 'Recommission:'
  491. },
  492. /**
  493. * cached map of service names
  494. * @type {object}
  495. */
  496. stackServiceRolesMap: {},
  497. /**
  498. * cached map of component names
  499. * @type {object}
  500. */
  501. stackComponentRolesMap: {},
  502. /**
  503. * convert role to readable string
  504. *
  505. * @memberof App.format
  506. * @method role
  507. * @param {string} role
  508. * @param {boolean} isServiceRole
  509. * return {string}
  510. */
  511. role: function (role, isServiceRole) {
  512. if (isServiceRole) {
  513. var model = App.StackService;
  514. var map = this.stackServiceRolesMap;
  515. } else {
  516. var model = App.StackServiceComponent;
  517. var map = this.stackComponentRolesMap;
  518. }
  519. this.initializeStackRolesMap(map, model);
  520. if (map[role]) {
  521. return map[role];
  522. }
  523. return this.normalizeName(role);
  524. },
  525. initializeStackRolesMap: function (map, model) {
  526. if (App.isEmptyObject(map)) {
  527. model.find().forEach(function (item) {
  528. map[item.get('id')] = item.get('displayName');
  529. });
  530. }
  531. },
  532. /**
  533. * Try to format non predefined names to readable format.
  534. *
  535. * @method normalizeNameBySeparator
  536. * @param name {String} - name to format
  537. * @param separators {String} - token use to split the string
  538. * @return {String}
  539. */
  540. normalizeNameBySeparators: function(name, separators) {
  541. if (!name || typeof name != 'string') return '';
  542. name = name.toLowerCase();
  543. if (!separators || separators.length == 0) {
  544. console.debug("No separators specified. Use default separator '_' instead");
  545. separators = ["_"];
  546. }
  547. for (var i = 0; i < separators.length; i++){
  548. var separator = separators[i];
  549. if (new RegExp(separator, 'g').test(name)) {
  550. name = name.split(separator).map(function(singleName) {
  551. return this.normalizeName(singleName.toUpperCase());
  552. }, this).join(' ');
  553. }
  554. }
  555. return name.capitalize();
  556. },
  557. /**
  558. * Try to format non predefined names to readable format.
  559. *
  560. * @method normalizeName
  561. * @param name {String} - name to format
  562. * @return {String}
  563. */
  564. normalizeName: function(name) {
  565. if (!name || typeof name != 'string') return '';
  566. if (this.components[name]) return this.components[name];
  567. name = name.toLowerCase();
  568. var suffixNoSpaces = ['node','tracker','manager'];
  569. var suffixRegExp = new RegExp('(\\w+)(' + suffixNoSpaces.join('|') + ')', 'gi');
  570. if (/_/g.test(name)) {
  571. name = name.split('_').map(function(singleName) {
  572. return this.normalizeName(singleName.toUpperCase());
  573. }, this).join(' ');
  574. } else if(suffixRegExp.test(name)) {
  575. suffixRegExp.lastIndex = 0;
  576. var matches = suffixRegExp.exec(name);
  577. name = matches[1].capitalize() + matches[2].capitalize();
  578. }
  579. return name.capitalize();
  580. },
  581. /**
  582. * convert command_detail to readable string, show the string for all tasks name
  583. *
  584. * @memberof App.format
  585. * @method commandDetail
  586. * @param {string} command_detail
  587. * @param {string} request_inputs
  588. * @return {string}
  589. */
  590. commandDetail: function (command_detail, request_inputs) {
  591. var detailArr = command_detail.split(' ');
  592. var self = this;
  593. var result = '';
  594. detailArr.forEach( function(item) {
  595. // if the item has the pattern SERVICE/COMPONENT, drop the SERVICE part
  596. if (item.contains('/')) {
  597. item = item.split('/')[1];
  598. }
  599. if (item == 'DECOMMISSION,') {
  600. // ignore text 'DECOMMISSION,'( command came from 'excluded/included'), here get the component name from request_inputs
  601. item = (jQuery.parseJSON(request_inputs)) ? jQuery.parseJSON(request_inputs).slave_type : '';
  602. }
  603. if (self.components[item]) {
  604. result = result + ' ' + self.components[item];
  605. } else if (self.command[item]) {
  606. result = result + ' ' + self.command[item];
  607. } else {
  608. result = result + ' ' + self.role(item, false);
  609. }
  610. });
  611. if (result.indexOf('Decommission:') > -1 || result.indexOf('Recommission:') > -1) {
  612. // for Decommission command, make sure the hostname is in lower case
  613. result = result.split(':')[0] + ': ' + result.split(':')[1].toLowerCase();
  614. }
  615. //TODO check if UI use this
  616. if (result === ' Nagios Update Ignore Actionexecute') {
  617. result = Em.I18n.t('common.maintenance.task');
  618. }
  619. if (result.indexOf('Install Packages Actionexecute') != -1) {
  620. result = Em.I18n.t('common.installRepo.task');
  621. }
  622. if (result === ' Rebalancehdfs NameNode') {
  623. result = Em.I18n.t('services.service.actions.run.rebalanceHdfsNodes.title');
  624. }
  625. if (result === " Startdemoldap Knox Gateway") {
  626. result = Em.I18n.t('services.service.actions.run.startLdapKnox.title');
  627. }
  628. if (result === " Stopdemoldap Knox Gateway") {
  629. result = Em.I18n.t('services.service.actions.run.stopLdapKnox.title');
  630. }
  631. if (result === ' Refreshqueues ResourceManager') {
  632. result = Em.I18n.t('services.service.actions.run.yarnRefreshQueues.title');
  633. }
  634. // HAWQ custom commands on back Ops page.
  635. if (result === ' Resync Hawq Standby HAWQ Standby Master') {
  636. result = Em.I18n.t('services.service.actions.run.resyncHawqStandby.label');
  637. }
  638. if (result === ' Immediate Stop Hawq Service HAWQ Master') {
  639. result = Em.I18n.t('services.service.actions.run.immediateStopHawqService.label');
  640. }
  641. if (result === ' Immediate Stop Hawq Segment HAWQ Segment') {
  642. result = Em.I18n.t('services.service.actions.run.immediateStopHawqSegment.label');
  643. }
  644. if(result === ' Activate Hawq Standby HAWQ Standby Master') {
  645. result = Em.I18n.t('admin.activateHawqStandby.button.enable');
  646. }
  647. if(result === ' Hawq Clear Cache HAWQ Master') {
  648. result = Em.I18n.t('services.service.actions.run.clearHawqCache.label');
  649. }
  650. if(result === ' Run Hawq Check HAWQ Master') {
  651. result = Em.I18n.t('services.service.actions.run.runHawqCheck.label');
  652. }
  653. //<---End HAWQ custom commands--->
  654. return result;
  655. },
  656. /**
  657. * Convert uppercase status name to lowercase.
  658. * <br>
  659. * <br>PENDING - Not queued yet for a host
  660. * <br>QUEUED - Queued for a host
  661. * <br>IN_PROGRESS - Host reported it is working
  662. * <br>COMPLETED - Host reported success
  663. * <br>FAILED - Failed
  664. * <br>TIMEDOUT - Host did not respond in time
  665. * <br>ABORTED - Operation was abandoned
  666. *
  667. * @memberof App.format
  668. * @method taskStatus
  669. * @param {string} _taskStatus
  670. * @return {string}
  671. *
  672. */
  673. taskStatus:function (_taskStatus) {
  674. return _taskStatus.toLowerCase();
  675. },
  676. /**
  677. * simplify kdc error msg
  678. * @param {string} message
  679. * @param {boolean} strict if this flag is true ignore not defined msgs return null
  680. * else return input msg as is;
  681. * @returns {*}
  682. */
  683. kdcErrorMsg: function(message, strict) {
  684. /**
  685. * Error messages for KDC administrator credentials error
  686. * is used for checking if error message is caused by bad KDC credentials
  687. * @type {{missingKDC: string, invalidKDC: string}}
  688. */
  689. var specialMsg = {
  690. "missingKDC": "Missing KDC administrator credentials.",
  691. "invalidKDC": "Invalid KDC administrator credentials.",
  692. "missingRDCForRealm": "Failed to find a KDC for the specified realm - kadmin"
  693. };
  694. for (var m in specialMsg) {
  695. if (specialMsg.hasOwnProperty(m) && message.contains(specialMsg[m]))
  696. return specialMsg[m];
  697. }
  698. return strict ? null : message;
  699. }
  700. };
  701. /**
  702. * wrapper to bootstrap popover
  703. * fix issue when popover stuck on view routing
  704. *
  705. * @memberof App
  706. * @method popover
  707. * @param {DOMElement} self
  708. * @param {object} options
  709. */
  710. App.popover = function (self, options) {
  711. if (!self) return;
  712. self.popover(options);
  713. self.on("remove", function () {
  714. $(this).trigger('mouseleave').off().removeData('popover');
  715. });
  716. };
  717. /**
  718. * wrapper to bootstrap tooltip
  719. * fix issue when tooltip stuck on view routing
  720. * @memberof App
  721. * @method tooltip
  722. * @param {DOMElement} self
  723. * @param {object} options
  724. */
  725. App.tooltip = function (self, options) {
  726. if (!self || !self.tooltip) return;
  727. self.tooltip(options);
  728. /* istanbul ignore next */
  729. self.on("remove", function () {
  730. $(this).trigger('mouseleave').off().removeData('tooltip');
  731. });
  732. };
  733. /**
  734. * wrapper to Date().getTime()
  735. * fix issue when client clock and server clock not sync
  736. *
  737. * @memberof App
  738. * @method dateTime
  739. * @return {Number} timeStamp of current server clock
  740. */
  741. App.dateTime = function() {
  742. return new Date().getTime() + App.clockDistance;
  743. };
  744. /**
  745. *
  746. * @param {number} [x] timestamp
  747. * @returns {number}
  748. */
  749. App.dateTimeWithTimeZone = function (x) {
  750. var timezone = App.router.get('userSettingsController.userSettings.timezone');
  751. if (timezone) {
  752. var tz = Em.getWithDefault(timezone, 'zones.0.value', '');
  753. return moment(moment.tz(x ? new Date(x) : new Date(), tz).toArray()).toDate().getTime();
  754. }
  755. return x || new Date().getTime();
  756. };
  757. App.formatDateTimeWithTimeZone = function (timeStamp, format) {
  758. var timezone = App.router.get('userSettingsController.userSettings.timezone'),
  759. time;
  760. if (timezone) {
  761. var tz = Em.getWithDefault(timezone, 'zones.0.value', '');
  762. time = moment.tz(timeStamp, tz);
  763. } else {
  764. time = moment(timeStamp);
  765. }
  766. return moment(time).format(format);
  767. };
  768. App.getTimeStampFromLocalTime = function (time) {
  769. var timezone = App.router.get('userSettingsController.userSettings.timezone'),
  770. offsetString = '',
  771. date = moment(time).format('YYYY-MM-DD HH:mm:ss');
  772. if (timezone) {
  773. var offset = timezone.utcOffset;
  774. offsetString = moment().utcOffset(offset).format('Z');
  775. }
  776. return moment(date + offsetString).toDate().getTime();
  777. };
  778. /**
  779. * Ambari overrides the default date transformer.
  780. * This is done because of the non-standard data
  781. * sent. For example Nagios sends date as "12345678".
  782. * The problem is that it is a String and is represented
  783. * only in seconds whereas Javascript's Date needs
  784. * milliseconds representation.
  785. */
  786. DS.attr.transforms.date = {
  787. from: function (serialized) {
  788. var type = typeof serialized;
  789. if (type === Em.I18n.t('common.type.string')) {
  790. serialized = parseInt(serialized);
  791. type = typeof serialized;
  792. }
  793. if (type === Em.I18n.t('common.type.number')) {
  794. if (!serialized ){ //serialized timestamp = 0;
  795. return 0;
  796. }
  797. // The number could be seconds or milliseconds.
  798. // If seconds, then the length is 10
  799. // If milliseconds, the length is 13
  800. if (serialized.toString().length < 13) {
  801. serialized = serialized * 1000;
  802. }
  803. return new Date(serialized);
  804. } else if (serialized === null || serialized === undefined) {
  805. // if the value is not present in the data,
  806. // return undefined, not null.
  807. return serialized;
  808. } else {
  809. return null;
  810. }
  811. },
  812. to: function (deserialized) {
  813. if (deserialized instanceof Date) {
  814. return deserialized.getTime();
  815. } else if (deserialized === undefined) {
  816. return undefined;
  817. } else {
  818. return null;
  819. }
  820. }
  821. };
  822. DS.attr.transforms.object = {
  823. from: function(serialized) {
  824. return Ember.none(serialized) ? null : Object(serialized);
  825. },
  826. to: function(deserialized) {
  827. return Ember.none(deserialized) ? null : Object(deserialized);
  828. }
  829. };
  830. /**
  831. * Allows EmberData models to have array properties.
  832. *
  833. * Declare the property as <code>
  834. * operations: DS.attr('array'),
  835. * </code> and
  836. * during load provide a JSON array for value.
  837. *
  838. * This transform simply assigns the same array in both directions.
  839. */
  840. DS.attr.transforms.array = {
  841. from : function(serialized) {
  842. return serialized;
  843. },
  844. to : function(deserialized) {
  845. return deserialized;
  846. }
  847. };
  848. /**
  849. * Utility method to delete all existing records of a DS.Model type from the model's associated map and
  850. * store's persistence layer (recordCache)
  851. * @param type DS.Model Class
  852. */
  853. App.resetDsStoreTypeMap = function(type) {
  854. var allRecords = App.get('store.recordCache'); //This fetches all records in the ember-data persistence layer
  855. var typeMaps = App.get('store.typeMaps');
  856. var guidForType = Em.guidFor(type);
  857. var typeMap = typeMaps[guidForType];
  858. if (typeMap) {
  859. var idToClientIdMap = typeMap.idToCid;
  860. for (var id in idToClientIdMap) {
  861. if (idToClientIdMap.hasOwnProperty(id) && idToClientIdMap[id]) {
  862. delete allRecords[idToClientIdMap[id]]; // deletes the cached copy of the record from the store
  863. }
  864. }
  865. typeMaps[guidForType] = {
  866. idToCid: {},
  867. clientIds: [],
  868. cidToHash: {},
  869. recordArrays: []
  870. };
  871. }
  872. };