ambari-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From onechipore...@apache.org
Subject git commit: AMBARI-6381. Make appropriate changes for GET requests that we will send as POST with custom header. (onechiporenko)
Date Fri, 04 Jul 2014 14:00:11 GMT
Repository: ambari
Updated Branches:
  refs/heads/trunk 68f047373 -> c5e04983a


AMBARI-6381. Make appropriate changes for GET requests that we will send as POST with custom
header. (onechiporenko)


Project: http://git-wip-us.apache.org/repos/asf/ambari/repo
Commit: http://git-wip-us.apache.org/repos/asf/ambari/commit/c5e04983
Tree: http://git-wip-us.apache.org/repos/asf/ambari/tree/c5e04983
Diff: http://git-wip-us.apache.org/repos/asf/ambari/diff/c5e04983

Branch: refs/heads/trunk
Commit: c5e04983aeb875c994e262cc30cadd6320caef91
Parents: 68f0473
Author: Oleg Nechiporenko <onechiporenko@apache.org>
Authored: Fri Jul 4 16:59:48 2014 +0300
Committer: Oleg Nechiporenko <onechiporenko@apache.org>
Committed: Fri Jul 4 16:59:48 2014 +0300

----------------------------------------------------------------------
 .../app/controllers/global/update_controller.js | 67 ++++++++++++-----
 ambari-web/app/controllers/main/host.js         | 79 +++++++++++++-------
 ambari-web/app/utils/ajax/ajax.js               | 34 ++++++---
 .../app/utils/batch_scheduled_requests.js       | 48 ++++++------
 ambari-web/app/utils/http_client.js             | 62 +++++++++++----
 ambari-web/app/views/main/host.js               | 25 +++----
 6 files changed, 208 insertions(+), 107 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ambari/blob/c5e04983/ambari-web/app/controllers/global/update_controller.js
