You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@ignite.apache.org by an...@apache.org on 2016/01/20 03:52:46 UTC

ignite git commit: IGNITE-843 Refactor agent route

Repository: ignite
Updated Branches:
  refs/heads/ignite-843-rc2 cd566ca82 -> 873b939b0


IGNITE-843 Refactor agent route


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

Branch: refs/heads/ignite-843-rc2
Commit: 873b939b0009bfcbe55ac7f9bf3868fd07c91a1f
Parents: cd566ca
Author: Andrey <an...@gridgain.com>
Authored: Wed Jan 20 09:53:08 2016 +0700
Committer: Andrey <an...@gridgain.com>
Committed: Wed Jan 20 09:53:08 2016 +0700

----------------------------------------------------------------------
 .../console/agent/handlers/RestExecutor.java    |  47 +++-
 .../console/agent/remote/RemoteHandler.java     |  33 +--
 .../src/main/js/agents/agent-manager.js         | 154 +++++++-----
 .../src/main/js/agents/agent-server.js          |  29 +--
 .../src/main/js/controllers/common-module.js    |   5 +-
 .../src/main/js/routes/agent.js                 | 246 ++++++++-----------
 6 files changed, 248 insertions(+), 266 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/ignite/blob/873b939b/modules/control-center-agent/src/main/java/org/apache/ignite/console/agent/handlers/RestExecutor.java
----------------------------------------------------------------------
diff --git a/modules/control-center-agent/src/main/java/org/apache/ignite/console/agent/handlers/RestExecutor.java b/modules/control-center-agent/src/main/java/org/apache/ignite/console/agent/handlers/RestExecutor.java
index 22aae18..aed1508 100644
--- a/modules/control-center-agent/src/main/java/org/apache/ignite/console/agent/handlers/RestExecutor.java
+++ b/modules/control-center-agent/src/main/java/org/apache/ignite/console/agent/handlers/RestExecutor.java
@@ -159,12 +159,12 @@ public class RestExecutor {
                 charset = Charsets.toCharset(encoding);
             }
 
-            return new RestResult(resp.getStatusLine().getStatusCode(), new String(out.toByteArray(), charset));
+            return RestResult.success(resp.getStatusLine().getStatusCode(), new String(out.toByteArray(), charset));
         }
         catch (ConnectException e) {
             log.info("Failed connect to node and execute REST command [uri=" + builder.build() + "]");
 
-            return new RestResult(404, "Failed connect to node and execute REST command.");
+            return RestResult.fail(404, "Failed connect to node and execute REST command.");
         }
     }
 