----------------------------------------------------------------------
diff --git a/ambari-web/app/controllers/global/update_controller.js b/ambari-web/app/controllers/global/update_controller.js
index f157fae..6007ba5 100644
--- a/ambari-web/app/controllers/global/update_controller.js
+++ b/ambari-web/app/controllers/global/update_controller.js
@@ -48,8 +48,8 @@ App.UpdateController = Em.Controller.extend({
    * @return {String}
    */
   getComplexUrl: function (testUrl, realUrl, queryParams) {
-    var prefix = App.apiPrefix + '/clusters/' + App.get('clusterName');
-    var params = '';
+    var prefix = App.get('apiPrefix') + '/clusters/' + App.get('clusterName'),
+      params = '';
 
     if (App.get('testMode')) {
       return testUrl;
@@ -146,8 +146,9 @@ App.UpdateController = Em.Controller.extend({
   },
 
   updateHost: function (callback, error) {
-    var testUrl = App.get('isHadoop2Stack') ? '/data/hosts/HDP2/hosts.json' : '/data/hosts/hosts.json';
-    var self = this;
+    var testUrl = App.get('isHadoop2Stack') ? '/data/hosts/HDP2/hosts.json' : '/data/hosts/hosts.json',
+      self = this,
+      p = '';
     var realUrl = '/hosts?<parameters>fields=Hosts/host_name,Hosts/maintenance_state,Hosts/public_host_name,Hosts/cpu_count,Hosts/ph_cpu_count,Hosts/total_mem,'
+
       'Hosts/host_status,Hosts/last_heartbeat_time,Hosts/os_arch,Hosts/os_type,Hosts/ip,host_components/HostRoles/state,host_components/HostRoles/maintenance_state,'
+
       'host_components/HostRoles/stale_configs,host_components/HostRoles/service_name,metrics/disk,metrics/load/load_one,metrics/cpu/cpu_system,metrics/cpu/cpu_user,'
+
@@ -155,17 +156,24 @@ App.UpdateController = Em.Controller.extend({
 
     if (App.router.get('currentState.name') == 'index' && App.router.get('currentState.parentState.name')
== 'hosts') {
       App.updater.updateInterval('updateHost', App.get('contentUpdateInterval'));
-    } else if(App.router.get('currentState.name') == 'summary' && App.router.get('currentState.parentState.name')
== 'hostDetails') {
-      realUrl = realUrl.replace('<parameters>', 'Hosts/host_name=' + App.router.get('location.lastSetURL').match(/\/hosts\/(.*)\/summary/)[1]
+ '&');
-      App.updater.updateInterval('updateHost', App.get('componentsUpdateInterval'));
-    } else {
-      callback();
-      // On pages except for hosts/hostDetails, making sure hostsMapper loaded only once
on page load, no need to update, but at least once
-      if (this.get('queryParams.Hosts') && this.get('queryParams.Hosts').length >
0) {
-        return;
+    }
+    else {
+      if(App.router.get('currentState.name') == 'summary' && App.router.get('currentState.parentState.name')
== 'hostDetails') {
+        p = 'Hosts/host_name=' + App.router.get('location.lastSetURL').match(/\/hosts\/(.*)\/summary/)[1]
+ '&';
+        App.updater.updateInterval('updateHost', App.get('componentsUpdateInterval'));
+      }
+      else {
+        callback();
+        // On pages except for hosts/hostDetails, making sure hostsMapper loaded only once
on page load, no need to update, but at least once
+        if (this.get('queryParams.Hosts') && this.get('queryParams.Hosts').length
> 0) {
+          return;
+        }
       }
     }
-    this.get('queryParams').set('Hosts', App.router.get('mainHostController').getQueryParameters());
+    var mainHostController = App.router.get('mainHostController'),
+      viewProperties = mainHostController.getViewProperties(),
+      sortProperties = mainHostController.getSortProperties();
+    this.get('queryParams').set('Hosts', mainHostController.getQueryParameters(true));
     var clientCallback = function (skipCall, queryParams) {
       if (skipCall) {
         //no hosts match filter by component
@@ -174,12 +182,33 @@ App.UpdateController = Em.Controller.extend({
           itemTotal: '0'
         });
         callback();
-      } else {
-        var hostsUrl = self.getComplexUrl(testUrl, realUrl, queryParams);
-        App.HttpClient.get(hostsUrl, App.hostsMapper, {
-          complete: callback,
-          error: error
-        });
+      }
+      else {
+        var params = p + self.computeParameters(queryParams),
+          viewProps = self.computeParameters(viewProperties),
+          sortProps = self.computeParameters(sortProperties);
+        if (!viewProps.length) viewProps = '&';
+        if (!sortProps.length) sortProps = '&';
+        if ((params.length + viewProps.length + sortProps.length) > 0) {
+          realUrl = App.get('apiPrefix') + '/clusters/' + App.get('clusterName') +
+            realUrl.replace('<parameters>', '') + '&' +
+            viewProps.substring(0, viewProps.length - 1) + '&' +
+            sortProps.substring(0, sortProps.length - 1);
+          App.HttpClient.get(realUrl, App.hostsMapper, {
+            complete: callback,
+            doGetAsPost: true,
+            params: params.substring(0, params.length - 1),
+            error: error
+          });
+        }
+        else {
+          var hostsUrl = self.getComplexUrl(testUrl, realUrl, queryParams);
+          App.HttpClient.get(hostsUrl, App.hostsMapper, {
+            complete: callback,
+            doGetAsPost: false,
+            error: error
+          });
+        }
       }
     };
 

http://git-wip-us.apache.org/repos/asf/ambari/blob/c5e04983/ambari-web/app/controllers/main/host.js
----------------------------------------------------------------------
diff --git a/ambari-web/app/controllers/main/host.js b/ambari-web/app/controllers/main/host.js
index 793f715..3cfaf44 100644
--- a/ambari-web/app/controllers/main/host.js
+++ b/ambari-web/app/controllers/main/host.js
@@ -218,26 +218,62 @@ App.MainHostController = Em.ArrayController.extend({
   },
 
   /**
-   * get query parameters computed from filter properties, sort properties and custom properties
of view
-   * @return {Array}
+   * Transform <code>viewProperties</code> to queryParameters
+   * @returns {Object[]}
+   * @method getViewProperties
    */
-  getQueryParameters: function () {
-    var queryParams = [];
-    var savedFilterConditions = App.db.getFilterConditions(this.get('name')) || [];
-    var savedSortConditions = App.db.getSortingStatuses(this.get('name')) || [];
-    var colPropAssoc = this.get('colPropAssoc');
-    var filterProperties = this.get('filterProperties');
-    var sortProperties = this.get('sortProps');
-    var oldProperties = App.router.get('updateController.queryParams.Hosts');
-
-    this.set('resetStartIndex', false);
-    this.get('viewProperties').forEach(function (property) {
-      queryParams.push({
+  getViewProperties: function() {
+    return this.get('viewProperties').map(function (property) {
+      return {
         key: property.get('alias'),
         value: property.getValue(this),
         type: 'EQUAL'
-      })
+      };
     }, this);
+  },
+
+  /**
+   * Transform <code>sortProps</code> to queryParameters
+   * @returns {Object[]}
+   * @method getSortProperties
+   */
+  getSortProperties: function() {
+    var savedSortConditions = App.db.getSortingStatuses(this.get('name')) || [],
+      sortProperties = this.get('sortProps'),
+      queryParams = [];
+    savedSortConditions.forEach(function (sort) {
+      var property = sortProperties.findProperty('key', sort.name);
+
+      if (property && (sort.status === 'sorting_asc' || sort.status === 'sorting_desc'))
{
+        queryParams.push({
+          key: property.alias,
+          value: sort.status.replace('sorting_', ''),
+          type: 'SORT'
+        });
+      }
+    });
+    return queryParams;
+  },
+
+  /**
+   * get query parameters computed from filter properties, sort properties and custom properties
of view
+   * @return {Array}
+   * @method getQueryParameters
+   */
+  getQueryParameters: function (skipNonFilterProperties) {
+    skipNonFilterProperties = skipNonFilterProperties || false;
+    var queryParams = [],
+      savedFilterConditions = App.db.getFilterConditions(this.get('name')) || [],
+      savedSortConditions = App.db.getSortingStatuses(this.get('name')) || [],
+      colPropAssoc = this.get('colPropAssoc'),
+      filterProperties = this.get('filterProperties'),
+      sortProperties = this.get('sortProps'),
+      oldProperties = App.router.get('updateController.queryParams.Hosts');
+
+    this.set('resetStartIndex', false);
+
+    queryParams.pushObjects(this.getViewProperties());
+
     savedFilterConditions.forEach(function (filter) {
       var property = filterProperties.findProperty('key', colPropAssoc[filter.iColumn]);
       if (property && filter.value.length > 0 && !filter.skipFilter) {
@@ -290,17 +326,10 @@ App.MainHostController = Em.ArrayController.extend({
         }
       }, this);
     }
-    savedSortConditions.forEach(function (sort) {
-      var property = sortProperties.findProperty('key', sort.name);
 
-      if (property && (sort.status === 'sorting_asc' || sort.status === 'sorting_desc'))
{
-        queryParams.push({
-          key: property.alias,
-          value: sort.status.replace('sorting_', ''),
-          type: 'SORT'
-        });
-      }
-    });
+    if (!skipNonFilterProperties) {
+      queryParams.pushObjects(this.getSortProperties());
+    }
 
     return queryParams;
   },

http://git-wip-us.apache.org/repos/asf/ambari/blob/c5e04983/ambari-web/app/utils/ajax/ajax.js
----------------------------------------------------------------------
diff --git a/ambari-web/app/utils/ajax/ajax.js b/ambari-web/app/utils/ajax/ajax.js
index 58db592..72b7dd1 100644
--- a/ambari-web/app/utils/ajax/ajax.js
+++ b/ambari-web/app/utils/ajax/ajax.js
@@ -1102,7 +1102,7 @@ var urls = {
         type: 'PUT',
         data: data.data
       };
-      if (App.testMode) {
+      if (App.get('testMode')) {
         d.type = 'GET';
       }
       return d;
@@ -1116,7 +1116,7 @@ var urls = {
         type: 'PUT',
         data: data.data
       };
-      if (App.testMode) {
+      if (App.get('testMode')) {
         d.type = 'GET';
       }
       return d;
@@ -1802,12 +1802,18 @@ var urls = {
     'mock': ''
   },
   'host.host_components.filtered': {
-    'real': '/clusters/{clusterName}/hosts',
+    'real': '/clusters/{clusterName}/hosts?{fields}',
     'mock': '',
-    format: function(data, opt) {
+    format: function(data) {
       return {
-        url: opt.url + data.urlParams
-      }
+        headers: {
+          'X-Http-Method-Override': 'GET'
+        },
+        type: 'POST',
+        data: JSON.stringify({
+          "RequestInfo": {"query" : data.parameters}
+        })
+      };
     }
   },
   'host.status.counters': {
@@ -1952,11 +1958,19 @@ var urls = {
     }
   },
   'hosts.bulk.operations': {
-    real: '',
+    real: '/clusters/{clusterName}/hosts?fields=Hosts/host_name,Hosts/maintenance_state,'
+
+      'host_components/HostRoles/state,host_components/HostRoles/maintenance_state,' +
+      'host_components/HostRoles/stale_configs&minimal_response=true',
     mock: '',
     format: function(data) {
       return {
-        url: data.url
+        headers: {
+          'X-Http-Method-Override': 'GET'
+        },
+        type: 'POST',
+        data: JSON.stringify({
+          "RequestInfo": {"query" : data.parameters }
+        })
       }
     }
   }
@@ -1999,7 +2013,7 @@ var formatRequest = function (data) {
     dataType: 'json',
     statusCode: require('data/statusCodes')
   };
-  if (App.testMode) {
+  if (App.get('testMode')) {
     opt.url = formatUrl(this.mock ? this.mock : '', data);
     opt.type = 'GET';
   }
@@ -2037,8 +2051,6 @@ var ajax = Em.Object.extend({
    */
   send: function (config) {
 
-    console.warn('============== ajax ==============', config.name, config.data);
-
     if (!config.sender) {
       console.warn('Ajax sender should be defined!');
       return null;

http://git-wip-us.apache.org/repos/asf/ambari/blob/c5e04983/ambari-web/app/utils/batch_scheduled_requests.js
----------------------------------------------------------------------
diff --git a/ambari-web/app/utils/batch_scheduled_requests.js b/ambari-web/app/utils/batch_scheduled_requests.js
index 13ec4b2..8b969b0 100644
--- a/ambari-web/app/utils/batch_scheduled_requests.js
+++ b/ambari-web/app/utils/batch_scheduled_requests.js
@@ -99,22 +99,22 @@ module.exports = {
   /**
    * construct URL from parameters for request in <code>getComponentsFromServer()</code>
    * @param options
-   * @return {String}
+   * @return {{fields: string, params: string}}
    */
   constructComponentsCallUrl: function (options) {
     var multipleValueParams = {
-      'services': 'host_components/HostRoles/service_name.in(<entity-names>)',
-      'hosts': 'Hosts/host_name.in(<entity-names>)',
-      'components': 'host_components/HostRoles/component_name.in(<entity-names>)'
-    };
-    var singleValueParams = {
-      staleConfigs: 'host_components/HostRoles/stale_configs=',
-      passiveState: 'Hosts/maintenance_state=',
-      workStatus: 'host_components/HostRoles/state='
-    };
-    var displayParams = options.displayParams || [];
-    var urlParams = '?';
-    var addAmpersand = false;
+        'services': 'host_components/HostRoles/service_name.in(<entity-names>)',
+        'hosts': 'Hosts/host_name.in(<entity-names>)',
+        'components': 'host_components/HostRoles/component_name.in(<entity-names>)'
+      },
+      singleValueParams = {
+        staleConfigs: 'host_components/HostRoles/stale_configs=',
+        passiveState: 'Hosts/maintenance_state=',
+        workStatus: 'host_components/HostRoles/state='
+      },
+      displayParams = options.displayParams || [],
+      urlParams = '',
+      addAmpersand = false;
 
     for (var i in multipleValueParams) {
       var arrayParams = options[i];
@@ -136,17 +136,19 @@ module.exports = {
         addAmpersand = true;
       }
     }
-
+    var params = urlParams,
+      fields = '';
     displayParams.forEach(function (displayParam, index, array) {
       if (index === 0) {
-        urlParams += (addAmpersand) ? '&' : '';
-        urlParams += 'fields=';
+        fields += (addAmpersand) ? '&' : '';
+        fields += 'fields=';
       }
-      urlParams += displayParam;
-      urlParams += (array.length === (index + 1)) ? '' : ",";
+      fields += displayParam;
+      fields += (array.length === (index + 1)) ? '' : ",";
     });
+    fields += '&minimal_response=true';
 
-    return urlParams + '&minimal_response=true';
+    return {fields: fields.substring(1, fields.length), params: params};
   },
 
   /**
@@ -156,13 +158,13 @@ module.exports = {
    * @param callback
    */
   getComponentsFromServer: function (options, callback) {
-    var urlParams = this.constructComponentsCallUrl(options);
-
-    App.ajax.send({
+    var request_parameters = this.constructComponentsCallUrl(options);
+    return App.ajax.send({
       name: 'host.host_components.filtered',
       sender: this,
       data: {
-        urlParams: urlParams,
+        parameters: request_parameters.params,
+        fields: request_parameters.fields,
         callback: callback
       },
       success: 'getComponentsFromServerSuccessCallback'

http://git-wip-us.apache.org/repos/asf/ambari/blob/c5e04983/ambari-web/app/utils/http_client.js
----------------------------------------------------------------------
diff --git a/ambari-web/app/utils/http_client.js b/ambari-web/app/utils/http_client.js
index 8d99069..ef3c94a 100644
--- a/ambari-web/app/utils/http_client.js
+++ b/ambari-web/app/utils/http_client.js
@@ -33,12 +33,12 @@ App.HttpClient = Em.Object.create({
   defaultErrorHandler: function (jqXHR, textStatus, errorThrown, url) {
     try {
       var json = $.parseJSON(jqXHR.responseText);
-    } catch (err) {
-    }
+    } catch (err) { }
     App.ajax.defaultErrorHandler(jqXHR, url);
     if (json) {
       Em.assert("HttpClient:", json);
-    } else {
+    }
+    else {
       if (!$.mocho) { // don't use this assert on tests
         Em.assert("HttpClient:", errorThrown);
       }
@@ -66,6 +66,34 @@ App.HttpClient = Em.Object.create({
     this.onReady(xhr, "", ajaxOptions, mapper, errorHandler, url);
   },
 
+  /**
+   * Do POST-request equal to GET-request but with some params put to body
+   * @param {string} url
+   * @param {{params: string, success: callback, error: callback}} ajaxOptions
+   * @param {App.QuickDataMapper} mapper
+   * @param errorHandler
+   * @method getAsPostRequest
+   */
+  getAsPostRequest: function (url, ajaxOptions, mapper, errorHandler) {
+
+    if (!errorHandler) {
+      errorHandler = this.defaultErrorHandler;
+    }
+
+    var xhr = new XMLHttpRequest(),
+      curTime = App.dateTime(),
+      params = JSON.stringify({
+        "RequestInfo": {"query" : ajaxOptions.params }
+      });
+
+    xhr.open('POST', url + (url.indexOf('?') >= 0 ? '&_=' : '?_=') + curTime, true);
+    xhr.setRequestHeader("X-Http-Method-Override", "GET");
+    xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
+    xhr.send(params);
+
+    this.onReady(xhr, "", ajaxOptions, mapper, errorHandler, url);
+  },
+
   /*
    This function checks if we get response from server
    Not using onreadystatechange cuz of possible closure
@@ -92,8 +120,8 @@ App.HttpClient = Em.Object.create({
         xhr = null;
         clearTimeout(timeout);
         timeout = null;
-
-      } else {
+      }
+      else {
         self.onReady(xhr, timeout, tmp_val, mapper, errorHandler, url);
       }
     }, 10);
@@ -110,19 +138,25 @@ App.HttpClient = Em.Object.create({
     if (!errorHandler && data.error) {
       errorHandler = data.error;
     }
-    var client = this;
-    var request = function () {
-      client.request(url, data, mapper, errorHandler);
-      url = null;
-      data = null;
-      mapper = null;
-      errorHandler = null;
-    };
+    var client = this,
+      request = function () {
+        if (data.doGetAsPost) {
+          client.getAsPostRequest(url, data, mapper, errorHandler);
+        }
+        else {
+          client.request(url, data, mapper, errorHandler);
+        }
+        url = null;
+        data = null;
+        mapper = null;
+        errorHandler = null;
+      };
 
     interval = "" + interval;
     if (interval.match(/\d+/)) {
       $.periodic({period: interval}, request);
-    } else {
+    }
+    else {
       request();
     }
   },

http://git-wip-us.apache.org/repos/asf/ambari/blob/c5e04983/ambari-web/app/views/main/host.js
----------------------------------------------------------------------
diff --git a/ambari-web/app/views/main/host.js b/ambari-web/app/views/main/host.js
index c315ebf..2333d14 100644
--- a/ambari-web/app/views/main/host.js
+++ b/ambari-web/app/views/main/host.js
@@ -200,10 +200,11 @@ App.MainHostView = App.TableView.extend(App.TableServerProvider, {
 
   /**
    * get query parameters computed in controller
+   * @param {bool} flag should non-filters params be skipped
    * @return {Array}
    */
-  getQueryParameters: function () {
-    return this.get('controller').getQueryParameters();
+  getQueryParameters: function (flag) {
+    return this.get('controller').getQueryParameters(flag);
   },
   /**
    * stub for filter function in TableView
@@ -356,11 +357,7 @@ App.MainHostView = App.TableView.extend(App.TableServerProvider, {
    */
   bulkOperationConfirm: function(operationData, selection) {
     var hostsNames = [],
-    realUrl = '/hosts?<parameters>fields=Hosts/host_name,Hosts/maintenance_state,'
+
-      'host_components/HostRoles/state,host_components/HostRoles/maintenance_state,' +
-      'host_components/HostRoles/stale_configs&minimal_response=true' +
-    '';
-    var queryParams = [];
+      queryParams = [];
     switch(selection) {
       case 's':
         hostsNames = this.get('selectedHosts');
@@ -373,11 +370,8 @@ App.MainHostView = App.TableView.extend(App.TableServerProvider, {
         }
         break;
       case 'f':
-        queryParams = this.getQueryParameters().filter(function (obj){
-          if(obj.key == 'page_size' || obj.key == 'from'){
-            return false;
-          }
-          return true;
+        queryParams = this.getQueryParameters(true).filter(function (obj) {
+          return !(obj.key == 'page_size' || obj.key == 'from');
         });
         break;
     }
@@ -387,15 +381,16 @@ App.MainHostView = App.TableView.extend(App.TableServerProvider, {
       primary: false,
       secondary: false,
       bodyClass: Ember.View.extend({
-        template: Ember.Handlebars.compile('<p><div class="spinner"></div></p>')
+        template: Ember.Handlebars.compile('<div class="spinner"></div>')
       })
     });
-
+    var parameters = App.router.get('updateController').computeParameters(queryParams);
+    if (!parameters.length) parameters = '&';
     App.ajax.send({
       name: 'hosts.bulk.operations',
       sender: this,
       data: {
-        url: App.router.get('updateController').getComplexUrl("", realUrl, queryParams),
+        parameters: parameters.substring(0, parameters.length - 1),
         operationData: operationData,
         loadingPopup: loadingPopup
       },


Mime
View raw message