@@ -172,19 +172,44 @@ public class RestExecutor {
      * Request result.
      */
     public static class RestResult {
-        /** Status code. */
-        private int code;
+        /** REST http code */
+        private int restCode;
 
-        /** Message. */
-        private String message;
+        /** The field contains description of error if server could not handle the request. */
+        private String error;
+
+        /** The field contains result of command. */
+        private String response;
+
+        /**
+         * @param restCode REST http code.
+         * @param error The field contains description of error if server could not handle the request.
+         * @param response The field contains result of command.
+         */
+        private RestResult(int restCode, String error, String response) {
+            this.restCode = restCode;
+            this.error = error;
+            this.response = response;
+        }
 
         /**
-         * @param code Code.
-         * @param msg Message.
+         * @param restCode REST http code.
+         * @param error The field contains description of error if server could not handle the request.
+
+         * @return Request result.
+         */
+        public static RestResult fail(int restCode, String error) {
+            return new RestResult(restCode, error, null);
+        }
+
+        /**
+         * @param restCode REST http code.
+         * @param response The field contains result of command.
+
+         * @return Request result.
          */
-        public RestResult(int code, String msg) {
-            this.code = code;
-            message = msg;
+        public static RestResult success(int restCode, String response) {
+            return new RestResult(restCode, null, response);
         }
     }
 }

http://git-wip-us.apache.org/repos/asf/ignite/blob/873b939b/modules/control-center-agent/src/main/java/org/apache/ignite/console/agent/remote/RemoteHandler.java
----------------------------------------------------------------------
diff --git a/modules/control-center-agent/src/main/java/org/apache/ignite/console/agent/remote/RemoteHandler.java b/modules/control-center-agent/src/main/java/org/apache/ignite/console/agent/remote/RemoteHandler.java
index 4eda313..e681b15 100644
--- a/modules/control-center-agent/src/main/java/org/apache/ignite/console/agent/remote/RemoteHandler.java
+++ b/modules/control-center-agent/src/main/java/org/apache/ignite/console/agent/remote/RemoteHandler.java
@@ -68,11 +68,10 @@ public class RemoteHandler implements AutoCloseable {
 
         for (Object hnd : hnds) {
             for (Method method : hnd.getClass().getMethods()) {
-                Remote remoteAnn = method.getAnnotation(Remote.class);
+                Remote ann = method.getAnnotation(Remote.class);
 
-                if (remoteAnn != null) {
-                    MethodDescriptor old = mtds.put(method.getName(), new MethodDescriptor(method, hnd,
-                        remoteAnn.async()));
+                if (ann != null) {
+                    MethodDescriptor old = mtds.put(method.getName(), new MethodDescriptor(method, hnd, ann.async()));
 
                     if (old != null)
                         throw new IllegalArgumentException("Duplicated method: " + method.getName());
@@ -97,12 +96,12 @@ public class RemoteHandler implements AutoCloseable {
 
         final Long reqId = reqIdJson == null ? null : reqIdJson.getAsLong();
 
-        String mtdName = req.getAsJsonPrimitive("mtdName").getAsString();
+        String method = req.getAsJsonPrimitive("method").getAsString();
 
-        final MethodDescriptor desc = mtds.get(mtdName);
+        final MethodDescriptor desc = mtds.get(method);
 
         if (desc == null) {
-            sendException(reqId, INTERNAL_EXCEPTION_TYPE, "Unknown method: " + mtdName);
+            sendException(reqId, INTERNAL_EXCEPTION_TYPE, "Unknown method: " + method);
 
             return;
         }
@@ -117,7 +116,7 @@ public class RemoteHandler implements AutoCloseable {
             args = new Object[paramTypes.length];
 
             if (argsJson == null || argsJson.size() != paramTypes.length) {
-                sendException(reqId, INTERNAL_EXCEPTION_TYPE, "Inconsistent parameters");
+                sendException(reqId, INTERNAL_EXCEPTION_TYPE, "Inconsistent parameters count");
 
                 return;
             }
@@ -125,16 +124,9 @@ public class RemoteHandler implements AutoCloseable {
             for (int i = 0; i < paramTypes.length; i++)
                 args[i] = GSON.fromJson(argsJson.get(i), paramTypes[i]);
         }
-        else {
+        else
             args = EMPTY_OBJECTS;
 
-            if (argsJson != null && argsJson.size() > 0) {
-                sendException(reqId, INTERNAL_EXCEPTION_TYPE, "Inconsistent parameters");
-
-                return;
-            }
-        }
-
         Runnable run = new Runnable() {
             @Override public void run() {
                 final Object res;
@@ -182,13 +174,10 @@ public class RemoteHandler implements AutoCloseable {
         JsonObject res = new JsonObject();
 
         res.addProperty("type", "CallRes");
-        res.addProperty("reqId", reqId);
 
-        JsonObject exJson = new JsonObject();
-        exJson.addProperty("type", exType);
-        exJson.addProperty("message", exMsg);
+        res.addProperty("reqId", reqId);
 
-        res.add("ex", exJson);
+        res.addProperty("error", exType + ": " + exMsg);
 
         snd.send(res);
     }
@@ -210,7 +199,7 @@ public class RemoteHandler implements AutoCloseable {
 
         JsonElement resJson = type == void.class ? JsonNull.INSTANCE : GSON.toJsonTree(res, type);
 
-        resp.add("res", resJson);
+        resp.add("response", resJson);
 
         snd.send(resp);
     }

http://git-wip-us.apache.org/repos/asf/ignite/blob/873b939b/modules/control-center-web/src/main/js/agents/agent-manager.js
----------------------------------------------------------------------
diff --git a/modules/control-center-web/src/main/js/agents/agent-manager.js b/modules/control-center-web/src/main/js/agents/agent-manager.js
index 2de4de8..d0ae33a 100644
--- a/modules/control-center-web/src/main/js/agents/agent-manager.js
+++ b/modules/control-center-web/src/main/js/agents/agent-manager.js
@@ -112,6 +112,19 @@ function Client(ws, manager) {
     this._cbMap = {};
 }
 
+Client.prototype._runCommand = function(method, args) {
+    var self = this;
+
+    return new Promise(function(resolve, reject) {
+        self._invokeRmtMethod(method, args, function(error, res) {
+            if (error != null)
+                return reject(error);
+
+            resolve(res);
+        });
+    });
+};
+
 /**
  * @param {String} uri
  * @param {Object} params
@@ -119,13 +132,13 @@ function Client(ws, manager) {
  * @param {String} [method]
  * @param {Object} [headers]
  * @param {String} [body]
- * @param {Function} [cb] Callback. Take 3 arguments: {String} error, {number} httpCode, {string} response.
+ * @param {callback} [callback] Callback. Take 3 arguments: {Number} successStatus, {String} error,  {String} response.
  */
-Client.prototype.executeRest = function(uri, params, demo, method, headers, body, cb) {
+Client.prototype.executeRest = function(uri, params, demo, method, headers, body, callback) {
     if (typeof(params) != 'object')
         throw '"params" argument must be an object';
 
-    if (typeof(cb) != 'function')
+    if (typeof(callback) != 'function')
         throw 'callback must be a function';
 
     if (body && typeof(body) != 'string')
@@ -142,83 +155,112 @@ Client.prototype.executeRest = function(uri, params, demo, method, headers, body
     if (method != 'GET' && method != 'POST')
         throw 'Unknown HTTP method: ' + method;
 
-    var newArgs = argsToArray(arguments);
+    const cb = function(error, restResult) {
+        if (error)
+            return callback(error);
+
+        const restError = restResult.error;
+
+        if (restError)
+            return callback(restError);
+
+        const restCode = restResult.restCode;
+
+        if (restCode !== 200) {
+            if (restCode === 401)
+                return callback.call({code: restCode, message: "Failed to authenticate on node."});
+
+            return callback.call({code: restCode, message: restError || "Failed connect to node and execute REST command."});
+        }
+
+        try {
+            var nodeResponse = JSON.parse(restResult.response);
+
+            if (nodeResponse.successStatus === 0)
+                return callback(null, nodeResponse.response);
+
+            switch (nodeResponse.successStatus) {
+                case 1:
+                    return callback({code: 500, message: nodeResponse.error});
+                case 2:
+                    return callback({code: 401, message: nodeResponse.error});
+                case 3:
+                    return callback({code: 403, message: nodeResponse.error});
+            }
 
-    newArgs[6] = function(ex, res) {
-        if (ex)
-            cb(ex.message);
-        else
-            cb(null, res.code, res.message)
+            callback(nodeResponse.error);
+        }
+        catch (e) {
+            callback(e);
+        }
     };
 
-    this._invokeRmtMethod('executeRest', newArgs);
+    this._invokeRmtMethod('executeRest', [uri, params, demo, method, headers, body], cb);
 };
 
 /**
  * @param {string} error
  */
 Client.prototype.authResult = function(error) {
-    this._invokeRmtMethod('authResult', arguments)
+    return this._runCommand('authResult', [].slice.call(arguments));
 };
 
 /**
- * @param {String} jdbcDriverJarPath
- * @param {String} jdbcDriverClass
- * @param {String} jdbcUrl
- * @param {Object} jdbcInfo
- * @param {Function} cb Callback. Take two arguments: {Object} exception, {Object} result.
- * @returns {Array} List of tables (see org.apache.ignite.schema.parser.DbTable java class)
+ * @param {String} driverPath
+ * @param {String} driverClass
+ * @param {String} url
+ * @param {Object} info
+ * @returns {Promise} Promise on list of tables (see org.apache.ignite.schema.parser.DbTable java class)
  */
-Client.prototype.metadataSchemas = function(jdbcDriverJarPath, jdbcDriverClass, jdbcUrl, jdbcInfo, cb) {
-    this._invokeRmtMethod('schemas', arguments)
+Client.prototype.metadataSchemas = function(driverPath, driverClass, url, info) {
+    return this._runCommand('schemas', [].slice.call(arguments));
 };
 
 /**
- * @param {String} jdbcDriverJarPath
- * @param {String} jdbcDriverClass
- * @param {String} jdbcUrl
- * @param {Object} jdbcInfo
+ * @param {String} driverPath
+ * @param {String} driverClass
+ * @param {String} url
+ * @param {Object} info
  * @param {Array} schemas
  * @param {Boolean} tablesOnly
- * @param {Function} cb Callback. Take two arguments: {Object} exception, {Object} result.
- * @returns {Array} List of tables (see org.apache.ignite.schema.parser.DbTable java class)
+ * @returns {Promise} Promise on list of tables (see org.apache.ignite.schema.parser.DbTable java class)
  */
-Client.prototype.metadataTables = function(jdbcDriverJarPath, jdbcDriverClass, jdbcUrl, jdbcInfo, schemas, tablesOnly, cb) {
-    this._invokeRmtMethod('metadata', arguments)
+Client.prototype.metadataTables = function(driverPath, driverClass, url, info, schemas, tablesOnly) {
+    return this._runCommand('metadata', [].slice.call(arguments));
 };
 
 /**
- * @param {Function} cb Callback. Take two arguments: {Object} exception, {Object} result.
- * @returns {Array} List of jars from driver folder.
+ * @returns {Promise} Promise on list of jars from driver folder.
  */
-Client.prototype.availableDrivers = function(cb) {
-    this._invokeRmtMethod('availableDrivers', arguments)
+Client.prototype.availableDrivers = function() {
+    return this._runCommand('availableDrivers', [].slice.call(arguments));
 };
 
-Client.prototype._invokeRmtMethod = function(methodName, args) {
-    var cb = null;
-
-    var m = argsToArray(args);
-
-    if (m.length > 0 && typeof m[m.length - 1] == 'function')
-        cb = m.pop();
-
+/**
+ * Run http request
+ *
+ * @this {AgentServer}
+ * @param {String} method Command name.
+ * @param {Array} args Command params.
+ * @param {Function} callback on finish
+ */
+Client.prototype._invokeRmtMethod = function(method, args, callback) {
     if (this._ws.readyState != 1) {
-        if (cb)
-            cb({type: 'org.apache.ignite.agent.AgentException', message: 'Connection is closed'});
+        if (callback)
+            callback('org.apache.ignite.agent.AgentException: Connection is closed');
 
         return
     }
 
     var msg = {
-        mtdName: methodName,
-        args: m
+        method: method,
+        args: args
     };
 
-    if (cb) {
+    if (callback) {
         var reqId = this._reqCounter++;
 
-        this._cbMap[reqId] = cb;
+        this._cbMap[reqId] = callback;
 
         msg.reqId = reqId;
     }
@@ -251,16 +293,13 @@ Client.prototype._rmtAuthMessage = function(msg) {
 };
 
 Client.prototype._rmtCallRes = function(msg) {
-    var cb = this._cbMap[msg.reqId];
+    var callback = this._cbMap[msg.reqId];
 
-    if (!cb) return;
+    if (!callback) return;
 
     delete this._cbMap[msg.reqId];
 
-    if (msg.ex)
-        cb(msg.ex);
-    else
-        cb(null, msg.res);
+    callback(msg.error, msg.response);
 };
 
 /**
@@ -278,19 +317,6 @@ function removeFromArray(arr, val) {
     }
 }
 
-/**
- * @param args
- * @returns {Array}
- */
-function argsToArray(args) {
-    var res = [];
-
-    for (var i = 0; i < args.length; i++)
-        res.push(args[i]);
-
-    return res;
-}
-
 exports.AgentManager = AgentManager;
 
 /**

http://git-wip-us.apache.org/repos/asf/ignite/blob/873b939b/modules/control-center-web/src/main/js/agents/agent-server.js
----------------------------------------------------------------------
diff --git a/modules/control-center-web/src/main/js/agents/agent-server.js b/modules/control-center-web/src/main/js/agents/agent-server.js
index ae5a87c..51303ba 100644
--- a/modules/control-center-web/src/main/js/agents/agent-server.js
+++ b/modules/control-center-web/src/main/js/agents/agent-server.js
@@ -58,34 +58,7 @@ AgentServer.prototype.runCommand = function(cmd, callback) {
         headers = {'JSONObject': 'application/json'};
     }
 
-    this._client.executeRest("ignite", params, this._demo, method, headers, body, function(error, code, message) {
-        if (error) {
-            callback(error);
-
-            return
-        }
-
-        if (code !== 200) {
-            if (code === 401)
-                callback.call(null, "Authentication failed. Status code: 401.");
-            else
-                callback.call(null, (message ? message : "Request failed.") +  " Status code: " + code);
-
-            return;
-        }
-
-        try {
-            var igniteResponse = JSON.parse(message);
-
-            if (igniteResponse.successStatus)
-                callback.call(null, igniteResponse.error, null);
-            else
-                callback.call(null, null, igniteResponse.response);
-        }
-        catch (e) {
-            callback.call(null, e, null);
-        }
-    });
+    this._client.executeRest("ignite", params, this._demo, method, headers, body, callback);
 };
 
 exports.AgentServer = AgentServer;

http://git-wip-us.apache.org/repos/asf/ignite/blob/873b939b/modules/control-center-web/src/main/js/controllers/common-module.js
----------------------------------------------------------------------
diff --git a/modules/control-center-web/src/main/js/controllers/common-module.js b/modules/control-center-web/src/main/js/controllers/common-module.js
index 57ced0b..f980c53 100644
--- a/modules/control-center-web/src/main/js/controllers/common-module.js
+++ b/modules/control-center-web/src/main/js/controllers/common-module.js
@@ -2069,8 +2069,11 @@ consoleModule.service('$agentDownload', [
         function _handleException (errMsg, status, timedOut) {
             if (_modal.skipSingleError)
                 _modal.skipSingleError = false;
-            else if (!_modal.$isShown)
+            else if (!_modal.$isShown) {
+                $loading.finish('loading');
+
                 _modal.$promise.then(_modal.show);
+            }
 
             scope.nodeFailedConnection = status === 404 || timedOut;
 

http://git-wip-us.apache.org/repos/asf/ignite/blob/873b939b/modules/control-center-web/src/main/js/routes/agent.js
----------------------------------------------------------------------
diff --git a/modules/control-center-web/src/main/js/routes/agent.js b/modules/control-center-web/src/main/js/routes/agent.js
index 02d5c7a..d4e67bc 100644
--- a/modules/control-center-web/src/main/js/routes/agent.js
+++ b/modules/control-center-web/src/main/js/routes/agent.js
@@ -23,22 +23,30 @@ var apacheIgnite = require('apache-ignite');
 var SqlFieldsQuery = apacheIgnite.SqlFieldsQuery;
 var ScanQuery = apacheIgnite.ScanQuery;
 
-function _client(req, res) {
-    var client = agentManager.getAgentManager().findClient(req.currentUserId());
+function _client(userId) {
+    return new Promise(function(resolve, reject) {
+        var client = agentManager.getAgentManager().findClient(userId);
 
-    if (!client) {
-        res.status(503).send('Connection to Ignite Web Agent is not established');
+        if (client)
+            return resolve(client);
 
-        return null;
-    }
-
-    return client;
+        reject({code: 503, message: 'Connection to Ignite Web Agent is not established'});
+    });
 }
 
 function _compact(className) {
     return className.replace('java.lang.', '').replace('java.util.', '').replace('java.sql.', '');
 }
 
+function _handleException(res) {
+    return function (error) {
+        if (_.isObject(error))
+            return res.status(error.code).send(error.message);
+
+        return res.status(500).send(error);
+    }
+}
+
 /* Get grid topology. */
 router.get('/download/zip', function (req, res) {
     var fs = require('fs');
@@ -78,124 +86,95 @@ router.get('/download/zip', function (req, res) {
 
 /* Get grid topology. */
 router.post('/topology', function (req, res) {
-    var client = _client(req, res);
-
-    if (client) {
-        client.ignite(req.body.demo).cluster(req.body.attr, req.body.mtr).then(
-            function (clusters) {
-                res.json(clusters);
-            },
-            function (err) {
-            var mStatusCode = /.*Status code:\s+(\d+)(?:\s|$)/g.exec(err);
-
-            res.status(mStatusCode != null && mStatusCode[1] ? mStatusCode[1] : 500).send(err);
-        });
-    }
+    _client(req.currentUserId())
+        .then((client) => client.ignite(req.body.demo).cluster(req.body.attr, req.body.mtr))
+        .then((clusters) => res.json(clusters))
+        .catch(_handleException(res));
 });
 
 /* Execute query. */
 router.post('/query', function (req, res) {
-    var client = _client(req, res);
-
-    if (client) {
-        // Create sql query.
-        var qry = new SqlFieldsQuery(req.body.query);
-
-        // Set page size for query.
-        qry.setPageSize(req.body.pageSize);
-
-        // Get query cursor.
-        client.ignite(req.body.demo).cache(req.body.cacheName).query(qry).nextPage().then(function (cursor) {
-            res.json({meta: cursor.fieldsMetadata(), rows: cursor.page(), queryId: cursor.queryId()});
-        }, function (err) {
-            res.status(500).send(err);
-        });
-    }
+    _client(req.currentUserId())
+        .then((client) => {
+            // Create sql query.
+            var qry = new SqlFieldsQuery(req.body.query);
+
+            // Set page size for query.
+            qry.setPageSize(req.body.pageSize);
+
+            return client.ignite(req.body.demo).cache(req.body.cacheName).query(qry).nextPage()
+        })
+        .then((cursor) => res.json({meta: cursor.fieldsMetadata(), rows: cursor.page(), queryId: cursor.queryId()}))
+        .catch(_handleException(res));
 });
 
 /* Execute query getAll. */
 router.post('/query/getAll', function (req, res) {
-    var client = _client(req, res);
-
-    if (client) {
-        // Create sql query.
-        var qry = new SqlFieldsQuery(req.body.query);
-
-        // Set page size for query.
-        qry.setPageSize(1024);
-
-        // Get query cursor.
-        var cursor = client.ignite(req.body.demo).cache(req.body.cacheName).query(qry);
-
-        cursor.getAll().then(function (rows) {
-            res.json({meta: cursor.fieldsMetadata(), rows: rows});
-        }, function (err) {
-            res.status(500).send(err);
-        });
-    }
+    _client(req.currentUserId())
+        .then((client) => {
+            // Create sql query.
+            var qry = new SqlFieldsQuery(req.body.query);
+
+            // Set page size for query.
+            qry.setPageSize(1024);
+
+            // Get query cursor.
+            return client.ignite(req.body.demo).cache(req.body.cacheName).query(qry).getAll();
+        })
+        .then((rows) => res.json({meta: cursor.fieldsMetadata(), rows: rows}))
+        .catch(_handleException(res));
 });
 
 /* Execute query. */
 router.post('/scan', function (req, res) {
-    var client = _client(req, res);
-
-    if (client) {
-        // Create sql query.
-        var qry = new ScanQuery();
-
-        // Set page size for query.
-        qry.setPageSize(req.body.pageSize);
-
-        // Get query cursor.
-        client.ignite(req.body.demo).cache(req.body.cacheName).query(qry).nextPage().then(function (cursor) {
-            res.json({meta: cursor.fieldsMetadata(), rows: cursor.page(), queryId: cursor.queryId()});
-        }, function (err) {
-            res.status(500).send(err);
-        });
-    }
+    _client(req.currentUserId())
+        .then((client) => {
+            // Create sql query.
+            var qry = new ScanQuery();
+
+            // Set page size for query.
+            qry.setPageSize(req.body.pageSize);
+
+            // Get query cursor.
+            return client.ignite(req.body.demo).cache(req.body.cacheName).query(qry).nextPage()
+        })
+        .then((cursor) => res.json({meta: cursor.fieldsMetadata(), rows: cursor.page(), queryId: cursor.queryId()}))
+        .catch(_handleException(res));
 });
 
 /* Get next query page. */
 router.post('/query/fetch', function (req, res) {
-    var client = _client(req, res);
-
-    if (client) {
-        var cache = client.ignite(req.body.demo).cache(req.body.cacheName);
-
-        var cmd = cache._createCommand('qryfetch').addParam('qryId', req.body.queryId).
-            addParam('pageSize', req.body.pageSize);
-
-        cache.__createPromise(cmd).then(function (page) {
-            res.json({rows: page['items'], last: page === null || page['last']});
-        }, function (err) {
-            res.status(500).send(err);
-        });
-    }
+    _client(req.currentUserId())
+        .then((client) => {
+            var cache = client.ignite(req.body.demo).cache(req.body.cacheName);
+
+            var cmd = cache._createCommand('qryfetch')
+                .addParam('qryId', req.body.queryId)
+                .addParam('pageSize', req.body.pageSize);
+
+            return cache.__createPromise(cmd);
+        })
+        .then((page) => res.json({rows: page['items'], last: page === null || page['last']}))
+        .catch(_handleException(res));
 });
 
 /* Close query cursor by id. */
 router.post('/query/close', function (req, res) {
-    var client = _client(req, res);
-
-    if (client) {
-        var cache = client.ignite(req.body.demo).cache(req.body.cacheName);
-
-        var cmd = cache._createCommand('qrycls').addParam('qryId', req.body.queryId);
-
-        cache.__createPromise(cmd).then(function () {
-            res.sendStatus(200);
-        }, function (err) {
-            res.status(500).send(err);
-        });
-    }
+    _client(req.currentUserId())
+        .then((client) => {
+            var cache = client.ignite(req.body.demo).cache(req.body.cacheName);
+
+            return cache.__createPromise(cache._createCommand('qrycls').addParam('qryId', req.body.queryId))
+        })
+        .then(() => res.sendStatus(200))
+        .catch(_handleException(res));
 });
 
 /* Get metadata for cache. */
 router.post('/cache/metadata', function (req, res) {
-    var client = _client(req, res);
-
-    if (client) {
-        client.ignite(req.body.demo).cache(req.body.cacheName).metadata().then(function (caches) {
+    _client(req.currentUserId())
+        .then((client) => client.ignite(req.body.demo).cache(req.body.cacheName).metadata())
+        .then((caches) => {
             var types = [];
 
             for (var meta of caches) {
@@ -256,64 +235,51 @@ router.post('/cache/metadata', function (req, res) {
             }
 
             res.json(types);
-        }, function (err) {
-            res.status(500).send(err);
-        });
-    }
+        })
+        .catch(_handleException(res));
 });
 
 /* Ping client. */
 router.post('/ping', function (req, res) {
-    if (_client(req, res) != null)
-        res.sendStatus(200);
+    _client(req.currentUserId())
+        .then(() => res.sendStatus(200))
+        .catch(_handleException(res));
 });
 
 /* Get JDBC drivers list. */
 router.post('/drivers', function (req, res) {
-    var client = _client(req, res);
-
-    if (client) {
-        client.availableDrivers(function (err, drivers) {
-            if (err)
-                return res.status(500).send(err);
-
-            res.json(drivers);
-        });
-    }
+    _client(req.currentUserId())
+        .then((client) => client.availableDrivers())
+        .then((arr) => res.json(arr))
+        .catch(_handleException(res));
 });
 
 /** Get database schemas. */
 router.post('/schemas', function (req, res) {
-    var client = _client(req, res);
+    _client(req.currentUserId())
+        .then((client) => {
+            var args = req.body;
 
-    if (client) {
-        var params = req.body;
+            args.jdbcInfo = {user: args.user, password: args.password};
 
-        client.metadataSchemas(params.jdbcDriverJar, params.jdbcDriverClass, params.jdbcUrl, {user: params.user, password: params.password}, function (err, meta) {
-            if (err)
-                return res.status(500).send(err);
-
-            res.json(meta);
-        });
-    }
+            return client.metadataSchemas(args.jdbcDriverJar, args.jdbcDriverClass, args.jdbcUrl, args.jdbcInfo)
+        })
+        .then((arr) => res.json(arr))
+        .catch(_handleException(res));
 });
 
 /** Get database tables. */
 router.post('/tables', function (req, res) {
-    var client = _client(req, res);
+    _client(req.currentUserId())
+        .then((client) => {
+            var args = req.body;
 
-    if (client) {
-        var params = req.body;
+            args.jdbcInfo = {user: args.user, password: args.password};
 
-        client.metadataTables(params.jdbcDriverJar, params.jdbcDriverClass, params.jdbcUrl,
-            {user: params.user, password: params.password}, params.schemas, params.tablesOnly,
-            function (err, meta) {
-                if (err)
-                    return res.status(500).send(err);
-
-                res.json(meta);
-            });
-    }
+            return client.metadataTables(args.jdbcDriverJar, args.jdbcDriverClass, args.jdbcUrl, args.jdbcInfo, args.schemas, args.tablesOnly)
+        })
+        .then((arr) => res.json(arr))
+        .catch(_handleException(res));
 });
 
 module.exports = router;