1 // generated by build.sh for running on Node.js
  2 if (typeof jQuery === 'undefined') { // jQuery is defined in server code env.
  3     if (typeof process === 'object' && typeof process.versions === 'object') {
  4         var XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest;
  5     }
  6 }
  7 ;(function () {
  8 var ctor = (function() {  // generated by build.sh for running on Node.js
  9 // Added to SDK by build script.
 10 // Object.keys() is defined in Javascript 1.8.5
 11 // This code will be used when the environment doen't support Object.keys()
 12 // For details refer to:
 13 // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
 14 if (!Object.keys) {
 15   Object.keys = (function () {
 16     var hasOwnProperty = Object.prototype.hasOwnProperty,
 17         hasDontEnumBug = !({toString: null}).propertyIsEnumerable('toString'),
 18         dontEnums = [
 19           'toString',
 20           'toLocaleString',
 21           'valueOf',
 22           'hasOwnProperty',
 23           'isPrototypeOf',
 24           'propertyIsEnumerable',
 25           'constructor'
 26         ],
 27         dontEnumsLength = dontEnums.length
 28 
 29     return function (obj) {
 30       if (typeof obj !== 'object' && typeof obj !== 'function' || obj === null) throw new TypeError('Object.keys called on non-object')
 31 
 32       var result = []
 33 
 34       for (var prop in obj) {
 35         if (hasOwnProperty.call(obj, prop)) result.push(prop)
 36       }
 37 
 38       if (hasDontEnumBug) {
 39         for (var i=0; i < dontEnumsLength; i++) {
 40           if (hasOwnProperty.call(obj, dontEnums[i])) result.push(dontEnums[i])
 41         }
 42       }
 43       return result
 44     }
 45   })()
 46 };
 47 /**@license MIT-promiscuous library-©2013 Ruben Verborgh*/
 48 if(typeof Promise === 'undefined') {
 49   /**@license MIT-promiscuous-©Ruben Verborgh*/
 50   !function(n,t){function c(n,t){return(typeof t)[0]==n}function u(i,o){return o=function f(e,h,l,a,s,p){function y(n){return function(t){s&&(s=0,f(c,n,t))}}if(a=f.q,e!=c)return u(function(n,t){a.push({p:this,r:n,j:t,1:e,0:h})});if(l&&c(n,l)|c(t,l))try{s=l.then}catch(j){h=0,l=j}if(c(n,s))try{s.call(l,y(1),h=y(0))}catch(j){h(j)}else for(o=function(t,o){return c(n,t=h?t:o)?u(function(n,c){r(this,n,c,l,t)}):i},p=0;p<a.length;)s=a[p++],c(n,e=s[h])?r(s.p,s.r,s.j,l,e):(h?s.r:s.j)(l)},o.q=[],i.call(i={then:function(n,t){return o(n,t)},"catch":function(n){return o(0,n)}},function(n){o(c,1,n)},function(n){o(c,0,n)}),i}function r(u,r,i,o,f){setTimeout(function(){try{o=f(o),f=o&&c(t,o)|c(n,o)&&o.then,c(n,f)?o==u?i(TypeError()):f.call(o,r,i):r(o)}catch(e){i(e)}})}function i(n){return u(function(t){t(n)})}Promise=u,u.resolve=i,u.reject=function(n){return u(function(t,c){c(n)})},u.all=function(n){return u(function(t,c,u,r){r=[],u=n.length||t(r),n.map(function(n,o){i(n).then(function(n){r[o]=n,--u||t(r)},c)})})}}("f","o");
 51 }
 52 // Generated by CoffeeScript 1.8.0
 53 var KiiJQXHRWrapper, KiiJQueryHttpRequest, KiiRequest, KiiTiXHRWrapper, KiiTitaniumHttpRequest, KiiUtilities, KiiXHRWrapper, KiiXHRWrapperFactory, KiiXMLHttpRequest, root, _Kii, _KiiSocialConnect,
 54   __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
 55   __hasProp = {}.hasOwnProperty,
 56   __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
 57 
 58 root = ((typeof exports) !== "undefined") && (exports !== null) ? new Object() : this;
 59 
 60 root.KiiSocialNetworkName = {
 61   FACEBOOK: 1,
 62   TWITTER: 2,
 63   QQ: 3,
 64   GOOGLEPLUS: 4,
 65   RENREN: 5
 66 };
 67 
 68 root.KiiSite = {
 69   US: "https://api.kii.com/api",
 70   JP: "https://api-jp.kii.com/api",
 71   SG: "https://api-sg.kii.com/api",
 72   EU: "https://api-eu.kii.com/api"
 73 };
 74 
 75 root.KiiServerCodeEnvironmentVersion = {
 76   V0: "0",
 77   V6: "6"
 78 };
 79 
 80 
 81 /**
 82     @class The main SDK class
 83     @exports root.Kii as Kii
 84 
 85     This class must be initialized before any Kii SDK functions are performed. This class also allows the application to make some high-level user calls and access some application-wide data at any time using static methods.
 86  */
 87 
 88 root.Kii = (function() {
 89   var _additionalHeaders, _instance;
 90 
 91   function Kii() {}
 92 
 93   _instance = null;
 94 
 95   _additionalHeaders = null;
 96 
 97 
 98   /**
 99       Kii SDK Build Number
100       @returns {String} current build number of the SDK
101    */
102 
103   Kii.getBuildNumber = function() {
104     return "1";
105   };
106 
107 
108   /**
109       Kii SDK Version Number
110       @returns {String} current version number of the SDK
111    */
112 
113   Kii.getSDKVersion = function() {
114     return "2.4.19";
115   };
116 
117   Kii.getBaseURL = function() {
118     return _instance._baseURL;
119   };
120 
121 
122   /**
123       Retrieve the current app ID
124       @returns {String} The current app ID
125    */
126 
127   Kii.getAppID = function() {
128     return _instance._appID;
129   };
130 
131   Kii.getAdditionalHeaders = function() {
132     return _additionalHeaders;
133   };
134 
135   Kii.setAdditionalHeaders = function(additionalHeaders) {
136     return _additionalHeaders = additionalHeaders;
137   };
138 
139 
140   /**
141       Retrieve the current app key
142       @returns {String} The current app key
143    */
144 
145   Kii.getAppKey = function() {
146     return _instance._appKey;
147   };
148 
149   Kii.isLogging = function() {
150     return _instance._logging;
151   };
152 
153   Kii.setLogging = function(logging) {
154     _instance._logging = logging;
155     root.Kii.logger("Setting logging: " + logging);
156     return root.Kii.logger("Base URL: " + _instance._baseURL);
157   };
158 
159 
160   /** Set the access token lifetime in seconds.
161   
162   If you don't call this method or call it with 0, token won't be expired.
163   Call this method if you like the access token to be expired
164   after a certain period. Once called, token retrieved
165   by each future authentication will have the specified lifetime.
166   Note that, it will not update the lifetime of token received prior
167   calling this method. Once expired, you have to login again to renew the token.
168   @param expiresIn The life time of access token in seconds.
169   @throws {InvalidArgumentException} If specified expiresIn is negative.
170   @throws {IllegalStateException} If Kii has not been initialized
171   @example
172   Kii.setAccessTokenExpiration(3600);
173    */
174 
175   Kii.setAccessTokenExpiration = function(expiresIn) {
176     if (!_instance) {
177       throw new root.IllegalStateException('Kii is not initialized');
178     }
179     if (isNaN(parseInt(expiresIn, 10))) {
180       throw new root.InvalidArgumentException('expiresIn should be a number');
181     }
182     if (expiresIn < 0) {
183       throw new root.InvalidArgumentException('expiresIn should not negative number');
184     }
185     if (_instance) {
186       return _instance._expiresIn = expiresIn;
187     }
188   };
189 
190 
191   /** Returns access token lifetime in seconds.
192   
193   If access token lifetime has not set explicitly by {@link Kii.setAccessTokenExpiration(expiresIn)}, returns 0.
194   @return access token lifetime in seconds.
195   @throws {IllegalStateException} If Kii has not been initialized
196    */
197 
198   Kii.getAccessTokenExpiration = function() {
199     if (!_instance) {
200       throw new root.IllegalStateException('Kii is not initialized');
201     }
202     return _instance._expiresIn;
203   };
204 
205 
206   /** Initialize the Kii SDK with a specific URL
207   
208   Should be the first Kii SDK action your application makes.
209   @param String appID The application ID found in your Kii developer console
210   @param String appKey The application key found in your Kii developer console
211   @param KiiSite site Can be one of the constants KiiSite.US, KiiSite.JP, KiiSite.SG depending on your location.
212   @example
213   Kii.initializeWithSite("my-app-id", "my-app-key", KiiSite.JP);
214    */
215 
216   Kii.initializeWithSite = function(appID, appKey, site) {
217     _instance = new _Kii(appID, appKey, site);
218     return root.Kii.logger("Initialized " + appID + ", " + appKey + ", " + site);
219   };
220 
221 
222   /** Initialize the Kii SDK
223   
224   Should be the first Kii SDK action your application makes.
225   @param String appID The application ID found in your Kii developer console
226   @param String appKey The application key found in your Kii developer console
227   @example
228   Kii.initialize("my-app-id", "my-app-key");
229    */
230 
231   Kii.initialize = function(appID, appKey) {
232     return root.Kii.initializeWithSite(appID, appKey, root.KiiSite.US);
233   };
234 
235   Kii.logger = function(message) {
236     if (_instance._logging) {
237       return console.log(message);
238     }
239   };
240 
241 
242   /**
243       Creates a reference to a bucket for this app
244   
245       <br><br>The bucket will be created/accessed within this app's scope
246       @param String bucketName The name of the bucket the app should create/access
247       @returns {KiiBucket} A working KiiBucket object
248       @example
249       var bucket = Kii.bucketWithName("myBucket");
250    */
251 
252   Kii.bucketWithName = function(bucketName) {
253     var bucket;
254     bucket = new root.KiiBucket(bucketName, null);
255     return bucket;
256   };
257 
258 
259   /**
260       Creates a reference to a encrypted bucket for this app
261   
262       <br><br>The bucket will be created/accessed within this app's scope
263       @param String bucketName The name of the bucket the app should create/access
264       @returns {KiiEncryptedBucket} A working KiiEncryptedBucket object
265       @example
266       var bucket = Kii.encryptedBucketWithName("myBucket");
267    */
268 
269   Kii.encryptedBucketWithName = function(bucketName) {
270     var bucket;
271     bucket = new root.KiiEncryptedBucket(bucketName, null);
272     return bucket;
273   };
274 
275 
276   /**
277       Creates a reference to a group with the given name
278   
279       @param {String} groupName An application-specific group name
280       @returns {KiiGroup} A new KiiGroup reference
281       @example
282       var group = new Kii.groupWithName("myGroup");
283    */
284 
285   Kii.groupWithName = function(groupName) {
286     return new root.Kii.groupWithNameAndMembers(groupName, null);
287   };
288 
289 
290   /**
291       Creates a reference to a group with the given name and a list of default members
292   
293       @param {String} groupName An application-specific group name
294       @param {Array} members An array of KiiUser objects to add to the group
295       @returns {KiiGroup} A new KiiGroup reference
296       @example
297       var group = new KiiGroup.groupWithName("myGroup", members);
298    */
299 
300   Kii.groupWithNameAndMembers = function(groupName, members) {
301     return new root.KiiGroup.groupWithNameAndMembers(groupName, members);
302   };
303 
304   Kii.logOut = function() {
305     _instance._currentUser = null;
306     return root.KiiSocialConnect.logOutAll();
307   };
308 
309   Kii.loggedIn = function() {
310     return _instance._currentUser != null;
311   };
312 
313   Kii.getCurrentUser = function() {
314     var user;
315     if (_instance._currentUser != null) {
316       user = KiiUtilities._clone(_instance._currentUser);
317       return user;
318     } else {
319       return null;
320     }
321   };
322 
323   Kii.setCurrentUser = function(user) {
324     return _instance._currentUser = KiiUtilities._clone(user);
325   };
326 
327 
328   /** Authenticate as app admin.
329   <br><br>
330   <b>This api call must not placed on code which can be accessed by browser.
331   This api is intended to be used by server side code like Node.js.
332   If you use this api in code accessible by browser, your application id and application secret could be stolen.
333   Attacker will be act as appadmin and all the data in your application will be suffered.
334   </b>
335   @param {String} clientId assigned to your application.
336   @param {String} clientSecret assigned to your application.
337   @param {Object} [callbacks] The callback methods called when authentication succeeded/failed.
338   @param {Method} callbacks.success The callback method called when authentication succeeded.
339   @param {Method} callbacks.failure The callback method called when authentication failed.
340   @return {Promise} return promise object.
341       <ul>
342         <li>fulfill callback function: function(adminContext). adminContext is a KiiAppAdminContext instance.</li>
343         <li>reject callback function: function(error). error is an Error instance.
344           <ul>
345             <li>error.message</li>
346           </ul>
347         </li>
348       </ul>
349   @example
350   // example to use callbacks directly
351   Kii.authenticateAsAppAdmin("your client id", "your client secret", {
352       success: function(adminContext) {
353           // adminContext : KiiAppAdminContext instance
354           // Operate entities with adminContext.
355       },
356       failure: function(error, statusCode) {
357           // Authentication failed.
358       }
359   );
360   
361   // example to use Promise
362   Kii.authenticateAsAppAdmin("your client id", "your client secret").then(
363       function(adminContext) { // fulfill callback function
364           // adminContext : KiiAppAdminContext instance
365           // Operate entities with adminContext.
366   
367       },
368       function(error) { // reject callback function
369           // Authentication failed.
370           var errorString = error.message;
371       }
372   );
373    */
374 
375   Kii.authenticateAsAppAdmin = function(clientId, clientSecret, callbacks) {
376     return new Promise((function(_this) {
377       return function(resolve, reject) {
378         var authenticateAsAppAdminCallbacks;
379         authenticateAsAppAdminCallbacks = {
380           success: function() {
381             if (callbacks != null) {
382               callbacks.success.apply(callbacks, arguments);
383             }
384             return resolve(arguments[0]);
385           },
386           failure: function() {
387             if (callbacks != null) {
388               callbacks.failure.apply(callbacks, arguments);
389             }
390             return reject(KiiUtilities._Error(arguments[0]));
391           }
392         };
393         return _this._authenticateAsAppAdminUsingCallbacks(clientId, clientSecret, authenticateAsAppAdminCallbacks);
394       };
395     })(this));
396   };
397 
398   Kii._authenticateAsAppAdminUsingCallbacks = function(clientId, clientSecret, callbacks) {
399     var authCallbacks, request;
400     request = new KiiRequest("/oauth2/token", false);
401     request.setAnonymous(true);
402     request.setMethod("POST");
403     request.setData({
404       'client_id': clientId,
405       'client_secret': clientSecret
406     });
407     authCallbacks = {
408       success: (function(_this) {
409         return function(data) {
410           var admin, id, token;
411           token = data.access_token;
412           id = data.id;
413           root.Kii.logger("token: " + token);
414           root.Kii.logger("id: " + id);
415           admin = new root.KiiAppAdminContext({
416             token: token,
417             id: id
418           });
419           if (callbacks != null) {
420             return callbacks.success(admin);
421           }
422         };
423       })(this),
424       failure: (function(_this) {
425         return function(error, statusCode) {
426           root.Kii.logger("error: " + error);
427           root.Kii.logger("statusCode: " + statusCode);
428           if (callbacks != null) {
429             return callbacks.failure(error, statusCode);
430           }
431         };
432       })(this)
433     };
434     return request.execute(authCallbacks, false);
435   };
436 
437   Kii.authenticateAsAdminWithToken = function(token) {
438     return new root.KiiAppAdminContext({
439       token: token
440     });
441   };
442 
443 
444   /**
445   Instantiate KiiServerCodeEntry.
446   @param {String} entryName Name of the entry.
447   @param {String} [version] Version of the entry.
448   @param {KiiServerCodeEnvironmentVersion} [environmentVersion] Version of the Node.js. Currently, supported versions are 0 and 6.
449   @returns {KiiServerCodeEntry} KiiServerCodeEntry instance.
450   @throws {InvalidArgumentException} Thrown in the following cases: <br>
451   <li>entryName or version is not type of string </li>
452   <li>entryName or version is empty string </li>
453   <li>entryName is invalid string. Valid entryName pattern is "[a-zA-Z][_a-zA-Z0-9]*$".</li>
454   
455   @example
456       var entry = Kii.serverCodeEntryWithVersion("main", "gulsdf6ful8jvf8uq6fe7vjy6", KiiServerCodeEnvironmentVersion.V0);
457    */
458 
459   Kii.serverCodeEntry = function(entryName, version, environmentVersion) {
460     if (!KiiUtilities._validateServerCodeEntryName(entryName)) {
461       throw new root.InvalidArgumentException('entryName is invalid');
462     }
463     if (version && !KiiUtilities._validateServerCodeEnryVersion(version)) {
464       throw new root.InvalidArgumentException('version is invalid');
465     }
466     return new root.KiiServerCodeEntry(entryName, version, environmentVersion);
467   };
468 
469 
470   /**
471   @deprecated Use {@link Kii.serverCodeEntry} instead. Instantiate serverCodeEntryWithVersion with specified entry name and version.
472   @param {String} entryName Name of the entry.
473   @param {String} version Version of the entry.
474   @returns {KiiServerCodeEntry} KiiServerCodeEntry instance.
475   @throws {InvalidArgumentException} Thrown in the following cases: <br>
476   <li>entryName or version is not type of string </li>
477   <li>entryName or version is empty string </li>
478   <li>entryName is invalid string. Valid entryName pattern is "[a-zA-Z][_a-zA-Z0-9]*$".</li>
479   
480   @example
481       var entry = Kii.serverCodeEntryWithVersion("main", "gulsdf6ful8jvf8uq6fe7vjy6");
482    */
483 
484   Kii.serverCodeEntryWithVersion = function(entryName, version) {
485     if (!KiiUtilities._validateServerCodeEntryName(entryName)) {
486       throw new root.InvalidArgumentException('entryName is invalid');
487     }
488     if (!KiiUtilities._validateServerCodeEnryVersion(version)) {
489       throw new root.InvalidArgumentException('version is invalid');
490     }
491     return new root.KiiServerCodeEntry(entryName, version);
492   };
493 
494   Kii._setHttpRequestType = function(requestType) {
495     root.Kii.logger("Set http request as " + requestType);
496     return _instance._httpRequestType = requestType;
497   };
498 
499   Kii._getHttpRequestType = function() {
500     return _instance._httpRequestType;
501   };
502 
503   Kii._getKiiUtilities = function() {
504     return KiiUtilities;
505   };
506 
507 
508   /**
509   Instantiate topic belongs to application.
510   @param {String} topicName name of the topic. Must be a not empty string.
511   @return {KiiTopic} topic instance.
512    */
513 
514   Kii.topicWithName = function(topicName) {
515     var puri;
516     if (typeof topicName !== "string" || topicName === "") {
517       throw new root.InvalidArgumentException('topicName should not null or empty');
518     }
519     puri = "" + (root.Kii.getBaseURL()) + "/apps/" + (root.Kii.getAppID());
520     return new root.KiiTopic(puri, topicName);
521   };
522 
523 
524   /** Gets a list of topics in app scope
525   @param {Object} [callbacks] An object with callback methods defined
526   @param {Method} callbacks.success The callback method to call on a successful list request
527   @param {Method} callbacks.failure The callback method to call on a failed list request
528   @param {String} [paginationKey] You can specify the pagination key with the nextPaginationKey passed by callbacks.success or fullfill callback of promise. If empty string or no string object is provided, this API regards no paginationKey specified.
529   @return {Promise} return promise object.
530       <ul>
531         <li>fulfill callback function: function(params). params is Array instance.
532           <ul>
533             <li>params[0] is array of KiiTopic instances.</li>
534             <li>params[1] is string of nextPaginationKey.</li>
535           </ul>
536         </li>
537         <li>reject callback function: function(error). error is an Error instance.
538           <ul>
539             <li>error.message</li>
540           </ul>
541         </li>
542       </ul>
543   @example
544   // example to use callbacks directly
545   Kii.listTopics({
546       success: function(topicList, nextPaginationKey) {
547           // do something with the result
548           for(var i=0; i<topicList.length; i++){
549               var topic = topicList[i];
550           }
551           if (nextPaginationKey != null) {
552               Kii.listTopics({
553                   success: function(topicList, nextPaginationKey) {...},
554                   failure: function(anErrorString) {...}
555               }, nextPaginationKey);
556           }
557       },
558       failure: function(anErrorString) {
559           // do something with the error response
560       }
561   });
562   
563   // example to use promise
564   Kii.listTopics().then(
565       function(params) {
566           var topicList = params[0];
567           var nextPaginationKey = params[1];
568           // do something with the result
569           for(var i=0; i<topicList.length; i++){
570               var topic = topicList[i];
571           }
572           if (nextPaginationKey != null) {
573               Kii.listTopics(null, nextPaginationKey).then(
574                   function(params) {...},
575                   function(error) {...}
576               );
577           }
578       },
579       function(error) {
580           // do something with the error response
581       }
582   );
583    */
584 
585   Kii.listTopics = function(callbacks, paginationKey) {
586     return Kii._listTopics(callbacks, paginationKey);
587   };
588 
589   Kii._listTopics = function(callbacks, paginationKey, context) {
590     return new Promise(function(resolve, reject) {
591       var listTopicsCallbacks;
592       listTopicsCallbacks = {
593         success: function() {
594           if (callbacks != null) {
595             callbacks.success.apply(callbacks, arguments);
596           }
597           return resolve(arguments);
598         },
599         failure: function() {
600           if (callbacks != null) {
601             callbacks.failure.apply(callbacks, arguments);
602           }
603           return reject(arguments[0]);
604         }
605       };
606       return Kii._listTopicsUsingCallbacks(listTopicsCallbacks, paginationKey, context);
607     });
608   };
609 
610   Kii._listTopicsUsingCallbacks = function(callbacks, paginationKey, context) {
611     var listCallbacks, uri, wrapper;
612     uri = "" + (root.Kii.getBaseURL()) + "/apps/" + (root.Kii.getAppID()) + "/topics";
613     if (typeof paginationKey === "string" && paginationKey !== "") {
614       uri = uri + "?paginationKey=" + encodeURIComponent(paginationKey);
615     }
616     wrapper = KiiXHRWrapperFactory.createXHRWrapper('GET', uri);
617     wrapper.setKiiHeaders();
618     if (context != null) {
619       wrapper.setAuthToken(context._getToken());
620     } else {
621       wrapper.setCurrentUserToken();
622     }
623     listCallbacks = {
624       success: function() {
625         var json, topic, topics, _i, _len, _ref;
626         json = JSON.parse(wrapper.xhr.responseText);
627         topics = [];
628         _ref = json.topics;
629         for (_i = 0, _len = _ref.length; _i < _len; _i++) {
630           topic = _ref[_i];
631           topics.push(Kii.topicWithName(topic.topicID));
632         }
633         return callbacks != null ? callbacks.success(topics, (json.paginationKey === void 0 ? null : json.paginationKey)) : void 0;
634       },
635       failure: function() {
636         var errObj, errString;
637         errString = wrapper.getErrorString("list topics");
638         errObj = KiiUtilities._Error(errString, Kii);
639         return callbacks != null ? callbacks.failure(errObj) : void 0;
640       }
641     };
642     return wrapper.send(listCallbacks);
643   };
644 
645 
646   /** Authenticate as Thing.
647   <br><br>
648   <b>This api is intended to be used in a Thing device, where the user
649   credentials or app admin context is not configured. This Thing must be
650   already registered in Kii Cloud.
651   </b>
652   @param {String} vendorThingID vendorThingID of a registered Thing.
653   @param {String} password password for the registered Thing.
654   @param {Object} [callbacks] The callback methods called when authentication succeeded/failed.
655   @param {Method} callbacks.success The callback method called when authentication succeeded.
656   @param {Method} callbacks.failure The callback method called when authentication failed.
657   @return {Promise} return promise object.
658       <ul>
659         <li>fulfill callback function: function(thingAuthContext). thingAuthContext is a KiiThingContext instance.</li>
660         <li>reject callback function: function(error). error is an Error instance.
661           <ul>
662             <li>error.message</li>
663           </ul>
664         </li>
665       </ul>
666   @example
667   // example to use callbacks directly
668   Kii.authenticateAsThing("vendor thing id", "password of this thing", {
669       success: function(thingAuthContext) {
670           // thingAuthContext : KiiThingContext instance
671           // Operate entities with thingAuthContext.
672       },
673       failure: function(error) {
674           // Authentication failed.
675       }
676   );
677   
678   // example to use Promise
679   Kii.authenticateAsThing("vendor thing id", "password of this thing").then(
680       function(thingAuthContext) { // fulfill callback function
681           // thingAuthContext : KiiThingContext instance
682           // Operate entities with thingAuthContext.
683   
684       },
685       function(error) { // reject callback function
686           // Authentication failed.
687           var errorString = error.message;
688       }
689   );
690    */
691 
692   Kii.authenticateAsThing = function(vendorThingID, password, callbacks) {
693     return new Promise((function(_this) {
694       return function(resolve, reject) {
695         var errObj, sendCallbacks, wrapper;
696         if (!KiiUtilities._isNonEmptyString(vendorThingID) || !KiiUtilities._isNonEmptyString(password)) {
697           errObj = KiiUtilities._Error("vendorThingID or password is invalid");
698           if (callbacks != null) {
699             callbacks.failure(errObj);
700           }
701           reject(errObj);
702           return;
703         }
704         wrapper = KiiXHRWrapperFactory.createXHRWrapper('POST', "" + (root.Kii.getBaseURL()) + "/oauth2/token");
705         wrapper.setKiiHeaders();
706         wrapper.setContentType("application/vnd.kii.OauthTokenRequest+json");
707         sendCallbacks = {
708           success: function() {
709             var accessToken, errString, respJson, thingAuthContext, thingID;
710             respJson = JSON.parse(decodeURIComponent(wrapper.xhr.responseText));
711             thingID = respJson.id;
712             accessToken = respJson.access_token;
713             if ((thingID != null) && (accessToken != null)) {
714               thingAuthContext = new root.KiiThingContext({
715                 thingId: thingID,
716                 token: accessToken,
717                 vendorThingID: vendorThingID
718               });
719               if (callbacks != null) {
720                 callbacks.success(thingAuthContext);
721               }
722               return resolve(thingAuthContext);
723             } else {
724               errString = wrapper.getErrorString("invalid format response when authenticate thing ");
725               errObj = KiiUtilities._Error(errString);
726               if (callbacks != null) {
727                 callbacks.failure(errObj);
728               }
729               return reject(errObj);
730             }
731           },
732           failure: function() {
733             var errString;
734             errString = wrapper.getErrorString("authenticate as thing");
735             errObj = KiiUtilities._Error(errString);
736             if (callbacks != null) {
737               callbacks.failure(errObj);
738             }
739             return reject(errObj);
740           }
741         };
742         return wrapper.sendData(JSON.stringify({
743           username: "VENDOR_THING_ID:" + vendorThingID,
744           password: password
745         }), sendCallbacks);
746       };
747     })(this));
748   };
749 
750 
751   /** Create a KiiThingContext reference
752   <br><br>
753   <b>This api is intended to be used in a Thing device, where the user
754   credentials or app admin context is not configured. This Thing must be
755   already registered in Kii Cloud.
756   </b>
757   @param {String} thingID thingID of a registered Thing.
758   @param {String} token token for the registered Thing.
759   @param {Object} [callbacks] The callback methods called when creation succeeded/failed.
760   @param {Method} callbacks.success The callback method called when creation succeeded.
761   @param {Method} callbacks.failure The callback method called when creation failed.
762   @return {Promise} return promise object.
763       <ul>
764         <li>fulfill callback function: function(thingContext). thingContext is a KiiThingContext instance.</li>
765         <li>reject callback function: function(error). error is an Error instance.
766           <ul>
767             <li>error.message</li>
768           </ul>
769         </li>
770       </ul>
771   @example
772   // example to use callbacks directly
773   Kii.authenticateAsThingWithToken("thing_id", "thing_token", {
774       success: function(thingContext) {
775           // thingContext : KiiThingContext instance
776           // Operate entities with thingContext.
777       },
778       failure: function(error) {
779           // Creation failed.
780       }
781   );
782   
783   // example to use Promise
784   Kii.authenticateAsThingWithToken("thing_id", "thing_token").then(
785       function(thingContext) { // fulfill callback function
786           // thingContext : KiiThingContext instance
787           // Operate entities with thingContext.
788   
789       },
790       function(error) { // reject callback function
791           // Creation failed.
792           var errorString = error.message;
793       }
794   );
795    */
796 
797   Kii.authenticateAsThingWithToken = function(thingID, token, callbacks) {
798     return new Promise((function(_this) {
799       return function(resolve, reject) {
800         var errObj, thingAuthContext;
801         if (!KiiUtilities._isNonEmptyString(thingID) || !KiiUtilities._isNonEmptyString(token)) {
802           errObj = KiiUtilities._Error("thingID or token is invalid");
803           if (callbacks != null) {
804             callbacks.failure(errObj);
805           }
806           return reject(errObj);
807         } else {
808           thingAuthContext = new root.KiiThingContext({
809             thingId: thingID,
810             token: token
811           });
812           if (callbacks != null) {
813             callbacks.success(thingAuthContext);
814           }
815           return resolve(thingAuthContext);
816         }
817       };
818     })(this));
819   };
820 
821   return Kii;
822 
823 })();
824 
825 root._KiiHttpRequestType = {
826   jQuery: "jQuery",
827   XMLHttpRequest: "XMLHttpRequest",
828   Titanium: "Titanium"
829 };
830 
831 _Kii = (function() {
832   _Kii.prototype._logging = false;
833 
834   _Kii.prototype._baseURL = null;
835 
836   _Kii.prototype._currentUser = null;
837 
838   _Kii.prototype._httpRequestType = null;
839 
840   function _Kii(appID, appKey, site) {
841     this._appKey = appKey;
842     this._appID = appID;
843     this._baseURL = site;
844     this._expiresIn = 0;
845   }
846 
847   return _Kii;
848 
849 })();
850 
851 
852 /**
853     @class Represents a KiiACL object
854     @exports root.KiiACL as KiiACL
855  */
856 
857 root.KiiACL = (function() {
858   function KiiACL() {
859     this._thingWithID = __bind(this._thingWithID, this);
860     this._userWithID = __bind(this._userWithID, this);
861     this._groupWithID = __bind(this._groupWithID, this);
862     this._getRequest = __bind(this._getRequest, this);
863     this._saveItr = __bind(this._saveItr, this);
864     this._saveUsingCallbacks = __bind(this._saveUsingCallbacks, this);
865     this.save = __bind(this.save, this);
866     this._getKeyOfEntry = __bind(this._getKeyOfEntry, this);
867     this.removeACLEntry = __bind(this.removeACLEntry, this);
868     this.putACLEntry = __bind(this.putACLEntry, this);
869     this._listACLEntriesUsingCallbacks = __bind(this._listACLEntriesUsingCallbacks, this);
870     this.listACLEntries = __bind(this.listACLEntries, this);
871     this.aclPath = __bind(this.aclPath, this);
872     this._setParent = __bind(this._setParent, this);
873     this._entriesMap = {};
874   }
875 
876   KiiACL.prototype._setParent = function(_parent) {
877     this._parent = _parent;
878   };
879 
880   KiiACL.prototype.aclPath = function() {
881     var bucket, bucketName, group, object, objectId, path, stringToRemove, thing, topic, user;
882     if (this._parent instanceof root.KiiObject) {
883       object = this._parent;
884       if (object.getBucket().getUser() != null) {
885         user = object.getBucket().getUser();
886       } else if (object.getBucket().getGroup() != null) {
887         group = object.getBucket().getGroup();
888       } else if (object.getBucket().getThing() != null) {
889         thing = object.getBucket().getThing();
890       }
891       bucketName = object.getBucket()._getQualifiedBucketName();
892       objectId = object.getUUID();
893     } else if (this._parent instanceof root.KiiBucket) {
894       bucket = this._parent;
895       if (bucket.getUser() != null) {
896         user = bucket.getUser();
897       } else if (bucket.getGroup() != null) {
898         group = bucket.getGroup();
899       } else if (bucket.getThing() != null) {
900         thing = bucket.getThing();
901       }
902       bucketName = bucket._getQualifiedBucketName();
903     } else if (this._parent instanceof root.KiiTopic) {
904       topic = this._parent;
905     } else {
906       root.Kii.logger("Invalid ACL parent. Must belong to a KiiObject");
907     }
908     path = "/";
909     if (group != null) {
910       path += "groups/" + (group.getUUID()) + "/";
911     } else if (user != null) {
912       path += "users/" + (user.getUUID()) + "/";
913     } else if (thing != null) {
914       path += "things/" + (thing.getThingID()) + "/";
915     }
916     if (topic) {
917       stringToRemove = "" + (root.Kii.getBaseURL()) + "/apps/" + (root.Kii.getAppID()) + "/";
918       if (topic._uri.indexOf(stringToRemove) !== 0) {
919         path = null;
920       } else {
921         path += topic._uri.substr(stringToRemove.length) + "/acl";
922       }
923     } else {
924       if (objectId != null) {
925         path += "buckets/" + bucketName + "/objects/" + objectId + "/acl";
926       } else {
927         path += "buckets/" + bucketName + "/acl";
928       }
929     }
930     return path;
931   };
932 
933 
934   /** Get the list of active ACLs associated with this object from the server
935   @param {Object} [callbacks] An object with callback methods defined
936   @param {Method} callbacks.success The callback method to call on a successful list request
937   @param {Method} callbacks.failure The callback method to call on a failed list request
938   @return {Promise} return promise object.
939       <ul>
940         <li>fulfill callback function: function(params). params is Array instance.
941           <ul>
942             <li>params[0] is the KiiACL instance which this method was called on.</li>
943             <li>params[1] is array of KiiACLEntry instances.</li>
944           </ul>
945         </li>
946         <li>reject callback function: function(error). error is an Error instance.
947           <ul>
948             <li>error.target is the KiiACL instance which this method was called on.</li>
949             <li>error.message</li>
950           </ul>
951         </li>
952       </ul>
953   @example
954   // example to use callbacks directly
955   var acl = . . .; // a KiiACL object
956   acl.listACLEntries({
957   	success: function(theACL, theEntries) {
958   		// do something
959   	},
960   
961   	failure: function(theACL, anErrorString) {
962   		// do something with the error response
963   	}
964   });
965   
966   // example to use Promise
967   var acl = . . .; // a KiiACL object
968   acl.listACLEntries().then(
969       function(params) { // fulfill callback function
970           var theACL = params[0];
971           var theEntries = params[1];
972           // do something
973       },
974       function(error) { // reject callback function
975           var theACL = error.target;
976           var anErrorString = error.message;
977       		// do something with the error response
978   });
979    */
980 
981   KiiACL.prototype.listACLEntries = function(callbacks) {
982     return new Promise((function(_this) {
983       return function(resolve, reject) {
984         var listACLEntriesCallbacks;
985         listACLEntriesCallbacks = {
986           success: function() {
987             if (callbacks != null) {
988               callbacks.success.apply(callbacks, arguments);
989             }
990             return resolve(arguments);
991           },
992           failure: function() {
993             if (callbacks != null) {
994               callbacks.failure.apply(callbacks, arguments);
995             }
996             return reject(KiiUtilities._Error(arguments[1], _this));
997           }
998         };
999         return _this._listACLEntriesUsingCallbacks(listACLEntriesCallbacks);
1000       };
1001     })(this));
1002   };
1003 
1004   KiiACL.prototype._listACLEntriesUsingCallbacks = function(callbacks) {
1005     var listCallbacks, request;
1006     root.Kii.logger("Listing ACL entries");
1007     request = this._getRequest({
1008       path: this.aclPath(),
1009       withApp: true
1010     });
1011     listCallbacks = {
1012       success: (function(_this) {
1013         return function(data, statusCode) {
1014           var action, entity, key, results, subject, value, _i, _len;
1015           if (statusCode < 300 && statusCode >= 200) {
1016             results = [];
1017             for (key in data) {
1018               value = data[key];
1019               if (key === "WRITE_EXISTING_OBJECT") {
1020                 action = root.KiiACLAction.KiiACLObjectActionWrite;
1021               } else if (key === "READ_EXISTING_OBJECT") {
1022                 action = root.KiiACLAction.KiiACLObjectActionRead;
1023               } else if (key === "QUERY_OBJECTS_IN_BUCKET") {
1024                 action = root.KiiACLAction.KiiACLBucketActionQueryObjects;
1025               } else if (key === "CREATE_OBJECTS_IN_BUCKET") {
1026                 action = root.KiiACLAction.KiiACLBucketActionCreateObjects;
1027               } else if (key === "DROP_BUCKET_WITH_ALL_CONTENT") {
1028                 action = root.KiiACLAction.KiiACLBucketActionDropBucket;
1029               } else if (key === "READ_OBJECTS_IN_BUCKET") {
1030                 action = root.KiiACLAction.KiiACLBucketActionReadObjects;
1031               } else if (key === "SUBSCRIBE_TO_TOPIC") {
1032                 action = root.KiiACLAction.KiiACLSubscribeToTopic;
1033               } else if (key === "SEND_MESSAGE_TO_TOPIC") {
1034                 action = root.KiiACLAction.KiiACLSendMessageToTopic;
1035               } else {
1036                 continue;
1037               }
1038               for (_i = 0, _len = value.length; _i < _len; _i++) {
1039                 entity = value[_i];
1040                 if (entity.groupID != null) {
1041                   subject = _this._groupWithID(entity.groupID);
1042                 } else if (entity.userID != null) {
1043                   subject = _this._userWithID(entity.userID);
1044                 } else if (entity.thingID != null) {
1045                   subject = _this._thingWithID(entity.thingID);
1046                 } else {
1047                   continue;
1048                 }
1049                 results.push(root.KiiACLEntry.entryWithSubject(subject, action));
1050               }
1051             }
1052             return callbacks.success(_this, results);
1053           } else {
1054             return callbacks.failure(_this, "Unable to retrieve ACL list");
1055           }
1056         };
1057       })(this),
1058       failure: (function(_this) {
1059         return function(error, statusCode) {
1060           return callbacks.failure(_this, error);
1061         };
1062       })(this)
1063     };
1064     return request.execute(listCallbacks, false);
1065   };
1066 
1067 
1068   /** Add a KiiACLEntry to the local object, if not already present. This does not explicitly grant any permissions, which should be done through the KiiACLEntry itself. This method simply adds the entry to the local ACL object so it can be saved to the server.
1069   @param {KiiACLEntry} entry The KiiACLEntry to add
1070   @throws {InvalidArgumentException} If specified entry is not an instance of KiiACLEntry.
1071   @example
1072   var aclEntry = . . .; // a KiiACLEntry object
1073   var acl = . . .; // a KiiACL object
1074   acl.putACLEntry(aclEntry);
1075    */
1076 
1077   KiiACL.prototype.putACLEntry = function(entry) {
1078     var key;
1079     if (!(entry instanceof root.KiiACLEntry)) {
1080       throw new root.InvalidArgumentException('invalid entry');
1081     }
1082     key = this._getKeyOfEntry(entry);
1083     return this._entriesMap[key] = entry;
1084   };
1085 
1086 
1087   /** Remove a KiiACLEntry to the local object. This does not explicitly revoke any permissions, which should be done through the KiiACLEntry itself. This method simply removes the entry from the local ACL object and will not be saved to the server.
1088   @param {KiiACLEntry} entry The KiiACLEntry to remove
1089   @throws {InvalidArgumentException} If specified entry is not an instance of KiiACLEntry.
1090   @example
1091   var aclEntry = . . .; // a KiiACLEntry object
1092   var acl = . . .; // a KiiACL object
1093   acl.removeACLEntry(aclEntry);
1094    */
1095 
1096   KiiACL.prototype.removeACLEntry = function(entry) {
1097     var key;
1098     if (!(entry instanceof root.KiiACLEntry)) {
1099       throw new root.InvalidArgumentException('invalid entry');
1100     }
1101     key = this._getKeyOfEntry(entry);
1102     return delete this._entriesMap[key];
1103   };
1104 
1105   KiiACL.prototype._getKeyOfEntry = function(entry) {
1106     var key1, key2, key3;
1107     key1 = entry.getActionString();
1108     key2 = entry.getEntityString();
1109     key3 = entry.getGrant();
1110     return "" + key1 + "/" + key2 + ":" + key3;
1111   };
1112 
1113 
1114   /** Save the list of ACLEntry objects associated with this ACL object to the server
1115   @param {Object} [callbacks] An object with callback methods defined
1116   @param {Method} callbacks.success The callback method to call on a successful save request
1117   @param {Method} callbacks.failure The callback method to call on a failed save request
1118   @return {Promise} return promise object.
1119       <ul>
1120         <li>fulfill callback function: function(theSavedACL). theSavedACL is KiiACL instance.</li>
1121         <li>reject callback function: function(error). error is an Error instance.
1122           <ul>
1123             <li>error.target is the KiiACL instance which this method was called on.</li>
1124             <li>error.message</li>
1125           </ul>
1126         </li>
1127       </ul>
1128   @example
1129   // example to use callbacks directly
1130   var acl = . . .; // a KiiACL object
1131   acl.save({
1132       success: function(theSavedACL) {
1133           // do something with the saved acl
1134       },
1135   
1136       failure: function(theACL, anErrorString) {
1137           // do something with the error response
1138       }
1139   });
1140   
1141   // example to use Promise
1142   var acl = . . .; // a KiiACL object
1143   acl.save().then(
1144       function(theSavedACL) { // fulfill callback function
1145           // do something with the saved acl
1146       },
1147       function(error) { // reject callback function
1148           var theACL = error.target;
1149           var anErrorString = error.message;
1150           // do something with the error response
1151   });
1152    */
1153 
1154   KiiACL.prototype.save = function(callbacks) {
1155     return new Promise((function(_this) {
1156       return function(resolve, reject) {
1157         var saveCallbacks;
1158         saveCallbacks = {
1159           success: function() {
1160             if (callbacks != null) {
1161               callbacks.success.apply(callbacks, arguments);
1162             }
1163             return resolve(arguments[0]);
1164           },
1165           failure: function() {
1166             if (callbacks != null) {
1167               callbacks.failure.apply(callbacks, arguments);
1168             }
1169             return reject(KiiUtilities._Error(arguments[1], _this));
1170           }
1171         };
1172         return _this._saveUsingCallbacks(saveCallbacks);
1173       };
1174     })(this));
1175   };
1176 
1177   KiiACL.prototype._saveUsingCallbacks = function(callbacks) {
1178     var keys;
1179     root.Kii.logger("SAving acl");
1180     if (!this._entriesMap) {
1181       callbacks.failure(this, "There is no entry to save.");
1182       return;
1183     }
1184     keys = Object.keys(this._entriesMap);
1185     root.Kii.logger("Saving total entries : " + keys.length);
1186     if (keys.length < 1) {
1187       callbacks.failure(this, "There is no entry to save.");
1188       return;
1189     }
1190     return this._saveItr(keys, 0, callbacks);
1191   };
1192 
1193   KiiACL.prototype._saveItr = function(keys, idx, callbacks) {
1194     var aclEntry, path, request, _errorStr;
1195     aclEntry = this._entriesMap[keys[idx]];
1196     path = "" + (this.aclPath()) + "/" + (aclEntry.getActionString()) + "/" + (aclEntry.getEntityString());
1197     root.Kii.logger("Saving single @path: " + path);
1198     root.Kii.logger("Saving  entries index : " + idx);
1199     request = this._getRequest({
1200       path: path,
1201       withApp: true
1202     });
1203     request.setMethod(aclEntry.getGrant() === true ? "PUT" : "DELETE");
1204     _errorStr = null;
1205     return request.execute({
1206       success: (function(_this) {
1207         return function(data, status, xhr) {
1208           _this.removeACLEntry(aclEntry);
1209           if (idx < keys.length - 1) {
1210             return _this._saveItr(keys, idx + 1, callbacks);
1211           } else {
1212             return callbacks.success(_this);
1213           }
1214         };
1215       })(this),
1216       failure: (function(_this) {
1217         return function(errorStr, statusCode, errorCode) {
1218           return callbacks.failure(_this, errorStr);
1219         };
1220       })(this)
1221     }, false);
1222   };
1223 
1224   KiiACL.aclWithParent = function(parent) {
1225     var acl;
1226     acl = new root.KiiACL();
1227     acl._setParent(parent);
1228     return acl;
1229   };
1230 
1231   KiiACL.prototype._getRequest = function(spec) {
1232     var path, request, withApp;
1233     path = spec.path;
1234     withApp = spec.withApp;
1235     request = new KiiRequest(path, withApp);
1236     return request;
1237   };
1238 
1239   KiiACL.prototype._groupWithID = function(id) {
1240     var group;
1241     group = root.KiiGroup.groupWithID(id);
1242     return group;
1243   };
1244 
1245   KiiACL.prototype._userWithID = function(id) {
1246     if (id === 'ANONYMOUS_USER') {
1247       return new root.KiiAnonymousUser();
1248     } else if (id === 'ANY_AUTHENTICATED_USER') {
1249       return new root.KiiAnyAuthenticatedUser();
1250     } else {
1251       return root.KiiUser.userWithID(id);
1252     }
1253   };
1254 
1255   KiiACL.prototype._thingWithID = function(id) {
1256     return root.KiiThing.thingWithID(id);
1257   };
1258 
1259   return KiiACL;
1260 
1261 })();
1262 
1263 root.KiiACLAction = {
1264   KiiACLActionStart: -1,
1265   KiiACLBucketActionCreateObjects: 0,
1266   KiiACLBucketActionQueryObjects: 1,
1267   KiiACLBucketActionDropBucket: 2,
1268   KiiACLBucketActionReadObjects: 3,
1269   KiiACLObjectActionRead: 4,
1270   KiiACLObjectActionWrite: 5,
1271   KiiACLSubscribeToTopic: 6,
1272   KiiACLSendMessageToTopic: 7,
1273   KiiACLActionEnd: 8
1274 };
1275 
1276 
1277 /**
1278     @class Represents a KiiACLEntry object
1279     @exports root.KiiACLEntry as KiiACLEntry
1280  */
1281 
1282 root.KiiACLEntry = (function() {
1283   function KiiACLEntry() {
1284     this.getEntityString = __bind(this.getEntityString, this);
1285     this.getActionString = __bind(this.getActionString, this);
1286     this.getGrant = __bind(this.getGrant, this);
1287     this.setGrant = __bind(this.setGrant, this);
1288     this.getSubject = __bind(this.getSubject, this);
1289     this.setSubject = __bind(this.setSubject, this);
1290     this.getAction = __bind(this.getAction, this);
1291     this.setAction = __bind(this.setAction, this);
1292     this._action = -1;
1293     this._grant = true;
1294   }
1295 
1296 
1297   /** The action that is being permitted/restricted. Possible values:
1298   <br><br>
1299   KiiACLAction.KiiACLBucketActionCreateObjects,<br>
1300   KiiACLAction.KiiACLBucketActionQueryObjects,  <br>
1301   KiiACLAction.KiiACLBucketActionDropBucket,<br>
1302   KiiACLAction.KiiACLBucketActionReadObjects,<br>
1303   KiiACLAction.KiiACLObjectActionRead,<br>
1304   KiiACLAction.KiiACLObjectActionWrite,<br>
1305   KiiACLAction.KiiACLSubscribeToTopic,<br>
1306   KiiACLAction.KiiACLSendMessageToTopic
1307   
1308   @param {KiiACLAction} value The action being permitted/restricted
1309   @throws {InvalidACLAction} If the value is not one of the permitted values
1310    */
1311 
1312   KiiACLEntry.prototype.setAction = function(value) {
1313     if (value > root.KiiACLAction.KiiACLActionStart && value < root.KiiACLAction.KiiACLActionEnd) {
1314       return this._action = value;
1315     } else {
1316       throw new root.InvalidACLAction;
1317     }
1318   };
1319 
1320 
1321   /** Get the action that is being permitted/restricted in this entry
1322   @returns {KiiACLAction}
1323    */
1324 
1325   KiiACLEntry.prototype.getAction = function() {
1326     return this._action;
1327   };
1328 
1329 
1330   /** Set the subject to which the action/grant is being applied
1331   @param {KiiGroup|KiiUser|KiiAnyAuthenticatedUser|KiiAnonymousUser|KiiThing} subject instance.
1332   @throws {InvalidACLSubject} If the value is not one of the permitted values
1333    */
1334 
1335   KiiACLEntry.prototype.setSubject = function(value) {
1336     if ((value instanceof root.KiiGroup && (value.getID() != null)) || (value instanceof root.KiiUser && (value.getID() != null)) || value instanceof root.KiiAnyAuthenticatedUser || value instanceof root.KiiAnonymousUser || (value instanceof root.KiiThing && (value.getThingID() != null))) {
1337       return this._subject = value;
1338     } else {
1339       throw new root.InvalidACLSubject;
1340     }
1341   };
1342 
1343 
1344   /** Get the subject that is being permitted/restricted in this entry
1345   @returns {KiiUser|KiiGroup|KiiThing}
1346    */
1347 
1348   KiiACLEntry.prototype.getSubject = function() {
1349     return this._subject;
1350   };
1351 
1352 
1353   /** Set whether or not the action is being permitted to the subject
1354   @param {Boolean} value true if the action is permitted, false otherwise
1355   @throws {InvalidACLGrant} If the value is not a boolean type
1356    */
1357 
1358   KiiACLEntry.prototype.setGrant = function(value) {
1359     if (value === true || value === false) {
1360       return this._grant = value;
1361     } else {
1362       throw new root.InvalidACLGrant;
1363     }
1364   };
1365 
1366 
1367   /** Get whether or not the action is being permitted to the subject
1368   @returns {Boolean}
1369    */
1370 
1371   KiiACLEntry.prototype.getGrant = function() {
1372     return this._grant;
1373   };
1374 
1375 
1376   /** Create a KiiACLEntry object with a subject and action
1377   
1378   The entry will not be applied on the server until the KiiACL object is
1379   explicitly saved. This method simply returns a working KiiACLEntry with
1380   a specified subject and action.
1381   @param {KiiGroup|KiiUser|KiiAnyAuthenticatedUser|KiiAnonymousUser|KiiThing} Subject
1382   to which the action/grant is being applied
1383   @param {KiiACLAction} action One of the specified KiiACLAction values the
1384   permissions is being applied to
1385   @return A KiiACLEntry object with the specified attributes
1386   @throws {InvalidACLSubject} If specified subject is invalid.
1387   @throws {InvalidACLAction} If the specified action is invalid.
1388    */
1389 
1390   KiiACLEntry.entryWithSubject = function(subject, action) {
1391     var entry;
1392     root.Kii.logger("EWS: " + subject + ", " + action);
1393     entry = new root.KiiACLEntry();
1394     entry.setSubject(subject);
1395     entry.setAction(action);
1396     return entry;
1397   };
1398 
1399   KiiACLEntry.prototype.getActionString = function() {
1400     var retString;
1401     root.Kii.logger("Action: " + this.action);
1402     switch (this._action) {
1403       case root.KiiACLAction.KiiACLBucketActionCreateObjects:
1404         retString = "CREATE_OBJECTS_IN_BUCKET";
1405         break;
1406       case root.KiiACLAction.KiiACLBucketActionQueryObjects:
1407         retString = "QUERY_OBJECTS_IN_BUCKET";
1408         break;
1409       case root.KiiACLAction.KiiACLBucketActionDropBucket:
1410         retString = "DROP_BUCKET_WITH_ALL_CONTENT";
1411         break;
1412       case root.KiiACLAction.KiiACLBucketActionReadObjects:
1413         retString = "READ_OBJECTS_IN_BUCKET";
1414         break;
1415       case root.KiiACLAction.KiiACLObjectActionRead:
1416         retString = "READ_EXISTING_OBJECT";
1417         break;
1418       case root.KiiACLAction.KiiACLObjectActionWrite:
1419         retString = "WRITE_EXISTING_OBJECT";
1420         break;
1421       case root.KiiACLAction.KiiACLSubscribeToTopic:
1422         retString = "SUBSCRIBE_TO_TOPIC";
1423         break;
1424       case root.KiiACLAction.KiiACLSendMessageToTopic:
1425         retString = "SEND_MESSAGE_TO_TOPIC";
1426         break;
1427       default:
1428         return retString;
1429     }
1430     return retString;
1431   };
1432 
1433   KiiACLEntry.prototype.getEntityString = function() {
1434     var entityId, type;
1435     if (this._subject instanceof root.KiiGroup) {
1436       entityId = this._subject.getUUID();
1437       type = "GroupID";
1438     } else if (this._subject instanceof root.KiiUser) {
1439       entityId = this._subject.getUUID();
1440       type = "UserID";
1441     } else if (this._subject instanceof root.KiiAnyAuthenticatedUser) {
1442       type = "UserID";
1443       entityId = "ANY_AUTHENTICATED_USER";
1444     } else if (this._subject instanceof root.KiiAnonymousUser) {
1445       type = "UserID";
1446       entityId = "ANONYMOUS_USER";
1447     } else if (this._subject instanceof root.KiiThing) {
1448       type = "ThingID";
1449       entityId = this._subject.getThingID();
1450     }
1451     return "" + type + ":" + entityId;
1452   };
1453 
1454   return KiiACLEntry;
1455 
1456 })();
1457 
1458 
1459 /**
1460     @class Represents a KiiBucket object
1461     @exports root.KiiBucket as KiiBucket
1462  */
1463 
1464 root.KiiBucket = (function() {
1465   KiiBucket.prototype._className = "KiiBucket";
1466 
1467   KiiBucket.prototype.getUser = function() {
1468     return this._user;
1469   };
1470 
1471   KiiBucket.prototype.getGroup = function() {
1472     return this._group;
1473   };
1474 
1475   KiiBucket.prototype.getThing = function() {
1476     return this._thing;
1477   };
1478 
1479 
1480   /** The name of this bucket
1481   @returns {String}
1482    */
1483 
1484   KiiBucket.prototype.getBucketName = function() {
1485     return this._bucketName;
1486   };
1487 
1488   KiiBucket.prototype._setBucketName = function(_bucketName) {
1489     this._bucketName = _bucketName;
1490   };
1491 
1492   KiiBucket.prototype._getQualifiedBucketName = function() {
1493     return this._bucketName;
1494   };
1495 
1496 
1497   /** Create a KiiObject within the current bucket
1498   
1499   <br><br>The object will not be created on the server until the KiiObject is explicitly saved. This method simply returns an empty working KiiObject.
1500   @returns {KiiObject} An empty KiiObject with no specific type
1501   @example
1502   var bucket = . . .; // a KiiBucket
1503   var object = bucket.createObject();
1504    */
1505 
1506   KiiBucket.prototype.createObject = function() {
1507     return root.KiiObject.objectWithBucket(this, null);
1508   };
1509 
1510 
1511   /** Create a KiiObject within the current bucket, with type
1512   
1513   <br><br>The object will not be created on the server until the KiiObject is explicitly saved. This method simply returns an empty working KiiObject with a specified type. The type allows for better indexing and improved query results. It is recommended to use this method - but for lazy creation, the createObject method is also available.
1514   @param String type A string representing the desired object type
1515   @returns An empty KiiObject with specified type
1516   @example
1517   var bucket = . . .; // a KiiBucket
1518   var object = bucket.createObjectWithType("scores");
1519    */
1520 
1521   KiiBucket.prototype.createObjectWithType = function(type) {
1522     return root.KiiObject.objectWithBucket(this, type);
1523   };
1524 
1525 
1526   /** Create a KiiObject within the current bucket, specifying its ID.
1527   
1528   <br><br> If the object has not exist on KiiCloud, {@link KiiObject#saveAllFields(callback)}
1529     will create new Object which has ID specified in the argument.
1530     If the object exist in KiiCloud, references the existing object which has
1531     specified ID. use {@link KiiObject#refresh(callback)} to retrieve the contents of
1532     KiiObject.
1533    @param String objectID ID of the obeject you want to instantiate.
1534    @returns {KiiObject} KiiObject instance.
1535    @throws {InvalidArgumentException} objectID is not acceptable.
1536    Refer to {@link KiiObject.isValidObjectID(string)} for details of acceptable string.
1537    @example
1538    var bucket = . . .; // KiiBucket
1539    var object = bucket.createObjectWithID('__OBJECT_ID_');
1540    */
1541 
1542   KiiBucket.prototype.createObjectWithID = function(objectID) {
1543     if (!root.KiiObject.isValidObjectID(objectID)) {
1544       throw root.InvalidArgumentException('Specified obejctID is invalid.');
1545     }
1546     return root.KiiObject.objectWithID(this, objectID);
1547   };
1548 
1549 
1550   /** Get the ACL handle for this bucket
1551   
1552   <br><br>Any KiiACLEntry objects added or revoked from this ACL object will be appended to/removed from the server on ACL save.
1553   	@returns {KiiACL} A KiiACL object associated with this KiiObject
1554   	@example
1555   	var bucket = . . .; // a KiiBucket
1556   	var acl = bucket.acl();
1557    */
1558 
1559   KiiBucket.prototype.acl = function() {
1560     return root.KiiACL.aclWithParent(this);
1561   };
1562 
1563 
1564   /** Perform a query on the given bucket
1565   
1566   <br><br>The query will be executed against the server, returning a result set.
1567   @param KiiQuery query An object with callback methods defined
1568   @param Object callbacks An object with callback methods defined
1569   @param {Method} callbacks.success The callback method to call on a successful query request
1570   @param {Method} callbacks.failure The callback method to call on a failed query request
1571   @return {Promise} return promise object.
1572     <ul>
1573       <li>fulfill callback function: function(params). params is Array instance.
1574         <ul>
1575           <li>params[0] is a performed KiiQuery instance.</li>
1576           <li>params[1] is resultSet Array instance. Could be KiiObject, KiiGroup, KiiUser, etc.</li>
1577           <li>params[2] is a KiiQuery instance for next query. If there are no more results to be retrieved, it will be null.</li>
1578         </ul>
1579       </li>
1580       <li>reject callback function: function(error). error is an Error instance.
1581         <ul>
1582           <li>error.target is the KiiBucket instance which this method was called on.</li>
1583           <li>error.message</li>
1584         </ul>
1585       </li>
1586     </ul>
1587   @example
1588   // example to use callbacks directly
1589   var bucket = . . .; // a KiiBucket
1590   var queryObject = . . .; // a KiiQuery
1591   
1592   // define the callbacks (stored in a variable for reusability)
1593   var queryCallbacks = {
1594       success: function(queryPerformed, resultSet, nextQuery) {
1595           // do something with the results
1596           for(var i=0; i<resultSet.length; i++) {
1597               // do something with the object
1598               // resultSet[i]; // could be KiiObject, KiiGroup, KiiUser, etc
1599           }
1600   
1601           // if there are more results to be retrieved
1602           if(nextQuery != null) {
1603   
1604               // get them and repeat recursively until no results remain
1605               bucket.executeQuery(nextQuery, queryCallbacks);
1606           }
1607       },
1608   
1609       failure: function(bucket, anErrorString) {
1610           // do something with the error response
1611       }
1612   };
1613   bucket.executeQuery(queryObject, queryCallbacks);
1614   
1615   // example to use Promise
1616   var bucket = . . .; // a KiiBucket
1617   var queryObject = . . .; // a KiiQuery
1618   bucket.executeQuery(queryObject).then(
1619       function(params) {
1620           var queryPerformed = params[0];
1621           var resultSet = params[1];
1622           var nextQuery = params[2];
1623           // do something with the results
1624           for(var i=0; i<resultSet.length; i++) {
1625               // do something with the object
1626               // resultSet[i]; // could be KiiObject, KiiGroup, KiiUser, etc
1627           }
1628   
1629           // if there are more results to be retrieved
1630           if(nextQuery != null) {
1631   
1632               // get them and repeat recursively until no results remain
1633               bucket.executeQuery(nextQuery).then(
1634                   function(params) {
1635                       // next query success
1636                   },
1637                   function(error) {
1638                       // next query failed, please handle the error
1639                   }
1640               );
1641           }
1642   
1643       },
1644       function(error) {
1645           // do something with the error response
1646       }
1647   );
1648    */
1649 
1650   KiiBucket.prototype.executeQuery = function(query, callbacks) {
1651     return new Promise((function(_this) {
1652       return function(resolve, reject) {
1653         var executeQueryCallbacks;
1654         executeQueryCallbacks = {
1655           success: function() {
1656             if (callbacks != null) {
1657               callbacks.success.apply(callbacks, arguments);
1658             }
1659             return resolve(arguments);
1660           },
1661           failure: function() {
1662             if (callbacks != null) {
1663               callbacks.failure.apply(callbacks, arguments);
1664             }
1665             return reject(KiiUtilities._Error(arguments[1], _this));
1666           }
1667         };
1668         return _this._executeQueryUsingCallbacks(query, executeQueryCallbacks);
1669       };
1670     })(this));
1671   };
1672 
1673   KiiBucket.prototype._executeQueryUsingCallbacks = function(query, callbacks) {
1674     var data, error, executeCallbacks, path, request;
1675     try {
1676       path = this._generatePath() + "/query";
1677       data = {};
1678       if (query != null) {
1679         data = query._dictValue();
1680       } else {
1681         data.bucketQuery = {
1682           "clause": root.KiiQuery._emptyDictValue()
1683         };
1684       }
1685       request = this._getRequest({
1686         path: path,
1687         withApp: true
1688       });
1689       request.setMethod("POST");
1690       request.setContentType("application/vnd.kii.QueryRequest+json");
1691       request.setData(data);
1692       executeCallbacks = {
1693         success: (function(_this) {
1694           return function(data, statusCode) {
1695             var nextQuery, result, resultSet, _i, _len, _ref;
1696             if (statusCode < 300 && statusCode >= 200) {
1697               resultSet = [];
1698               _ref = data.results;
1699               for (_i = 0, _len = _ref.length; _i < _len; _i++) {
1700                 result = _ref[_i];
1701                 resultSet.push(_this.objectWithJSON(result));
1702               }
1703               if (data.nextPaginationKey != null) {
1704                 nextQuery = new root.KiiQuery(query);
1705                 nextQuery.setPaginationKey(data.nextPaginationKey);
1706               } else {
1707                 nextQuery = null;
1708               }
1709               if (callbacks != null) {
1710                 return callbacks.success(query, resultSet, nextQuery);
1711               }
1712             } else if (callbacks != null) {
1713               return callbacks.failure(_this, "Unable to parse response");
1714             }
1715           };
1716         })(this),
1717         failure: (function(_this) {
1718           return function(error, statusCode) {
1719             if (callbacks != null) {
1720               return callbacks.failure(_this, error);
1721             }
1722           };
1723         })(this)
1724       };
1725       return request.execute(executeCallbacks, false);
1726     } catch (_error) {
1727       error = _error;
1728       return callbacks.failure(this, error);
1729     }
1730   };
1731 
1732 
1733   /** Execute count aggregation of specified query on current bucket.
1734   Query that passed as nextQuery in success callback of {@link #executeQuery}, is not
1735   supported, callbacks.failure will be fired in this case.
1736   
1737   @param {KiiQuery} query to be executed. If null, the operation will be same as {@link #count}.
1738   @param {Object} [callbacks] An object with callback methods defined.
1739   @param {Method} callbacks.success The callback method to call on a successful query request.
1740   @param {Method} callbacks.failure The callback method to call on a failed query request.
1741   @return {Promise} return promise object.
1742     <ul>
1743       <li>fulfill callback function: function(params). params is Array instance.
1744         <ul>
1745           <li>params[0] is a KiiBucket instance which this method was called on.</li>
1746           <li>params[1] is a KiiQuery instance.</li>
1747           <li>params[2] is an integer count result. </li>
1748         </ul>
1749       </li>
1750       <li>reject callback function: function(error). error is an Error instance.
1751         <ul>
1752           <li>error.target is the KiiBucket instance which this method was called on.</li>
1753           <li>error.message</li>
1754         </ul>
1755       </li>
1756     </ul>
1757   @example
1758   // example to use callbacks directly
1759   var bucket = . . .; // a KiiBucket
1760   var queryObject = . . .; // a KiiQuery
1761   
1762   // define the callbacks
1763   var callbacks = {
1764       success: function(bucket, query, count) {
1765           // do something with the results
1766       },
1767   
1768       failure: function(bucket, errorString) {
1769           // error happened.
1770       }
1771   };
1772   
1773   bucket.countWithQuery(queryObject, callbacks);
1774   
1775   // example to use Promise
1776   var bucket = . . .; // a KiiBucket
1777   var queryObject = . . .; // a KiiQuery
1778   
1779   bucket.countWithQuery(queryObject, callbacks).then(
1780       function(params) {
1781           var bucket = params[0];
1782           var query = params[1];
1783           var count = params[2];
1784           // do something with the results
1785       },
1786       function(error) {
1787           var bucket = error.target;
1788           var errorString = error.message;
1789           // error happened.
1790       }
1791   );
1792    */
1793 
1794   KiiBucket.prototype.countWithQuery = function(query, callbacks) {
1795     return new Promise((function(_this) {
1796       return function(resolve, reject) {
1797         var countWithQueryCallbacks;
1798         countWithQueryCallbacks = {
1799           success: function() {
1800             if (callbacks != null) {
1801               callbacks.success.apply(callbacks, arguments);
1802             }
1803             return resolve(arguments);
1804           },
1805           failure: function() {
1806             if (callbacks != null) {
1807               callbacks.failure.apply(callbacks, arguments);
1808             }
1809             return reject(KiiUtilities._Error(arguments[1], _this));
1810           }
1811         };
1812         return _this._countWithQueryUsingCallbacks(query, countWithQueryCallbacks);
1813       };
1814     })(this));
1815   };
1816 
1817   KiiBucket.prototype._countWithQueryUsingCallbacks = function(query, callbacks) {
1818     var data, executeCallbacks, path, request;
1819     path = this._generatePath() + "/query";
1820     data = {};
1821     if (query != null) {
1822       data = query._dictValue();
1823     } else {
1824       data.bucketQuery = {
1825         "clause": root.KiiQuery._emptyDictValue()
1826       };
1827       query = root.KiiQuery.queryWithClause();
1828     }
1829     data.bucketQuery.aggregations = [
1830       {
1831         "type": "COUNT",
1832         "putAggregationInto": "count_field"
1833       }
1834     ];
1835     request = this._getRequest({
1836       path: path,
1837       withApp: true
1838     });
1839     request.setMethod("POST");
1840     request.setContentType("application/vnd.kii.QueryRequest+json");
1841     request.setData(data);
1842     executeCallbacks = {
1843       success: (function(_this) {
1844         return function(data, statusCode) {
1845           var count;
1846           if (statusCode < 300 && statusCode >= 200) {
1847             count = data.aggregations.count_field;
1848             if (callbacks != null) {
1849               return callbacks.success(_this, query, count);
1850             }
1851           } else if (callbacks != null) {
1852             return callbacks.failure(_this, "Unable to parse response");
1853           }
1854         };
1855       })(this),
1856       failure: (function(_this) {
1857         return function(error, statusCode) {
1858           if (callbacks != null) {
1859             return callbacks.failure(_this, error);
1860           }
1861         };
1862       })(this)
1863     };
1864     return request.execute(executeCallbacks, false);
1865   };
1866 
1867 
1868   /** Execute count aggregation of all clause query on current bucket.
1869   @param {Object} [callbacks] An object with callback methods defined.
1870   @param {Method} callbacks.success The callback method to call on a successful query request.
1871   @param {Method} callbacks.failure The callback method to call on a failed query request.
1872   @return {Promise} return promise object.
1873     <ul>
1874       <li>fulfill callback function: function(params). params is Array instance.
1875         <ul>
1876           <li>params[0] is a KiiBucket instance which this method was called on.</li>
1877           <li>params[1] is a KiiQuery instance.</li>
1878           <li>params[2] is an integer count result. </li>
1879         </ul>
1880       </li>
1881       <li>reject callback function: function(error). error is an Error instance.
1882         <ul>
1883           <li>error.target is the KiiBucket instance which this method was called on.</li>
1884           <li>error.message</li>
1885         </ul>
1886       </li>
1887     </ul>
1888   @example
1889   // example to use callbacks directly
1890   var bucket = . . .; // a KiiBucket
1891   // define the callbacks
1892   var callbacks = {
1893       success: function(bucket, query, count) {
1894           // do something with the results
1895       },
1896   
1897       failure: function(bucket, errorString) {
1898           // error happened.
1899       }
1900   };
1901   
1902   bucket.count(callbacks);
1903   
1904   // example to use Promise
1905   var bucket = . . .; // a KiiBucket
1906   var queryObject = . . .; // a KiiQuery
1907   
1908   bucket.count().then(
1909       function(params) {
1910           var bucket = params[0];
1911           var count = params[2];
1912           // do something with the results
1913       },
1914       function(error) {
1915           var bucket = error.target;
1916           var errorString = error.message;
1917           // error happened.
1918       }
1919   );
1920    */
1921 
1922   KiiBucket.prototype.count = function(callbacks) {
1923     var all_query;
1924     all_query = root.KiiQuery.queryWithClause();
1925     return this.countWithQuery(all_query, callbacks);
1926   };
1927 
1928 
1929   /** Delete the given bucket from the server
1930   @name delete
1931   @memberOf root.KiiBucket#
1932   @function
1933   @param Object callbacks An object with callback methods defined
1934   @param {Method} callbacks.success The callback method to call on a successful query request
1935   @param {Method} callbacks.failure The callback method to call on a failed query request
1936   @return {Promise} return promise object.
1937     <ul>
1938       <li>fulfill callback function: function(deletedBucket). deletedBucket is KiiBucket instance.</li>
1939       <li>reject callback function: function(error). error is an Error instance.
1940         <ul>
1941           <li>error.target is the KiiBucket instance which this method was called on.</li>
1942           <li>error.message</li>
1943         </ul>
1944       </li>
1945     </ul>
1946   @example
1947   // example to use callbacks directly
1948   var bucket = . . .; // a KiiBucket
1949   bucket.delete({
1950       success: function(deletedBucket) {
1951           // do something with the result
1952       },
1953   
1954       failure: function(bucketToDelete, anErrorString) {
1955           // do something with the error response
1956       }
1957   });
1958   
1959   // example to use Promise
1960   var bucket = . . .; // a KiiBucket
1961   bucket.delete({
1962       success: function(deletedBucket) {
1963           // do something with the result
1964       },
1965   
1966       failure: function(bucketToDelete, anErrorString) {
1967           // do something with the error response
1968       }
1969   }).then(
1970       function(deletedBucket) {
1971         // do something with the result
1972       },
1973       function(error) {
1974         // do something with the error response
1975       }
1976   );
1977    */
1978 
1979   KiiBucket.prototype["delete"] = function(callbacks) {
1980     return new Promise((function(_this) {
1981       return function(resolve, reject) {
1982         var deleteCallbacks;
1983         deleteCallbacks = {
1984           success: function() {
1985             if (callbacks != null) {
1986               callbacks.success.apply(callbacks, arguments);
1987             }
1988             return resolve(arguments[0]);
1989           },
1990           failure: function() {
1991             if (callbacks != null) {
1992               callbacks.failure.apply(callbacks, arguments);
1993             }
1994             return reject(KiiUtilities._Error(arguments[1], _this));
1995           }
1996         };
1997         return _this._deleteUsingCallbacks(deleteCallbacks);
1998       };
1999     })(this));
2000   };
2001 
2002   KiiBucket.prototype._deleteUsingCallbacks = function(callbacks) {
2003     var executeCallbacks, request;
2004     request = this._getRequest({
2005       path: this._generatePath(),
2006       withApp: true
2007     });
2008     request.setMethod("DELETE");
2009     executeCallbacks = {
2010       success: (function(_this) {
2011         return function(data, statusCode) {
2012           if (callbacks != null) {
2013             return callbacks.success(_this);
2014           }
2015         };
2016       })(this),
2017       failure: (function(_this) {
2018         return function(error, statusCode) {
2019           if (callbacks != null) {
2020             return callbacks.failure(_this, error);
2021           }
2022         };
2023       })(this)
2024     };
2025     return request.execute(executeCallbacks, true);
2026   };
2027 
2028   function KiiBucket(bucketName, parent) {
2029     this.objectWithJSON = __bind(this.objectWithJSON, this);
2030     this._getHttpUri = __bind(this._getHttpUri, this);
2031     this._generatePath = __bind(this._generatePath, this);
2032     this._getRequest = __bind(this._getRequest, this);
2033     this._deleteUsingCallbacks = __bind(this._deleteUsingCallbacks, this);
2034     this["delete"] = __bind(this["delete"], this);
2035     this.count = __bind(this.count, this);
2036     this._countWithQueryUsingCallbacks = __bind(this._countWithQueryUsingCallbacks, this);
2037     this.countWithQuery = __bind(this.countWithQuery, this);
2038     this._executeQueryUsingCallbacks = __bind(this._executeQueryUsingCallbacks, this);
2039     this.executeQuery = __bind(this.executeQuery, this);
2040     this.acl = __bind(this.acl, this);
2041     this.createObjectWithID = __bind(this.createObjectWithID, this);
2042     this.createObjectWithType = __bind(this.createObjectWithType, this);
2043     this.createObject = __bind(this.createObject, this);
2044     this._getQualifiedBucketName = __bind(this._getQualifiedBucketName, this);
2045     this._setBucketName = __bind(this._setBucketName, this);
2046     this.getBucketName = __bind(this.getBucketName, this);
2047     this.getThing = __bind(this.getThing, this);
2048     this.getGroup = __bind(this.getGroup, this);
2049     this.getUser = __bind(this.getUser, this);
2050     if (!KiiUtilities._isNonEmptyString(bucketName)) {
2051       throw root.InvalidArgumentException('Specified bucket name is null or empty.');
2052     }
2053     this._bucketName = bucketName;
2054     if (parent != null) {
2055       if (parent instanceof root.KiiGroup) {
2056         this._group = parent;
2057       } else if (parent instanceof root.KiiUser) {
2058         this._user = parent;
2059       } else if (parent instanceof root.KiiThing) {
2060         this._thing = parent;
2061       }
2062     }
2063   }
2064 
2065   KiiBucket._bucketWithName = function(bucketName, parent) {
2066     var bucket;
2067     bucket = new root.KiiBucket(bucketName, parent);
2068     return bucket;
2069   };
2070 
2071   KiiBucket.prototype._getRequest = function(spec) {
2072     var path, request, withApp;
2073     path = spec.path;
2074     withApp = spec.withApp;
2075     request = new KiiRequest(path, withApp);
2076     return request;
2077   };
2078 
2079   KiiBucket.prototype._generatePath = function() {
2080     var path;
2081     if (this._user != null) {
2082       path = "/users/" + (this._user.getUUID()) + "/buckets/" + (this._getQualifiedBucketName());
2083     } else if (this._group != null) {
2084       path = "/groups/" + (this._group.getUUID()) + "/buckets/" + (this._getQualifiedBucketName());
2085     } else if (this._thing != null) {
2086       path = "/things/" + (this._thing.getThingID()) + "/buckets/" + (this._getQualifiedBucketName());
2087     } else {
2088       path = "/buckets/" + (this._getQualifiedBucketName());
2089     }
2090     return path;
2091   };
2092 
2093   KiiBucket.prototype._getHttpUri = function() {
2094     return "" + (root.Kii.getBaseURL()) + "/apps/" + (root.Kii.getAppID()) + "/" + (this._generatePath());
2095   };
2096 
2097   KiiBucket.prototype.objectWithJSON = function(json) {
2098     var newobject;
2099     newobject = this.createObject();
2100     newobject._updateWithJSON(json);
2101     return newobject;
2102   };
2103 
2104   return KiiBucket;
2105 
2106 })();
2107 
2108 root.KiiEncryptedBucket = (function(_super) {
2109   __extends(KiiEncryptedBucket, _super);
2110 
2111   function KiiEncryptedBucket(bucketName, parent) {
2112     this._getQualifiedBucketName = __bind(this._getQualifiedBucketName, this);
2113     if (!KiiUtilities._isNonEmptyString(bucketName)) {
2114       throw root.InvalidArgumentException('Specified bucket name is null or empty.');
2115     }
2116     if (root.KiiEncryptedBucket._isEncrypted(bucketName)) {
2117       KiiEncryptedBucket.__super__.constructor.call(this, bucketName.replace("CRYPTO:", ""), parent);
2118     } else {
2119       KiiEncryptedBucket.__super__.constructor.call(this, bucketName, parent);
2120     }
2121   }
2122 
2123   KiiEncryptedBucket.prototype._getQualifiedBucketName = function() {
2124     return "CRYPTO:" + this._bucketName;
2125   };
2126 
2127   KiiEncryptedBucket._bucketWithName = function(bucketName, parent) {
2128     var bucket;
2129     bucket = new root.KiiEncryptedBucket(bucketName, parent);
2130     return bucket;
2131   };
2132 
2133   KiiEncryptedBucket._isEncrypted = function(bucketName) {
2134     var isEncrypted;
2135     isEncrypted = bucketName.indexOf("CRYPTO:") === 0;
2136     return isEncrypted;
2137   };
2138 
2139   return KiiEncryptedBucket;
2140 
2141 })(root.KiiBucket);
2142 
2143 root.KiiEncryptedBucketWithToken = (function(_super) {
2144   __extends(KiiEncryptedBucketWithToken, _super);
2145 
2146   function KiiEncryptedBucketWithToken(bucketName, parent, token) {
2147     this.acl = __bind(this.acl, this);
2148     this.createObjectWithID = __bind(this.createObjectWithID, this);
2149     this.createObjectWithType = __bind(this.createObjectWithType, this);
2150     this.createObject = __bind(this.createObject, this);
2151     this._getRequest = __bind(this._getRequest, this);
2152     KiiEncryptedBucketWithToken.__super__.constructor.call(this, bucketName, parent);
2153     this._authToken = token;
2154   }
2155 
2156   KiiEncryptedBucketWithToken.prototype._getRequest = function(spec) {
2157     var request;
2158     request = KiiEncryptedBucketWithToken.__super__._getRequest.call(this, spec);
2159     request.setAdminToken(this._authToken);
2160     return request;
2161   };
2162 
2163   KiiEncryptedBucketWithToken.prototype.createObject = function() {
2164     return root.KiiObjectWithToken.objectWithBucket(this, null, this._authToken);
2165   };
2166 
2167   KiiEncryptedBucketWithToken.prototype.createObjectWithType = function(type) {
2168     return root.KiiObjectWithToken.objectWithBucket(this, type, this._authToken);
2169   };
2170 
2171   KiiEncryptedBucketWithToken.prototype.createObjectWithID = function(id) {
2172     return root.KiiObjectWithToken.objectWithID(this, id, this._authToken);
2173   };
2174 
2175   KiiEncryptedBucketWithToken.prototype.acl = function() {
2176     var acl;
2177     acl = new root.KiiACLWithToken(this, this._authToken);
2178     return acl;
2179   };
2180 
2181   return KiiEncryptedBucketWithToken;
2182 
2183 })(root.KiiEncryptedBucket);
2184 
2185 root.KiiBucketWithToken = (function(_super) {
2186   __extends(KiiBucketWithToken, _super);
2187 
2188   function KiiBucketWithToken(bucketName, parent, token) {
2189     this.acl = __bind(this.acl, this);
2190     this.createObjectWithID = __bind(this.createObjectWithID, this);
2191     this.createObjectWithType = __bind(this.createObjectWithType, this);
2192     this.createObject = __bind(this.createObject, this);
2193     this._getRequest = __bind(this._getRequest, this);
2194     KiiBucketWithToken.__super__.constructor.call(this, bucketName, parent);
2195     this._authToken = token;
2196   }
2197 
2198   KiiBucketWithToken.prototype._getRequest = function(spec) {
2199     var request;
2200     request = KiiBucketWithToken.__super__._getRequest.call(this, spec);
2201     request.setAdminToken(this._authToken);
2202     return request;
2203   };
2204 
2205   KiiBucketWithToken.prototype.createObject = function() {
2206     return root.KiiObjectWithToken.objectWithBucket(this, null, this._authToken);
2207   };
2208 
2209   KiiBucketWithToken.prototype.createObjectWithType = function(type) {
2210     return root.KiiObjectWithToken.objectWithBucket(this, type, this._authToken);
2211   };
2212 
2213   KiiBucketWithToken.prototype.createObjectWithID = function(id) {
2214     return root.KiiObjectWithToken.objectWithID(this, id, this._authToken);
2215   };
2216 
2217   KiiBucketWithToken.prototype.acl = function() {
2218     var acl;
2219     acl = new root.KiiACLWithToken(this, this._authToken);
2220     return acl;
2221   };
2222 
2223   return KiiBucketWithToken;
2224 
2225 })(root.KiiBucket);
2226 
2227 
2228 /**
2229     @class Represents a KiiGroup object
2230     @exports root.KiiGroup as KiiGroup
2231  */
2232 
2233 root.KiiGroup = (function() {
2234   KiiGroup.prototype._getAddMembers = function() {
2235     return this._addMembers;
2236   };
2237 
2238   KiiGroup.prototype._getRemoveMembers = function() {
2239     return this._removeMembers;
2240   };
2241 
2242   function KiiGroup() {
2243     this._setAuthToken = __bind(this._setAuthToken, this);
2244     this._getHttpURI = __bind(this._getHttpURI, this);
2245     this._listTopicsUsingCallbacks = __bind(this._listTopicsUsingCallbacks, this);
2246     this.listTopics = __bind(this.listTopics, this);
2247     this.topicWithName = __bind(this.topicWithName, this);
2248     this._setOwnerFromContext = __bind(this._setOwnerFromContext, this);
2249     this._userWithID = __bind(this._userWithID, this);
2250     this._getRequest = __bind(this._getRequest, this);
2251     this._updateWithJSON = __bind(this._updateWithJSON, this);
2252     this._getOwnerUsingCallbacks = __bind(this._getOwnerUsingCallbacks, this);
2253     this.getOwner = __bind(this.getOwner, this);
2254     this._deleteUsingCallbacks = __bind(this._deleteUsingCallbacks, this);
2255     this["delete"] = __bind(this["delete"], this);
2256     this._refreshUsingCallbacks = __bind(this._refreshUsingCallbacks, this);
2257     this.refresh = __bind(this.refresh, this);
2258     this._saveWithOwnerUsingCallbacks = __bind(this._saveWithOwnerUsingCallbacks, this);
2259     this.saveWithOwner = __bind(this.saveWithOwner, this);
2260     this._saveUsingCallbacks = __bind(this._saveUsingCallbacks, this);
2261     this.save = __bind(this.save, this);
2262     this._changeGroupNameUsingCallbacks = __bind(this._changeGroupNameUsingCallbacks, this);
2263     this.changeGroupName = __bind(this.changeGroupName, this);
2264     this._changeOwner = __bind(this._changeOwner, this);
2265     this._saveMembers = __bind(this._saveMembers, this);
2266     this._getMemberListUsingCallbacks = __bind(this._getMemberListUsingCallbacks, this);
2267     this.getMemberList = __bind(this.getMemberList, this);
2268     this._removeMember = __bind(this._removeMember, this);
2269     this._addMember = __bind(this._addMember, this);
2270     this.removeUser = __bind(this.removeUser, this);
2271     this.addUser = __bind(this.addUser, this);
2272     this.encryptedBucketWithName = __bind(this.encryptedBucketWithName, this);
2273     this.bucketWithName = __bind(this.bucketWithName, this);
2274     this.objectURI = __bind(this.objectURI, this);
2275     this._setOwner = __bind(this._setOwner, this);
2276     this.getCachedOwner = __bind(this.getCachedOwner, this);
2277     this._setName = __bind(this._setName, this);
2278     this.getName = __bind(this.getName, this);
2279     this.getID = __bind(this.getID, this);
2280     this._setUUID = __bind(this._setUUID, this);
2281     this.getUUID = __bind(this.getUUID, this);
2282     this._setAddMembers = __bind(this._setAddMembers, this);
2283     this._getRemoveMembers = __bind(this._getRemoveMembers, this);
2284     this._getAddMembers = __bind(this._getAddMembers, this);
2285     this._addMembers = {};
2286     this._removeMembers = {};
2287   }
2288 
2289   KiiGroup.prototype._setAddMembers = function(members) {
2290     var member, _i, _len, _results;
2291     if (members != null) {
2292       _results = [];
2293       for (_i = 0, _len = members.length; _i < _len; _i++) {
2294         member = members[_i];
2295         _results.push(this.addUser(member));
2296       }
2297       return _results;
2298     }
2299   };
2300 
2301 
2302   /** @deprecated Use {@link KiiGroup.getId} instead.
2303   Get the UUID of the given group, assigned by the server
2304   @returns {String}
2305    */
2306 
2307   KiiGroup.prototype.getUUID = function() {
2308     return this._uuid;
2309   };
2310 
2311   KiiGroup.prototype._setUUID = function(_uuid) {
2312     this._uuid = _uuid;
2313   };
2314 
2315 
2316   /** Get the ID of the current KiiGroup instance.
2317   @returns {String} Id of the group or null if the group has not saved to cloud.
2318    */
2319 
2320   KiiGroup.prototype.getID = function() {
2321     return this._uuid;
2322   };
2323 
2324 
2325   /** The name of this group
2326   @returns {String}
2327    */
2328 
2329   KiiGroup.prototype.getName = function() {
2330     return this._groupName;
2331   };
2332 
2333   KiiGroup.prototype._setName = function(_groupName) {
2334     this._groupName = _groupName;
2335   };
2336 
2337 
2338   /** Returns the owner of this group if this group holds the information of owner.
2339   
2340   Group will holds the information of owner when "saving group on cloud" or "retrieving group info/owner from cloud".
2341   The cache will not be shared among the different instances of KiiGroup.
2342   <UL>
2343   <LI>This API will not access to server.
2344   To update the group owner information on cloud, please call {@link KiiGroup#refresh} or {@link KiiGroup#getOwner}.
2345   </LI>
2346   <LI>This API does not return all the properties of the owner.
2347   To get all owner properties, {@link KiiUser#refresh} is necessary.</LI>
2348   </UL>
2349   @returns {KiiUser} KiiUser who owns this group, undefined if this group doesn't hold the information of owner yet.
2350   @link KiiGroup#getOwner
2351    */
2352 
2353   KiiGroup.prototype.getCachedOwner = function() {
2354     return this._owner;
2355   };
2356 
2357   KiiGroup.prototype._setOwner = function(_owner) {
2358     this._owner = _owner;
2359   };
2360 
2361 
2362   /** Get a specifically formatted string referencing the group
2363   
2364   <br><br>The group must exist in the cloud (have a valid UUID).
2365   @returns {String} A URI string based on the current group. null if a URI couldn't be generated.
2366   @example
2367   var group = . . .; // a KiiGroup
2368   var uri = group.objectURI();
2369    */
2370 
2371   KiiGroup.prototype.objectURI = function() {
2372     if (this._uuid != null) {
2373       return "kiicloud://groups/" + this._uuid;
2374     } else {
2375       return null;
2376     }
2377   };
2378 
2379 
2380   /** Register new group own by current user on Kii Cloud with specified ID.
2381   
2382   <br><br>If the group that has specified id already exists, registration will be failed.
2383   
2384   @param {String} groupID ID of the KiiGroup
2385   @param {String} groupName Name of the KiiGroup
2386   @param {Array} members An array of KiiUser objects to add to the group
2387   @param {Object} [callbacks] An object with callback methods defined
2388   @param {Method} callbacks.success The callback method to call on a successful register request
2389   @param {Method} callbacks.failure The callback method to call on a failed register request
2390   @return {Promise} return promise object.
2391         <ul>
2392           <li>fulfill callback function: function(theSavedGroup). theSavedGroup is KiiGroup instance.</li>
2393           <li>reject callback function: function(error). error is an Error instance.
2394             <ul>
2395               <li>error.target is the KiiGroup instance which this method was called on.</li>
2396               <li>error.message</li>
2397               <li>error.addMembersArray is array of KiiUser to be added as memebers of this group.</li>
2398               <li>error.removeMembersArray is array of KiiUser to be removed from the memebers list of this group.</li>
2399             </ul>
2400           </li>
2401         </ul>
2402   @example
2403   // example to use callbacks directly
2404   var members = [];
2405   members.push(KiiUser.userWithID("Member User Id"));
2406   KiiGroup.registerGroupWithID("Group ID", "Group Name", members, {
2407       success: function(theSavedGroup) {
2408           // do something with the saved group
2409       },
2410       failure: function(theGroup, anErrorString, addMembersArray, removeMembersArray) {
2411           // do something with the error response
2412       }
2413   });
2414   
2415   // example to use Promise
2416   var members = [];
2417   members.push(KiiUser.userWithID("Member User Id"));
2418   KiiGroup.registerGroupWithID("Group ID", "Group Name", members).then(
2419       function(theSavedGroup) {
2420           // do something with the saved group
2421       },
2422       function(error) {
2423           var theGroup = error.target;
2424           var anErrorString = error.message;
2425           var addMembersArray = error.addMembersArray;
2426           // do something with the error response
2427   });
2428    */
2429 
2430   KiiGroup.registerGroupWithID = function(groupID, groupName, members, callbacks) {
2431     return new Promise(function(resolve, reject) {
2432       var registerGroupWithIDCallbacks, _ref, _ref1;
2433       registerGroupWithIDCallbacks = {
2434         success: function() {
2435           if (callbacks != null) {
2436             callbacks.success.apply(callbacks, arguments);
2437           }
2438           return resolve(arguments[0]);
2439         },
2440         failure: function() {
2441           var error;
2442           if (callbacks != null) {
2443             callbacks.failure.apply(callbacks, arguments);
2444           }
2445           error = KiiUtilities._Error(arguments[1], arguments[0]);
2446           error.addMembersArray = arguments[2];
2447           error.removeMembersArray = arguments[3];
2448           return reject(error);
2449         }
2450       };
2451       return KiiGroup._registerGroupWithIDUsingCallbacks((_ref = root.KiiUser.getCurrentUser()) != null ? _ref.getAccessToken() : void 0, groupID, groupName, (_ref1 = root.Kii.getCurrentUser()) != null ? _ref1.getID() : void 0, members, registerGroupWithIDCallbacks);
2452     });
2453   };
2454 
2455   KiiGroup._registerGroupWithIDUsingCallbacks = function(token, groupID, groupName, owner, members, callbacks) {
2456     var data, i, member, memberIDs, requestCallbacks, url, wrapper, xhr, _i, _len;
2457     if (!KiiUtilities._isNonEmptyString(groupID)) {
2458       callbacks.failure(null, "groupID is null or empty", members, null);
2459       return;
2460     }
2461     if (!KiiUtilities._validateGroupID(groupID)) {
2462       callbacks.failure(null, "invalid groupID : " + groupID, members, null);
2463       return;
2464     }
2465     if (!KiiUtilities._isNonEmptyString(groupName)) {
2466       callbacks.failure(null, "groupName is null or empty", members, null);
2467       return;
2468     }
2469     if (owner == null) {
2470       callbacks.failure(null, "owner is null", members, null);
2471       return;
2472     }
2473     url = root.Kii.getBaseURL() + "/apps/" + root.Kii.getAppID() + "/groups/" + groupID;
2474     wrapper = KiiXHRWrapperFactory.createXHRWrapper("PUT", url);
2475     xhr = wrapper.xhr;
2476     wrapper.setKiiHeaders();
2477     wrapper.setAuthToken(token);
2478     wrapper.setContentType("application/vnd.kii.GroupCreationRequest+json");
2479     data = {};
2480     data.name = groupName;
2481     data.owner = owner;
2482     if ((members != null) && members.length > 0) {
2483       memberIDs = [];
2484       for (i = _i = 0, _len = members.length; _i < _len; i = ++_i) {
2485         member = members[i];
2486         memberIDs.push(member.getID());
2487       }
2488       data.members = memberIDs;
2489     }
2490     requestCallbacks = {
2491       success: function() {
2492         var group;
2493         try {
2494           group = KiiGroup.groupWithNameAndMembers(groupName, members);
2495           group._setUUID(groupID);
2496           return callbacks.success(group);
2497         } catch (_error) {
2498           return callbacks.failure(null, wrapper.getErrorString("failed to register group."));
2499         }
2500       },
2501       failure: function() {
2502         var errString;
2503         errString = wrapper.getErrorString("failed to register group.");
2504         return callbacks.failure(null, errString, members, null);
2505       }
2506     };
2507     return wrapper.sendData(JSON.stringify(data), requestCallbacks);
2508   };
2509 
2510 
2511   /** Creates a reference to a bucket for this group
2512   
2513   <br><br>The bucket will be created/accessed within this group's scope
2514   @param {String} bucketName The name of the bucket the user should create/access
2515   @returns {KiiBucket} A working KiiBucket object
2516   @example
2517   var group = . . .; // a KiiGroup
2518   var bucket = group.bucketWithName("myBucket");
2519    */
2520 
2521   KiiGroup.prototype.bucketWithName = function(bucketName) {
2522     var bucket;
2523     bucket = new root.KiiBucket(bucketName, this);
2524     return bucket;
2525   };
2526 
2527 
2528   /** Creates a reference to a encrypted bucket for this group
2529   
2530   <br><br>The bucket will be created/accessed within this group's scope
2531   @param {String} bucketName The name of the bucket the user should create/access
2532   @returns {KiiEncryptedBucket} A working KiiEncryptedBucket object
2533   @example
2534   var group = . . .; // a KiiGroup
2535   var bucket = group.encryptedBucketWithName("myBucket");
2536    */
2537 
2538   KiiGroup.prototype.encryptedBucketWithName = function(bucketName) {
2539     var bucket;
2540     bucket = new root.KiiEncryptedBucket(bucketName, this);
2541     return bucket;
2542   };
2543 
2544 
2545   /** Adds a user to the given group
2546   
2547   <br><br>This method will NOT access the server immediately. You must call save to add the user on the server. This allows multiple users to be added/removed before calling save.
2548   @param {KiiUser} member The user to be added to the group
2549   @example
2550   var user = . . .; // a KiiUser
2551   var group = . . .; // a KiiGroup
2552   group.addUser(user);
2553   group.save(callbacks);
2554    */
2555 
2556   KiiGroup.prototype.addUser = function(member) {
2557     var userID;
2558     if (member == null) {
2559       root.Kii.logger("Passed member is null");
2560       return;
2561     }
2562     if (member.getUUID() == null) {
2563       root.Kii.logger("Passed member ID is null");
2564       return;
2565     }
2566     userID = member.getUUID();
2567     if (!(userID in this._addMembers)) {
2568       this._addMembers[userID] = member;
2569     }
2570     if (userID in this._removeMembers) {
2571       return delete this._removeMembers[userID];
2572     }
2573   };
2574 
2575 
2576   /** Removes a user from the given group
2577   
2578   <br><br>This method will NOT access the server immediately. You must call save to remove the user on the server. This allows multiple users to be added/removed before calling save.
2579   @param {KiiUser} member The user to be added to the group
2580   @example
2581   var user = . . .; // a KiiUser
2582   var group = . . .; // a KiiGroup
2583   group.removeUser(user);
2584   group.save(callbacks);
2585    */
2586 
2587   KiiGroup.prototype.removeUser = function(member) {
2588     var userID;
2589     if (member == null) {
2590       root.Kii.logger("Passed member is null");
2591       return;
2592     }
2593     if (member.getUUID() == null) {
2594       root.Kii.logger("Passed member uuid is null");
2595       return;
2596     }
2597     userID = member.getUUID();
2598     if (!(userID in this._removeMembers)) {
2599       this._removeMembers[userID] = member;
2600     }
2601     if (userID in this._addMembers) {
2602       return delete this._addMembers[userID];
2603     }
2604   };
2605 
2606   KiiGroup.prototype._addMember = function(member, callback) {
2607     var memberCallbacks, request;
2608     root.Kii.logger("Adding member " + (member.getUUID()) + " to group " + this._groupName);
2609     request = this._getRequest({
2610       path: "/groups/" + this._uuid + "/members/" + (member.getUUID()),
2611       withApp: true
2612     });
2613     request.setMethod("PUT");
2614     memberCallbacks = {
2615       success: (function(_this) {
2616         return function(data, statusCode) {
2617           delete _this._addMembers[member.getUUID()];
2618           return _this._saveMembers(callback);
2619         };
2620       })(this),
2621       failure: (function(_this) {
2622         return function(error, statusCode) {
2623           var addMembersArray, removeMembersArray, userID;
2624           addMembersArray = (function() {
2625             var _ref, _results;
2626             _ref = this._addMembers;
2627             _results = [];
2628             for (userID in _ref) {
2629               member = _ref[userID];
2630               _results.push(member);
2631             }
2632             return _results;
2633           }).call(_this);
2634           removeMembersArray = (function() {
2635             var _ref, _results;
2636             _ref = this._removeMembers;
2637             _results = [];
2638             for (userID in _ref) {
2639               member = _ref[userID];
2640               _results.push(member);
2641             }
2642             return _results;
2643           }).call(_this);
2644           return callback.failure(_this, error, addMembersArray, removeMembersArray);
2645         };
2646       })(this)
2647     };
2648     return request.execute(memberCallbacks, false);
2649   };
2650 
2651   KiiGroup.prototype._removeMember = function(member, callback) {
2652     var removeCallbacks, request;
2653     root.Kii.logger("Removing member " + (member.getUUID()) + " to group " + this._groupName);
2654     request = this._getRequest({
2655       path: "/groups/" + this._uuid + "/members/" + (member.getUUID()),
2656       withApp: true
2657     });
2658     request.setMethod("DELETE");
2659     removeCallbacks = {
2660       success: (function(_this) {
2661         return function(data, statusCode) {
2662           delete _this._getRemoveMembers()[member.getUUID()];
2663           return _this._saveMembers(callback);
2664         };
2665       })(this),
2666       failure: (function(_this) {
2667         return function(error, statusCode) {
2668           var addMembersArray, removeMembersArray, userID;
2669           addMembersArray = (function() {
2670             var _ref, _results;
2671             _ref = this._addMembers;
2672             _results = [];
2673             for (userID in _ref) {
2674               member = _ref[userID];
2675               _results.push(member);
2676             }
2677             return _results;
2678           }).call(_this);
2679           removeMembersArray = (function() {
2680             var _ref, _results;
2681             _ref = this._removeMembers;
2682             _results = [];
2683             for (userID in _ref) {
2684               member = _ref[userID];
2685               _results.push(member);
2686             }
2687             return _results;
2688           }).call(_this);
2689           return callback.failure(_this, error, addMembersArray, removeMembersArray);
2690         };
2691       })(this)
2692     };
2693     return request.execute(removeCallbacks, false);
2694   };
2695 
2696 
2697   /** Gets a list of all current members of a group
2698   @param {Object} [callbacks] An object with callback methods defined
2699   @param {Method} callbacks.success The callback method to call on a successful list request
2700   @param {Method} callbacks.failure The callback method to call on a failed list request
2701   @return {Promise} return promise object.
2702     <ul>
2703       <li>fulfill callback function: function(params). params is Array instance.
2704         <ul>
2705           <li>params[0] is a KiiGroup instance which this method was called on.</li>
2706           <li>params[1] is array of memeber KiiUser instances.</li>
2707         </ul>
2708       </li>
2709       <li>reject callback function: function(error). error is an Error instance.
2710         <ul>
2711           <li>error.target is the KiiGroup instance which this method was called on.</li>
2712           <li>error.message</li>
2713         </ul>
2714       </li>
2715     </ul>
2716   @example
2717   // example to use callbacks directly
2718   var group = . . .; // a KiiGroup
2719   group.getMemberList({
2720       success: function(theGroup, memberList) {
2721           // do something with the result
2722           for(var i=0; i<memberList.length; i++){
2723               var u = memberList[i]; // a KiiUser within the group
2724           }
2725       },
2726   
2727       failure: function(theGroup, anErrorString) {
2728           // do something with the error response
2729       }
2730   });
2731   
2732   // example to use Promise
2733   var group = . . .; // a KiiGroup
2734   group.getMemberList().then(
2735       function(params) {
2736           var theGroup = params[0];
2737           var memberlist = params[1];
2738           // do something with the result
2739           for(var i=0; i<memberList.length; i++){
2740               var u = memberList[i]; // a KiiUser within the group
2741           }
2742       },
2743       function(error) {
2744           // do something with the error response
2745       }
2746   );
2747    */
2748 
2749   KiiGroup.prototype.getMemberList = function(callbacks) {
2750     return new Promise((function(_this) {
2751       return function(resolve, reject) {
2752         var getMemberListCallbacks;
2753         getMemberListCallbacks = {
2754           success: function() {
2755             if (callbacks != null) {
2756               callbacks.success.apply(callbacks, arguments);
2757             }
2758             return resolve(arguments);
2759           },
2760           failure: function() {
2761             if (callbacks != null) {
2762               callbacks.failure.apply(callbacks, arguments);
2763             }
2764             return reject(KiiUtilities._Error(arguments[1], _this));
2765           }
2766         };
2767         return _this._getMemberListUsingCallbacks(getMemberListCallbacks);
2768       };
2769     })(this));
2770   };
2771 
2772   KiiGroup.prototype._getMemberListUsingCallbacks = function(callbacks) {
2773     var listCallbacks, request;
2774     root.Kii.logger("Getting member list for group " + this._groupName);
2775     request = this._getRequest({
2776       path: "/groups/" + this._uuid + "/members",
2777       withApp: true
2778     });
2779     request.setAccept("application/vnd.kii.MembersRetrievalResponse+json");
2780     listCallbacks = {
2781       success: (function(_this) {
2782         return function(data, statusCode) {
2783           var member, memberList, members, _i, _len;
2784           if (statusCode < 300 && statusCode >= 200) {
2785             memberList = [];
2786             members = data['members'];
2787             for (_i = 0, _len = members.length; _i < _len; _i++) {
2788               member = members[_i];
2789               memberList.push(_this._userWithID(member.userID));
2790             }
2791             if (callbacks != null) {
2792               return callbacks.success(_this, memberList);
2793             }
2794           } else if (callbacks != null) {
2795             return callbacks.failure(_this, "Unable to get member list of group");
2796           }
2797         };
2798       })(this),
2799       failure: (function(_this) {
2800         return function(error, statusCode) {
2801           if (callbacks != null) {
2802             return callbacks.failure(_this, error);
2803           }
2804         };
2805       })(this)
2806     };
2807     return request.execute(listCallbacks, false);
2808   };
2809 
2810   KiiGroup.prototype._saveMembers = function(callbacks) {
2811     var addMemberKeys, removeMemberKeys;
2812     addMemberKeys = Object.keys(this._addMembers);
2813     removeMemberKeys = Object.keys(this._removeMembers);
2814     if (addMemberKeys.length === 0 && removeMemberKeys.length === 0) {
2815       callbacks.success(this);
2816     }
2817     if (addMemberKeys.length > 0) {
2818       this._addMember(this._addMembers[addMemberKeys[0]], callbacks);
2819       return;
2820     }
2821     if (removeMemberKeys.length > 0) {
2822       this._removeMember(this._removeMembers[removeMemberKeys[0]], callbacks);
2823     }
2824   };
2825 
2826   KiiGroup.prototype._changeOwner = function(owner, callbacks) {
2827     var data, request, saveCallbacks;
2828     request = this._getRequest({
2829       path: "/groups/" + this._uuid + "/owner",
2830       withApp: true
2831     });
2832     request.setContentType("application/vnd.kii.GroupOwnerChangeRequest+json");
2833     request.setMethod("PUT");
2834     data = {};
2835     data.owner = owner;
2836     request.setData(data);
2837     saveCallbacks = {
2838       success: (function(_this) {
2839         return function(data, statusCode) {
2840           if (statusCode < 300 && statusCode >= 200) {
2841             return callbacks.success(_this);
2842           }
2843         };
2844       })(this),
2845       failure: (function(_this) {
2846         return function(error, statusCode) {
2847           if (callbacks != null) {
2848             return callbacks.failure(_this, error);
2849           }
2850         };
2851       })(this)
2852     };
2853     return request.execute(saveCallbacks, false);
2854   };
2855 
2856 
2857   /** Updates the group name on the server
2858   
2859   @param {String} newName A String of the desired group name
2860   @param {Object} [callbacks] An object with callback methods defined
2861   @param {Method} callbacks.success The callback method to call on a successful save request
2862   @param {Method} callbacks.failure The callback method to call on a failed save request
2863   @return {Promise} return promise object.
2864     <ul>
2865       <li>fulfill callback function: function(theRenamedGroup). theRenamedGroup is KiiGroup instance.</li>
2866       <li>reject callback function: function(error). error is an Error instance.
2867         <ul>
2868           <li>error.target is the KiiGroup instance which this method was called on.</li>
2869           <li>error.message</li>
2870         </ul>
2871       </li>
2872     </ul>
2873   @example
2874   // example to use callbacks directly
2875   var group = . . .; // a KiiGroup
2876   group.changeGroupName("myNewName", {
2877       success: function(theRenamedGroup) {
2878           // do something with the group
2879       },
2880   
2881       failure: function(theGroup, anErrorString) {
2882           // do something with the error response
2883       }
2884   });
2885   
2886   // example to use Promise
2887   var group = . . .; // a KiiGroup
2888   group.changeGroupName("myNewName").then(
2889       function(theRenamedGroup) {
2890           // do something with the group
2891       },
2892       function(error) {
2893           // do something with the error response
2894       }
2895   );
2896    */
2897 
2898   KiiGroup.prototype.changeGroupName = function(newName, callbacks) {
2899     return new Promise((function(_this) {
2900       return function(resolve, reject) {
2901         var changeGroupNameCallbacks;
2902         changeGroupNameCallbacks = {
2903           success: function() {
2904             if (callbacks != null) {
2905               callbacks.success.apply(callbacks, arguments);
2906             }
2907             return resolve(arguments[0]);
2908           },
2909           failure: function() {
2910             if (callbacks != null) {
2911               callbacks.failure.apply(callbacks, arguments);
2912             }
2913             return reject(KiiUtilities._Error(arguments[1], _this));
2914           }
2915         };
2916         return _this._changeGroupNameUsingCallbacks(newName, changeGroupNameCallbacks);
2917       };
2918     })(this));
2919   };
2920 
2921   KiiGroup.prototype._changeGroupNameUsingCallbacks = function(newName, callbacks) {
2922     var request, saveCallbacks;
2923     root.Kii.logger("Saving group: " + this.name);
2924     if (this._uuid != null) {
2925       request = this._getRequest({
2926         path: "/groups/" + this._uuid + "/name",
2927         withApp: true
2928       });
2929       request.setContentType("text/plain");
2930       request.setMethod("PUT");
2931       request.setData(newName);
2932       saveCallbacks = {
2933         success: (function(_this) {
2934           return function(data, statusCode) {
2935             if (statusCode < 300 && statusCode >= 200) {
2936               _this._setName(newName);
2937               if (callbacks != null) {
2938                 return callbacks.success(_this);
2939               }
2940             } else if (callbacks != null) {
2941               return callbacks.failure(_this, "Unable to change group name - invalid response");
2942             }
2943           };
2944         })(this),
2945         failure: (function(_this) {
2946           return function(error, statusCode) {
2947             if (callbacks != null) {
2948               return callbacks.failure(_this, error);
2949             }
2950           };
2951         })(this)
2952       };
2953       return request.execute(saveCallbacks, true);
2954     } else {
2955       return callbacks.failure(this, "Invalid group. Save the group on the server before updating the name.");
2956     }
2957   };
2958 
2959 
2960   /** Saves the latest group values to the server
2961   
2962   <br><br>If the group does not yet exist, it will be created. If the group already exists, the members that have changed will be updated accordingly. If the group already exists and there is no updates of members, it will allways succeed but does not execute update. To change the name of group, use {@link #changeGroupName}.
2963   @param {Object} [callbacks] An object with callback methods defined
2964   @param {Method} callbacks.success The callback method to call on a successful save request
2965   @param {Method} callbacks.failure The callback method to call on a failed save request
2966   @return {Promise} return promise object.
2967         <ul>
2968           <li>fulfill callback function: function(theSavedGroup). theSavedGroup is KiiGroup instance.</li>
2969           <li>reject callback function: function(error). error is an Error instance.
2970             <ul>
2971               <li>error.target is the KiiGroup instance which this method was called on.</li>
2972               <li>error.message</li>
2973               <li>error.addMembersArray is array of KiiUser to be added as memebers of this group.</li>
2974               <li>error.removeMembersArray is array of KiiUser to be removed from the memebers list of this group.</li>
2975             </ul>
2976           </li>
2977         </ul>
2978   @example
2979   // example to use callbacks directly
2980   var group = . . .; // a KiiGroup
2981   group.save({
2982       success: function(theSavedGroup) {
2983           // do something with the saved group
2984       },
2985   
2986       failure: function(theGroup, anErrorString, addMembersArray, removeMembersArray) {
2987           // do something with the error response
2988       }
2989   });
2990   
2991   // example to use Promise
2992   var group = . . .; // a KiiGroup
2993   group.save().then(
2994       function(theSavedGroup) {
2995           // do something with the saved group
2996       },
2997       function(error) {
2998           var theGroup = error.target;
2999           var anErrorString = error.message;
3000           var addMembersArray = error.addMembersArray;
3001           var removeMembersArray = error.removeMembersArray;
3002           // do something with the error response
3003   });
3004    */
3005 
3006   KiiGroup.prototype.save = function(callbacks) {
3007     return new Promise((function(_this) {
3008       return function(resolve, reject) {
3009         var saveCallbacks;
3010         saveCallbacks = {
3011           success: function() {
3012             if (callbacks != null) {
3013               callbacks.success.apply(callbacks, arguments);
3014             }
3015             return resolve(arguments[0]);
3016           },
3017           failure: function() {
3018             var error;
3019             if (callbacks != null) {
3020               callbacks.failure.apply(callbacks, arguments);
3021             }
3022             error = KiiUtilities._Error(arguments[1], _this);
3023             error.addMembersArray = arguments[2];
3024             error.removeMembersArray = arguments[3];
3025             return reject(error);
3026           }
3027         };
3028         return _this._saveUsingCallbacks(saveCallbacks);
3029       };
3030     })(this));
3031   };
3032 
3033   KiiGroup.prototype._saveUsingCallbacks = function(callbacks) {
3034     var data, request, saveCallbacks;
3035     root.Kii.logger("Saving group: " + this.name);
3036     if (this._uuid == null) {
3037       request = this._getRequest({
3038         path: "/groups",
3039         withApp: true
3040       });
3041       request.setContentType("application/vnd.kii.GroupCreationRequest+json");
3042       request.setMethod("POST");
3043       data = {};
3044       if (this._groupName != null) {
3045         data.name = this._groupName;
3046       }
3047       this._setOwnerFromContext(data);
3048       request.setData(data);
3049       saveCallbacks = {
3050         success: (function(_this) {
3051           return function(data, statusCode) {
3052             if (statusCode < 300 && statusCode >= 200) {
3053               _this._setUUID(data.groupID);
3054               return _this._saveMembers(callbacks);
3055             }
3056           };
3057         })(this),
3058         failure: (function(_this) {
3059           return function(error, statusCode) {
3060             var addMembersArray, member, removeMembersArray, userID;
3061             if (callbacks != null) {
3062               addMembersArray = (function() {
3063                 var _ref, _results;
3064                 _ref = this._addMembers;
3065                 _results = [];
3066                 for (userID in _ref) {
3067                   member = _ref[userID];
3068                   _results.push(member);
3069                 }
3070                 return _results;
3071               }).call(_this);
3072               removeMembersArray = (function() {
3073                 var _ref, _results;
3074                 _ref = this._removeMembers;
3075                 _results = [];
3076                 for (userID in _ref) {
3077                   member = _ref[userID];
3078                   _results.push(member);
3079                 }
3080                 return _results;
3081               }).call(_this);
3082               return callbacks.failure(_this, error, addMembersArray, removeMembersArray);
3083             }
3084           };
3085         })(this)
3086       };
3087       return request.execute(saveCallbacks, false);
3088     } else {
3089       return this._saveMembers(callbacks);
3090     }
3091   };
3092 
3093 
3094   /** Saves the latest group values to the server with specified owner.
3095   This method can be used only by the group owner or app admin.
3096   
3097   <br><br>If the group does not yet exist, it will be created. If the group already exists, the members and owner that have changed will be updated accordingly. If the group already exists and there is no updates of members and owner, it will allways succeed but does not execute update. To change the name of group, use {@link #changeGroupName}.
3098   @param {String} user id of owner
3099   @param {Object} [callbacks] An object with callback methods defined
3100   @param {Method} callbacks.success The callback method to call on a successful save request
3101   @param {Method} callbacks.failure The callback method to call on a failed save request
3102   @return {Promise} return promise object.
3103         <ul>
3104           <li>fulfill callback function: function(theSavedGroup). theSavedGroup is KiiGroup instance.</li>
3105           <li>reject callback function: function(error). error is an Error instance.
3106             <ul>
3107               <li>error.target is the KiiGroup instance which this method was called on.</li>
3108               <li>error.message</li>
3109               <li>error.addMembersArray is array of KiiUser to be added as memebers of this group.</li>
3110               <li>error.removeMembersArray is array of KiiUser to be removed from the memebers list of this group.</li>
3111             </ul>
3112           </li>
3113         </ul>
3114   @example
3115   // example to use callbacks directly
3116   var group = . . .; // a KiiGroup
3117   group.saveWithOwner("UserID of owner", {
3118       success: function(theSavedGroup) {
3119           // do something with the saved group
3120       },
3121   
3122       failure: function(theGroup, anErrorString, addMembersArray, removeMembersArray) {
3123           // do something with the error response
3124       }
3125   });
3126   
3127   // example to use Promise
3128   var group = . . .; // a KiiGroup
3129   group.saveWithOwner("UserID of owner").then(
3130       function(theSavedGroup) {
3131           // do something with the saved group
3132       },
3133       function(error) {
3134           var theGroup = error.target;
3135           var anErrorString = error.message;
3136           var addMembersArray = error.addMembersArray;
3137           var removeMembersArray = error.removeMembersArray;
3138           // do something with the error response
3139   });
3140    */
3141 
3142   KiiGroup.prototype.saveWithOwner = function(owner, callbacks) {
3143     return new Promise((function(_this) {
3144       return function(resolve, reject) {
3145         var saveCallbacks;
3146         saveCallbacks = {
3147           success: function() {
3148             if (callbacks != null) {
3149               callbacks.success.apply(callbacks, arguments);
3150             }
3151             return resolve(arguments[0]);
3152           },
3153           failure: function() {
3154             var error;
3155             if (callbacks != null) {
3156               callbacks.failure.apply(callbacks, arguments);
3157             }
3158             error = KiiUtilities._Error(arguments[1], _this);
3159             error.addMembersArray = arguments[2];
3160             error.removeMembersArray = arguments[3];
3161             return reject(error);
3162           }
3163         };
3164         return _this._saveWithOwnerUsingCallbacks(owner, saveCallbacks);
3165       };
3166     })(this));
3167   };
3168 
3169   KiiGroup.prototype._saveWithOwnerUsingCallbacks = function(owner, callbacks) {
3170     var data, request, saveCallbacks, saveMemberCallbacks;
3171     if (this._uuid == null) {
3172       request = this._getRequest({
3173         path: "/groups",
3174         withApp: true
3175       });
3176       request.setContentType("application/vnd.kii.GroupCreationRequest+json");
3177       request.setMethod("POST");
3178       data = {};
3179       if (this._groupName != null) {
3180         data.name = this._groupName;
3181       }
3182       data.owner = owner;
3183       request.setData(data);
3184       saveCallbacks = {
3185         success: (function(_this) {
3186           return function(data, statusCode) {
3187             if (statusCode < 300 && statusCode >= 200) {
3188               _this._setUUID(data.groupID);
3189               return _this._saveMembers(callbacks);
3190             }
3191           };
3192         })(this),
3193         failure: (function(_this) {
3194           return function(error, statusCode) {
3195             var addMembersArray, member, removeMembersArray, userID;
3196             if (callbacks != null) {
3197               addMembersArray = (function() {
3198                 var _ref, _results;
3199                 _ref = this._addMembers;
3200                 _results = [];
3201                 for (userID in _ref) {
3202                   member = _ref[userID];
3203                   _results.push(member);
3204                 }
3205                 return _results;
3206               }).call(_this);
3207               removeMembersArray = (function() {
3208                 var _ref, _results;
3209                 _ref = this._removeMembers;
3210                 _results = [];
3211                 for (userID in _ref) {
3212                   member = _ref[userID];
3213                   _results.push(member);
3214                 }
3215                 return _results;
3216               }).call(_this);
3217               return callbacks.failure(_this, error, addMembersArray, removeMembersArray);
3218             }
3219           };
3220         })(this)
3221       };
3222       return request.execute(saveCallbacks, false);
3223     } else {
3224       saveMemberCallbacks = {
3225         success: (function(_this) {
3226           return function(group) {
3227             return _this._changeOwner(owner, callbacks);
3228           };
3229         })(this),
3230         failure: (function(_this) {
3231           return function(group, error) {
3232             var addMembersArray, member, removeMembersArray, userID;
3233             addMembersArray = (function() {
3234               var _ref, _results;
3235               _ref = this._addMembers;
3236               _results = [];
3237               for (userID in _ref) {
3238                 member = _ref[userID];
3239                 _results.push(member);
3240               }
3241               return _results;
3242             }).call(_this);
3243             removeMembersArray = (function() {
3244               var _ref, _results;
3245               _ref = this._removeMembers;
3246               _results = [];
3247               for (userID in _ref) {
3248                 member = _ref[userID];
3249                 _results.push(member);
3250               }
3251               return _results;
3252             }).call(_this);
3253             return callbacks.failure(_this, error, addMembersArray, removeMembersArray);
3254           };
3255         })(this)
3256       };
3257       return this._saveMembers(saveMemberCallbacks);
3258     }
3259   };
3260 
3261 
3262   /** Updates the local group's data with the group data on the server
3263   
3264   <br><br>The group must exist on the server. Local data will be overwritten.
3265   @param {Object} [callbacks] An object with callback methods defined
3266   @param {Method} callbacks.success The callback method to call on a successful refresh request
3267   @param {Method} callbacks.failure The callback method to call on a failed refresh request
3268   @return {Promise} return promise object.
3269     <ul>
3270       <li>fulfill callback function: function(theRefreshedGroup). theRefreshedGroup is KiiGroup instance.</li>
3271       <li>reject callback function: function(error). error is an Error instance.
3272         <ul>
3273           <li>error.target is the KiiGroup instance which this method was called on.</li>
3274           <li>error.message</li>
3275         </ul>
3276       </li>
3277     </ul>
3278   @example
3279   // example to use callbacks directly
3280   var group = . . .; // a KiiGroup
3281   group.refresh({
3282       success: function(theRefreshedGroup) {
3283           // do something with the refreshed group
3284       },
3285   
3286       failure: function(theGroup, anErrorString) {
3287           // do something with the error response
3288       }
3289   });
3290   
3291   // example to use Promise
3292   var group = . . .; // a KiiGroup
3293   group.refresh().then(
3294       function(theRefreshedGroup) {
3295           // do something with the refreshed group
3296       },
3297       function(error) {
3298           // do something with the error response
3299       }
3300   );
3301    */
3302 
3303   KiiGroup.prototype.refresh = function(callbacks) {
3304     return new Promise((function(_this) {
3305       return function(resolve, reject) {
3306         var refreshCallbacks;
3307         refreshCallbacks = {
3308           success: function() {
3309             if (callbacks != null) {
3310               callbacks.success.apply(callbacks, arguments);
3311             }
3312             return resolve(arguments[0]);
3313           },
3314           failure: function() {
3315             if (callbacks != null) {
3316               callbacks.failure.apply(callbacks, arguments);
3317             }
3318             return reject(KiiUtilities._Error(arguments[1], _this));
3319           }
3320         };
3321         return _this._refreshUsingCallbacks(refreshCallbacks);
3322       };
3323     })(this));
3324   };
3325 
3326   KiiGroup.prototype._refreshUsingCallbacks = function(callbacks) {
3327     var refreshCallbacks, request;
3328     root.Kii.logger("Refreshing group: " + this._groupName);
3329     request = new this._getRequest({
3330       path: "/groups/" + this._uuid,
3331       withApp: true
3332     });
3333     request.setAccept("application/vnd.kii.GroupRetrievalResponse+json");
3334     refreshCallbacks = {
3335       success: (function(_this) {
3336         return function(data, statusCode) {
3337           _this._updateWithJSON(data);
3338           if (callbacks != null) {
3339             return callbacks.success(_this);
3340           }
3341         };
3342       })(this),
3343       failure: (function(_this) {
3344         return function(error, statusCode) {
3345           if (callbacks != null) {
3346             return callbacks.failure(_this, error);
3347           }
3348         };
3349       })(this)
3350     };
3351     return request.execute(refreshCallbacks, false);
3352   };
3353 
3354 
3355   /** Delete the group from the server
3356   @name delete
3357   @memberOf root.KiiGroup#
3358   @function
3359   @param {Object} [callbacks] An object with callback methods defined
3360   @param {Method} callbacks.success The callback method to call on a successful delete request
3361   @param {Method} callbacks.failure The callback method to call on a failed delete request
3362   @return {Promise} return promise object.
3363     <ul>
3364       <li>fulfill callback function: function(theDeletedGroup). theDeletedGroup is KiiGroup instance.</li>
3365       <li>reject callback function: function(error). error is an Error instance.
3366         <ul>
3367           <li>error.target is the KiiGroup instance which this method was called on.</li>
3368           <li>error.message</li>
3369         </ul>
3370       </li>
3371     </ul>
3372   @example
3373   // example to use callbacks directly
3374   var group = . . .; // a KiiGroup
3375   group.delete({
3376       success: function(theDeletedGroup) {
3377           // do something
3378       },
3379   
3380       failure: function(theGroup, anErrorString) {
3381           // do something with the error response
3382       }
3383   });
3384   
3385   // example to use Promise
3386   var group = . . .; // a KiiGroup
3387   group.delete({
3388       success: function(theDeletedGroup) {
3389       },
3390   
3391       failure: function(theGroup, anErrorString) {
3392       }
3393   }).then(
3394       function(theDeletedGroup) {
3395           // do something
3396       },
3397       function(error) {
3398           // do something with the error response
3399       }
3400   );
3401    */
3402 
3403   KiiGroup.prototype["delete"] = function(callbacks) {
3404     return new Promise((function(_this) {
3405       return function(resolve, reject) {
3406         var deleteCallbacks;
3407         deleteCallbacks = {
3408           success: function() {
3409             if (callbacks != null) {
3410               callbacks.success.apply(callbacks, arguments);
3411             }
3412             return resolve(arguments[0]);
3413           },
3414           failure: function() {
3415             if (callbacks != null) {
3416               callbacks.failure.apply(callbacks, arguments);
3417             }
3418             return reject(KiiUtilities._Error(arguments[1], _this));
3419           }
3420         };
3421         return _this._deleteUsingCallbacks(deleteCallbacks);
3422       };
3423     })(this));
3424   };
3425 
3426   KiiGroup.prototype._deleteUsingCallbacks = function(callbacks) {
3427     var deleteCallbacks, request;
3428     root.Kii.logger("Deleting group: " + this._groupName);
3429     request = this._getRequest({
3430       path: "/groups/" + this._uuid,
3431       withApp: true
3432     });
3433     request.setMethod("DELETE");
3434     deleteCallbacks = {
3435       success: (function(_this) {
3436         return function(data, statusCode) {
3437           if (statusCode < 300 && statusCode >= 200 && (callbacks != null)) {
3438             return callbacks.success(_this);
3439           } else if (callbacks != null) {
3440             return callbacks.failure(_this, "Unable to parse response");
3441           }
3442         };
3443       })(this),
3444       failure: (function(_this) {
3445         return function(error, statusCode) {
3446           if (callbacks != null) {
3447             return callbacks.failure(_this, error);
3448           }
3449         };
3450       })(this)
3451     };
3452     return request.execute(deleteCallbacks, true);
3453   };
3454 
3455 
3456   /** Gets the owner of the associated group
3457   
3458   This API does not return all the properties of the owner.
3459   To get all owner properties, {@link KiiUser#refresh} is necessary.
3460   
3461   @param {Object} [callbacks] An object with callback methods defined
3462   @param {Method} callbacks.success The callback method to call on a successful add request
3463   @param {Method} callbacks.failure The callback method to call on a failed add request
3464   @return {Promise} return promise object.
3465     <ul>
3466       <li>fulfill callback function: function(params). params is Array instance.
3467         <ul>
3468           <li>params[0] is the KiiGroup instance which this method was called on.</li>
3469           <li>params[1] is an group owner KiiUser instances.</li>
3470         </ul>
3471       </li>
3472       <li>reject callback function: function(error). error is an Error instance.
3473         <ul>
3474           <li>error.target is the KiiGroup instance which this method was called on.</li>
3475           <li>error.message</li>
3476         </ul>
3477       </li>
3478     </ul>
3479   @example
3480   // example to use callbacks directly
3481   var group = . . .; // a KiiGroup
3482   group.getOwner({
3483       success: function(theGroup, theOwner) {
3484           // do something
3485       },
3486       failure: function(theGroup, anErrorString) {
3487           // do something with the error response
3488       }
3489   });
3490   
3491   // example to use Promise
3492   var group = . . .; // a KiiGroup
3493   group.getOwner().then(
3494       function(params) {
3495           // do something
3496       },
3497       function(error) {
3498           // do something with the error response
3499       }
3500   );
3501    */
3502 
3503   KiiGroup.prototype.getOwner = function(callbacks) {
3504     return new Promise((function(_this) {
3505       return function(resolve, reject) {
3506         var getOwnerCallbacks;
3507         getOwnerCallbacks = {
3508           success: function() {
3509             if (callbacks != null) {
3510               callbacks.success.apply(callbacks, arguments);
3511             }
3512             return resolve(arguments);
3513           },
3514           failure: function() {
3515             if (callbacks != null) {
3516               callbacks.failure.apply(callbacks, arguments);
3517             }
3518             return reject(KiiUtilities._Error(arguments[1], _this));
3519           }
3520         };
3521         return _this._getOwnerUsingCallbacks(getOwnerCallbacks);
3522       };
3523     })(this));
3524   };
3525 
3526   KiiGroup.prototype._getOwnerUsingCallbacks = function(callbacks) {
3527     root.Kii.logger("Getting owner of group " + this._groupName);
3528     return this.refresh({
3529       success: (function(_this) {
3530         return function(group) {
3531           if (callbacks != null) {
3532             return callbacks.success(group, group.getCachedOwner());
3533           }
3534         };
3535       })(this),
3536       failure: (function(_this) {
3537         return function(group, error) {
3538           if (callbacks != null) {
3539             return callbacks.failure(group, error);
3540           }
3541         };
3542       })(this)
3543     });
3544   };
3545 
3546 
3547   /** Creates a reference to a group with the given name
3548   <br><br>
3549   <b>Note:</b>
3550   Returned instance from this API can not operate existing KiiGroup.<br>
3551   If you want to operate existing KiiGroup, please use {@link KiiGroup.groupWithURI}.
3552   
3553   @param {String} groupName An application-specific group name
3554   @returns {KiiGroup} A new KiiGroup reference
3555   @example
3556   var group = new KiiGroup.groupWithName("myGroup");
3557    */
3558 
3559   KiiGroup.groupWithName = function(groupName) {
3560     return root.KiiGroup.groupWithNameAndMembers(groupName, null);
3561   };
3562 
3563 
3564   /** Creates a reference to a group with the given name and a list of default members
3565   <br><br>
3566   <b>Note:</b>
3567   Returned instance from this API can not operate existing KiiGroup.<br>
3568   If you want to operate existing KiiGroup, please use {@link KiiGroup.groupWithURI}.
3569   
3570   @param {String} groupName An application-specific group name
3571   @param {Array} members An array of KiiUser objects to add to the group
3572   @returns {KiiGroup} A new KiiGroup reference
3573   @example
3574   var group = new KiiGroup.groupWithName("myGroup", members);
3575    */
3576 
3577   KiiGroup.groupWithNameAndMembers = function(groupName, members) {
3578     var group;
3579     group = new root.KiiGroup();
3580     group._setName(groupName);
3581     group._setAddMembers(members);
3582     return group;
3583   };
3584 
3585 
3586   /** Instantiate KiiGroup that refers to existing group which has specified ID.
3587   You have to specify the ID of existing KiiGroup. Unlike KiiObject,
3588   you can not assign ID in the client side.<br>
3589   <b>NOTE</b>: This API does not access to the server.
3590   After instantiation, call {@link KiiGroup#refresh} to fetch the properties.
3591   @param groupId ID of the KiiGroup to instantiate.
3592   @return instance of KiiGroup.
3593   @throws {InvalidArgumentException} when passed groupID is empty or null.
3594   @example
3595   var group = new KiiUser.groupWithID("__GROUP_ID__");
3596    */
3597 
3598   KiiGroup.groupWithID = function(groupID) {
3599     var group;
3600     if ((groupID == null) || groupID === "") {
3601       throw new root.InvalidArgumentException('groupID should not null or empty');
3602     }
3603     group = new root.KiiGroup();
3604     group._setUUID(groupID);
3605     return group;
3606   };
3607 
3608 
3609   /** Generate a new KiiGroup based on a given URI
3610   <br><br>
3611   <b>Note:</b>
3612   Returned instance from this API can operate existing KiiGroup.<br>
3613   If you want to create a new KiiGroup, please use {@link KiiGroup.groupWithName}.
3614   
3615   @param {String} uri The URI of the group to be represented
3616   @returns {KiiGroup} A new KiiGroup with its parameters filled in from the URI
3617   @throws {InvalidURIException} If the URI given is invalid
3618   @example
3619   var group = new KiiGroup.groupWithURI("kiicloud://myuri");
3620    */
3621 
3622   KiiGroup.groupWithURI = function(uri) {
3623     var compLength, components, group, newURI;
3624     group = null;
3625     newURI = uri.substr("kiicloud://".length);
3626     components = newURI.split("/");
3627     compLength = components.length;
3628     if (compLength > 0) {
3629       group = new root.KiiGroup();
3630       group._setUUID(components[compLength - 1]);
3631     } else {
3632       throw new root.InvalidURIException;
3633     }
3634     return group;
3635   };
3636 
3637   KiiGroup._groupWithJSON = function(json) {
3638     var group;
3639     group = new root.KiiGroup();
3640     if (json.groupID != null) {
3641       group._setUUID(json.groupID);
3642     }
3643     if (json.name != null) {
3644       group._setName(json.name);
3645     }
3646     if (json.owner != null) {
3647       group._setOwner(root.KiiUser.userWithID(json.owner));
3648     }
3649     return group;
3650   };
3651 
3652   KiiGroup.prototype._updateWithJSON = function(json) {
3653     if (json.groupID != null) {
3654       this._setUUID(json.groupID);
3655     }
3656     if (json.name != null) {
3657       this._setName(json.name);
3658     } else {
3659       this._setName(null);
3660     }
3661     if (json.owner != null) {
3662       return this._setOwner(this._userWithID(json.owner));
3663     } else {
3664       return this._setOwner(null);
3665     }
3666   };
3667 
3668   KiiGroup.prototype._getRequest = function(spec) {
3669     var path, request, withApp;
3670     path = spec.path;
3671     withApp = spec.withApp;
3672     request = new KiiRequest(path, withApp);
3673     return request;
3674   };
3675 
3676   KiiGroup.prototype._userWithID = function(id) {
3677     var user;
3678     user = root.KiiUser.userWithID(id);
3679     return user;
3680   };
3681 
3682   KiiGroup.prototype._setOwnerFromContext = function(data) {
3683     if (root.Kii.getCurrentUser() != null) {
3684       this._owner = root.Kii.getCurrentUser();
3685       return data.owner = this._owner.getUUID();
3686     }
3687   };
3688 
3689 
3690   /**
3691   Instantiate topic belongs to this group.
3692   @param {String} topicName name of the topic. Must be a not empty string.
3693   @return {KiiTopic} topic instance.
3694    */
3695 
3696   KiiGroup.prototype.topicWithName = function(topicName) {
3697     var id, puri;
3698     if (typeof topicName !== "string" || topicName === "") {
3699       throw new root.InvalidArgumentException('topicName should not null or empty');
3700     }
3701     id = this.getID();
3702     if (!id) {
3703       throw 'can not instantiate topic from instance which doesn\'t have ID';
3704     }
3705     puri = this._getHttpURI();
3706     return new root.KiiTopic(puri, topicName);
3707   };
3708 
3709 
3710   /** Gets a list of topics in this group scope
3711   @param {Object} [callbacks] An object with callback methods defined
3712   @param {Method} callbacks.success The callback method to call on a successful list request
3713   @param {Method} callbacks.failure The callback method to call on a failed list request
3714   @param {String} [paginationKey] You can specify the pagination key with the nextPaginationKey passed by callbacks.success. If empty string or no string object is provided, this API regards no paginationKey specified.
3715   @return {Promise} return promise object.
3716       <ul>
3717         <li>fulfill callback function: function(params). params is Array instance.
3718           <ul>
3719             <li>params[0] is array of KiiTopic instances.</li>
3720             <li>params[1] is string of nextPaginationKey.</li>
3721           </ul>
3722         </li>
3723         <li>reject callback function: function(error). error is an Error instance.
3724           <ul>
3725             <li>error.target is the KiiGroup instance which this method was called on. </li>
3726             <li>error.message</li>
3727           </ul>
3728         </li>
3729       </ul>
3730   @example
3731   // example to use callbacks directly
3732   var group = . . .; // a KiiGroup
3733   group.listTopics({
3734       success: function(topicList, nextPaginationKey) {
3735           // do something with the result
3736           for(var i=0; i<topicList.length; i++){
3737               var topic = topicList[i];
3738           }
3739           if (nextPaginationKey != null) {
3740               group.listTopics({
3741                   success: function(topicList, nextPaginationKey) {...},
3742                   failure: function(anErrorString) {...}
3743               }, nextPaginationKey);
3744           }
3745       },
3746       failure: function(anErrorString) {
3747           // do something with the error response
3748       }
3749   });
3750   
3751   // example to use promise
3752   var group = . . .; // a KiiGroup
3753   group.listTopics().then(
3754       function(params) {
3755           var topicList = params[0];
3756           var nextPaginationKey = params[1];
3757           // do something with the result
3758           for(var i=0; i<topicList.length; i++){
3759               var topic = topicList[i];
3760           }
3761           if (nextPaginationKey != null) {
3762               group.listTopics(null, nextPaginationKey).then(
3763                   function(params) {...},
3764                   function(error) {...}
3765               );
3766           }
3767       },
3768       function(error) {
3769           // do something with the error response
3770       }
3771   );
3772    */
3773 
3774   KiiGroup.prototype.listTopics = function(callbacks, paginationKey) {
3775     return new Promise((function(_this) {
3776       return function(resolve, reject) {
3777         var listTopicsCallbacks;
3778         listTopicsCallbacks = {
3779           success: function() {
3780             if (callbacks != null) {
3781               callbacks.success.apply(callbacks, arguments);
3782             }
3783             return resolve(arguments);
3784           },
3785           failure: function() {
3786             if (callbacks != null) {
3787               callbacks.failure.apply(callbacks, arguments);
3788             }
3789             return reject(arguments[0]);
3790           }
3791         };
3792         return _this._listTopicsUsingCallbacks(listTopicsCallbacks, paginationKey);
3793       };
3794     })(this));
3795   };
3796 
3797   KiiGroup.prototype._listTopicsUsingCallbacks = function(callbacks, paginationKey) {
3798     var listCallbacks, uri, wrapper;
3799     uri = "" + (this._getHttpURI()) + "/topics";
3800     if (typeof paginationKey === "string" && paginationKey !== "") {
3801       uri = uri + "?paginationKey=" + encodeURIComponent(paginationKey);
3802     }
3803     wrapper = KiiXHRWrapperFactory.createXHRWrapper('GET', uri);
3804     wrapper.setKiiHeaders();
3805     this._setAuthToken(wrapper);
3806     listCallbacks = {
3807       success: (function(_this) {
3808         return function() {
3809           var json, topic, topics, _i, _len, _ref;
3810           json = JSON.parse(wrapper.xhr.responseText);
3811           topics = [];
3812           _ref = json.topics;
3813           for (_i = 0, _len = _ref.length; _i < _len; _i++) {
3814             topic = _ref[_i];
3815             topics.push(_this.topicWithName(topic.topicID));
3816           }
3817           return callbacks != null ? callbacks.success(topics, (json.paginationKey === void 0 ? null : json.paginationKey)) : void 0;
3818         };
3819       })(this),
3820       failure: (function(_this) {
3821         return function() {
3822           var errObj, errString;
3823           errString = wrapper.getErrorString("list topics");
3824           errObj = KiiUtilities._Error(errString, _this);
3825           return callbacks != null ? callbacks.failure(errObj) : void 0;
3826         };
3827       })(this)
3828     };
3829     return wrapper.send(listCallbacks);
3830   };
3831 
3832   KiiGroup.prototype._getHttpURI = function() {
3833     return "" + (root.Kii.getBaseURL()) + "/apps/" + (root.Kii.getAppID()) + "/groups/" + (this.getID());
3834   };
3835 
3836   KiiGroup.prototype._setAuthToken = function(wrapper) {
3837     return wrapper.setCurrentUserToken();
3838   };
3839 
3840   return KiiGroup;
3841 
3842 })();
3843 
3844 
3845 /**
3846     @class Represents a KiiObject object
3847     @exports root.KiiObject as KiiObject
3848  */
3849 
3850 root.KiiObject = (function() {
3851 
3852   /** Get the UUID of the given object, assigned by the server
3853   @returns {String}
3854    */
3855   KiiObject.prototype.getUUID = function() {
3856     return this._uuid;
3857   };
3858 
3859   KiiObject.prototype._setUUID = function(_uuid) {
3860     this._uuid = _uuid;
3861   };
3862 
3863 
3864   /** Get Id of the object or null if the object ID hasn't been assigned.
3865   @returns {String}
3866    */
3867 
3868   KiiObject.prototype.getID = function() {
3869     return this._uuid;
3870   };
3871 
3872 
3873   /** Get the server's creation date of this object
3874   @returns {String}
3875    */
3876 
3877   KiiObject.prototype.getCreated = function() {
3878     return this._created;
3879   };
3880 
3881   KiiObject.prototype._setCreated = function(_created) {
3882     this._created = _created;
3883   };
3884 
3885 
3886   /** Get the modified date of the given object, assigned by the server
3887   @returns {String}
3888    */
3889 
3890   KiiObject.prototype.getModified = function() {
3891     return this._modified;
3892   };
3893 
3894   KiiObject.prototype._setModified = function(_modified) {
3895     this._modified = _modified;
3896   };
3897 
3898 
3899   /** Get the application-defined type name of the object
3900   @returns {String} type of this object. null or undefined if none exists
3901    */
3902 
3903   KiiObject.prototype.getObjectType = function() {
3904     return this._objectType;
3905   };
3906 
3907   KiiObject.prototype._setObjectType = function(_objectType) {
3908     this._objectType = _objectType;
3909   };
3910 
3911   KiiObject.prototype.getBucket = function() {
3912     root.Kii.logger("GEtting bucket " + this._bucket);
3913     return this._bucket;
3914   };
3915 
3916   KiiObject.prototype._setBucket = function(_bucket) {
3917     this._bucket = _bucket;
3918   };
3919 
3920 
3921   /** Get the body content-type.
3922   It will be updated after the success of {@link KiiObject#uploadBody} and {@link KiiObject#downloadBody}
3923   returns null or undefined when this object doesn't have body content-type information.
3924   @returns {String} content-type of object body
3925    */
3926 
3927   KiiObject.prototype.getBodyContentType = function() {
3928     return this._bodyContentType;
3929   };
3930 
3931   KiiObject.prototype._setBodyContentType = function(_bodyContentType) {
3932     this._bodyContentType = _bodyContentType;
3933   };
3934 
3935   function KiiObject() {
3936     this._deleteBodyUsingCallbacks = __bind(this._deleteBodyUsingCallbacks, this);
3937     this.deleteBody = __bind(this.deleteBody, this);
3938     this._publishBodyExpiresInUsingCallbacks = __bind(this._publishBodyExpiresInUsingCallbacks, this);
3939     this.publishBodyExpiresIn = __bind(this.publishBodyExpiresIn, this);
3940     this._publishBodyExpiresAtUsingCallbacks = __bind(this._publishBodyExpiresAtUsingCallbacks, this);
3941     this.publishBodyExpiresAt = __bind(this.publishBodyExpiresAt, this);
3942     this._publishBodyUsingCallbacks = __bind(this._publishBodyUsingCallbacks, this);
3943     this.publishBody = __bind(this.publishBody, this);
3944     this._downloadBodyUsingCallbacks = __bind(this._downloadBodyUsingCallbacks, this);
3945     this.downloadBody = __bind(this.downloadBody, this);
3946     this._uploadBodyUsingCallbacks = __bind(this._uploadBodyUsingCallbacks, this);
3947     this.uploadBody = __bind(this.uploadBody, this);
3948     this._moveBodyUsingCallbacks = __bind(this._moveBodyUsingCallbacks, this);
3949     this.moveBody = __bind(this.moveBody, this);
3950     this._parseObjectUri = __bind(this._parseObjectUri, this);
3951     this._userWithID = __bind(this._userWithID, this);
3952     this._setAuthorizationHeader = __bind(this._setAuthorizationHeader, this);
3953     this._getToken = __bind(this._getToken, this);
3954     this._getRequest = __bind(this._getRequest, this);
3955     this._setETag = __bind(this._setETag, this);
3956     this._deleteUsingCallbacks = __bind(this._deleteUsingCallbacks, this);
3957     this["delete"] = __bind(this["delete"], this);
3958     this._refreshUsingCallbacks = __bind(this._refreshUsingCallbacks, this);
3959     this.refresh = __bind(this.refresh, this);
3960     this._saveUsingCallbacks = __bind(this._saveUsingCallbacks, this);
3961     this.save = __bind(this.save, this);
3962     this._saveAllFieldsUsingCallbacks = __bind(this._saveAllFieldsUsingCallbacks, this);
3963     this.saveAllFields = __bind(this.saveAllFields, this);
3964     this._performUpdate = __bind(this._performUpdate, this);
3965     this._performSave = __bind(this._performSave, this);
3966     this._updateWithJSON = __bind(this._updateWithJSON, this);
3967     this._convertToObjectType = __bind(this._convertToObjectType, this);
3968     this.objectURI = __bind(this.objectURI, this);
3969     this.objectACL = __bind(this.objectACL, this);
3970     this.getGeoPoint = __bind(this.getGeoPoint, this);
3971     this.setGeoPoint = __bind(this.setGeoPoint, this);
3972     this.remove = __bind(this.remove, this);
3973     this.getKeys = __bind(this.getKeys, this);
3974     this.get = __bind(this.get, this);
3975     this.set = __bind(this.set, this);
3976     this._getPath = __bind(this._getPath, this);
3977     this._setBodyContentType = __bind(this._setBodyContentType, this);
3978     this.getBodyContentType = __bind(this.getBodyContentType, this);
3979     this._setBucket = __bind(this._setBucket, this);
3980     this.getBucket = __bind(this.getBucket, this);
3981     this._setObjectType = __bind(this._setObjectType, this);
3982     this.getObjectType = __bind(this.getObjectType, this);
3983     this._setModified = __bind(this._setModified, this);
3984     this.getModified = __bind(this.getModified, this);
3985     this._setCreated = __bind(this._setCreated, this);
3986     this.getCreated = __bind(this.getCreated, this);
3987     this.getID = __bind(this.getID, this);
3988     this._setUUID = __bind(this._setUUID, this);
3989     this.getUUID = __bind(this.getUUID, this);
3990     this._customInfo = {};
3991     this._alteredFields = [];
3992   }
3993 
3994   KiiObject.prototype._getPath = function() {
3995     var path;
3996     if (this._bucket.getUser() != null) {
3997       path = "/users/" + (this._bucket.getUser().getUUID()) + "/buckets/" + (this._bucket._getQualifiedBucketName()) + "/objects/";
3998     } else if (this._bucket.getGroup() != null) {
3999       path = "/groups/" + (this._bucket.getGroup().getUUID()) + "/buckets/" + (this._bucket._getQualifiedBucketName()) + "/objects/";
4000     } else if (this._bucket.getThing() != null) {
4001       path = "/things/" + (this._bucket.getThing().getThingID()) + "/buckets/" + (this._bucket._getQualifiedBucketName()) + "/objects/";
4002     } else {
4003       path = "/buckets/" + (this._bucket._getQualifiedBucketName()) + "/objects/";
4004     }
4005     if (this._uuid != null) {
4006       path += this._uuid;
4007     }
4008     return path;
4009   };
4010 
4011 
4012   /** Sets a key/value pair to a KiiObject
4013   
4014   <br><br>If the key already exists, its value will be written over.
4015   <br><b>NOTE: Before involving floating point value, please consider using integer instead. For example, use percentage, permil, ppm, etc.</br></b>
4016   The reason is:
4017    <li>Will dramatically improve the performance of bucket query.</li>
4018    <li>Bucket query does not support the mixed result of integer and floating point.
4019    ex.) If you use same key for integer and floating point and inquire object with the integer value, objects which has floating point value with the key would not be evaluated in the query. (and vice versa)</li>
4020   @param {String} key The key to set.
4021   if null, empty string or string prefixed with '_' is specified, silently ignored and have no effect.
4022   We don't check if actual type is String or not. If non-string type is specified, it will be encoded as key by JSON.stringify()
4023   @param {Object} value The value to be set. Object must be JSON-encodable type (dictionary, array, string, number, boolean)
4024   We don't check actual type of the value. It will be encoded as value by JSON.stringify()
4025   @example
4026   var obj = . . .; // a KiiObject
4027   obj.set("score", 4298);
4028    */
4029 
4030   KiiObject.prototype.set = function(key, value) {
4031     if (!KiiUtilities._isNonEmptyString(key) || key.indexOf("_") === 0) {
4032       root.Kii.logger("[WARN] Reserved key is used for custom field. key=" + key);
4033       return;
4034     }
4035     this._customInfo[key] = value;
4036     return this._alteredFields.push(key);
4037   };
4038 
4039 
4040   /** Gets the value associated with the given key
4041   @param {String} key The key to retrieve
4042   @returns {Object} The object associated with the key. null or undefined if none exists
4043   @example
4044   var obj = . . .; // a KiiObject
4045   var score = obj.get("score");
4046    */
4047 
4048   KiiObject.prototype.get = function(key) {
4049     return this._customInfo[key];
4050   };
4051 
4052 
4053   /** Gets the array object that contains all keys of custom field.
4054   The array of keys from local cache will be returned.
4055   To get the latest array of keys from cloud, calling refresh() is necessary prior calling this method.
4056   The returned array object does not include reserved keys such as _created, _modified, etc.
4057   @returns {Array} keys An array of all keys of custom field.
4058   @example
4059   var obj = . . .; // a KiiObject
4060   for(var key of obj.keys()) {
4061   }
4062    */
4063 
4064   KiiObject.prototype.getKeys = function() {
4065     var key, keys;
4066     keys = [];
4067     for (key in this._customInfo) {
4068       keys.push(key);
4069     }
4070     return keys;
4071   };
4072 
4073 
4074   /** Removes a pair of key/value from this object.
4075   This pair is also removed from server when saveAllFields() is succeeded. 
4076   @param {String} key The key to be removed
4077   @example
4078   var obj = . . .; // a KiiObject
4079   obj.remove("score");
4080    */
4081 
4082   KiiObject.prototype.remove = function(key) {
4083     var index;
4084     delete this._customInfo[key];
4085     index = this._alteredFields.indexOf(key);
4086     if (index >= 0) {
4087       return this._alteredFields.splice(index, 1);
4088     }
4089   };
4090 
4091 
4092   /**
4093       Set Geo point to this object with the specified key.
4094       @param {String} key The key to set.
4095       @param {KiiGeoPoint} KiiGeoPoint to be tied to the specified key.
4096       @throws {String}  Specified kiiGeoPint is not an instance of KiiGeoPoint.
4097    */
4098 
4099   KiiObject.prototype.setGeoPoint = function(key, kiiGeoPoint) {
4100     if (!(kiiGeoPoint instanceof root.KiiGeoPoint)) {
4101       throw root.InvalidArgumentException("Specified kiiGeoPoint is not an instance of KiiGeoPoint");
4102     }
4103     this._customInfo[key] = kiiGeoPoint._toDict();
4104     return this._alteredFields.push(key);
4105   };
4106 
4107 
4108   /**
4109       Gets the geo point associated with the given key.
4110       @param {String} key The key of the geo point to retrieve.
4111       @returns {KiiGeoPoint} KiiGeoPoint tied to the key. null if null exists.
4112    */
4113 
4114   KiiObject.prototype.getGeoPoint = function(key) {
4115     var lat, lon, point;
4116     point = this._customInfo[key];
4117     lat = point.lat;
4118     lon = point.lon;
4119     return root.KiiGeoPoint.geoPoint(lat, lon);
4120   };
4121 
4122 
4123   /** Get the ACL handle for this file
4124   
4125   <br><br>Any KiiACLEntry objects added or revoked from this ACL object will be appended to/removed from the server on ACL save.
4126   	@returns {KiiACL} A KiiACL object associated with this KiiObject
4127   	@example
4128   	var obj = . . .; // a KiiObject
4129   	var acl = obj.objectACL();
4130    */
4131 
4132   KiiObject.prototype.objectACL = function() {
4133     return root.KiiACL.aclWithParent(this);
4134   };
4135 
4136 
4137   /** Get a specifically formatted string referencing the object
4138   
4139   <br><br>The object must exist in the cloud (have a valid UUID).
4140   @returns {String} A URI string based on the current object. null if a URI couldn't be generated.
4141   @example
4142   var obj = . . .; // a KiiObject
4143   var uri = obj.objectURI();
4144    */
4145 
4146   KiiObject.prototype.objectURI = function() {
4147     var base, uri;
4148     base = "kiicloud://";
4149     if ((this._bucket != null) && (this._uuid != null)) {
4150       uri = base;
4151       if (this._bucket.getGroup() != null) {
4152         uri += "groups/" + (this._bucket.getGroup().getUUID()) + "/";
4153       } else if (this._bucket.getUser() != null) {
4154         uri += "users/" + (this._bucket.getUser().getUUID()) + "/";
4155       } else if (this._bucket.getThing() != null) {
4156         uri += "things/" + (this._bucket.getThing().getThingID()) + "/";
4157       }
4158       uri += "buckets/" + (this._bucket._getQualifiedBucketName()) + "/objects/" + this._uuid;
4159     }
4160     return uri;
4161   };
4162 
4163   KiiObject.prototype._convertToObjectType = function(contentType) {
4164     var result;
4165     if ('application/json' === contentType) {
4166       return {
4167         'success': true,
4168         'type': null
4169       };
4170     }
4171     result = contentType.match(RegExp("$application/vnd\\." + (root.Kii.getAppID()) + "\\.([^\\.])+\\+json"));
4172     if (result != null) {
4173       return {
4174         'success': true,
4175         'type': result
4176       };
4177     }
4178     return {
4179       'success': false,
4180       'type': null
4181     };
4182   };
4183 
4184   KiiObject.prototype._updateWithJSON = function(json, patch) {
4185     var key, val, _results;
4186     if (!patch) {
4187       this._customInfo = {};
4188     }
4189     _results = [];
4190     for (key in json) {
4191       val = json[key];
4192       if (key === "_id") {
4193         if (this._uuid == null) {
4194           root.Kii.logger("Setting uuid: " + val);
4195           _results.push(this._uuid = val);
4196         } else {
4197           _results.push(void 0);
4198         }
4199       } else if (key === "_created") {
4200         _results.push(this._created = val);
4201       } else if (key === "_modified") {
4202         _results.push(this._modified = val);
4203       } else if (key === "_owner") {
4204         _results.push(this._owner = this._userWithID(val));
4205       } else if (key === "_dataType") {
4206         _results.push(this._objectType = val);
4207       } else if (key === "_calculated") {
4208         _results.push(this._customInfo[key] = val);
4209       } else if (key[0] !== "_") {
4210         _results.push(this._customInfo[key] = val);
4211       } else if (key === "_version") {
4212         _results.push(this._etag = val);
4213       } else {
4214         _results.push(void 0);
4215       }
4216     }
4217     return _results;
4218   };
4219 
4220   KiiObject.prototype._performSave = function(callbacks) {
4221     var data, path, request, saveCallbacks;
4222     path = this._getPath();
4223     path = path.slice(0, +(path.length - 2) + 1 || 9e9);
4224     request = new this._getRequest({
4225       path: path,
4226       withApp: true
4227     });
4228     request.setMethod("POST");
4229     data = this._customInfo;
4230     request.setData(data);
4231     if (this._objectType != null) {
4232       request.setContentType("application/vnd." + (root.Kii.getAppID()) + "." + this._objectType + "+json");
4233     }
4234     saveCallbacks = {
4235       success: (function(_this) {
4236         return function(data, statusCode, headers) {
4237           var result;
4238           if (statusCode < 300 && statusCode >= 200) {
4239             _this._etag = headers['etag'];
4240             if (data['objectID'] != null) {
4241               _this._uuid = data['objectID'];
4242               if (data['createdAt'] != null) {
4243                 _this._created = data['createdAt'];
4244               }
4245               if (data['dataType'] != null) {
4246                 result = _this._convertToObjectType(data['dataType']);
4247                 if (result['success']) {
4248                   _this._objectType = result['type'];
4249                 }
4250               }
4251               _this._modified = _this._created;
4252               _this._alteredFields = [];
4253               if (callbacks != null) {
4254                 return callbacks.success(_this);
4255               }
4256             } else {
4257               return callbacks.failure(_this, "No objectID response");
4258             }
4259           } else if (callbacks != null) {
4260             return callbacks.failure(_this, "Unable to parse response");
4261           }
4262         };
4263       })(this),
4264       failure: (function(_this) {
4265         return function(error, statusCode) {
4266           if (callbacks != null) {
4267             return callbacks.failure(_this, error);
4268           }
4269         };
4270       })(this)
4271     };
4272     return request.execute(saveCallbacks, false);
4273   };
4274 
4275   KiiObject.prototype._performUpdate = function(patch, callbacks, overwrite) {
4276     var data, isSaved, key, path, request, updateCallbacks, _i, _len, _ref;
4277     path = this._getPath();
4278     request = new this._getRequest({
4279       path: path,
4280       withApp: true
4281     });
4282     data = {};
4283     if (patch) {
4284       request.addHeader("X-HTTP-Method-Override", "PATCH");
4285       request.setMethod("POST");
4286       _ref = this._alteredFields;
4287       for (_i = 0, _len = _ref.length; _i < _len; _i++) {
4288         key = _ref[_i];
4289         data[key] = this._customInfo[key];
4290       }
4291     } else {
4292       request.setMethod("PUT");
4293       data = this._customInfo;
4294     }
4295     request.setData(data);
4296     isSaved = this._created > 0;
4297     if (!overwrite) {
4298       if (isSaved) {
4299         if (this._etag == null) {
4300           callbacks.failure(this, "IllegalState! Call KiiObject#refresh() prior call this method.");
4301           return;
4302         }
4303         request.addHeader("If-Match", this._etag);
4304       } else {
4305         if (patch && (this._etag == null)) {
4306           callbacks.failure(this, "IllegalState! Call KiiObject#refresh() prior call this method.");
4307           return;
4308         }
4309         request.addHeader("If-None-Match", "*");
4310       }
4311     }
4312     if (this._objectType != null) {
4313       request.setContentType("application/vnd." + (root.Kii.getAppID()) + "." + this._objectType + "+json");
4314     }
4315     updateCallbacks = {
4316       success: (function(_this) {
4317         return function(data, statusCode, headers) {
4318           if (statusCode < 300 && statusCode >= 200) {
4319             _this._etag = headers['etag'];
4320             if (patch) {
4321               _this._updateWithJSON(data, true);
4322             } else {
4323               if (data['createdAt'] != null) {
4324                 _this._created = data['createdAt'];
4325               }
4326               if (data['modifiedAt'] != null) {
4327                 _this._modified = data['modifiedAt'];
4328               }
4329             }
4330             _this._alteredFields = [];
4331             if (callbacks != null) {
4332               return callbacks.success(_this);
4333             }
4334           } else if (callbacks != null) {
4335             return callbacks.failure(_this, "Unable to parse response");
4336           }
4337         };
4338       })(this),
4339       failure: (function(_this) {
4340         return function(error, statusCode) {
4341           if (callbacks != null) {
4342             return callbacks.failure(_this, error);
4343           }
4344         };
4345       })(this)
4346     };
4347     return request.execute(updateCallbacks, false);
4348   };
4349 
4350 
4351   /** Create or update the KiiObject on KiiCloud.
4352   <br><br>When call this method for the object that has not saved on cloud, will send all fields.
4353   Call this method for the object that has saved on cloud, Update all field of this object.
4354   @param {Object} [callbacks] An object with callback methods defined
4355       sucess: function called when save succeeded.<br>
4356       failure: function called when save failed.
4357   @param overwrite optional, true by default.
4358           <ul>
4359             <li><b>If overwrite is true:</b>
4360             <ul>
4361               <li>If a KiiObject with the same ID exists in cloud, the local copy will overwrite the remote copy, even if the remote copy is newer. </li>
4362             </ul>
4363               <li><b>Otherwise:</b>
4364             <ul>
4365               <li>If a KiiObject with the same ID exists in cloud and the remote copy is newer, save will fail.</li>
4366             </ul>
4367           </ul>
4368   @return {Promise} return promise object.
4369     <ul>
4370       <li>fulfill callback function: function(theSavedObject). theSavedObject is KiiObject instance.</li>
4371       <li>reject callback function: function(error). error is an Error instance.
4372         <ul>
4373           <li>error.target is the KiiObject instance which this method was called on.</li>
4374           <li>error.message</li>
4375         </ul>
4376       </li>
4377     </ul>
4378   @example
4379   // example to use callbacks directly
4380   var obj = . . .; // a KiiObject
4381   obj.saveAllFields({
4382       success: function(theSavedObject) {
4383           // do something with the saved object
4384       },
4385   
4386       failure: function(theObject, anErrorString) {
4387           // do something with the error response
4388       }
4389   });
4390   
4391   // example to use Promise
4392   var obj = . . .; // a KiiObject
4393   obj.saveAllFields().then(
4394       function(theSavedObject) {
4395           // do something with the saved object
4396       },
4397       function(error) {
4398           // do something with the error response
4399       }
4400   );
4401    */
4402 
4403   KiiObject.prototype.saveAllFields = function(callbacks, overwrite) {
4404     if (overwrite == null) {
4405       overwrite = true;
4406     }
4407     return new Promise((function(_this) {
4408       return function(resolve, reject) {
4409         var saveCallbacks;
4410         saveCallbacks = {
4411           success: function() {
4412             if (callbacks != null) {
4413               callbacks.success.apply(callbacks, arguments);
4414             }
4415             return resolve(arguments[0]);
4416           },
4417           failure: function() {
4418             if (callbacks != null) {
4419               callbacks.failure.apply(callbacks, arguments);
4420             }
4421             return reject(KiiUtilities._Error(arguments[1], _this));
4422           }
4423         };
4424         return _this._saveAllFieldsUsingCallbacks(saveCallbacks, overwrite);
4425       };
4426     })(this));
4427   };
4428 
4429   KiiObject.prototype._saveAllFieldsUsingCallbacks = function(callbacks, overwrite) {
4430     if (overwrite == null) {
4431       overwrite = true;
4432     }
4433     if (this._uuid != null) {
4434       return this._performUpdate(false, callbacks, overwrite);
4435     } else {
4436       return this._performSave(callbacks);
4437     }
4438   };
4439 
4440 
4441   /** Create or update the KiiObject on KiiCloud.
4442   <br><br>When call this method for the object that has not saved on cloud, will send all fields.
4443   Call this method for the object that has saved on cloud, Update only updated fields.
4444   Do not send fields that has not updated locally. To send all fields regardless of updates, call {@link KiiObject#saveAllFields}.
4445   @param {Object} [callbacks] An object with callback methods defined
4446       sucess: function called when save succeeded.<br>
4447       failure: function called when save failed.
4448   @param overwrite optional, true by default.
4449           <ul>
4450             <li><b>If overwrite is true:</b>
4451             <ul>
4452               <li>If a KiiObject with the same ID exists in cloud, the local copy will overwrite the remote copy, even if the remote copy is newer. </li>
4453             </ul>
4454               <li><b>Otherwise:</b>
4455             <ul>
4456               <li>If a KiiObject with the same ID exists in cloud and the remote copy is newer, save will fail.</li>
4457             </ul>
4458           </ul>
4459   @return {Promise} return promise object.
4460     <ul>
4461       <li>fulfill callback function: function(theSavedObject). theSavedObject is KiiObject instance.</li>
4462       <li>reject callback function: function(error). error is an Error instance.
4463         <ul>
4464           <li>error.target is the KiiObject instance which this method was called on.</li>
4465           <li>error.message</li>
4466         </ul>
4467       </li>
4468     </ul>
4469   @example
4470   // example to use callbacks directly
4471   var obj = . . .; // a KiiObject
4472   obj.save({
4473       success: function(theSavedObject) {
4474           // do something with the saved object
4475       },
4476   
4477       failure: function(theObject, anErrorString) {
4478           // do something with the error response
4479       }
4480   });
4481   
4482   // example to use Promise
4483   var obj = . . .; // a KiiObject
4484   obj.save().then(
4485       function(theSavedObject) {
4486           // do something with the saved object
4487       },
4488       function(error) {
4489           // do something with the error response
4490       }
4491   );
4492    */
4493 
4494   KiiObject.prototype.save = function(callbacks, overwrite) {
4495     if (overwrite == null) {
4496       overwrite = true;
4497     }
4498     return new Promise((function(_this) {
4499       return function(resolve, reject) {
4500         var saveCallbacks;
4501         saveCallbacks = {
4502           success: function() {
4503             if (callbacks != null) {
4504               callbacks.success.apply(callbacks, arguments);
4505             }
4506             return resolve(arguments[0]);
4507           },
4508           failure: function() {
4509             if (callbacks != null) {
4510               callbacks.failure.apply(callbacks, arguments);
4511             }
4512             return reject(KiiUtilities._Error(arguments[1], _this));
4513           }
4514         };
4515         return _this._saveUsingCallbacks(saveCallbacks, overwrite);
4516       };
4517     })(this));
4518   };
4519 
4520   KiiObject.prototype._saveUsingCallbacks = function(callbacks, overwrite) {
4521     if (overwrite == null) {
4522       overwrite = true;
4523     }
4524     if (this._uuid != null) {
4525       return this._performUpdate(true, callbacks, overwrite);
4526     } else {
4527       return this._performSave(callbacks);
4528     }
4529   };
4530 
4531 
4532   /** Updates the local object's data with the user data on the server
4533   
4534   <br><br>The object must exist on the server. Local data will be overwritten.
4535   @param {Object} [callbacks] An object with callback methods defined
4536   @param {Method} callbacks.success The callback method to call on a successful refresh request
4537   @param {Method} callbacks.failure The callback method to call on a failed refresh request
4538   @return {Promise} return promise object.
4539     <ul>
4540       <li>fulfill callback function: function(theRefreshedObject). theRefreshedObject is KiiObject instance.</li>
4541       <li>reject callback function: function(error). error is an Error instance.
4542         <ul>
4543           <li>error.target is the KiiObject instance which this method was called on.</li>
4544           <li>error.message</li>
4545         </ul>
4546       </li>
4547     </ul>
4548   @example
4549   // example to use callbacks directly
4550   var obj = . . .; // a KiiObject
4551   obj.refresh({
4552       success: function(theRefreshedObject) {
4553           // do something with the refreshed object
4554       },
4555   
4556       failure: function(theObject, anErrorString) {
4557           // do something with the error response
4558       }
4559   });
4560   
4561   // example to use Promise
4562   var obj = . . .; // a KiiObject
4563   obj.refresh().then(
4564       function(theRefreshedObject) {
4565           // do something with the refreshed object
4566       },
4567       function(error) {
4568           // do something with the error response
4569       }
4570   );
4571    */
4572 
4573   KiiObject.prototype.refresh = function(callbacks) {
4574     return new Promise((function(_this) {
4575       return function(resolve, reject) {
4576         var refreshCallbacks;
4577         refreshCallbacks = {
4578           success: function() {
4579             if (callbacks != null) {
4580               callbacks.success.apply(callbacks, arguments);
4581             }
4582             return resolve(arguments[0]);
4583           },
4584           failure: function() {
4585             if (callbacks != null) {
4586               callbacks.failure.apply(callbacks, arguments);
4587             }
4588             return reject(KiiUtilities._Error(arguments[1], _this));
4589           }
4590         };
4591         return _this._refreshUsingCallbacks(refreshCallbacks);
4592       };
4593     })(this));
4594   };
4595 
4596   KiiObject.prototype._refreshUsingCallbacks = function(callbacks) {
4597     var path, refreshCallbacks, request;
4598     path = this._getPath();
4599     request = new this._getRequest({
4600       path: path,
4601       withApp: true
4602     });
4603     refreshCallbacks = {
4604       success: (function(_this) {
4605         return function(data, statusCode, headers) {
4606           if (statusCode < 300 && statusCode >= 200) {
4607             _this._etag = headers['etag'];
4608             _this._updateWithJSON(data, false);
4609             if (callbacks != null) {
4610               return callbacks.success(_this);
4611             }
4612           } else if (callbacks != null) {
4613             return callbacks.failure(_this, "Unable to parse response");
4614           }
4615         };
4616       })(this),
4617       failure: (function(_this) {
4618         return function(error, statusCode) {
4619           if (callbacks != null) {
4620             return callbacks.failure(_this, error);
4621           }
4622         };
4623       })(this)
4624     };
4625     return request.execute(refreshCallbacks, false);
4626   };
4627 
4628 
4629   /** Delete the object from the server
4630   @name delete
4631   @memberOf root.KiiObject#
4632   @function
4633   @param {Object} [callbacks] An object with callback methods defined
4634   @param {Method} callbacks.success The callback method to call on a successful delete request
4635   @param {Method} callbacks.failure The callback method to call on a failed delete request
4636   @return {Promise} return promise object.
4637     <ul>
4638       <li>fulfill callback function: function(theDeletedObject). theDeletedObject is KiiObject instance.</li>
4639       <li>reject callback function: function(error). error is an Error instance.
4640         <ul>
4641           <li>error.target is the KiiObject instance which this method was called on.</li>
4642           <li>error.message</li>
4643         </ul>
4644       </li>
4645     </ul>
4646   @example
4647   // example to use callbacks directly
4648   var obj = . . .; // a KiiObject
4649   obj.delete({
4650       success: function(theDeletedObject) {
4651           // do something
4652       },
4653   
4654       failure: function(theObject, anErrorString) {
4655           // do something with the error response
4656       }
4657   });
4658   
4659   // example to use Promise
4660   var obj = . . .; // a KiiObject
4661   obj.delete().then(
4662       function(theDeletedObject) {
4663           // do something
4664       },
4665       function(error) {
4666           // do something with the error response
4667       }
4668   );
4669    */
4670 
4671   KiiObject.prototype["delete"] = function(callbacks) {
4672     return new Promise((function(_this) {
4673       return function(resolve, reject) {
4674         var deleteCallbacks;
4675         deleteCallbacks = {
4676           success: function() {
4677             if (callbacks != null) {
4678               callbacks.success.apply(callbacks, arguments);
4679             }
4680             return resolve(arguments[0]);
4681           },
4682           failure: function() {
4683             if (callbacks != null) {
4684               callbacks.failure.apply(callbacks, arguments);
4685             }
4686             return reject(KiiUtilities._Error(arguments[1], _this));
4687           }
4688         };
4689         return _this._deleteUsingCallbacks(deleteCallbacks);
4690       };
4691     })(this));
4692   };
4693 
4694   KiiObject.prototype._deleteUsingCallbacks = function(callbacks) {
4695     var path, refreshCallbacks, request;
4696     path = this._getPath();
4697     request = new this._getRequest({
4698       path: path,
4699       withApp: true
4700     });
4701     request.setMethod("DELETE");
4702     refreshCallbacks = {
4703       success: (function(_this) {
4704         return function(data, statusCode) {
4705           if (statusCode < 300 && statusCode >= 200 && (callbacks != null)) {
4706             return callbacks.success(_this);
4707           } else if (callbacks != null) {
4708             return callbacks.failure(_this, "Unable to parse response");
4709           }
4710         };
4711       })(this),
4712       failure: (function(_this) {
4713         return function(error, statusCode) {
4714           if (callbacks != null) {
4715             return callbacks.failure(_this, error);
4716           }
4717         };
4718       })(this)
4719     };
4720     return request.execute(refreshCallbacks, true);
4721   };
4722 
4723   KiiObject.objectWithBucket = function(bucket, type) {
4724     var obj;
4725     root.Kii.logger("Creating object w type: " + type);
4726     obj = new root.KiiObject;
4727     obj._setBucket(bucket);
4728     obj._setObjectType(type);
4729     root.Kii.logger(obj);
4730     return obj;
4731   };
4732 
4733   KiiObject.objectWithID = function(bucket, objectID) {
4734     var obj;
4735     root.Kii.logger("Creating object with id: " + objectID);
4736     obj = new root.KiiObject;
4737     obj._setBucket(bucket);
4738     obj._setUUID(objectID);
4739     root.Kii.logger(obj);
4740     return obj;
4741   };
4742 
4743   KiiObject.prototype._setETag = function(_etag) {
4744     this._etag = _etag;
4745   };
4746 
4747 
4748   /** Generate a new KiiObject based on a given URI
4749   @param {String} uri The URI of the object to be represented
4750   @returns {KiiObject} A new KiiObject with its parameters filled in from the URI
4751   @throws {InvalidURIException} If the URI is not in the proper format
4752   @example
4753   var group = new KiiObject.objectWithURI("kiicloud://myuri");
4754    */
4755 
4756   KiiObject.objectWithURI = function(uri) {
4757     var bucket, bucketIndex, bucketName, compLength, components, newURI, obj, subject;
4758     newURI = uri.substr("kiicloud://".length);
4759     components = newURI.split("/");
4760     compLength = components.length;
4761     root.Kii.logger(components);
4762     if (compLength >= 4) {
4763       bucketIndex = compLength === 4 ? 1 : 3;
4764       bucketName = components[bucketIndex];
4765       subject = null;
4766       if (components[0] === "groups") {
4767         subject = new root.KiiGroup.groupWithID(components[1]);
4768       } else if (components[0] === "users") {
4769         subject = root.KiiUser.userWithID(components[1]);
4770       } else if (components[0] === "things") {
4771         subject = root.KiiThing.thingWithID(components[1]);
4772       }
4773       bucket = null;
4774       if (root.KiiEncryptedBucket._isEncrypted(bucketName)) {
4775         bucket = new root.KiiEncryptedBucket._bucketWithName(bucketName, subject);
4776       } else {
4777         bucket = new root.KiiBucket._bucketWithName(bucketName, subject);
4778       }
4779       root.Kii.logger(bucket);
4780       obj = bucket.createObject();
4781       obj._setUUID(components[compLength - 1]);
4782       root.Kii.logger(obj);
4783     } else {
4784       throw new root.InvalidURIException;
4785     }
4786     return obj;
4787   };
4788 
4789   KiiObject.prototype._getRequest = function(spec) {
4790     var path, request, withApp;
4791     path = spec.path;
4792     withApp = spec.withApp;
4793     request = new KiiRequest(path, withApp);
4794     return request;
4795   };
4796 
4797   KiiObject.prototype._getToken = function() {
4798     var currUser, token;
4799     currUser = root.KiiUser.getCurrentUser();
4800     token = currUser ? currUser.getAccessToken() : null;
4801     if (token) {
4802       return token;
4803     } else {
4804       return null;
4805     }
4806   };
4807 
4808   KiiObject.prototype._setAuthorizationHeader = function(xhr) {
4809     var token;
4810     token = this._getToken();
4811     if (token) {
4812       return xhr.setRequestHeader("Authorization", "Bearer " + token);
4813     }
4814   };
4815 
4816   KiiObject.prototype._userWithID = function(id) {
4817     var user;
4818     user = root.KiiUser.userWithID(id);
4819     return user;
4820   };
4821 
4822   KiiObject.prototype._parseObjectUri = function(uri) {
4823     var data, targetData, uriElement, uriPrefix;
4824     uriElement = uri.replace(/^kiicloud:\/\//g, "").split("/");
4825     uriPrefix = uriElement[0];
4826     if (uriPrefix === "users") {
4827       targetData = {
4828         'appID': root.Kii.getAppID(),
4829         'userID': uriElement[1],
4830         'type': "APP_AND_USER"
4831       };
4832       if (root.KiiEncryptedBucket._isEncrypted(uriElement[3])) {
4833         data = {
4834           'targetObjectScope': targetData,
4835           'targetBucketType': "crypto",
4836           'targetBucketID': uriElement[3].replace("CRYPTO:", ""),
4837           'targetObjectID': uriElement[5]
4838         };
4839       } else {
4840         data = {
4841           'targetObjectScope': targetData,
4842           'targetBucketID': uriElement[3],
4843           'targetObjectID': uriElement[5]
4844         };
4845       }
4846     } else if (uriPrefix === "groups") {
4847       targetData = {
4848         'appID': root.Kii.getAppID(),
4849         'groupID': uriElement[1],
4850         'type': "APP_AND_GROUP"
4851       };
4852       if (root.KiiEncryptedBucket._isEncrypted(uriElement[3])) {
4853         data = {
4854           'targetObjectScope': targetData,
4855           'targetBucketType': "crypto",
4856           'targetBucketID': uriElement[3].replace("CRYPTO:", ""),
4857           'targetObjectID': uriElement[5]
4858         };
4859       } else {
4860         data = {
4861           'targetObjectScope': targetData,
4862           'targetBucketID': uriElement[3],
4863           'targetObjectID': uriElement[5]
4864         };
4865       }
4866     } else if (uriPrefix === "things") {
4867       throw new root.InvalidURIException;
4868     } else {
4869       targetData = {
4870         'appID': root.Kii.getAppID(),
4871         'type': "APP"
4872       };
4873       if (root.KiiEncryptedBucket._isEncrypted(uriElement[1])) {
4874         data = {
4875           'targetObjectScope': targetData,
4876           'targetBucketType': "crypto",
4877           'targetBucketID': uriElement[1].replace("CRYPTO:", ""),
4878           'targetObjectID': uriElement[3]
4879         };
4880       } else {
4881         data = {
4882           'targetObjectScope': targetData,
4883           'targetBucketID': uriElement[1],
4884           'targetObjectID': uriElement[3]
4885         };
4886       }
4887     }
4888     return data;
4889   };
4890 
4891 
4892   /** Move KiiObject body from an object to another object.
4893   <br>
4894   This moving can be allowed under same application, across different scopes
4895   and source/target KiiObject have a read and write permission (READ_EXISTING_OBJECT and WRITE_EXISTING_OBJECT).
4896   <br><br>If target KiiObject has a body, it will be overwritten.
4897   @param {String} targetObjectUri A KiiObject URI which KiiObject body is moved to.
4898   @param {Object} [callbacks] An object with callback methods defined
4899   @param {Method} callbacks.success The callback method to call on a successful move request
4900   @param {Method} callbacks.failure The callback method to call on a failed move request
4901   @return {Promise} return promise object.
4902     <ul>
4903       <li>fulfill callback function: function(params). params is Array instance.
4904         <ul>
4905           <li>params[0] is the source KiiObject instance which this method was called on.</li>
4906           <li>params[1] is the target targetObjectUri String.</li>
4907         </ul>
4908       </li>
4909       <li>reject callback function: function(error). error is an Error instance.
4910         <ul>
4911           <li>error.target is the source KiiObject instance which this method was called on.</li>
4912           <li>error.targetObjectUri is the targetObjectUri String.</li>
4913           <li>error.message</li>
4914         </ul>
4915       </li>
4916     </ul>
4917   @example
4918   // example to use callbacks directly
4919   var sourceObject = ...; // Source KiiObject
4920   var targetObject = ...; // Target KiiObject
4921   var targetObjectUri = targetObject.objectURI();
4922   sourceObject.moveBody(targetObjectUri, {
4923       success: function(theSrcObject, theTgtObjectUri) {
4924           // Do something with the objects
4925       },
4926   
4927       failure: function(theSrcObject, theTgtObjectUri, anErrorString) {
4928           // Do something with the error response
4929       }
4930   });
4931   
4932   // example to use Promise
4933   var sourceObject = ...; // Source KiiObject
4934   var targetObject = ...; // Target KiiObject
4935   var targetObjectUri = targetObject.objectURI();
4936   sourceObject.moveBody(targetObjectUri).then(
4937       function(params) {
4938           var theSrcObject = params[0];
4939           var theTgtObjectUri = params[1];
4940           // Do something with the objects
4941       },
4942       function(error) {
4943           // Do something with the error response
4944       }
4945   );
4946    */
4947 
4948   KiiObject.prototype.moveBody = function(targetObjectUri, callbacks) {
4949     return new Promise((function(_this) {
4950       return function(resolve, reject) {
4951         var moveBodyCallbacks;
4952         moveBodyCallbacks = {
4953           success: function() {
4954             if (callbacks != null) {
4955               callbacks.success.apply(callbacks, arguments);
4956             }
4957             return resolve(arguments);
4958           },
4959           failure: function() {
4960             var error;
4961             if (callbacks != null) {
4962               callbacks.failure.apply(callbacks, arguments);
4963             }
4964             error = KiiUtilities._Error(arguments[2], _this);
4965             error.targetObjectUri = arguments[1];
4966             return reject(error);
4967           }
4968         };
4969         return _this._moveBodyUsingCallbacks(targetObjectUri, moveBodyCallbacks);
4970       };
4971     })(this));
4972   };
4973 
4974   KiiObject.prototype._moveBodyUsingCallbacks = function(targetObjectUri, callbacks) {
4975     var errorMessage, moveCallbacks, path, request;
4976     if (targetObjectUri == null) {
4977       return callbacks.failure(this, null, root.InvalidArgumentException('targetObjectUri is required'));
4978     }
4979     if (this.getUUID() == null) {
4980       return callbacks.failure(this, targetObjectUri, root.InvalidArgumentException('Source object is not saved on the cloud'));
4981     }
4982     path = this._getPath() + "/body/move";
4983     request = new this._getRequest({
4984       path: path,
4985       withApp: true
4986     });
4987     request.setMethod("POST");
4988     request.setContentType("application/vnd.kii.ObjectBodyMoveRequest+json");
4989     try {
4990       request.setData(this._parseObjectUri(targetObjectUri));
4991     } catch (_error) {
4992       errorMessage = _error;
4993       return callbacks.failure(this, targetObjectUri, "Not support to move body of thing scope object.");
4994     }
4995     moveCallbacks = {
4996       success: (function(_this) {
4997         return function(data, statusCode) {
4998           if (statusCode < 300 && statusCode >= 200 && (callbacks != null)) {
4999             return callbacks.success(_this, targetObjectUri);
5000           } else if (callbacks != null) {
5001             return callbacks.failure(_this, targetObjectUri, "Unable to parse response");
5002           }
5003         };
5004       })(this),
5005       failure: (function(_this) {
5006         return function(error, statusCode) {
5007           if (callbacks != null) {
5008             return callbacks.failure(_this, targetObjectUri, error);
5009           }
5010         };
5011       })(this)
5012     };
5013     return request.execute(moveCallbacks, true);
5014   };
5015 
5016 
5017   /** Upload body data of this object.<br>
5018   If the KiiObject has not saved on the cloud or deleted,
5019   request will be failed.
5020   <br>NOTE: this requires XMLHttpRequest Level 2, FileReader and Blob supports. Do not use it in server code.<br>
5021   @param {Blob} srcDataBlob data to be uploaded.
5022   type is used to determin content-type managed in Kii Cloud.
5023   If type was not specified in the Blob,
5024   'application/octet-stream' will be used.
5025   @param {Object} [callbacks]
5026       progress: function called on XMLHttpRequest 'progress' event listener.<br>
5027       sucess: function called when upload succeeded.<br>
5028       failure: function called when upload failed.
5029   @return {Promise} return promise object.
5030   <br>NOTE: Promise will not handle progress event. Please pass callbacks with progress function to handle progress.
5031     <ul>
5032       <li>fulfill callback function: function(theObject). theObject is a KiiObject instance which this method was called on.</li>
5033       <li>reject callback function: function(error). error is an Error instance.
5034         <ul>
5035           <li>error.target is the KiiObject instance which this method was called on.</li>
5036           <li>error.message</li>
5037         </ul>
5038       </li>
5039     </ul>
5040   @example
5041   // example to use callbacks directly
5042   var myObject = Kii.bucketWithName('myBucket').createObject();
5043   myObject.save({
5044       success: function(obj) {
5045           var srcData = new Blob(['Hello Blob'], {type: 'text/plain'});
5046           obj.uploadBody(srcData, {
5047               progress: function (oEvent) {
5048                 if (oEvent.lengthComputable) {
5049                   var percentComplete = oEvent.loaded / oEvent.total;
5050                   //getting upload progress. You can update progress bar on this function.
5051                 }
5052               },
5053               success: function(obj) {
5054                   // Upload succeeded.
5055               },
5056               failure: function(obj, anErrorString) {
5057                   // Handle error.
5058               }
5059           });
5060       },
5061       failure: function(obj, error) {
5062           // Handle error.
5063       }
5064   });
5065   
5066   // example to use Promise
5067   var myObject = Kii.bucketWithName('myBucket').createObject();
5068   myObject.save().then(
5069       function(obj) {
5070           var srcData = new Blob(['Hello Blob'], {type: 'text/plain'});
5071           obj.uploadBody(srcData, {
5072               progress: function (oEvent) {
5073                 if (oEvent.lengthComputable) {
5074                   var percentComplete = oEvent.loaded / oEvent.total;
5075                   //getting upload progress. You can update progress bar on this function.
5076                 }
5077               }
5078           }).then(
5079               function(obj) { // fullfill callback function
5080                   // Upload succeeded.
5081               },
5082               function(error) { // reject callback function
5083                   // Handle error.
5084               }
5085           );
5086       },
5087       function(error) {
5088           // Handle error.
5089       }
5090   );
5091    */
5092 
5093   KiiObject.prototype.uploadBody = function(srcDataBlob, callbacks) {
5094     return new Promise((function(_this) {
5095       return function(resolve, reject) {
5096         var uploadBodyCallbacks;
5097         uploadBodyCallbacks = {
5098           success: function() {
5099             var _ref;
5100             if (callbacks != null) {
5101               if ((_ref = callbacks.success) != null) {
5102                 _ref.apply(callbacks, arguments);
5103               }
5104             }
5105             return resolve(arguments[0]);
5106           },
5107           failure: function() {
5108             var _ref;
5109             if (callbacks != null) {
5110               if ((_ref = callbacks.failure) != null) {
5111                 _ref.apply(callbacks, arguments);
5112               }
5113             }
5114             return reject(KiiUtilities._Error(arguments[1], _this));
5115           },
5116           progress: function() {
5117             var _ref;
5118             return callbacks != null ? (_ref = callbacks.progress) != null ? _ref.apply(callbacks, arguments) : void 0 : void 0;
5119           }
5120         };
5121         return _this._uploadBodyUsingCallbacks(srcDataBlob, uploadBodyCallbacks);
5122       };
5123     })(this));
5124   };
5125 
5126   KiiObject.prototype._uploadBodyUsingCallbacks = function(srcDataBlob, callbacks) {
5127     var contentType, requestCallback, url, wrapper, xhr;
5128     if (!srcDataBlob || !(srcDataBlob instanceof Blob)) {
5129       callbacks.failure(this, "Invalid parameter");
5130       return;
5131     }
5132     url = root.Kii.getBaseURL() + "/apps/" + root.Kii.getAppID() + this._getPath() + "/body";
5133     contentType = "application/octet-stream";
5134     if (srcDataBlob.type) {
5135       contentType = srcDataBlob.type;
5136     }
5137     wrapper = KiiXHRWrapperFactory.createXHRWrapper("PUT", url);
5138     xhr = wrapper.xhr;
5139     xhr.setRequestHeader('Content-Type', contentType);
5140     xhr.setRequestHeader("x-kii-appid", root.Kii.getAppID());
5141     xhr.setRequestHeader("x-kii-appkey", root.Kii.getAppKey());
5142     xhr.setRequestHeader("x-kii-sdk", root.KiiSDKClientInfo.getSDKClientInfo());
5143     this._setAuthorizationHeader(xhr);
5144     requestCallback = {
5145       success: (function(_this) {
5146         return function() {
5147           var json;
5148           json = JSON.parse(xhr.responseText);
5149           if (json['modifiedAt'] != null) {
5150             _this._modified = json['modifiedAt'];
5151           }
5152           _this._setBodyContentType(contentType);
5153           if (callbacks != null) {
5154             return callbacks.success(_this);
5155           }
5156         };
5157       })(this),
5158       failure: (function(_this) {
5159         return function() {
5160           var errString, json;
5161           errString = "failed to upload body. statusCode: " + xhr.status;
5162           if (callbacks != null) {
5163             try {
5164               json = JSON.parse(decodeURIComponent(xhr.responseText));
5165               if (json.errorCode != null) {
5166                 errString += " error code: " + json.errorCode;
5167               }
5168               if (json.message != null) {
5169                 return errString += " message: " + json.message;
5170               }
5171             } catch (_error) {
5172 
5173             } finally {
5174               root.Kii.logger("Failure: " + errString);
5175               root.Kii.logger(xhr.responseText);
5176               callbacks.failure(_this, errString);
5177             }
5178           }
5179         };
5180       })(this),
5181       progress: (function(_this) {
5182         return function(event) {
5183           if (callbacks && callbacks.progress) {
5184             return callbacks.progress(event);
5185           }
5186         };
5187       })(this)
5188     };
5189     return wrapper.sendData(srcDataBlob, requestCallback);
5190   };
5191 
5192 
5193   /** Download body data of this object.<br>
5194   If the KiiObject has not saved on the cloud or deleted
5195   or exist but does not have body object, request will be failed.
5196   <br>NOTE: this requires XMLHttpRequest Level 2, FileReader and Blob supports. Do not use it in server code.<br>
5197   @param {Object} [callbacks]
5198       progress: function called on XMLHttpRequest 'progress' event listener.<br>
5199       sucess: function called when download succeeded.<br>
5200       failure: function called when download failed.
5201   @return {Promise} return promise object.
5202   <br>NOTE: Promise will not handle progress event. Please pass callbacks with progress function to handle progress.
5203     <ul>
5204       <li>fulfill callback function: function(params). params is Array instance.
5205         <ul>
5206           <li>params[0] is a KiiObject instance which this method was called on.</li>
5207           <li>params[1] is the returned body blob object.</li>
5208         </ul>
5209       </li>
5210       <li>reject callback function: function(error). error is an Error instance.</li>
5211         <ul>
5212           <li>error.target is the KiiObject instance which this method was called on.</li>
5213           <li>error.message</li>
5214         </ul>
5215       </li>
5216     </ul>
5217   @example
5218   // example to use callbacks directly
5219   var myObject = KiiObject.objectWithURI('put existing object uri here');
5220   myObject.downloadBody({
5221       progress: function (oEvent) {
5222         if (oEvent.lengthComputable) {
5223           var percentComplete = oEvent.loaded / oEvent.total;
5224           //getting download progress. You can update progress bar on this function.
5225   
5226         }
5227       },
5228       success: function(obj, bodyBlob) {
5229           // Obtaind body contents as bodyBlob.
5230           // content-type managed in Kii Cloud can be obtained from type attr.
5231           // It is same as obj.getBodyContentType();
5232           var contentType = bodyBlob.type;
5233       },
5234       failure: function(obj, anErrorString) {
5235           // Handle error.
5236       }
5237   });
5238   
5239   // example to use Promise
5240   var myObject = KiiObject.objectWithURI('put existing object uri here');
5241   myObject.downloadBody({
5242       progress: function (oEvent) {
5243         if (oEvent.lengthComputable) {
5244           var percentComplete = oEvent.loaded / oEvent.total;
5245           //getting download progress. You can update progress bar on this function.
5246   
5247         }
5248       }
5249   ).then(
5250       function(params) {
5251           // Obtaind body contents as bodyBlob.
5252           // content-type managed in Kii Cloud can be obtained from type attr.
5253           // It is same as obj.getBodyContentType();
5254           var obj = params[0];
5255           var bodyBlob = params[1];
5256           var contentType = bodyBlob.type;
5257       },
5258       function(error) {
5259           // Handle error.
5260       }
5261   );
5262    */
5263 
5264   KiiObject.prototype.downloadBody = function(callbacks) {
5265     return new Promise((function(_this) {
5266       return function(resolve, reject) {
5267         var downloadBodyCallbacks;
5268         downloadBodyCallbacks = {
5269           success: function() {
5270             var _ref;
5271             if (callbacks != null) {
5272               if ((_ref = callbacks.success) != null) {
5273                 _ref.apply(callbacks, arguments);
5274               }
5275             }
5276             return resolve(arguments);
5277           },
5278           failure: function() {
5279             var _ref;
5280             if (callbacks != null) {
5281               if ((_ref = callbacks.failure) != null) {
5282                 _ref.apply(callbacks, arguments);
5283               }
5284             }
5285             return reject(KiiUtilities._Error(arguments[1], _this));
5286           },
5287           progress: function() {
5288             var _ref;
5289             return callbacks != null ? (_ref = callbacks.progress) != null ? _ref.apply(callbacks, arguments) : void 0 : void 0;
5290           }
5291         };
5292         return _this._downloadBodyUsingCallbacks(downloadBodyCallbacks);
5293       };
5294     })(this));
5295   };
5296 
5297   KiiObject.prototype._downloadBodyUsingCallbacks = function(callbacks) {
5298     var requestCallback, url, wrapper, xhr;
5299     url = root.Kii.getBaseURL() + "/apps/" + root.Kii.getAppID() + this._getPath() + "/body";
5300     wrapper = KiiXHRWrapperFactory.createXHRWrapper("GET", url);
5301     xhr = wrapper.xhr;
5302     xhr.setRequestHeader("x-kii-appid", root.Kii.getAppID());
5303     xhr.setRequestHeader("x-kii-appkey", root.Kii.getAppKey());
5304     xhr.setRequestHeader("x-kii-sdk", root.KiiSDKClientInfo.getSDKClientInfo());
5305     this._setAuthorizationHeader(xhr);
5306     xhr.responseType = 'blob';
5307     requestCallback = {
5308       success: (function(_this) {
5309         return function() {
5310           var statusCode;
5311           statusCode = xhr.status;
5312           _this._setBodyContentType(xhr.getResponseHeader('content-type'));
5313           if (callbacks != null) {
5314             return callbacks.success(_this, xhr.response);
5315           }
5316         };
5317       })(this),
5318       failure: (function(_this) {
5319         return function() {
5320           var errString, fileReader, obj, responseText;
5321           if (callbacks != null) {
5322             errString = "failed to download body. statusCode: " + xhr.status;
5323             fileReader = new FileReader();
5324             responseText = null;
5325             obj = _this;
5326             fileReader.onload = function() {
5327               var json;
5328               responseText = this.result;
5329               try {
5330                 json = JSON.parse(decodeURIComponent(responseText));
5331                 if (json.errorCode != null) {
5332                   errString += " error code: " + json.errorCode;
5333                 }
5334                 if (json.message != null) {
5335                   return errString += " message: " + json.message;
5336                 }
5337               } catch (_error) {
5338 
5339               } finally {
5340                 root.Kii.logger("Failure: " + errString);
5341                 root.Kii.logger(xhr.response);
5342                 callbacks.failure(obj, errString);
5343               }
5344             };
5345             return fileReader.readAsText(xhr.response);
5346           }
5347         };
5348       })(this),
5349       progress: (function(_this) {
5350         return function(event) {
5351           if (callbacks && callbacks.progress) {
5352             return callbacks.progress(event);
5353           }
5354         };
5355       })(this)
5356     };
5357     return wrapper.send(requestCallback);
5358   };
5359 
5360 
5361   /** Publish object body.<br>
5362   Publish object body and obtain public URL links to the body.<br>
5363   It doesn't expires.<br>
5364   If the KiiObject has not saved on the cloud or deleted
5365   or exist but does not have body object, request will be failed.
5366   @param {Object} [callbacks]
5367       sucess: function called when publish succeeded.<br>
5368       failure: function called when publish failed.
5369   @return {Promise} return promise object.
5370     <ul>
5371       <li>fulfill callback function: function(params). params is Array instance.
5372         <ul>
5373           <li>params[0] is the KiiObject instance which this method was called on.</li>
5374           <li>params[1] is the published url string.</li>
5375         </ul>
5376       </li>
5377       <li>reject callback function: function(error). error is an Error instance.
5378         <ul>
5379           <li>error.target is the KiiObject instance which this method was called on.</li>
5380           <li>error.message</li>
5381         </ul>
5382       </li>
5383     </ul>
5384   @example
5385   // example to use callbacks directly
5386   var myObject = KiiObject.objectWithURI('put existing object uri here');
5387   myObject.publishBody({
5388       success: function(obj, publishedUrl) {
5389           // ex.) You can show publishedUrl in the view.
5390       },
5391       failure: function(obj, anErrorString) {
5392           // Handle error.
5393       }
5394   });
5395   
5396   // example to use Promise
5397   var myObject = KiiObject.objectWithURI('put existing object uri here');
5398   myObject.publishBody().then(
5399       function(params) {
5400           // ex.) You can show publishedUrl in the view.
5401           var obj = params[0];
5402           var publishedUrl = params[1];
5403       },
5404       function(error) {
5405           // Handle error.
5406       }
5407   );
5408    */
5409 
5410   KiiObject.prototype.publishBody = function(callbacks) {
5411     return new Promise((function(_this) {
5412       return function(resolve, reject) {
5413         var publishBodyCallbacks;
5414         publishBodyCallbacks = {
5415           success: function() {
5416             if (callbacks != null) {
5417               callbacks.success.apply(callbacks, arguments);
5418             }
5419             return resolve(arguments);
5420           },
5421           failure: function() {
5422             if (callbacks != null) {
5423               callbacks.failure.apply(callbacks, arguments);
5424             }
5425             return reject(KiiUtilities._Error(arguments[1], _this));
5426           }
5427         };
5428         return _this._publishBodyUsingCallbacks(publishBodyCallbacks);
5429       };
5430     })(this));
5431   };
5432 
5433   KiiObject.prototype._publishBodyUsingCallbacks = function(callbacks) {
5434     var jsonBody, requestBody, requestCallbacks, url, wrapper, xhr;
5435     url = root.Kii.getBaseURL() + "/apps/" + root.Kii.getAppID() + this._getPath() + "/body/publish";
5436     wrapper = KiiXHRWrapperFactory.createXHRWrapper("POST", url);
5437     xhr = wrapper.xhr;
5438     xhr.setRequestHeader("x-kii-appid", root.Kii.getAppID());
5439     xhr.setRequestHeader("x-kii-appkey", root.Kii.getAppKey());
5440     xhr.setRequestHeader("x-kii-sdk", root.KiiSDKClientInfo.getSDKClientInfo());
5441     xhr.setRequestHeader("Content-Type", "application/vnd.kii.ObjectBodyPublicationRequest+json");
5442     this._setAuthorizationHeader(xhr);
5443     requestCallbacks = {
5444       success: (function(_this) {
5445         return function() {
5446           var json;
5447           if (callbacks != null) {
5448             try {
5449               json = JSON.parse(xhr.responseText);
5450               if (json.url) {
5451                 return callbacks.success(_this, json.url);
5452               } else {
5453                 return callbacks.failure(_this, "failed to parse response");
5454               }
5455             } catch (_error) {
5456               return callbacks.failure(_this, "failed to parse response");
5457             }
5458           }
5459         };
5460       })(this),
5461       failure: (function(_this) {
5462         return function() {
5463           var errString, json;
5464           if (callbacks != null) {
5465             errString = "failed to publish body. statusCode: " + xhr.status;
5466             try {
5467               json = JSON.parse(xhr.responseText);
5468               if (json.errorCode != null) {
5469                 errString += " error code: " + json.errorCode;
5470               }
5471               if (json.message != null) {
5472                 return errString += " error message: " + json.message;
5473               }
5474             } catch (_error) {
5475 
5476             } finally {
5477               callbacks.failure(_this, errString);
5478             }
5479           }
5480         };
5481       })(this)
5482     };
5483     requestBody = {};
5484     jsonBody = JSON.stringify(requestBody);
5485     return wrapper.sendData(jsonBody, requestCallbacks);
5486   };
5487 
5488 
5489   /** Publish object body with expiration date.<br>
5490   Publish object body and obtain public URL links to the body.<br>
5491   Expires at specified date <br>
5492   If the KiiObject has not saved on the cloud or deleted
5493   or exist but does not have body object, request will be failed.
5494   @param {Date} expiresAt expiration date. should specify future date.
5495   @param {Object} [callbacks]
5496       sucess: function called when publish succeeded.<br>
5497       failure: function called when publish failed.
5498   @return {Promise} return promise object.
5499     <ul>
5500       <li>fulfill callback function: function(params). params is Array instance.
5501         <ul>
5502           <li>params[0] is the KiiObject instance which this method was called on.</li>
5503           <li>params[1] is the published url string.</li>
5504         </ul>
5505       </li>
5506       <li>reject callback function: function(error). error is an Error instance.
5507         <ul>
5508           <li>error.target is the KiiObject instance which this method was called on.</li>
5509           <li>error.message</li>
5510         </ul>
5511       </li>
5512     </ul>
5513   @example
5514   // example to use callbacks directly
5515   var myObject = KiiObject.objectWithURI('put existing object uri here');
5516   var expiresAt = new Date(2014, 11, 24);
5517   myObject.publishBodyExpiresAt(expiresAt, {
5518       success: function(obj, publishedUrl) {
5519           // ex.) You can show publishedUrl in the view.
5520       },
5521       failure: function(obj, anErrorString) {
5522           // Handle error.
5523       }
5524   });
5525   
5526   // example to use Promise
5527   var myObject = KiiObject.objectWithURI('put existing object uri here');
5528   var expiresAt = new Date(2014, 11, 24);
5529   myObject.publishBodyExpiresAt(expiresAt).then(
5530       function(params) {
5531           // ex.) You can show publishedUrl in the view.
5532           var obj = params[0];
5533           var publishedUrl = params[1];
5534       },
5535       function(error) {
5536           // Handle error.
5537       }
5538   );
5539    */
5540 
5541   KiiObject.prototype.publishBodyExpiresAt = function(expiresAt, callbacks) {
5542     return new Promise((function(_this) {
5543       return function(resolve, reject) {
5544         var publishBodyExpiresAtCallbacks;
5545         publishBodyExpiresAtCallbacks = {
5546           success: function() {
5547             if (callbacks != null) {
5548               callbacks.success.apply(callbacks, arguments);
5549             }
5550             return resolve(arguments);
5551           },
5552           failure: function() {
5553             if (callbacks != null) {
5554               callbacks.failure.apply(callbacks, arguments);
5555             }
5556             return reject(KiiUtilities._Error(arguments[1], _this));
5557           }
5558         };
5559         return _this._publishBodyExpiresAtUsingCallbacks(expiresAt, publishBodyExpiresAtCallbacks);
5560       };
5561     })(this));
5562   };
5563 
5564   KiiObject.prototype._publishBodyExpiresAtUsingCallbacks = function(expiresAt, callbacks) {
5565     var jsonBody, requestBody, requestCallbacks, url, wrapper, xhr;
5566     url = root.Kii.getBaseURL() + "/apps/" + root.Kii.getAppID() + this._getPath() + "/body/publish";
5567     wrapper = KiiXHRWrapperFactory.createXHRWrapper("POST", url);
5568     xhr = wrapper.xhr;
5569     xhr.setRequestHeader("x-kii-appid", root.Kii.getAppID());
5570     xhr.setRequestHeader("x-kii-appkey", root.Kii.getAppKey());
5571     xhr.setRequestHeader("x-kii-sdk", root.KiiSDKClientInfo.getSDKClientInfo());
5572     xhr.setRequestHeader("Content-Type", "application/vnd.kii.ObjectBodyPublicationRequest+json");
5573     this._setAuthorizationHeader(xhr);
5574     requestCallbacks = {
5575       success: (function(_this) {
5576         return function() {
5577           var json;
5578           if (callbacks != null) {
5579             try {
5580               json = JSON.parse(xhr.responseText);
5581               if (json.url) {
5582                 return callbacks.success(_this, json.url);
5583               } else {
5584                 return callbacks.failure(_this, "failed to parse response");
5585               }
5586             } catch (_error) {
5587               return callbacks.failure(_this, "failed to parse response");
5588             }
5589           }
5590         };
5591       })(this),
5592       failure: (function(_this) {
5593         return function() {
5594           var errString, json;
5595           if (callbacks != null) {
5596             errString = "failed to publish body. statusCode: " + xhr.status;
5597             if (xhr.responseText == null) {
5598               callbacks.failure(_this, errString);
5599               retunr;
5600             }
5601             try {
5602               json = JSON.parse(xhr.responseText);
5603               if (json.errorCode != null) {
5604                 errString += " error code: " + json.errorCode;
5605               }
5606               if (json.message != null) {
5607                 return errString += " error message: " + json.message;
5608               }
5609             } catch (_error) {
5610 
5611             } finally {
5612               callbacks.failure(_this, errString);
5613             }
5614           }
5615         };
5616       })(this)
5617     };
5618     requestBody = {};
5619     requestBody.expiresAt = expiresAt;
5620     jsonBody = JSON.stringify(requestBody);
5621     return wrapper.sendData(jsonBody, requestCallbacks);
5622   };
5623 
5624 
5625   /** Publish object body with expiration duration.<br>
5626   Publish object body and obtain public URL links to the body.<br>
5627   Expires in specified duration<br>
5628   If the KiiObject has not saved on the cloud or deleted
5629   or exist but does not have body object, request will be failed.
5630   @param {Number} expiresIn duration in seconds. greater than 0.
5631   @param {Object} [callbacks]
5632       sucess: function called when publish succeeded.<br>
5633       failure: function called when publish failed.
5634   @return {Promise} return promise object.
5635     <ul>
5636       <li>fulfill callback function: function(params). params is Array instance.
5637         <ul>
5638           <li>params[0] is the KiiObject instance which this method was called on.</li>
5639           <li>params[1] is the published url string.</li>
5640         </ul>
5641       </li>
5642       <li>reject callback function: function(error). error is an Error instance.
5643         <ul>
5644           <li>error.target is the KiiObject instance which this method was called on.</li>
5645           <li>error.message</li>
5646         </ul>
5647       </li>
5648     </ul>
5649   @example
5650   // example to use callbacks directly
5651   var myObject = KiiObject.objectWithURI('put existing object uri here');
5652   var expiresIn = 60 * 60; // Expires in 1 hour.
5653   myObject.publishBodyExpiresIn(expiresIn, {
5654       success: function(obj, publishedUrl) {
5655           // ex.) You can show publishedUrl in the view.
5656       },
5657       failure: function(obj, anErrorString) {
5658           // Handle error.
5659       }
5660   });
5661   
5662   // example to use Promise
5663   var myObject = KiiObject.objectWithURI('put existing object uri here');
5664   var expiresIn = 60 * 60; // Expires in 1 hour.
5665   myObject.publishBodyExpiresIn(expiresIn).then(
5666       function(params) {
5667           // ex.) You can show publishedUrl in the view.
5668           var obj = params[0];
5669           var publishedUrl = params[1];
5670       },
5671       function(error) {
5672           // Handle error.
5673       }
5674   );
5675    */
5676 
5677   KiiObject.prototype.publishBodyExpiresIn = function(expiresIn, callbacks) {
5678     return new Promise((function(_this) {
5679       return function(resolve, reject) {
5680         var publishBodyExpiresInCallbacks;
5681         publishBodyExpiresInCallbacks = {
5682           success: function() {
5683             if (callbacks != null) {
5684               callbacks.success.apply(callbacks, arguments);
5685             }
5686             return resolve(arguments);
5687           },
5688           failure: function() {
5689             if (callbacks != null) {
5690               callbacks.failure.apply(callbacks, arguments);
5691             }
5692             return reject(KiiUtilities._Error(arguments[1], _this));
5693           }
5694         };
5695         return _this._publishBodyExpiresInUsingCallbacks(expiresIn, publishBodyExpiresInCallbacks);
5696       };
5697     })(this));
5698   };
5699 
5700   KiiObject.prototype._publishBodyExpiresInUsingCallbacks = function(expiresIn, callbacks) {
5701     var jsonBody, requestBody, requestCallbacks, url, wrapper, xhr;
5702     url = root.Kii.getBaseURL() + "/apps/" + root.Kii.getAppID() + this._getPath() + "/body/publish";
5703     wrapper = KiiXHRWrapperFactory.createXHRWrapper("POST", url);
5704     xhr = wrapper.xhr;
5705     xhr.setRequestHeader("x-kii-appid", root.Kii.getAppID());
5706     xhr.setRequestHeader("x-kii-appkey", root.Kii.getAppKey());
5707     xhr.setRequestHeader("x-kii-sdk", root.KiiSDKClientInfo.getSDKClientInfo());
5708     xhr.setRequestHeader("Content-Type", "application/vnd.kii.ObjectBodyPublicationRequest+json");
5709     this._setAuthorizationHeader(xhr);
5710     requestCallbacks = {
5711       success: (function(_this) {
5712         return function() {
5713           var json;
5714           try {
5715             json = JSON.parse(xhr.responseText);
5716             if (json.url) {
5717               return callbacks.success(_this, json.url);
5718             } else {
5719               return callbacks.failure(_this, "failed to parse response");
5720             }
5721           } catch (_error) {
5722             return callbacks.failure(_this, "failed to parse response");
5723           }
5724         };
5725       })(this),
5726       failure: (function(_this) {
5727         return function() {
5728           var errString, json;
5729           errString = "failed to publish body. statusCode: " + xhr.status;
5730           try {
5731             json = JSON.parse(xhr.responseText);
5732             if (json.errorCode != null) {
5733               errString += " error code: " + json.errorCode;
5734             }
5735             if (json.message != null) {
5736               return errString += " error message: " + json.message;
5737             }
5738           } catch (_error) {
5739 
5740           } finally {
5741             callbacks.failure(_this, errString);
5742           }
5743         };
5744       })(this)
5745     };
5746     requestBody = {};
5747     requestBody.expiresIn = expiresIn;
5748     jsonBody = JSON.stringify(requestBody);
5749     return wrapper.sendData(jsonBody, requestCallbacks);
5750   };
5751 
5752 
5753   /** Delete the object body from the server.<br>
5754   If the KiiObject has not saved on the cloud or deleted
5755   or exist but does not have body object, request will be failed.<br>
5756   If succeeded, The object body content type will be nullified.
5757   @name deleteBody
5758   @memberOf root.KiiObject#
5759   @function
5760   @param {Object} [callbacks] An object with callback methods defined
5761   @param {Method} callbacks.success The callback method to call on a successful delete request
5762   @param {Method} callbacks.failure The callback method to call on a failed delete request
5763   @return {Promise} return promise object.
5764     <ul>
5765       <li>fulfill callback function: function(theDeletedObject). theDeletedObject is the KiiObject instance which this method was called on.</li>
5766       <li>reject callback function: function(error). error is an Error instance.
5767         <ul>
5768           <li>error.target is the KiiObject instance which this method was called on.</li>
5769           <li>error.message</li>
5770         </ul>
5771       </li>
5772     </ul>
5773   @example
5774   // example to use callbacks directly
5775   var obj = . . .; // a KiiObject
5776   obj.deleteBody({
5777       success: function(theDeletedObject) {
5778           // do something
5779       },
5780   
5781       failure: function(obj, anErrorString) {
5782           // do something with the error response
5783       }
5784   });
5785   
5786   // example to use Promise
5787   var obj = . . .; // a KiiObject
5788   obj.deleteBody().then(
5789       function(theDeletedObject) {
5790           // do something
5791       },
5792       function(error) {
5793           // do something with the error response
5794       }
5795   );
5796    */
5797 
5798   KiiObject.prototype.deleteBody = function(callbacks) {
5799     return new Promise((function(_this) {
5800       return function(resolve, reject) {
5801         var deleteBodyCallbacks;
5802         deleteBodyCallbacks = {
5803           success: function() {
5804             if (callbacks != null) {
5805               callbacks.success.apply(callbacks, arguments);
5806             }
5807             return resolve(arguments[0]);
5808           },
5809           failure: function() {
5810             if (callbacks != null) {
5811               callbacks.failure.apply(callbacks, arguments);
5812             }
5813             return reject(KiiUtilities._Error(arguments[1], _this));
5814           }
5815         };
5816         return _this._deleteBodyUsingCallbacks(deleteBodyCallbacks);
5817       };
5818     })(this));
5819   };
5820 
5821   KiiObject.prototype._deleteBodyUsingCallbacks = function(callbacks) {
5822     var requestCallbacks, url, wrapper, xhr;
5823     url = root.Kii.getBaseURL() + "/apps/" + root.Kii.getAppID() + this._getPath() + "/body";
5824     wrapper = KiiXHRWrapperFactory.createXHRWrapper("DELETE", url);
5825     xhr = wrapper.xhr;
5826     xhr.setRequestHeader("x-kii-appid", root.Kii.getAppID());
5827     xhr.setRequestHeader("x-kii-appkey", root.Kii.getAppKey());
5828     xhr.setRequestHeader("x-kii-sdk", root.KiiSDKClientInfo.getSDKClientInfo());
5829     this._setAuthorizationHeader(xhr);
5830     requestCallbacks = {
5831       success: (function(_this) {
5832         return function() {
5833           _this._setBodyContentType(null);
5834           if (callbacks != null) {
5835             return callbacks.success(_this);
5836           }
5837         };
5838       })(this),
5839       failure: (function(_this) {
5840         return function() {
5841           var errString, json;
5842           if (callbacks != null) {
5843             errString = "failed to delete body. statusCode: " + xhr.status;
5844             try {
5845               json = JSON.parse(xhr.responseText);
5846               if (json.errorCode != null) {
5847                 errString += " error code: " + json.errorCode;
5848               }
5849               if (json.message != null) {
5850                 return errString += " error message: " + json.message;
5851               }
5852             } catch (_error) {
5853 
5854             } finally {
5855               callbacks.failure(_this, errString);
5856             }
5857           }
5858         };
5859       })(this)
5860     };
5861     return wrapper.send(requestCallbacks);
5862   };
5863 
5864 
5865   /** Check if given ID is valid for object ID.
5866    Valid pattern: ^[a-zA-Z0-9-_\\.]{2,100}$
5867    @param {String} objectID to be checked.
5868    @returns true if given ID is valid, false otherwise.
5869    */
5870 
5871   KiiObject.isValidObjectID = function(objectID) {
5872     var pattern;
5873     pattern = /^[a-zA-Z0-9-_.]{2,100}$/i;
5874     if ((typeof objectID).toLowerCase() !== "string") {
5875       return false;
5876     } else if ((objectID.match(pattern)) !== null) {
5877       return true;
5878     } else {
5879       return false;
5880     }
5881   };
5882 
5883   return KiiObject;
5884 
5885 })();
5886 
5887 
5888 /**
5889     @class Represents a KiiQuery object
5890     @exports root.KiiQuery as KiiQuery
5891  */
5892 
5893 root.KiiQuery = (function() {
5894   function KiiQuery(query) {
5895     this._dictValue = __bind(this._dictValue, this);
5896     this.sortByAsc = __bind(this.sortByAsc, this);
5897     this.sortByDesc = __bind(this.sortByDesc, this);
5898     this.setLimit = __bind(this.setLimit, this);
5899     this.getLimit = __bind(this.getLimit, this);
5900     this._setClause = __bind(this._setClause, this);
5901     this.setPaginationKey = __bind(this.setPaginationKey, this);
5902     this.getPaginationKey = __bind(this.getPaginationKey, this);
5903     this._clone = __bind(this._clone, this);
5904     return this._clone(query);
5905   }
5906 
5907   KiiQuery.prototype._clone = function(obj) {
5908     var key, newInstance;
5909     if ((obj == null) || typeof obj !== 'object') {
5910       return obj;
5911     }
5912     newInstance = new obj.constructor();
5913     for (key in obj) {
5914       newInstance[key] = this._clone(obj[key]);
5915     }
5916     return newInstance;
5917   };
5918 
5919   KiiQuery.prototype.getPaginationKey = function() {
5920     return this._paginationKey;
5921   };
5922 
5923   KiiQuery.prototype.setPaginationKey = function(_paginationKey) {
5924     this._paginationKey = _paginationKey;
5925   };
5926 
5927   KiiQuery.prototype._setClause = function(_clause) {
5928     this._clause = _clause;
5929   };
5930 
5931 
5932   /** Get the limit of the current query
5933   @returns {Number}
5934    */
5935 
5936   KiiQuery.prototype.getLimit = function() {
5937     return this._limit;
5938   };
5939 
5940 
5941   /** Set the limit of the given query
5942   @param value The desired limit. Must be an integer > 0
5943   @throws InvalidLimitException
5944    */
5945 
5946   KiiQuery.prototype.setLimit = function(value) {
5947     if (value > 0) {
5948       return this._limit = value;
5949     } else {
5950       throw new root.InvalidLimitException;
5951     }
5952   };
5953 
5954 
5955   /** Create a KiiQuery object based on a KiiClause
5956   <br><br>
5957   By passing null as the ‘clause’ parameter, all objects can be retrieved.
5958   @param clause The KiiClause to be executed with the query
5959    */
5960 
5961   KiiQuery.queryWithClause = function(clause) {
5962     var query;
5963     query = new root.KiiQuery();
5964     query._setClause(clause);
5965     return query;
5966   };
5967 
5968 
5969   /** Set the query to sort by a field in descending order
5970   
5971   If a sort has already been set, it will be overwritten.
5972   @param {String} field The key that should be used to sort
5973    */
5974 
5975   KiiQuery.prototype.sortByDesc = function(_sortField) {
5976     this._sortField = _sortField;
5977     return this._sortDescending = true;
5978   };
5979 
5980 
5981   /** Set the query to sort by a field in ascending order
5982   
5983   If a sort has already been set, it will be overwritten.
5984   @param {String} field The key that should be used to sort
5985    */
5986 
5987   KiiQuery.prototype.sortByAsc = function(_sortField) {
5988     this._sortField = _sortField;
5989     return this._sortDescending = false;
5990   };
5991 
5992   KiiQuery._emptyDictValue = function() {
5993     return {
5994       type: "all"
5995     };
5996   };
5997 
5998   KiiQuery.prototype._dictValue = function() {
5999     var bucketQuery, data;
6000     data = {};
6001     data.bestEffortLimit = this._limit;
6002     if (this._paginationKey != null) {
6003       data.paginationKey = this._paginationKey;
6004     }
6005     bucketQuery = {
6006       descending: this._sortDescending
6007     };
6008     if (this._clause != null) {
6009       bucketQuery.clause = this._clause._getDictValue();
6010     } else {
6011       bucketQuery.clause = root.KiiQuery._emptyDictValue();
6012     }
6013     if (this._sortField != null) {
6014       bucketQuery.orderBy = this._sortField;
6015     }
6016     data.bucketQuery = bucketQuery;
6017     return data;
6018   };
6019 
6020   return KiiQuery;
6021 
6022 })();
6023 
6024 
6025 /**
6026     @class Represents a KiiClause expression object
6027     @exports root.KiiClause as KiiClause
6028  */
6029 
6030 root.KiiClause = (function() {
6031   function KiiClause() {
6032     this._getDictValue = __bind(this._getDictValue, this);
6033     this._setDictValue = __bind(this._setDictValue, this);
6034     this._setWhereClauses = __bind(this._setWhereClauses, this);
6035     this._setWhereType = __bind(this._setWhereType, this);
6036   }
6037 
6038   KiiClause.constructor = function() {
6039     KiiClause._whereClauses = [];
6040     return KiiClause._dictExpression = {};
6041   };
6042 
6043   KiiClause.prototype._setWhereType = function(_whereType) {
6044     this._whereType = _whereType;
6045   };
6046 
6047   KiiClause.prototype._setWhereClauses = function(_whereClauses) {
6048     this._whereClauses = _whereClauses;
6049   };
6050 
6051   KiiClause.prototype._setDictValue = function(_dictExpression) {
6052     this._dictExpression = _dictExpression;
6053   };
6054 
6055   KiiClause.prototype._getDictValue = function() {
6056     var clause, clauses, retDict, _i, _len, _ref;
6057     retDict = {};
6058     if ((this._whereClauses != null) && (this._whereType != null)) {
6059       clauses = [];
6060       if (this._whereClauses.length === 1) {
6061         clause = this._whereClauses[0];
6062         if (this._whereType === "not") {
6063           retDict = {
6064             "type": this._whereType,
6065             "clause": clause._getDictValue()
6066           };
6067         } else {
6068           retDict = clause._getDictValue();
6069         }
6070       } else {
6071         _ref = this._whereClauses;
6072         for (_i = 0, _len = _ref.length; _i < _len; _i++) {
6073           clause = _ref[_i];
6074           clauses.push(clause._getDictValue());
6075         }
6076         retDict = {
6077           "type": this._whereType,
6078           "clauses": clauses
6079         };
6080       }
6081     } else if (this._whereClauses != null) {
6082       if (this._whereClauses.length > 0) {
6083         retDict = this._whereClauses[0]._getDictValue();
6084       }
6085     } else if (this._dictExpression != null) {
6086       retDict = this._dictExpression;
6087     }
6088     if (retDict == null) {
6089       retDict = root.KiiQuery.emptyDictValue();
6090     }
6091     return retDict;
6092   };
6093 
6094   KiiClause.createWithWhere = function(whereType, whereClauses) {
6095     var expression;
6096     expression = new root.KiiClause();
6097     expression._setWhereType(whereType);
6098     expression._setWhereClauses(whereClauses);
6099     return expression;
6100   };
6101 
6102   KiiClause.create = function(operator, key, value) {
6103     var expression, _dict;
6104     expression = new root.KiiClause();
6105     _dict = {};
6106     if (operator === "=") {
6107       _dict.type = "eq";
6108       _dict.field = key;
6109       _dict.value = value;
6110     } else if (operator === "<") {
6111       _dict.type = "range";
6112       _dict.field = key;
6113       _dict.upperLimit = value;
6114       _dict.upperIncluded = false;
6115     } else if (operator === "<=") {
6116       _dict.type = "range";
6117       _dict.field = key;
6118       _dict.upperLimit = value;
6119       _dict.upperIncluded = true;
6120     } else if (operator === ">") {
6121       _dict.type = "range";
6122       _dict.field = key;
6123       _dict.lowerLimit = value;
6124       _dict.lowerIncluded = false;
6125     } else if (operator === ">=") {
6126       _dict.type = "range";
6127       _dict.field = key;
6128       _dict.lowerLimit = value;
6129       _dict.lowerIncluded = true;
6130     } else if (operator === "in") {
6131       _dict.type = "in";
6132       _dict.field = key;
6133       _dict.values = value;
6134     } else if (operator === "prefix") {
6135       _dict.type = "prefix";
6136       _dict.field = key;
6137       _dict.prefix = value;
6138     } else if (operator === "hasField") {
6139       _dict.type = "hasField";
6140       _dict.field = key;
6141       _dict.fieldType = value;
6142     }
6143     expression._setDictValue(_dict);
6144     return expression;
6145   };
6146 
6147 
6148   /** Create a KiiClause with the AND operator concatenating multiple KiiClause objects
6149   @param {List} A variable-length list of KiiClause objects to concatenate
6150   @example
6151   KiiClause clause = KiiClause.and(clause1, clause2, clause3, . . .)
6152    */
6153 
6154   KiiClause.and = function() {
6155     return KiiClause.createWithWhere("and", arguments);
6156   };
6157 
6158 
6159   /** Create a KiiClause with the OR operator concatenating multiple KiiClause objects
6160   <br><br>
6161   <b>Note:</b>
6162   Query performance will be worse as the number of objects in bucket increases, so we recommend you avoid the OR clause if possible.
6163   @param {List} A variable-length list of KiiClause objects to concatenate
6164   @example
6165   KiiClause clause = KiiClause.or(clause1, clause2, clause3, . . .)
6166    */
6167 
6168   KiiClause.or = function() {
6169     return KiiClause.createWithWhere("or", arguments);
6170   };
6171 
6172 
6173   /** Create a KiiClause with the NOT operator concatenating a KiiClause object
6174   <br><br>
6175   <b>Note:</b>
6176   Query performance will be worse as the number of objects in bucket increases, so we recommend you avoid the NOT clause if possible.
6177   @param {Object} clause KiiClause object to negate
6178    */
6179 
6180   KiiClause.not = function(clause) {
6181     return KiiClause.createWithWhere("not", [clause]);
6182   };
6183 
6184 
6185   /** Create an expression of the form (key == value)
6186   @param {String} key The key to compare
6187   @param {Object} value the value to compare
6188    */
6189 
6190   KiiClause.equals = function(key, value) {
6191     if (value._className != null) {
6192       value = value.objectURI;
6193     }
6194     return root.KiiClause.create("=", key, value);
6195   };
6196 
6197 
6198   /** Create an expression of the form (key != value)
6199   @param {String} key The key to compare
6200   @param {Object} value the value to compare
6201    */
6202 
6203   KiiClause.notEquals = function(key, value) {
6204     if (value._className != null) {
6205       value = value.objectURI;
6206     }
6207     return root.KiiClause.createWithWhere("not", [root.KiiClause.equals(key, value)]);
6208   };
6209 
6210 
6211   /** Create an expression of the form (key > value)
6212   @param {String} key The key to compare
6213   @param {Object} value the value to compare
6214    */
6215 
6216   KiiClause.greaterThan = function(key, value) {
6217     return root.KiiClause.create(">", key, value);
6218   };
6219 
6220 
6221   /** Create an expression of the form (key >= value)
6222   @param {String} key The key to compare
6223   @param {Object} value the value to compare
6224    */
6225 
6226   KiiClause.greaterThanOrEqual = function(key, value) {
6227     return root.KiiClause.create(">=", key, value);
6228   };
6229 
6230 
6231   /** Create an expression of the form (key < value)
6232   @param {String} key The key to compare
6233   @param {Object} value the value to compare
6234    */
6235 
6236   KiiClause.lessThan = function(key, value) {
6237     return root.KiiClause.create("<", key, value);
6238   };
6239 
6240 
6241   /** Create an expression of the form (key <= value)
6242   @param {String} key The key to compare
6243   @param {Object} value the value to compare
6244    */
6245 
6246   KiiClause.lessThanOrEqual = function(key, value) {
6247     return root.KiiClause.create("<=", key, value);
6248   };
6249 
6250 
6251   /** Create an expression of the form (key in values)
6252   @param {String} key The key to compare
6253   @param {Array} values to be compared with.
6254    */
6255 
6256   KiiClause["in"] = function(key, values) {
6257     return root.KiiClause.create("in", key, values);
6258   };
6259 
6260 
6261   /** Create an expression of the form (key in values)
6262   @param {String} key The key to compare
6263   @param {Array} values to be compared with.
6264    */
6265 
6266   KiiClause.inClause = function(key, values) {
6267     return root.KiiClause.create("in", key, values);
6268   };
6269 
6270 
6271   /** Create an expression of the form (key STARTS WITH value)
6272   @param {String} key The key to compare
6273   @param {Object} value the value to compare
6274    */
6275 
6276   KiiClause.startsWith = function(key, value) {
6277     return root.KiiClause.create("prefix", key, value);
6278   };
6279 
6280 
6281   /**
6282       Create a clause of geo distance. This clause inquires objects in the specified circle.
6283       @param {String} key Name of the key to inquire, which holds geo point.
6284       @param {KiiGeoPoint} center Geo point which specify center of the circle.
6285       @param {Number} radius Radius of the circle. unit is meter. value should be in range of ]0, 20000000]
6286       @param {String} putDistanceInto Used for retrieve distance from the center from the query result.Must match the pattern "^[a-zA-Z_][a-zA-Z0-9_]*$".
6287       If the specified value is null, query result will not contain the distance.
6288       <b>Note:</b> You can get the results in ascending order of distances from center. To do so, build the orderBy field  by
6289       "_calculated.{specified value of putDistanceInto}" and pass it in {@link KiiQuery#sortByAsc}. Note that, descending order
6290       of distances is not supported. The unit of distance is meter.
6291       @return {KiiClause} KiiClaluse reference.
6292       @throws {String}<li> Specified key is not a string or an empty string.</li>
6293               <li>center is not an object of KiiGeoPoint.</li>
6294               <li>putDistanceInto is not a string or an empty string.</li>
6295   
6296       @example
6297           var putDistanceInto = "distanceFromCurrentLoc";
6298           var currentLoc = ..; // current location
6299           var clause = KiiClause.geoDistance("location", currentLoc, 4000, putDistanceInto);
6300           var query = KiiQuery.queryWithClause(clause);
6301           // Sort by distances by ascending order.(Optional, use only if you intend to retrieve the distances in a ascending order).
6302           var orderByKey = "_calculated." + putDistanceInto;
6303           query.sortByAsc(orderByKey);
6304           // Define the callbacks
6305           var bucket = Kii.bucketWithName("MyBucket");
6306           var queryCallback = {
6307               success: function(queryPerformed, resultSet, nextQuery) {
6308                   // check the first object from resultSet.
6309                   var object = resultSet[0];
6310                   var point = object.get("location");
6311                   var distanceToMyLocation = object.get("_calculated")[putDistanceInto];
6312               },
6313               failure: function(queryPerformed, anErrorString) {
6314                   // do something with the error response
6315               }
6316           };
6317           bucket.executeQuery(query, queryCallback);
6318    */
6319 
6320   KiiClause.geoDistance = function(key, center, radius, putDistanceInto) {
6321     var expression, isValidGeoPoint, isValidString, pattern, _dict;
6322     isValidString = function(str) {
6323       return typeof str === 'string' && str.length > 0;
6324     };
6325     isValidGeoPoint = function(point) {
6326       if (point == null) {
6327         return false;
6328       }
6329       return point instanceof root.KiiGeoPoint;
6330     };
6331     if (!isValidString(key)) {
6332       throw root.InvalidArgumentException("Specified key is not a string or is an empty string.");
6333     }
6334     if (!isValidGeoPoint(center)) {
6335       throw root.InvalidArgumentException("center is not a reference of KiiGeoPoint.");
6336     }
6337     pattern = "^[a-zA-Z_][a-zA-Z0-9_]*$";
6338     if ((putDistanceInto != null) && !putDistanceInto.match(pattern)) {
6339       throw root.InvalidArgumentException("putDistanceInto is invalid.");
6340     }
6341     if (radius <= 0 || radius > 20000000 || isNaN(radius)) {
6342       throw root.InvalidArgumentException("radius is invalid.");
6343     }
6344     expression = new root.KiiClause();
6345     _dict = {};
6346     _dict.type = "geodistance";
6347     _dict.field = key;
6348     center = center._toDict();
6349     _dict.center = center;
6350     _dict.radius = radius;
6351     _dict.putDistanceInto = putDistanceInto;
6352     expression._setDictValue(_dict);
6353     return expression;
6354   };
6355 
6356 
6357   /**
6358       Create a clause of geo box. This clause inquires objects in the specified rectangle.
6359       Rectangle would be placed parallel to the equator with specified coordinates of the corner.
6360       @param {String} key Key to inquire which holds geo point.
6361       @param {KiiGeoPoint} northEast North-Eest corner of the rectangle.
6362       @param {KiiGeoPoint} southWest South-Wast corner of the rectangle.
6363       @return {KiiClause}  KiiClause reference.
6364       @throws {String}<li> Specified key is not a string or is an empty string.</li>
6365               <li>northEast or southWest is not a reference of KiiGeoPoint.</li>
6366    */
6367 
6368   KiiClause.geoBox = function(key, northEast, southWest) {
6369     var expression, isValidGeoPoint, isValidKey, ne, sw, _dict;
6370     isValidKey = function(key) {
6371       return typeof key === 'string' && key.length > 0;
6372     };
6373     isValidGeoPoint = function(point) {
6374       if (point == null) {
6375         return false;
6376       }
6377       return point instanceof root.KiiGeoPoint;
6378     };
6379     if (!isValidKey(key)) {
6380       throw root.InvalidArgumentException("Specified key is not a string or is an empty string.");
6381     }
6382     if (!isValidGeoPoint(northEast) || !isValidGeoPoint(southWest)) {
6383       throw root.InvalidArgumentException("northEast or southWest is not a reference of KiiGeoPoint.");
6384     }
6385     expression = new root.KiiClause();
6386     _dict = {};
6387     _dict.type = "geobox";
6388     _dict.field = key;
6389     ne = northEast._toDict();
6390     sw = southWest._toDict();
6391     _dict.box = {
6392       ne: ne,
6393       sw: sw
6394     };
6395     expression._setDictValue(_dict);
6396     return expression;
6397   };
6398 
6399 
6400   /** Create an expression to returns all entities that have a specified field and type.
6401   @param {String} key name of the specified field.
6402   @param {String} fieldType The type of the content of the field. The type of the content of the field must be provided, possible values are "STRING", "INTEGER", "DECIMAL" and "BOOLEAN".
6403    */
6404 
6405   KiiClause.hasField = function(key, fieldType) {
6406     if (fieldType !== "STRING" && fieldType !== "INTEGER" && fieldType !== "DECIMAL" && fieldType !== "BOOLEAN") {
6407       throw root.InvalidArgumentException("fieldType is invalid.");
6408     }
6409     return root.KiiClause.create("hasField", key, fieldType);
6410   };
6411 
6412   return KiiClause;
6413 
6414 })();
6415 
6416 
6417 /*
6418  * This class has deprecated.
6419  * Use KiiXHRWrapper.
6420  */
6421 
6422 KiiRequest = (function() {
6423   KiiRequest.prototype.getPath = function() {
6424     return this._path;
6425   };
6426 
6427   KiiRequest.prototype.setPath = function(_path) {
6428     this._path = _path;
6429   };
6430 
6431   KiiRequest.prototype.getMethod = function() {
6432     return this._method;
6433   };
6434 
6435   KiiRequest.prototype.setMethod = function(_method) {
6436     this._method = _method;
6437   };
6438 
6439   KiiRequest.prototype.getHeaders = function() {
6440     return this._headers;
6441   };
6442 
6443   KiiRequest.prototype.setHeaders = function(_headers) {
6444     this._headers = _headers;
6445   };
6446 
6447   KiiRequest.prototype.getData = function() {
6448     return this._data;
6449   };
6450 
6451   KiiRequest.prototype.setData = function(_data) {
6452     this._data = _data;
6453   };
6454 
6455   KiiRequest.prototype.getContentType = function() {
6456     return this._contentType;
6457   };
6458 
6459   KiiRequest.prototype.setContentType = function(_contentType) {
6460     this._contentType = _contentType;
6461   };
6462 
6463   KiiRequest.prototype.isAnonymous = function() {
6464     return this._anonymous;
6465   };
6466 
6467   KiiRequest.prototype.setAnonymous = function(_anonymous) {
6468     this._anonymous = _anonymous;
6469   };
6470 
6471   KiiRequest.prototype.getAccept = function() {
6472     return this._accept;
6473   };
6474 
6475   KiiRequest.prototype.setAccept = function(_accept) {
6476     this._accept = _accept;
6477   };
6478 
6479   KiiRequest.prototype.addHeader = function(name, value) {
6480     return this._headers[name] = value;
6481   };
6482 
6483   KiiRequest.prototype.setAdminToken = function(token) {
6484     return this._adminToken = token;
6485   };
6486 
6487   function KiiRequest(path, withApp) {
6488     this.execute = __bind(this.execute, this);
6489     this.setAdminToken = __bind(this.setAdminToken, this);
6490     this.addHeader = __bind(this.addHeader, this);
6491     this.setAccept = __bind(this.setAccept, this);
6492     this.getAccept = __bind(this.getAccept, this);
6493     this.setAnonymous = __bind(this.setAnonymous, this);
6494     this.isAnonymous = __bind(this.isAnonymous, this);
6495     this.setContentType = __bind(this.setContentType, this);
6496     this.getContentType = __bind(this.getContentType, this);
6497     this.setData = __bind(this.setData, this);
6498     this.getData = __bind(this.getData, this);
6499     this.setHeaders = __bind(this.setHeaders, this);
6500     this.getHeaders = __bind(this.getHeaders, this);
6501     this.setMethod = __bind(this.setMethod, this);
6502     this.getMethod = __bind(this.getMethod, this);
6503     this.setPath = __bind(this.setPath, this);
6504     this.getPath = __bind(this.getPath, this);
6505     this._path = withApp ? "/apps/" + (root.Kii.getAppID()) + path : path;
6506     this._method = "GET";
6507     this._headers = {
6508       "accept": "*/*"
6509     };
6510     this._contentType = "application/json";
6511     this._anonymous = false;
6512     this._success = (function(_this) {
6513       return function() {};
6514     })(this);
6515     this._failure = (function(_this) {
6516       return function() {};
6517     })(this);
6518     this._httpRequest = null;
6519   }
6520 
6521   KiiRequest.prototype.execute = function(callbacks, ignoreBody) {
6522     var h, key, name, sendData, url, value, _ref;
6523     this._success = callbacks.success != null ? callbacks.success : this._success;
6524     this._failure = callbacks.failure != null ? callbacks.failure : this._failure;
6525     this._ignoreBody = ignoreBody;
6526     url = root.Kii.getBaseURL() + this._path;
6527     root.Kii.logger("POSTING: ");
6528     root.Kii.logger(JSON.stringify(this._data));
6529     if (KiiUtilities._isJSONType(this._contentType)) {
6530       sendData = JSON.stringify(this._data);
6531     } else {
6532       sendData = this._data;
6533     }
6534     root.Kii.logger("Making request[" + this._method + "] to " + url + " with data: " + sendData);
6535     h = root.Kii.getAdditionalHeaders();
6536     if (h != null) {
6537       for (name in h) {
6538         value = h[name];
6539         this._headers[name] = value;
6540       }
6541     }
6542     this._headers['x-kii-appid'] = root.Kii.getAppID();
6543     this._headers['x-kii-appkey'] = root.Kii.getAppKey();
6544     this._headers['x-kii-sdk'] = root.KiiSDKClientInfo.getSDKClientInfo();
6545     if (this._accept != null) {
6546       this._headers['accept'] = this._accept;
6547     }
6548     if (!this._anonymous && (root.KiiUser.getCurrentUser() != null)) {
6549       this._headers['Authorization'] = "Bearer " + (root.KiiUser.getCurrentUser().getAccessToken());
6550     }
6551     if (this._adminToken != null) {
6552       this._headers['Authorization'] = "Bearer " + this._adminToken;
6553     }
6554     if (this._contentType != null) {
6555       this._headers['Content-Type'] = this._contentType;
6556     }
6557     root.Kii.logger("Headers: ");
6558     root.Kii.logger(JSON.stringify(this._headers));
6559     callbacks = {
6560       onComplete: (function(_this) {
6561         return function() {
6562           var e, errString, error, json, responseHeaders, xhr, _ref;
6563           xhr = _this._httpRequest.xhr;
6564           if (xhr.readyState === 4) {
6565             if ((200 <= (_ref = xhr.status) && _ref < 400)) {
6566               root.Kii.logger("Completed Request[" + xhr.status + "]");
6567               root.Kii.logger(xhr.responseText);
6568               responseHeaders = _this._parseResponseHeaders(xhr.getAllResponseHeaders());
6569               if (_this._ignoreBody) {
6570                 return _this._success(null, xhr.status);
6571               } else {
6572                 try {
6573                   json = JSON.parse(xhr.responseText);
6574                 } catch (_error) {
6575                   e = _error;
6576                   json = null;
6577                 }
6578                 if (json != null) {
6579                   if (json.errorCode != null) {
6580                     errString = json.errorCode;
6581                     if (json.message != null) {
6582                       errString += ": " + json.message;
6583                     } else if (json.error_description != null) {
6584                       errString += ": " + json.error_description;
6585                     }
6586                     return _this._failure(errString, xhr.status, json.errorCode);
6587                   } else {
6588                     return _this._success(json, xhr.status, responseHeaders);
6589                   }
6590                 } else {
6591                   return _this._success(null, xhr.status, null);
6592                 }
6593               }
6594             } else {
6595               root.Kii.logger('Error loading data...');
6596               errString = xhr.status + " : " + root.Kii.getBaseURL() + _this._path;
6597               try {
6598                 json = JSON.parse(decodeURIComponent(xhr.responseText));
6599               } catch (_error) {
6600                 error = _error;
6601                 json = null;
6602               }
6603               if (json != null) {
6604                 if (json.errorCode != null) {
6605                   errString = json.errorCode;
6606                   if (json.message != null) {
6607                     errString += ": " + json.message;
6608                   } else if (json.error_description != null) {
6609                     errString += ": " + json.error_description;
6610                   }
6611                 }
6612               }
6613               root.Kii.logger("Failure: " + errString);
6614               root.Kii.logger(xhr.responseText);
6615               return _this._failure(errString, xhr.status);
6616             }
6617           }
6618         };
6619       })(this),
6620       onError: (function(_this) {
6621         return function() {
6622           var errString, error, json, xhr;
6623           xhr = _this._httpRequest.xhr;
6624           root.Kii.logger('Error loading data...');
6625           errString = xhr.status + " : " + root.Kii.getBaseURL() + _this._path;
6626           try {
6627             json = JSON.parse(decodeURIComponent(xhr.responseText));
6628           } catch (_error) {
6629             error = _error;
6630             json = null;
6631           }
6632           if (json != null) {
6633             if (json.errorCode != null) {
6634               errString = json.errorCode;
6635               if (json.message != null) {
6636                 errString += ": " + json.message;
6637               } else if (json.error_description != null) {
6638                 errString += ": " + json.error_description;
6639               }
6640             }
6641           }
6642           root.Kii.logger("Failure: " + errString);
6643           root.Kii.logger(xhr.responseText);
6644           return _this._failure(errString, xhr.status);
6645         };
6646       })(this)
6647     };
6648     this._httpRequest = this._createHttpRequest(this._method, url, callbacks);
6649     if (this._httpRequest.xhr == null) {
6650       this._failure("Cross-Origin Resource Sharing is not supported by the browser.", 0);
6651     }
6652     _ref = this._headers;
6653     for (key in _ref) {
6654       value = _ref[key];
6655       this._httpRequest.xhr.setRequestHeader(key, value);
6656     }
6657     if (this._method !== "GET" && this._method !== "DELETE") {
6658       return this._httpRequest.xhr.send(sendData);
6659     } else {
6660       return this._httpRequest.xhr.send();
6661     }
6662   };
6663 
6664   KiiRequest.prototype._createHttpRequest = function(method, url, callbacks) {
6665     var request;
6666     request = null;
6667     if (root.Kii._getHttpRequestType() === null) {
6668       if (typeof jQuery !== 'undefined') {
6669         root.Kii.logger("Use jQuery " + method + ":" + url);
6670         request = new KiiJQueryHttpRequest(method, url, callbacks);
6671       } else if (typeof XMLHttpRequest !== 'undefined') {
6672         root.Kii.logger("Use XMLHttpRequest " + method + ":" + url);
6673         request = new KiiXMLHttpRequest(method, url, callbacks);
6674       } else if (typeof Titanium !== 'undefined') {
6675         root.Kii.logger("Use Titanium " + method + ":" + url);
6676         request = new KiiTitaniumHttpRequest(method, url, callbacks);
6677       }
6678     } else {
6679       root.Kii.logger("Use http request backdoor");
6680       if (root.Kii._getHttpRequestType() === root._KiiHttpRequestType.jQuery) {
6681         root.Kii.logger("Use jQuery " + method + ":" + url);
6682         request = new KiiJQueryHttpRequest(method, url, callbacks);
6683       } else if (root.Kii._getHttpRequestType() === root._KiiHttpRequestType.XMLHttpRequest) {
6684         root.Kii.logger("Use XMLHttpRequest " + method + ":" + url);
6685         request = new KiiXMLHttpRequest(method, url, callbacks);
6686       } else if (root.Kii._getHttpRequestType() === root._KiiHttpRequestType.Titanium) {
6687         root.Kii.logger("Use Titanium " + method + ":" + url);
6688         request = new KiiTitaniumHttpRequest(method, url, callbacks);
6689       }
6690     }
6691     return request;
6692   };
6693 
6694   KiiRequest.prototype._parseResponseHeaders = function(headerStr) {
6695     var headerPair, headerPairs, headers, i, index, key, val;
6696     headers = {};
6697     if (!headerStr) {
6698       return headers;
6699     }
6700     headerPairs = headerStr.split("\r\n");
6701     i = 0;
6702     while (i < headerPairs.length) {
6703       headerPair = headerPairs[i];
6704       index = headerPair.indexOf(": ");
6705       if (index > 0) {
6706         key = headerPair.substring(0, index).toLowerCase();
6707         val = headerPair.substring(index + 2);
6708         headers[key] = val;
6709       }
6710       i++;
6711     }
6712     return headers;
6713   };
6714 
6715   return KiiRequest;
6716 
6717 })();
6718 
6719 
6720 /**
6721     @class Represents a KiiUser object
6722     @exports root.KiiUser as KiiUser
6723  */
6724 
6725 root.KiiUser = (function() {
6726   function KiiUser() {
6727     this._setAuthToken = __bind(this._setAuthToken, this);
6728     this._getHttpURI = __bind(this._getHttpURI, this);
6729     this._clone = __bind(this._clone, this);
6730     this._getSubscriberPath = __bind(this._getSubscriberPath, this);
6731     this.pushInstallation = __bind(this.pushInstallation, this);
6732     this.pushSubscription = __bind(this.pushSubscription, this);
6733     this._listTopicsUsingCallbacks = __bind(this._listTopicsUsingCallbacks, this);
6734     this.listTopics = __bind(this.listTopics, this);
6735     this.topicWithName = __bind(this.topicWithName, this);
6736     this._groupWithJSON = __bind(this._groupWithJSON, this);
6737     this._setAuthHeader = __bind(this._setAuthHeader, this);
6738     this._getXhrWrapper = __bind(this._getXhrWrapper, this);
6739     this._getRequest = __bind(this._getRequest, this);
6740     this._updateWithJSON = __bind(this._updateWithJSON, this);
6741     this._validateLocalPhoneNumber = __bind(this._validateLocalPhoneNumber, this);
6742     this._validateIdentityData = __bind(this._validateIdentityData, this);
6743     this._updateWithUserFields = __bind(this._updateWithUserFields, this);
6744     this._updateWithIdentityData = __bind(this._updateWithIdentityData, this);
6745     this._deleteUsingCallbacks = __bind(this._deleteUsingCallbacks, this);
6746     this["delete"] = __bind(this["delete"], this);
6747     this._refreshUsingCallbacks = __bind(this._refreshUsingCallbacks, this);
6748     this.refresh = __bind(this.refresh, this);
6749     this._saveUsingCallbacks = __bind(this._saveUsingCallbacks, this);
6750     this.save = __bind(this.save, this);
6751     this._changeEmailUsingCallbacks = __bind(this._changeEmailUsingCallbacks, this);
6752     this.changeEmail = __bind(this.changeEmail, this);
6753     this._changePhoneUsingCallbacks = __bind(this._changePhoneUsingCallbacks, this);
6754     this.changePhone = __bind(this.changePhone, this);
6755     this._ownerOfGroupsUsingCallbacks = __bind(this._ownerOfGroupsUsingCallbacks, this);
6756     this.ownerOfGroups = __bind(this.ownerOfGroups, this);
6757     this._memberOfGroupsUsingCallbacks = __bind(this._memberOfGroupsUsingCallbacks, this);
6758     this.memberOfGroups = __bind(this.memberOfGroups, this);
6759     this.resendPhoneNumberVerification = __bind(this.resendPhoneNumberVerification, this);
6760     this.resendEmailVerification = __bind(this.resendEmailVerification, this);
6761     this._resendVerificationUsingCallbacks = __bind(this._resendVerificationUsingCallbacks, this);
6762     this.resendVerification = __bind(this.resendVerification, this);
6763     this.verifyPhoneNumber = __bind(this.verifyPhoneNumber, this);
6764     this._verifyCredentialsUsingCallbacks = __bind(this._verifyCredentialsUsingCallbacks, this);
6765     this.verifyCredentials = __bind(this.verifyCredentials, this);
6766     this._updatePasswordUsingCallbacks = __bind(this._updatePasswordUsingCallbacks, this);
6767     this.updatePassword = __bind(this.updatePassword, this);
6768     this._updateUsingCallbacks = __bind(this._updateUsingCallbacks, this);
6769     this.update = __bind(this.update, this);
6770     this._putIdentityUsingCallbacks = __bind(this._putIdentityUsingCallbacks, this);
6771     this.putIdentity = __bind(this.putIdentity, this);
6772     this._registerUsingCallbacks = __bind(this._registerUsingCallbacks, this);
6773     this.register = __bind(this.register, this);
6774     this._authenticateWithMfa = __bind(this._authenticateWithMfa, this);
6775     this._authenticateWithToken = __bind(this._authenticateWithToken, this);
6776     this._authenticate = __bind(this._authenticate, this);
6777     this.encryptedBucketWithName = __bind(this.encryptedBucketWithName, this);
6778     this.bucketWithName = __bind(this.bucketWithName, this);
6779     this.get = __bind(this.get, this);
6780     this.set = __bind(this.set, this);
6781     this.objectURI = __bind(this.objectURI, this);
6782     this._setScope = __bind(this._setScope, this);
6783     this.getScope = __bind(this.getScope, this);
6784     this.getAccessTokenObject = __bind(this.getAccessTokenObject, this);
6785     this._setExpiresAt = __bind(this._setExpiresAt, this);
6786     this._setAccessToken = __bind(this._setAccessToken, this);
6787     this.getAccessToken = __bind(this.getAccessToken, this);
6788     this.getLinkedSocialAccounts = __bind(this.getLinkedSocialAccounts, this);
6789     this._setPhoneVerified = __bind(this._setPhoneVerified, this);
6790     this.getPhoneVerified = __bind(this.getPhoneVerified, this);
6791     this._setEmailVerified = __bind(this._setEmailVerified, this);
6792     this.getEmailVerified = __bind(this.getEmailVerified, this);
6793     this._setModified = __bind(this._setModified, this);
6794     this.getModified = __bind(this.getModified, this);
6795     this._setCreated = __bind(this._setCreated, this);
6796     this.getCreated = __bind(this.getCreated, this);
6797     this.setLocale = __bind(this.setLocale, this);
6798     this.getLocale = __bind(this.getLocale, this);
6799     this.setCountry = __bind(this.setCountry, this);
6800     this.getCountry = __bind(this.getCountry, this);
6801     this._clearPassword = __bind(this._clearPassword, this);
6802     this._setPassword = __bind(this._setPassword, this);
6803     this._setLocalPhone = __bind(this._setLocalPhone, this);
6804     this.getPendingPhoneNumber = __bind(this.getPendingPhoneNumber, this);
6805     this._setPhoneNumber = __bind(this._setPhoneNumber, this);
6806     this.getPhoneNumber = __bind(this.getPhoneNumber, this);
6807     this.getPendingEmailAddress = __bind(this.getPendingEmailAddress, this);
6808     this._setEmailAddress = __bind(this._setEmailAddress, this);
6809     this.getEmailAddress = __bind(this.getEmailAddress, this);
6810     this.isPseudoUser = __bind(this.isPseudoUser, this);
6811     this.setDisplayName = __bind(this.setDisplayName, this);
6812     this.getDisplayName = __bind(this.getDisplayName, this);
6813     this._setDisabled = __bind(this._setDisabled, this);
6814     this.disabled = __bind(this.disabled, this);
6815     this._setUsername = __bind(this._setUsername, this);
6816     this.getUsername = __bind(this.getUsername, this);
6817     this.getID = __bind(this.getID, this);
6818     this._setUUID = __bind(this._setUUID, this);
6819     this.getUUID = __bind(this.getUUID, this);
6820     this._customInfo = {};
6821   }
6822 
6823 
6824   /** @deprecated Use {@link KiiUser.getId} instead.
6825   Get the UUID of the given user, assigned by the server
6826   @returns {String}
6827    */
6828 
6829   KiiUser.prototype.getUUID = function() {
6830     return this._uuid;
6831   };
6832 
6833   KiiUser.prototype._setUUID = function(_uuid) {
6834     this._uuid = _uuid;
6835   };
6836 
6837 
6838   /** Get the ID of the current KiiUser instance.
6839   @returns {String} Id of the user or null if the user has not saved to cloud.
6840    */
6841 
6842   KiiUser.prototype.getID = function() {
6843     return this._uuid;
6844   };
6845 
6846 
6847   /** Get the username of the given user
6848   @returns {String}
6849    */
6850 
6851   KiiUser.prototype.getUsername = function() {
6852     return this._username;
6853   };
6854 
6855   KiiUser.prototype._setUsername = function(value) {
6856     var trimmedUsername;
6857     trimmedUsername = KiiUtilities._trim(value);
6858     root.Kii.logger("Setting username: " + trimmedUsername);
6859     if (KiiUtilities._validateUsername(trimmedUsername)) {
6860       return this._username = trimmedUsername;
6861     } else {
6862       throw new root.InvalidUsernameException;
6863     }
6864   };
6865 
6866 
6867   /**
6868   Return true if the user is disabled, false when enabled and undefined
6869   when user is not refreshed.
6870   Call {@link KiiUser#refresh()} prior calling this method to get
6871   correct status.
6872    */
6873 
6874   KiiUser.prototype.disabled = function() {
6875     return this._disabled;
6876   };
6877 
6878   KiiUser.prototype._setDisabled = function(_disabled) {
6879     this._disabled = _disabled;
6880   };
6881 
6882 
6883   /** Get the display name associated with this user
6884   @returns {String}
6885    */
6886 
6887   KiiUser.prototype.getDisplayName = function() {
6888     return this._displayName;
6889   };
6890 
6891 
6892   /** Set the display name associated with this user. Cannot be used for logging a user in; is non-unique
6893   @param {String} value Must be between 1-50 alphanumeric characters.
6894   @throws {InvalidDisplayNameException} If the displayName is not a valid format
6895    */
6896 
6897   KiiUser.prototype.setDisplayName = function(value) {
6898     if (!KiiUtilities._validateDisplayName(value)) {
6899       throw new root.InvalidDisplayNameException;
6900     }
6901     return this._displayName = value;
6902   };
6903 
6904 
6905   /** Get whether or not the user is pseudo user.
6906   If this method is not called for current login user, calling
6907   {@link KiiUser#refresh()} method is necessary to get a correct value.
6908   @returns {Boolean} whether this user is pseudo user or not.
6909    */
6910 
6911   KiiUser.prototype.isPseudoUser = function() {
6912     if (this._hasPassword != null) {
6913       return !this._hasPassword;
6914     } else {
6915       return !this._username && !this._emailAddress && !this._phoneNumber;
6916     }
6917   };
6918 
6919 
6920   /** Get the email address associated with this user
6921   @returns {String}
6922    */
6923 
6924   KiiUser.prototype.getEmailAddress = function() {
6925     return this._emailAddress;
6926   };
6927 
6928   KiiUser.prototype._setEmailAddress = function(value) {
6929     var trimmedEmail;
6930     trimmedEmail = KiiUtilities._trim(value);
6931     root.Kii.logger("Setting email: " + trimmedEmail);
6932     if (KiiUtilities._validateEmail(trimmedEmail)) {
6933       return this._emailAddress = trimmedEmail;
6934     } else {
6935       throw new root.InvalidEmailException;
6936     }
6937   };
6938 
6939 
6940   /** Get the email of this user that has not been verified.
6941   When the user's email has been changed and email verification is required in you app configuration,
6942   New email is stored as pending email.
6943   After the new email has been verified, the address can be obtained by {@link KiiUser.getEmailAddress}
6944   @returns {String} User's new email address has not been verified.
6945   null if no pending email field is included in refresh
6946   response or undefined when no refresh operation has been done before.
6947    */
6948 
6949   KiiUser.prototype.getPendingEmailAddress = function() {
6950     return this._emailAddressPending;
6951   };
6952 
6953 
6954   /** Get the phone number associated with this user
6955   @returns {String}
6956    */
6957 
6958   KiiUser.prototype.getPhoneNumber = function() {
6959     return this._phoneNumber;
6960   };
6961 
6962   KiiUser.prototype._setPhoneNumber = function(value) {
6963     root.Kii.logger("Setting phone number: " + value);
6964     if (KiiUtilities._validatePhoneNumber(value)) {
6965       return this._phoneNumber = value;
6966     } else {
6967       throw new root.InvalidPhoneNumberException;
6968     }
6969   };
6970 
6971 
6972   /** Get the phone of this user that has not been verified.
6973   When the user's phone has been changed and phone verification is required in you app configuration,
6974   New phone is stored as pending phone.
6975   After the new phone has been verified, the address can be obtained by {@link KiiUser.getPhoneNumber}
6976   @returns {String} User's new phone number has not been verified.
6977   null if no pending phone field is included in refresh
6978   response or undefined when no refresh operation has been done before.
6979    */
6980 
6981   KiiUser.prototype.getPendingPhoneNumber = function() {
6982     return this._phoneNumberPending;
6983   };
6984 
6985   KiiUser.prototype._setLocalPhone = function(phoneNumber, country) {
6986     root.Kii.logger("Setting local phone number: " + phoneNumber + ", country: " + country);
6987     if (!KiiUtilities._validateLocalPhone(phoneNumber)) {
6988       throw new root.InvalidPhoneNumberException;
6989     }
6990     if (!KiiUtilities._validateCountryCode(country)) {
6991       throw new root.InvalidCountryException;
6992     }
6993     this._phoneNumber = phoneNumber;
6994     return this._country = country;
6995   };
6996 
6997   KiiUser.prototype._setPassword = function(value) {
6998     if (KiiUtilities._validatePassword(value)) {
6999       return this._password = value;
7000     } else {
7001       throw new root.InvalidPasswordException;
7002     }
7003   };
7004 
7005   KiiUser.prototype._clearPassword = function() {
7006     return this._password = null;
7007   };
7008 
7009 
7010   /** Get the country code associated with this user
7011   @returns {String}
7012    */
7013 
7014   KiiUser.prototype.getCountry = function() {
7015     return this._country;
7016   };
7017 
7018 
7019   /** Set the country code associated with this user
7020   @param {String} value The country code to set. Must be 2 alphabetic characters. Ex: US, JP, CN
7021   @throws {InvalidCountryException} If the country code is not a valid format
7022    */
7023 
7024   KiiUser.prototype.setCountry = function(value) {
7025     if (KiiUtilities._validateCountryCode(value)) {
7026       return this._country = value;
7027     } else {
7028       throw new root.InvalidCountryException;
7029     }
7030   };
7031 
7032 
7033   /** Get the locale associated with this user
7034   @returns {String}
7035    */
7036 
7037   KiiUser.prototype.getLocale = function() {
7038     return this._locale;
7039   };
7040 
7041 
7042   /** Set the locale associated with this user
7043   The locale argument must be BCP 47 language tag.
7044   Examples:
7045   "en": English
7046   "de-AT": German as used in Austria.
7047   "zh-Hans-CN": Chinese written in simplified characters as used in China.
7048   @param {String} value The locale to set.
7049    */
7050 
7051   KiiUser.prototype.setLocale = function(value) {
7052     return this._locale = value;
7053   };
7054 
7055 
7056   /** Get the server's creation date of this user
7057   @returns {String}
7058    */
7059 
7060   KiiUser.prototype.getCreated = function() {
7061     return this._created;
7062   };
7063 
7064   KiiUser.prototype._setCreated = function(_created) {
7065     this._created = _created;
7066   };
7067 
7068 
7069   /** @deprecated Get the modified date of the given user, assigned by the server
7070   @returns {String}
7071    */
7072 
7073   KiiUser.prototype.getModified = function() {
7074     return this._modified;
7075   };
7076 
7077   KiiUser.prototype._setModified = function(_modified) {
7078     this._modified = _modified;
7079   };
7080 
7081 
7082   /** Get the status of the user's email verification. This field is assigned by the server
7083   @returns {Boolean} true if the user's email address has been verified by the user, false otherwise.
7084   Could be undefined if haven't obtained value from server or not allowed to see the value.
7085   Should be used by current login user to check the email verification status.
7086    */
7087 
7088   KiiUser.prototype.getEmailVerified = function() {
7089     return this._emailVerified;
7090   };
7091 
7092   KiiUser.prototype._setEmailVerified = function(_emailVerified) {
7093     this._emailVerified = _emailVerified;
7094   };
7095 
7096 
7097   /** Get the status of the user's phone number verification. This field is assigned by the server
7098   @returns {Boolean} true if the user's email address has been verified by the user, false otherwise
7099   Could be undefined if haven't obtained value from server or not allowed to see the value.
7100   Should be used by current login user to check the phone verification status.
7101    */
7102 
7103   KiiUser.prototype.getPhoneVerified = function() {
7104     return this._phoneVerified;
7105   };
7106 
7107   KiiUser.prototype._setPhoneVerified = function(_phoneVerified) {
7108     this._phoneVerified = _phoneVerified;
7109   };
7110 
7111 
7112   /** Get the social accounts that is linked to this user.
7113   Refresh the user by {@link KiiUser#refresh()} prior call the method.
7114   Otherwise, it returns empty object.
7115   @returns {Object} Social network name as key and account info as value.
7116    */
7117 
7118   KiiUser.prototype.getLinkedSocialAccounts = function() {
7119     root.Kii.logger("third party accounts: " + this._thirdPartyAccounts);
7120     return this._thirdPartyAccounts != null ? this._thirdPartyAccounts : this._thirdPartyAccounts = {};
7121   };
7122 
7123 
7124   /** Get the access token for the user - only available if the user is currently logged in
7125   @returns {String}
7126    */
7127 
7128   KiiUser.prototype.getAccessToken = function() {
7129     root.Kii.logger("Getting access token: " + this._accessToken);
7130     return this._accessToken;
7131   };
7132 
7133   KiiUser.prototype._setAccessToken = function(_accessToken) {
7134     this._accessToken = _accessToken;
7135     return root.Kii.logger("Setting access token: " + this._accessToken);
7136   };
7137 
7138   KiiUser.prototype._setExpiresAt = function(_expiresAt) {
7139     this._expiresAt = _expiresAt;
7140     return root.Kii.logger("Setting expires at: " + this._expiresAt);
7141   };
7142 
7143 
7144   /** Return the access token and token expire time in a object.
7145   <table border=4 width=250>
7146     <tr>
7147       <th>Key</th>
7148       <th>Type</th>
7149       <th>Value</th>
7150     </tr>
7151     <tr>
7152       <td>"access_token"</td>
7153       <td>String</td>
7154       <td>required for accessing KiiCloud</td>
7155     </tr>
7156     <tr>
7157       <td>"expires_at"</td>
7158       <td>Date</td>
7159       <td>Access token expiration time, null if the user is not login user.</td>
7160     </tr>
7161   </table>
7162   @return {Object} Access token and token expires in a object.
7163    */
7164 
7165   KiiUser.prototype.getAccessTokenObject = function() {
7166     var accessTokenObject;
7167     accessTokenObject = null;
7168     if (this._accessToken != null) {
7169       accessTokenObject = {
7170         access_token: this._accessToken,
7171         expires_at: this._expiresAt
7172       };
7173     }
7174     return accessTokenObject;
7175   };
7176 
7177   KiiUser.prototype.getScope = function() {
7178     return this._scope;
7179   };
7180 
7181   KiiUser.prototype._setScope = function(_scope) {
7182     this._scope = _scope;
7183   };
7184 
7185 
7186   /** Get a specifically formatted string referencing the user
7187   
7188   <br><br>The user must exist in the cloud (have a valid UUID).
7189   @returns {String} A URI string based on the given user. null if a URI couldn't be generated.
7190   @example
7191   var user = . . .; // a KiiUser
7192   var uri = user.objectURI();
7193    */
7194 
7195   KiiUser.prototype.objectURI = function() {
7196     var uri;
7197     uri = null;
7198     if (this._uuid != null) {
7199       uri = "kiicloud://users/" + this._uuid;
7200     }
7201     return uri;
7202   };
7203 
7204 
7205   /** Sets a key/value pair to a KiiUser
7206   
7207   <br><br>If the key already exists, its value will be written over. If key is empty or starting with '_', it will do nothing. Accepted types are any JSON-encodable objects.
7208   @param {String} key The key to set. The key must not be a system key (created, metadata, modified, type, uuid) or begin with an underscore (_)
7209   @param {Object} value The value to be set. Object must be of a JSON-encodable type (Ex: dictionary, array, string, number, etc)
7210   @example
7211   var user = . . .; // a KiiUser
7212   user.set("score", 4298);
7213    */
7214 
7215   KiiUser.prototype.set = function(key, value) {
7216     if (!KiiUtilities._isNonEmptyString(key) || key.indexOf("_") === 0) {
7217       root.Kii.logger("[WARN] Reserved key is used for custom field. key=" + key);
7218       return;
7219     }
7220     root.Kii.logger(this);
7221     root.Kii.logger(this._customInfo);
7222     return this._customInfo[key] = value;
7223   };
7224 
7225 
7226   /** Gets the value associated with the given key
7227   @param {String} key The key to retrieve
7228   @returns {Object} The object associated with the key. null or undefined if none exists
7229   @example
7230   var user = . . .; // a KiiUser
7231   var score = user.get("score");
7232    */
7233 
7234   KiiUser.prototype.get = function(key) {
7235     return this._customInfo[key];
7236   };
7237 
7238 
7239   /**
7240       The currently authenticated user
7241   
7242       @returns {KiiUser}
7243       @example
7244       var user = KiiUser.getCurrentUser();
7245    */
7246 
7247   KiiUser.getCurrentUser = function() {
7248     return root.Kii.getCurrentUser();
7249   };
7250 
7251 
7252   /** Create a user object to prepare for registration with credentials pre-filled
7253   
7254   <br><br>Creates an pre-filled user object for manipulation. This user will not be authenticated until one of the authentication methods are called on it. It can be treated as any other KiiObject before it is authenticated.
7255   @param username The user's desired username. Must be between 3 and 64 characters, which can include alphanumeric characters as well as underscores '_', dashes '-' and periods '.'
7256   @param password The user's password. Must be between 4-50 characters, made up of ascii characters excludes control characters.
7257   @returns a working KiiUser object
7258   @throws {InvalidUsernameException} If the username is not in the proper format
7259   @throws {InvalidPasswordException} If the password is not in the proper format
7260   @example
7261   var user = KiiUser.userWithUsername("myusername", "mypassword");
7262    */
7263 
7264   KiiUser.userWithUsername = function(username, password) {
7265     var user;
7266     user = new root.KiiUser();
7267     user._setUsername(username);
7268     user._setPassword(password);
7269     return user;
7270   };
7271 
7272   KiiUser._userWithEmailAddress = function(emailAddress, password) {
7273     var user;
7274     user = new root.KiiUser();
7275     user._setEmailAddress(emailAddress);
7276     user._setPassword(password);
7277     return user;
7278   };
7279 
7280   KiiUser._userWithPhoneNumber = function(phoneNumber, password) {
7281     var user;
7282     user = new root.KiiUser();
7283     user._setPhoneNumber(phoneNumber);
7284     user._setPassword(password);
7285     return user;
7286   };
7287 
7288 
7289   /** Create a user object to prepare for registration with credentials pre-filled
7290   
7291   <br><br>Creates an pre-filled user object for registration. This user will not be authenticated until the registration method is called on it. It can be treated as any other KiiUser before it is registered.
7292   @param phoneNumber The user's phone number
7293   @param password The user's password. Must be at least 4 characters, made up of alphanumeric and/or: @,#,$,%,^,&
7294   @throws {InvalidPasswordException} If the password is not in the proper format
7295   @throws {InvalidPhoneNumberException} If the phone number is not in the proper format
7296   @returns a working KiiUser object
7297   @example
7298   var user = KiiUser.userWithPhoneNumber("+874012345678", "mypassword");
7299    */
7300 
7301   KiiUser.userWithPhoneNumber = function(phoneNumber, password) {
7302     return KiiUser._userWithPhoneNumber(phoneNumber, password);
7303   };
7304 
7305 
7306   /** Create a user object to prepare for registration with credentials pre-filled
7307   
7308   <br><br>Creates an pre-filled user object for registration. This user will not be authenticated until the registration method is called on it. It can be treated as any other KiiUser before it is registered.
7309   @param phoneNumber The user's phone number
7310   @param username The user's desired username. Must be between 3 and 64 characters, which can include alphanumeric characters as well as underscores '_', dashes '-' and periods '.'
7311   @param password The user's password. Must be at least 4 characters, made up of alphanumeric and/or: @,#,$,%,^,&
7312   @throws {InvalidUsernameException} If the username is not in the proper format
7313   @throws {InvalidPasswordException} If the password is not in the proper format
7314   @throws {InvalidPhoneNumberException} If the phone number is not in the proper format
7315   @returns a working KiiUser object
7316   @example
7317   var user = KiiUser.userWithPhoneNumberAndUsername("+874012345678", "johndoe", "mypassword");
7318    */
7319 
7320   KiiUser.userWithPhoneNumberAndUsername = function(phoneNumber, username, password) {
7321     var user;
7322     user = new root.KiiUser();
7323     user._setPhoneNumber(phoneNumber);
7324     user._setUsername(username);
7325     user._setPassword(password);
7326     return user;
7327   };
7328 
7329 
7330   /** Create a user object to prepare for registration with credentials pre-filled
7331   
7332   <br><br>Creates an pre-filled user object for registration. This user will not be authenticated until the registration method is called on it. It can be treated as any other KiiUser before it is registered.
7333   @param emailAddress The user's email address
7334   @param password The user's password. Must be at least 4 characters, made up of alphanumeric and/or: @,#,$,%,^,&
7335   @throws {InvalidPasswordException} If the password is not in the proper format
7336   @throws {InvalidEmailException} If the email address is not in the proper format
7337   @returns a working KiiUser object
7338   @example
7339   var user = KiiUser.userWithEmailAddress("johndoe@example.com", "mypassword");
7340    */
7341 
7342   KiiUser.userWithEmailAddress = function(emailAddress, password) {
7343     return KiiUser._userWithEmailAddress(emailAddress, password);
7344   };
7345 
7346 
7347   /** Create a user object to prepare for registration with credentials pre-filled
7348   
7349   <br><br>Creates an pre-filled user object for registration. This user will not be authenticated until the registration method is called on it. It can be treated as any other KiiUser before it is registered.
7350   @param emailAddress The user's email address
7351   @param username The user's desired username. Must be between 3 and 64 characters, which can include alphanumeric characters as well as underscores '_', dashes '-' and periods '.'
7352   @param password The user's password. Must be at least 4 characters, made up of alphanumeric and/or: @,#,$,%,^,&
7353   @throws {InvalidUsernameException} If the username is not in the proper format
7354   @throws {InvalidPasswordException} If the password is not in the proper format
7355   @throws {InvalidEmailException} If the phone number is not in the proper format
7356   @returns a working KiiUser object
7357   @example
7358   var user = KiiUser.userWithEmailAddressAndUsername("johndoe@example.com", "johndoe", "mypassword");
7359    */
7360 
7361   KiiUser.userWithEmailAddressAndUsername = function(emailAddress, username, password) {
7362     var user;
7363     user = new root.KiiUser();
7364     user._setEmailAddress(emailAddress);
7365     user._setUsername(username);
7366     user._setPassword(password);
7367     return user;
7368   };
7369 
7370 
7371   /** Create a user object to prepare for registration with credentials pre-filled
7372   
7373   <br><br>Creates an pre-filled user object for registration. This user will not be authenticated until the registration method is called on it. It can be treated as any other KiiUser before it is registered.
7374   @param emailAddress The user's email address
7375   @param phoneNumber The user's phone number
7376   @param password The user's password. Must be at least 4 characters, made up of alphanumeric and/or: @,#,$,%,^,&
7377   @throws {InvalidPhoneNumberException} If the phone number is not in the proper format
7378   @throws {InvalidPasswordException} If the password is not in the proper format
7379   @throws {InvalidEmailException} If the phone number is not in the proper format
7380   @returns a working KiiUser object
7381   @example
7382   var user = KiiUser.userWithEmailAddressAndPhoneNumber("johndoe@example.com", "+874012345678", "mypassword");
7383    */
7384 
7385   KiiUser.userWithEmailAddressAndPhoneNumber = function(emailAddress, phoneNumber, password) {
7386     var user;
7387     user = new root.KiiUser();
7388     user._setEmailAddress(emailAddress);
7389     user._setPhoneNumber(phoneNumber);
7390     user._setPassword(password);
7391     return user;
7392   };
7393 
7394 
7395   /** Create a user object to prepare for registration with credentials pre-filled
7396   
7397   <br><br>Creates an pre-filled user object for registration. This user will not be authenticated until the registration method is called on it. It can be treated as any other KiiUser before it is registered.
7398   @param emailAddress The user's email address
7399   @param phoneNumber The user's phone number
7400   @param username The user's desired username. Must be between 3 and 64 characters, which can include alphanumeric characters as well as underscores '_', dashes '-' and periods '.'
7401   @param password The user's password. Must be at least 4 characters, made up of alphanumeric and/or: @,#,$,%,^,&
7402   @throws {InvalidPhoneNumberException} If the phone number is not in the proper format
7403   @throws {InvalidEmailException} If the phone number is not in the proper format
7404   @throws {InvalidUsernameException} If the username is not in the proper format
7405   @throws {InvalidPasswordException} If the password is not in the proper format
7406   @returns a working KiiUser object
7407   @example
7408   var user = KiiUser.userWithCredentials("johndoe@example.com", "+874012345678", "johndoe", "mypassword");
7409    */
7410 
7411   KiiUser.userWithCredentials = function(emailAddress, phoneNumber, username, password) {
7412     var user;
7413     user = new root.KiiUser();
7414     user._setEmailAddress(emailAddress);
7415     user._setPhoneNumber(phoneNumber);
7416     user._setUsername(username);
7417     user._setPassword(password);
7418     return user;
7419   };
7420 
7421   KiiUser._validateURI = function(value) {
7422     var match, pattern, retValue;
7423     value = KiiUtilities._trim(value);
7424     pattern = /^kiicloud:\/\/users\/(.*$)/i;
7425     if ((typeof value).toLowerCase() === "string") {
7426       match = value.match(pattern);
7427       if (match != null) {
7428         retValue = match[1];
7429       }
7430     }
7431     return retValue;
7432   };
7433 
7434 
7435   /** Instantiate KiiUser that refers to existing user which has specified ID.
7436   You have to specify the ID of existing KiiUser. Unlike KiiObject,
7437   you can not assign ID in the client side.<br>
7438   <b>NOTE</b>: This API does not access to the server.
7439   After instantiation, call {@link KiiUser#refresh} to fetch the properties.
7440   @param userID ID of the KiiUser to instantiate.
7441   @return instance of KiiUser.
7442   @throws {InvalidArgumentException} when passed userID is empty or null.
7443   @example
7444   var user = new KiiUser.userWithID("__USER_ID__");
7445    */
7446 
7447   KiiUser.userWithID = function(userID) {
7448     var user;
7449     if ((userID == null) || userID === "") {
7450       throw new root.InvalidArgumentException('userID should not null or empty');
7451     }
7452     user = new root.KiiUser();
7453     user._setUUID(userID);
7454     return user;
7455   };
7456 
7457 
7458   /** Generate a new KiiUser based on a given URI
7459   @param {String} uri The URI of the object to be represented
7460   @returns {KiiUser} A new KiiUser with its parameters filled in from the URI
7461   @throws {InvalidURIException} If the URI is not in the proper format
7462   @example
7463   var user = new KiiUser.userWithURI("kiicloud://myuri");
7464    */
7465 
7466   KiiUser.userWithURI = function(uri) {
7467     var user, uuid;
7468     root.Kii.logger("About to extract from: " + uri);
7469     uuid = root.KiiUser._validateURI(uri);
7470     root.Kii.logger("Extracted uuid from uri: " + uuid);
7471     if (uuid != null) {
7472       user = new root.KiiUser();
7473       user._setUUID(uuid);
7474     } else {
7475       throw new root.InvalidURIException;
7476     }
7477     return user;
7478   };
7479 
7480 
7481   /** Creates a reference to a bucket for this user
7482   
7483   <br><br>The bucket will be created/accessed within this user's scope
7484   @param {String} bucketName The name of the bucket the user should create/access
7485   @returns {KiiBucket} A working KiiBucket object
7486   @example
7487   var user = . . .; // a KiiUser
7488   var bucket = user.bucketWithName("myBucket");
7489    */
7490 
7491   KiiUser.prototype.bucketWithName = function(bucketName) {
7492     var bucket;
7493     bucket = new root.KiiBucket(bucketName, this);
7494     return bucket;
7495   };
7496 
7497 
7498   /** Creates a reference to a encrypted bucket for this user
7499   
7500   <br><br>The bucket will be created/accessed within this user's scope
7501   @param {String} bucketName The name of the bucket the user should create/access
7502   @returns {KiiEncryptedBucket} A working KiiEncryptedBucket object
7503   @example
7504   var user = . . .; // a KiiUser
7505   var bucket = user.encryptedBucketWithName("myBucket");
7506    */
7507 
7508   KiiUser.prototype.encryptedBucketWithName = function(bucketName) {
7509     var bucket;
7510     bucket = new root.KiiEncryptedBucket(bucketName, this);
7511     return bucket;
7512   };
7513 
7514   KiiUser.prototype._authenticate = function(callbacks) {
7515     var authCallbacks, currentTime, data, now, request, username;
7516     root.Kii.logger("Authenticating user:");
7517     root.Kii.logger(this);
7518     root.Kii.logger("Email verified: " + this._emailVerified);
7519     root.Kii.logger("Phone verified: " + this._phoneVerified);
7520     if (this._username != null) {
7521       username = this._username;
7522     } else if ((this._emailAddress != null) && this._emailVerified === true) {
7523       username = this._emailAddress;
7524     } else if ((this._phoneNumber != null) && this._phoneVerified === true) {
7525       username = this._phoneNumber;
7526     } else if (this._emailAddress != null) {
7527       username = this._emailAddress;
7528     } else if (this._phoneNumber != null) {
7529       username = this._phoneNumber;
7530     }
7531     data = {
7532       username: username,
7533       password: this._password
7534     };
7535     now = new Date();
7536     currentTime = now.getTime();
7537     if (root.Kii.getAccessTokenExpiration() > 0) {
7538       data.expiresAt = KiiUtilities._safeCalculateExpiresAtAsNumber(root.Kii.getAccessTokenExpiration(), currentTime);
7539     }
7540     request = this._getRequest({
7541       path: "/oauth2/token",
7542       withApp: false
7543     });
7544     request.setAnonymous(true);
7545     request.setMethod("POST");
7546     request.setData(data);
7547     authCallbacks = {
7548       success: (function(_this) {
7549         return function(data) {
7550           _this._setUUID(data.id);
7551           _this._clearPassword();
7552           _this._setAccessToken(data.access_token);
7553           _this._setScope(data.scope);
7554           if (data.expires_in != null) {
7555             now = new Date;
7556             currentTime = now.getTime();
7557             _this._expiresAt = KiiUtilities._safeCalculateExpiresAtAsDate(data.expires_in, currentTime);
7558           }
7559           root.Kii.setCurrentUser(_this);
7560           if (callbacks != null) {
7561             return callbacks.success(root.Kii.getCurrentUser());
7562           }
7563         };
7564       })(this),
7565       failure: (function(_this) {
7566         return function(error, statusCode) {
7567           _this._clearPassword();
7568           if (callbacks != null) {
7569             return callbacks.failure(_this, error);
7570           }
7571         };
7572       })(this)
7573     };
7574     return request.execute(authCallbacks, false);
7575   };
7576 
7577   KiiUser.prototype._authenticateWithToken = function(token, callbacks, expiresAt) {
7578     var authCallbacks, request;
7579     root.Kii.logger("Authenticating user " + this);
7580     root.Kii.logger(callbacks);
7581     request = this._getRequest({
7582       path: "/users/me",
7583       withApp: true
7584     });
7585     request.setAnonymous(true);
7586     request.addHeader("Authorization", "Bearer " + token);
7587     authCallbacks = {
7588       success: (function(_this) {
7589         return function(data) {
7590           _this._updateWithJSON(data);
7591           _this._setAccessToken(token);
7592           if (typeof expiresAt === "undefined") {
7593             _this._setExpiresAt(new Date(KiiUtilities.MAX_DATE_IN_MILLIS));
7594           } else {
7595             _this._setExpiresAt(expiresAt);
7596           }
7597           root.Kii.setCurrentUser(_this);
7598           if (callbacks != null) {
7599             return callbacks.success(root.Kii.getCurrentUser());
7600           }
7601         };
7602       })(this),
7603       failure: (function(_this) {
7604         return function(error, statusCode) {
7605           if (callbacks != null) {
7606             return callbacks.failure(_this, error);
7607           }
7608         };
7609       })(this)
7610     };
7611     return request.execute(authCallbacks, false);
7612   };
7613 
7614   KiiUser.prototype._authenticateWithMfa = function(data, callbacks) {
7615     var authCallbacks, request;
7616     root.Kii.logger("Authenticating user " + this);
7617     root.Kii.logger(callbacks);
7618     request = this._getRequest({
7619       path: "/oauth2/token",
7620       withApp: true
7621     });
7622     request.setMethod("POST");
7623     request.setData(data);
7624     authCallbacks = {
7625       success: (function(_this) {
7626         return function(data) {
7627           var currentTime, now;
7628           _this._setUUID(data.id);
7629           _this._clearPassword();
7630           _this._setAccessToken(data.access_token);
7631           if (data.expires_in != null) {
7632             now = new Date;
7633             currentTime = now.getTime();
7634             _this._expiresAt = KiiUtilities._safeCalculateExpiresAtAsDate(data.expires_in, currentTime);
7635           }
7636           root.Kii.setCurrentUser(_this);
7637           if (callbacks != null) {
7638             return callbacks.success(root.Kii.getCurrentUser());
7639           }
7640         };
7641       })(this),
7642       failure: (function(_this) {
7643         return function(error, statusCode) {
7644           _this._clearPassword();
7645           if (callbacks != null) {
7646             return callbacks.failure(_this, error);
7647           }
7648         };
7649       })(this)
7650     };
7651     return request.execute(authCallbacks, false);
7652   };
7653 
7654 
7655   /** Authenticates a user with the server.
7656   If authentication successful, the user is cached inside SDK as current user,and accessible via
7657   {@link KiiUser.getCurrentUser()}.
7658   User token and token expiration is also cached and can be get by {@link KiiUser#getAccessTokenObject()}.
7659   Access token won't be expired unless you set it explicitly by {@link Kii.setAccessTokenExpiration()}.<br>
7660   If password or userIdentifier is invalid, callbacks.failure or reject callback of promise will be called. <br>
7661   
7662   @param {String} userIdentifier The username, validated email address, or validated phone number of the user to authenticate
7663   @param {String} password The password of the user to authenticate
7664   @param {Object} [callbacks] An object with callback methods defined
7665   @param {Method} callbacks.success The callback method to call on a successful authentication request
7666   @param {Method} callbacks.failure The callback method to call on a failed authentication request
7667   @return {Promise} return promise object.
7668     <ul>
7669       <li>fulfill callback function: function(theAuthenticatedUser). theAuthenticatedUser is KiiUser instance.</li>
7670       <li>reject callback function: function(error). error is an Error instance.
7671         <ul>
7672           <li>error.target is a KiiUser instance.If given password or userIdentifier is invalid, it will be null.</li>
7673           <li>error.message</li>
7674         </ul>
7675       </li>
7676     </ul>
7677   @example
7678   // example to use callbacks directly
7679   KiiUser.authenticate("myusername", "mypassword", {
7680       success: function(theAuthenticatedUser) {
7681           // do something with the authenticated user
7682       },
7683   
7684       failure: function(theUser, anErrorString) {
7685           // do something with the error response
7686       }
7687   });
7688   
7689   // example to use Promise
7690   KiiUser.authenticate("myusername", "mypassword").then(
7691       function(theAuthenticatedUser) {
7692           // do something with the authenticated user
7693       },
7694       function(error) {
7695           // do something with the error response
7696       }
7697   );
7698    */
7699 
7700   KiiUser.authenticate = function(userIdentifier, password, callbacks) {
7701     return new Promise(function(resolve, reject) {
7702       var authenticateCallbacks;
7703       authenticateCallbacks = {
7704         success: function() {
7705           if (callbacks != null) {
7706             callbacks.success.apply(callbacks, arguments);
7707           }
7708           return resolve(arguments[0]);
7709         },
7710         failure: function() {
7711           var error;
7712           if (callbacks != null) {
7713             callbacks.failure.apply(callbacks, arguments);
7714           }
7715           error = KiiUtilities._Error(arguments[1]);
7716           error.target = arguments[0];
7717           return reject(error);
7718         }
7719       };
7720       return KiiUser._authenticateUsingCallbacks(userIdentifier, password, authenticateCallbacks);
7721     });
7722   };
7723 
7724   KiiUser._authenticateUsingCallbacks = function(userIdentifier, password, callbacks) {
7725     var error, user;
7726     try {
7727       root.Kii.logger("UserIdentifier: " + userIdentifier);
7728       if (!KiiUtilities._validatePassword(password)) {
7729         throw new root.InvalidPasswordException;
7730       }
7731       if (KiiUtilities._validateEmail(userIdentifier)) {
7732         user = root.KiiUser._userWithEmailAddress(userIdentifier, password);
7733       } else if (KiiUtilities._validatePhoneNumber(userIdentifier)) {
7734         user = root.KiiUser._userWithPhoneNumber(userIdentifier, password);
7735       } else if (KiiUtilities._validateUsername(userIdentifier)) {
7736         user = root.KiiUser.userWithUsername(userIdentifier, password);
7737       } else {
7738         throw new root.InvalidUserIdentifierException;
7739       }
7740       return user._authenticate(callbacks);
7741     } catch (_error) {
7742       error = _error;
7743       if (user != null) {
7744         user._clearPassword();
7745       }
7746       if (callbacks != null) {
7747         return callbacks.failure(null, error.message);
7748       }
7749     }
7750   };
7751 
7752 
7753   /** Asynchronously authenticates a user with the server using specified access token.
7754   This method is non-blocking.<br><br>
7755   Specified expiresAt won't be used by SDK. IF login successful,
7756   we set this property so that you can get it later along with token
7757   by {@link KiiUser#getAccessTokenObject()}.<br>
7758   Also, if successful, the user is cached inside SDK as current user
7759   and accessible via {@link KiiUser.getCurrentUser()}.<br>
7760   
7761   Note that, if not specified, token expiration time is not cached
7762   and set to value equivalant to 275760 years.<br>
7763   
7764   If the specified token is expired, authenticataiton will be failed.
7765   Authenticate the user again to renew the token.<br>
7766   
7767   If expiresAt is invalid, callbacks.failure or reject callback of promise will be called. <br>
7768   
7769   @param {String} accessToken A valid access token associated with the desired user
7770   @param {Object} [callbacks] An object with callback methods defined
7771   @param {Method} callbacks.success The callback method to call on a successful authentication request
7772   @param {Method} callbacks.failure The callback method to call on a failed authentication request
7773   @param {Date} expiresAt Access token expire time that has received by {@link KiiUser#getAccessTokenObject()}. This param is optional and can be omitted.
7774   @return {Promise} return promise object.
7775     <ul>
7776       <li>fulfill callback function: function(theAuthenticatedUser). theAuthenticatedUser is KiiUser instance.</li>
7777       <li>reject callback function: function(error). error is an Error instance.
7778         <ul>
7779           <li>error.target is a KiiUser instance.If expiresAt is invalid, it will be null.</li>
7780           <li>error.message</li>
7781         </ul>
7782       </li>
7783     </ul>
7784   @example
7785   // example to use callbacks directly
7786   // Assume you stored the object get from KiiUser#getAccessTokenObject()
7787   // and now accessing by 'tokenObject' var.
7788   var token = tokenObject["access_token"];
7789   var expiresAt = tokenObject["expires_at"];
7790   expireDate.setHours(expireDate.getHours() + 24);
7791   KiiUser.authenticateWithToken(token, {
7792       success: function(theAuthenticatedUser) {
7793           // do something with the authenticated user
7794       },
7795   
7796       failure: function(theUser, anErrorString) {
7797           // do something with the error response
7798       }
7799   }, expiresAt);
7800   
7801   // example to use Promise
7802   // Assume you stored the object get from KiiUser#getAccessTokenObject()
7803   // and now accessing by 'tokenObject' var.
7804   var token = tokenObject["access_token"];
7805   var expiresAt = tokenObject["expires_at"];
7806   expireDate.setHours(expireDate.getHours() + 24);
7807   KiiUser.authenticateWithToken(token, null, expiresAt).then(
7808       function(theAuthenticatedUser) {
7809           // do something with the authenticated user
7810       },
7811       function(error) {
7812           // do something with the error response
7813       }
7814   );
7815    */
7816 
7817   KiiUser.authenticateWithToken = function(token, callbacks, expiresAt) {
7818     return new Promise(function(resolve, reject) {
7819       var authenticateWithTokenCallbacks;
7820       authenticateWithTokenCallbacks = {
7821         success: function() {
7822           if (callbacks != null) {
7823             callbacks.success.apply(callbacks, arguments);
7824           }
7825           return resolve(arguments[0]);
7826         },
7827         failure: function() {
7828           var error;
7829           if (callbacks != null) {
7830             callbacks.failure.apply(callbacks, arguments);
7831           }
7832           error = KiiUtilities._Error(arguments[1]);
7833           error.target = arguments[0];
7834           return reject(error);
7835         }
7836       };
7837       return KiiUser._authenticateWithTokenUsingCallbacks(token, authenticateWithTokenCallbacks, expiresAt);
7838     });
7839   };
7840 
7841   KiiUser._authenticateWithTokenUsingCallbacks = function(token, callbacks, expiresAt) {
7842     var expiresAtType, user;
7843     expiresAtType = KiiUtilities._type(expiresAt);
7844     if (expiresAtType !== 'undefined' && expiresAtType !== 'date') {
7845       return callbacks.failure(null, root.InvalidArgumentException('Specified expiresAt must be a Date'));
7846     }
7847     user = new root.KiiUser();
7848     return user._authenticateWithToken(token, callbacks, expiresAt);
7849   };
7850 
7851 
7852   /** Asynchronously authenticates a user with the server using specified totp code.
7853   This method is non-blocking.<br><br>
7854   
7855   @param {String} totpCode A valid totp code
7856   @param {Object} [callbacks] An object with callback methods defined
7857   @param {Method} callbacks.success The callback method to call on a successful authentication request
7858   @param {Method} callbacks.failure The callback method to call on a failed authentication request
7859   @param {Date} expiresAt Access token expire time that has received by {@link KiiUser#getAccessTokenObject()}. This param is optional and can be omitted.
7860   @return {Promise} return promise object.
7861     <ul>
7862       <li>fulfill callback function: function(theAuthenticatedUser). theAuthenticatedUser is KiiUser instance.</li>
7863       <li>reject callback function: function(error). error is an Error instance.
7864         <ul>
7865           <li>error.target is a KiiUser instance.</li>
7866           <li>error.message</li>
7867         </ul>
7868       </li>
7869     </ul>
7870   @example
7871   // example to use callbacks directly
7872   KiiUser.authenticateWithTotp(totpCode, {
7873       success: function(theAuthenticatedUser) {
7874           // do something with the authenticated user
7875       },
7876   
7877       failure: function(theUser, anErrorString) {
7878           // do something with the error response
7879       }
7880   }, expiresAt);
7881   
7882   // example to use Promise
7883   KiiUser.authenticateWithTotp(totpCode).then(
7884       function(theAuthenticatedUser) {
7885           // do something with the authenticated user
7886       },
7887       function(error) {
7888           // do something with the error response
7889       }
7890   );
7891    */
7892 
7893   KiiUser.authenticateWithTotp = function(totpCode, callbacks) {
7894     return new Promise(function(resolve, reject) {
7895       var authenticateWithTotpCallbacks;
7896       authenticateWithTotpCallbacks = {
7897         success: function() {
7898           if (callbacks != null) {
7899             callbacks.success.apply(callbacks, arguments);
7900           }
7901           return resolve(arguments[0]);
7902         },
7903         failure: function() {
7904           var error;
7905           if (callbacks != null) {
7906             callbacks.failure.apply(callbacks, arguments);
7907           }
7908           error = KiiUtilities._Error(arguments[1]);
7909           error.target = arguments[0];
7910           return reject(error);
7911         }
7912       };
7913       return KiiUser._authenticateWithTotpUsingCallbacks(totpCode, authenticateWithTotpCallbacks);
7914     });
7915   };
7916 
7917   KiiUser._authenticateWithTotpUsingCallbacks = function(totpCode, callbacks) {
7918     var data, user;
7919     data = {
7920       grant_type: "mfa",
7921       totp_code: totpCode
7922     };
7923     user = new root.KiiUser();
7924     return user._authenticateWithMfa(data, callbacks);
7925   };
7926 
7927 
7928   /** Asynchronously authenticates a user with the server using specified recovery code.
7929   This method is non-blocking.<br><br>
7930   
7931   @param {String} recoveryCode A valid recovery code
7932   @param {Object} [callbacks] An object with callback methods defined
7933   @param {Method} callbacks.success The callback method to call on a successful authentication request
7934   @param {Method} callbacks.failure The callback method to call on a failed authentication request
7935   @param {Date} expiresAt Access token expire time that has received by {@link KiiUser#getAccessTokenObject()}. This param is optional and can be omitted.
7936   @return {Promise} return promise object.
7937     <ul>
7938       <li>fulfill callback function: function(theAuthenticatedUser). theAuthenticatedUser is KiiUser instance.</li>
7939       <li>reject callback function: function(error). error is an Error instance.
7940         <ul>
7941           <li>error.target is a KiiUser instance.</li>
7942           <li>error.message</li>
7943         </ul>
7944       </li>
7945     </ul>
7946   @example
7947   // example to use callbacks directly
7948   KiiUser.authenticateWithRecoveryCode(recoveryCode, {
7949       success: function(theAuthenticatedUser) {
7950           // do something with the authenticated user
7951       },
7952   
7953       failure: function(theUser, anErrorString) {
7954           // do something with the error response
7955       }
7956   }, expiresAt);
7957   
7958   // example to use Promise
7959   KiiUser.authenticateWithRecoveryCode(recoveryCode).then(
7960       function(theAuthenticatedUser) {
7961           // do something with the authenticated user
7962       },
7963       function(error) {
7964           // do something with the error response
7965       }
7966   );
7967    */
7968 
7969   KiiUser.authenticateWithRecoveryCode = function(recoveryCode, callbacks) {
7970     return new Promise(function(resolve, reject) {
7971       var authenticateWithRecoveryCodeCallbacks;
7972       authenticateWithRecoveryCodeCallbacks = {
7973         success: function() {
7974           if (callbacks != null) {
7975             callbacks.success.apply(callbacks, arguments);
7976           }
7977           return resolve(arguments[0]);
7978         },
7979         failure: function() {
7980           var error;
7981           if (callbacks != null) {
7982             callbacks.failure.apply(callbacks, arguments);
7983           }
7984           error = KiiUtilities._Error(arguments[1]);
7985           error.target = arguments[0];
7986           return reject(error);
7987         }
7988       };
7989       return KiiUser._authenticateWithRecoveryCodeUsingCallbacks(recoveryCode, authenticateWithRecoveryCodeCallbacks);
7990     });
7991   };
7992 
7993   KiiUser._authenticateWithRecoveryCodeUsingCallbacks = function(recoveryCode, callbacks) {
7994     var data, user;
7995     data = {
7996       grant_type: "mfa",
7997       recovery_code: recoveryCode
7998     };
7999     user = new root.KiiUser();
8000     return user._authenticateWithMfa(data, callbacks);
8001   };
8002 
8003 
8004   /** Registers a user with the server
8005   
8006   <br><br>The user object must have an associated email/password combination.
8007   @param {Object} [callbacks] An object with callback methods defined
8008   @param {Method} callbacks.success The callback method to call on a successful registration request
8009   @param {Method} callbacks.failure The callback method to call on a failed registration request
8010   @return {Promise} return promise object.
8011     <ul>
8012       <li>fulfill callback function: function(theAuthenticatedUser). theAuthenticatedUser is KiiUser instance.</li>
8013       <li>reject callback function: function(error). error is an Error instance.
8014         <ul>
8015           <li>error.target is a KiiUser instance.</li>
8016           <li>error.message</li>
8017         </ul>
8018       </li>
8019     </ul>
8020   @example
8021   // example to use callbacks directly
8022   var user = KiiUser.userWithUsername("myusername", "mypassword");
8023   user.register({
8024       success: function(theAuthenticatedUser) {
8025           // do something with the authenticated user
8026       },
8027   
8028       failure: function(theUser, anErrorString) {
8029           // do something with the error response
8030       }
8031   });
8032   
8033   // example to use Promise
8034   var user = KiiUser.userWithUsername("myusername", "mypassword");
8035   user.register().then(
8036       function(params) {
8037           // do something with the authenticated user
8038       },
8039       function(error) {
8040           // do something with the error response
8041       }
8042   );
8043    */
8044 
8045   KiiUser.prototype.register = function(callbacks) {
8046     return new Promise((function(_this) {
8047       return function(resolve, reject) {
8048         var registerCallbacks;
8049         registerCallbacks = {
8050           success: function() {
8051             if (callbacks != null) {
8052               callbacks.success.apply(callbacks, arguments);
8053             }
8054             return resolve(arguments[0]);
8055           },
8056           failure: function() {
8057             if (callbacks != null) {
8058               callbacks.failure.apply(callbacks, arguments);
8059             }
8060             return reject(KiiUtilities._Error(arguments[1], _this));
8061           }
8062         };
8063         return _this._registerUsingCallbacks(registerCallbacks);
8064       };
8065     })(this));
8066   };
8067 
8068   KiiUser.prototype._registerUsingCallbacks = function(callbacks) {
8069     var data, key, registrationCallbacks, request, value, _ref;
8070     root.Kii.logger("Registering user " + this);
8071     data = {
8072       password: this._password
8073     };
8074     if (this._username != null) {
8075       data.loginName = this._username;
8076     }
8077     if (this._displayName != null) {
8078       data.displayName = this._displayName;
8079     }
8080     if (this._emailAddress != null) {
8081       data.emailAddress = this._emailAddress;
8082     }
8083     if (this._phoneNumber != null) {
8084       data.phoneNumber = this._phoneNumber;
8085     }
8086     if (!this._validateLocalPhoneNumber(this._phoneNumber, this._country)) {
8087       callbacks.failure(this, "needs to provide country for the local phone number");
8088       return;
8089     }
8090     if (this._country != null) {
8091       data.country = this._country;
8092     }
8093     if (this._locale != null) {
8094       data.locale = this._locale;
8095     }
8096     root.Kii.logger("CINFO");
8097     root.Kii.logger(JSON.stringify(this._customInfo));
8098     _ref = this._customInfo;
8099     for (key in _ref) {
8100       value = _ref[key];
8101       root.Kii.logger("Key/val: " + key + "/" + value);
8102       data[key] = value;
8103     }
8104     request = this._getRequest({
8105       path: "/users",
8106       withApp: true
8107     });
8108     request.setMethod("POST");
8109     request.setData(data);
8110     request.setAnonymous(true);
8111     request.setContentType("application/vnd.kii.RegistrationRequest+json");
8112     registrationCallbacks = {
8113       success: (function(_this) {
8114         return function(data) {
8115           root.Kii.logger("Succreg");
8116           _this._updateWithJSON(data);
8117           return _this._authenticate(callbacks);
8118         };
8119       })(this),
8120       failure: (function(_this) {
8121         return function(error, statusCode) {
8122           root.Kii.logger("Failreg");
8123           _this._clearPassword();
8124           if (callbacks != null) {
8125             return callbacks.failure(_this, error);
8126           }
8127         };
8128       })(this)
8129     };
8130     return request.execute(registrationCallbacks, false);
8131   };
8132 
8133 
8134   /** Registers a user as pseudo user with the server
8135   
8136   @param {Object} [callbacks] An object with callback methods defined.
8137   This argument is mandatory and can't be ommited.
8138   @param {Method} callbacks.success The callback method to call on a successful registration request
8139   @param {Method} callbacks.failure The callback method to call on a failed registration request
8140   @param {Object} userFields Custom Fields to add to the user. This is optional and can be omitted.
8141   @return {Promise} return promise object.
8142     <ul>
8143       <li>fulfill callback function: function(theAuthenticatedUser). theAuthenticatedUser is KiiUser instance.</li>
8144       <li>reject callback function: function(error). error is an Error instance.
8145         <ul>
8146           <li>error.message</li>
8147         </ul>
8148       </li>
8149     </ul>
8150   @example
8151   // example to use callbacks directly
8152   var userFields = {"displayName":"yourName", "country":"JP", "age":30};
8153   KiiUser.registerAsPseudoUser({
8154       success: function(theAuthenticatedUser) {
8155           // do something with the authenticated user
8156       },
8157   
8158       failure: function(theUser, anErrorString) {
8159           // do something with the error response
8160       }
8161   }, userFields);
8162   
8163   // example to use Promise
8164   var userFields = {"displayName":"yourName", "country":"JP", "age":30};
8165   KiiUser.registerAsPseudoUser(null, userFields).then(
8166       function(theAuthenticatedUser) {
8167           // do something with the authenticated user
8168       },
8169       function(error) {
8170           // do something with the error response
8171       }
8172   );
8173    */
8174 
8175   KiiUser.registerAsPseudoUser = function(callbacks, userFields) {
8176     return new Promise(function(resolve, reject) {
8177       var registerAsPseudoUserCallbacks;
8178       registerAsPseudoUserCallbacks = {
8179         success: function() {
8180           if (callbacks != null) {
8181             callbacks.success.apply(callbacks, arguments);
8182           }
8183           return resolve(arguments[0]);
8184         },
8185         failure: function() {
8186           if (callbacks != null) {
8187             callbacks.failure.apply(callbacks, arguments);
8188           }
8189           return reject(KiiUtilities._Error(arguments[1]));
8190         }
8191       };
8192       return KiiUser._registerAsPseudoUserUsingCallbacks(registerAsPseudoUserCallbacks, userFields);
8193     });
8194   };
8195 
8196   KiiUser._registerAsPseudoUserUsingCallbacks = function(callbacks, userFields) {
8197     var jsonBody, requestCallbacks, url, wrapper, xhr;
8198     url = root.Kii.getBaseURL() + "/apps/" + root.Kii.getAppID() + "/users";
8199     wrapper = KiiXHRWrapperFactory.createXHRWrapper("POST", url);
8200     xhr = wrapper.xhr;
8201     xhr.setRequestHeader("x-kii-appid", root.Kii.getAppID());
8202     xhr.setRequestHeader("x-kii-appkey", root.Kii.getAppKey());
8203     xhr.setRequestHeader("x-kii-sdk", root.KiiSDKClientInfo.getSDKClientInfo());
8204     xhr.setRequestHeader("Content-Type", "application/vnd.kii.RegistrationAndAuthorizationRequest+json");
8205     requestCallbacks = {
8206       success: function() {
8207         var accessToken, errString, json, user;
8208         try {
8209           if (xhr.status < 300 && xhr.status >= 200) {
8210             json = JSON.parse(xhr.responseText);
8211             accessToken = json["_accessToken"];
8212             user = new root.KiiUser();
8213             user._updateWithJSON(json);
8214             user._setAccessToken(accessToken);
8215             user._setExpiresAt(new Date(KiiUtilities.MAX_DATE_IN_MILLIS));
8216             root.Kii.setCurrentUser(user);
8217             return callbacks.success(user);
8218           } else {
8219             errString = xhr.status + " : " + url;
8220             return callbacks.failure(null, errString);
8221           }
8222         } catch (_error) {
8223           return callbacks.failure(null, "failed to parse response");
8224         }
8225       },
8226       failure: function() {
8227         var errString, json;
8228         errString = "failed to register pseudo user. statusCode: " + xhr.status;
8229         try {
8230           json = JSON.parse(xhr.responseText);
8231           if (json.errorCode != null) {
8232             errString += " error code: " + json.errorCode;
8233           }
8234           if (json.message != null) {
8235             return errString += " error message: " + json.message;
8236           }
8237         } catch (_error) {
8238 
8239         } finally {
8240           callbacks.failure(null, errString);
8241         }
8242       }
8243     };
8244     if (userFields == null) {
8245       userFields = {};
8246     }
8247     jsonBody = JSON.stringify(userFields);
8248     return wrapper.sendData(jsonBody, requestCallbacks);
8249   };
8250 
8251 
8252   /** Sets credentials data and custom fields to pseudo user.
8253   
8254   <br><br>This method is exclusive to pseudo user.
8255   <br>password is mandatory and needs to provide at least one of login name, email address or phone number.
8256   @param {Object} identityData
8257   @param identityData.emailAddress The user's email address. Valid pattern is ^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,6}$
8258   @param identityData.phoneNumber The user's phone number. Global phone valid pattern is ^[\\+]{1}[0-9]{2}. Note that you must provide country code in userFields if you speficy local phone number.
8259   @param identityData.username The user's desired username. Valid pattern is ^[a-zA-Z0-9-_\\.]{3,64}$
8260   @param password The user's password. Valid pattern is ^[\x20-\x7E]{4,50}$.
8261   @param {Object} [callbacks] An object with callback methods defined.
8262   This argument is mandatory and can't be ommited.
8263   @param {Method} callbacks.success The callback method to call on a successful authentication request
8264   @param {Method} callbacks.failure The callback method to call on a failed authentication request
8265   @param {Object} userFields Custom Fields to add to the user. This is optional and can be omitted.
8266   @param {Array} removeFields An array of field names to remove from the user custom fields. Default fields are not removed from server.
8267   This is optional and can be omitted.
8268   @return {Promise} return promise object.
8269     <ul>
8270       <li>fulfill callback function: function(user). user is KiiUser instance which this method was called on.</li>
8271       <li>reject callback function: function(error). error is an Error instance.
8272         <ul>
8273           <li>error.target is the KiiUser instance which this method was called on.</li>
8274           <li>error.message</li>
8275         </ul>
8276       </li>
8277     </ul>
8278   @example
8279   // example to use callbacks directly
8280   var identityData = { "username": "__USER_NAME_" };
8281   var userFields = { "displayName":"__DISPLAY_NAME","score":12344300 };
8282   var removeFields = ["age"];
8283   user.putIdentity(
8284       identityData,
8285       "__PASSWORD__",
8286       {
8287           success: function(user) {
8288             // do something with the updated user.
8289           },
8290           failure: function(user, errorString) {
8291             // check error response.
8292           }
8293       },
8294       userFields,
8295       removeFields
8296   );
8297   
8298   // example to use Promise
8299   var identityData = { "username": "__USER_NAME_" };
8300   var userFields = { "displayName":"__DISPLAY_NAME","score":12344300 };
8301   var removeFields = ["age"];
8302   user.putIdentity(
8303       identityData,
8304       "__PASSWORD__",
8305       null,
8306       userFields,
8307       removeFields
8308   ).then(
8309       function(user) {
8310           // do something with the updated user.
8311       },
8312       function(error) {
8313           // check error response.
8314       }
8315   );
8316    */
8317 
8318   KiiUser.prototype.putIdentity = function(identityData, password, callbacks, userFields, removeFields) {
8319     return new Promise((function(_this) {
8320       return function(resolve, reject) {
8321         var putIdentityCallbacks;
8322         putIdentityCallbacks = {
8323           success: function() {
8324             if (callbacks != null) {
8325               callbacks.success.apply(callbacks, arguments);
8326             }
8327             return resolve(arguments[0]);
8328           },
8329           failure: function() {
8330             if (callbacks != null) {
8331               callbacks.failure.apply(callbacks, arguments);
8332             }
8333             return reject(KiiUtilities._Error(arguments[1], _this));
8334           }
8335         };
8336         return _this._putIdentityUsingCallbacks(identityData, password, putIdentityCallbacks, userFields, removeFields);
8337       };
8338     })(this));
8339   };
8340 
8341   KiiUser.prototype._putIdentityUsingCallbacks = function(identityData, password, callbacks, userFields, removeFields) {
8342     var country, data, errorString, hasIdentityData;
8343     root.Kii.logger("Put identity user: " + this._uuid + ", data: " + (JSON.stringify(identityData)));
8344     data = {};
8345     if (!this.isPseudoUser()) {
8346       if (callbacks != null) {
8347         callbacks.failure(this, "This user has the identity already");
8348       }
8349       return;
8350     }
8351     if (identityData == null) {
8352       if (callbacks != null) {
8353         callbacks.failure(this, "identityData is null");
8354       }
8355       return;
8356     }
8357     try {
8358       this._validateIdentityData(identityData);
8359     } catch (_error) {
8360       errorString = _error;
8361       if (callbacks != null) {
8362         callbacks.failure(this, errorString);
8363       }
8364       return;
8365     }
8366     hasIdentityData = false;
8367     if (identityData.emailAddress != null) {
8368       hasIdentityData = true;
8369     }
8370     if (identityData.phoneNumber != null) {
8371       hasIdentityData = true;
8372     }
8373     if (identityData.username != null) {
8374       hasIdentityData = true;
8375     }
8376     if (!hasIdentityData) {
8377       if (callbacks != null) {
8378         callbacks.failure(this, "needs to provide at least one of login name, email address or phone number");
8379       }
8380       return;
8381     }
8382     if (password != null) {
8383       if (!KiiUtilities._validatePassword(password)) {
8384         if (callbacks != null) {
8385           callbacks.failure(this, "invalid password");
8386         }
8387         return;
8388       }
8389     } else {
8390       if (callbacks != null) {
8391         callbacks.failure(this, "password is null");
8392       }
8393       return;
8394     }
8395     country = userFields != null ? userFields.country : null;
8396     if ((identityData.phoneNumber != null) && !this._validateLocalPhoneNumber(identityData.phoneNumber, country)) {
8397       callbacks.failure(this, "needs to provide country for the local phone number");
8398       return;
8399     }
8400     return this.refresh({
8401       failure: (function(_this) {
8402         return function(user, error) {
8403           root.Kii.logger("Failreg");
8404           if (callbacks != null) {
8405             return callbacks.failure(_this, error);
8406           }
8407         };
8408       })(this),
8409       success: (function(_this) {
8410         return function(user) {
8411           var jsonBody, key, removeField, requestCallbacks, url, value, wrapper, xhr, _i, _len;
8412           if (!user.isPseudoUser()) {
8413             if (callbacks != null) {
8414               callbacks.failure(user, "This user has the identity already");
8415             }
8416             return;
8417           }
8418           data = _this._clone(user._customInfo);
8419           if (identityData.emailAddress != null) {
8420             data.emailAddress = identityData.emailAddress;
8421           }
8422           if (identityData.phoneNumber != null) {
8423             data.phoneNumber = identityData.phoneNumber;
8424           }
8425           if (identityData.username != null) {
8426             data.loginName = identityData.username;
8427           }
8428           data.password = password;
8429           if (userFields != null) {
8430             for (key in userFields) {
8431               value = userFields[key];
8432               data[key] = value;
8433             }
8434           }
8435           if (removeFields != null) {
8436             for (_i = 0, _len = removeFields.length; _i < _len; _i++) {
8437               removeField = removeFields[_i];
8438               delete data[removeField];
8439             }
8440           }
8441           url = root.Kii.getBaseURL() + "/apps/" + root.Kii.getAppID() + ("/users/" + _this._uuid);
8442           wrapper = _this._getXhrWrapper("POST", url);
8443           xhr = wrapper.xhr;
8444           _this._setAuthHeader(xhr);
8445           xhr.setRequestHeader("Content-Type", "application/vnd.kii.UserUpdateRequest+json");
8446           requestCallbacks = {
8447             success: function() {
8448               var errString, json;
8449               try {
8450                 json = JSON.parse(xhr.responseText);
8451                 if (xhr.status < 300 && xhr.status >= 200) {
8452                   user._setModified(json.modifiedAt);
8453                   user._updateWithIdentityData(identityData);
8454                   user._updateWithUserFields(userFields, removeFields);
8455                   _this._hasPassword = true;
8456                   return callbacks.success(user);
8457                 } else {
8458                   errString = xhr.status + " : " + url;
8459                   return callbacks.failure(_this, errString);
8460                 }
8461               } catch (_error) {
8462                 return callbacks.failure(_this, "failed to parse response");
8463               }
8464             },
8465             failure: function() {
8466               var errString, json;
8467               errString = "failed to put identity data. statusCode: " + xhr.status;
8468               try {
8469                 json = JSON.parse(xhr.responseText);
8470                 if (json.errorCode != null) {
8471                   errString += " error code: " + json.errorCode;
8472                 }
8473                 if (json.message != null) {
8474                   return errString += " error message: " + json.message;
8475                 }
8476               } catch (_error) {
8477 
8478               } finally {
8479                 callbacks.failure(_this, errString);
8480               }
8481             }
8482           };
8483           jsonBody = JSON.stringify(data);
8484           root.Kii.logger(jsonBody);
8485           return wrapper.sendData(jsonBody, requestCallbacks);
8486         };
8487       })(this)
8488     });
8489   };
8490 
8491 
8492   /** Update user attributes.
8493   
8494   
8495   <br><br>If you want to update identity data of pseudo user, you must use KiiUser.putIdentity instead.
8496   @param {Object} identityData
8497   @param identityData.emailAddress The user's email address. Valid pattern is ^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,6}$
8498   @param identityData.phoneNumber The user's phone number. Global phone valid pattern is ^[\\+]{1}[0-9]{2}. Note that you must provide country code in userFields if you specify local phone number.
8499   @param identityData.username The user's desired username. Valid pattern is ^[a-zA-Z0-9-_\\.]{3,64}$
8500   @param {Object} [callbacks] An object with callback methods defined.
8501   This argument is mandatory and can't be ommited.
8502   @param {Method} callbacks.success The callback method to call on a successful authentication request
8503   @param {Method} callbacks.failure The callback method to call on a failed authentication request
8504   @param {Object} userFields Custom Fields to add to the user.
8505   @param {Array} removeFields An array of field names to remove from the user custom fields. Default fields are not removed from server.
8506   @return {Promise} return promise object.
8507     <ul>
8508       <li>fulfill callback function: function(user). user is KiiUser instance which this method was called on.</li>
8509       <li>reject callback function: function(error). error is an Error instance.
8510         <ul>
8511           <li>error.target is a KiiUser instance.</li>
8512           <li>error.message</li>
8513         </ul>
8514       </li>
8515     </ul>
8516   @example
8517   // example to use callbacks directly
8518   var identityData = { "username": "__USER_NAME_" };
8519   var userFields = { "displayName":"__DISPLAY_NAME","score":12344300 };
8520   var removeFields = ["age"];
8521   user.update(
8522       identityData,
8523       {
8524           success: function(user) {
8525             // do something with the updated user.
8526           },
8527           failure: function(user, errorString) {
8528             // check error response.
8529           }
8530       },
8531       userFields,
8532       removeFields
8533   );
8534   
8535   // example to use Promise
8536   var identityData = { "username": "__USER_NAME_" };
8537   var userFields = { "displayName":"__DISPLAY_NAME","score":12344300 };
8538   var removeFields = ["age"];
8539   user.update(
8540       identityData,
8541       null,
8542       userFields,
8543       removeFields
8544   ).then(
8545       function(user) {
8546           // do something with the updated user.
8547       },
8548       function(error) {
8549           // check error response.
8550       }
8551   );
8552    */
8553 
8554   KiiUser.prototype.update = function(identityData, callbacks, userFields, removeFields) {
8555     return new Promise((function(_this) {
8556       return function(resolve, reject) {
8557         var updateCallbacks;
8558         updateCallbacks = {
8559           success: function() {
8560             if (callbacks != null) {
8561               callbacks.success.apply(callbacks, arguments);
8562             }
8563             return resolve(arguments[0]);
8564           },
8565           failure: function() {
8566             if (callbacks != null) {
8567               callbacks.failure.apply(callbacks, arguments);
8568             }
8569             return reject(KiiUtilities._Error(arguments[1], _this));
8570           }
8571         };
8572         return _this._updateUsingCallbacks(identityData, updateCallbacks, userFields, removeFields);
8573       };
8574     })(this));
8575   };
8576 
8577   KiiUser.prototype._updateUsingCallbacks = function(identityData, callbacks, userFields, removeFields) {
8578     var country, data, errorString, hasIdentityData, hasRemoveFields, hasUserFields, key, removeField, value, _i, _len;
8579     root.Kii.logger("update user: " + this._uuid);
8580     data = {};
8581     hasIdentityData = false;
8582     hasUserFields = false;
8583     hasRemoveFields = false;
8584     if (identityData != null) {
8585       try {
8586         this._validateIdentityData(identityData);
8587       } catch (_error) {
8588         errorString = _error;
8589         if (callbacks != null) {
8590           callbacks.failure(this, errorString);
8591         }
8592         return;
8593       }
8594       if (identityData.emailAddress != null) {
8595         hasIdentityData = true;
8596       }
8597       if (identityData.phoneNumber != null) {
8598         hasIdentityData = true;
8599       }
8600       if (identityData.username != null) {
8601         hasIdentityData = true;
8602       }
8603     }
8604     if (userFields != null) {
8605       for (key in userFields) {
8606         value = userFields[key];
8607         hasUserFields = true;
8608         break;
8609       }
8610     }
8611     if (removeFields != null) {
8612       for (_i = 0, _len = removeFields.length; _i < _len; _i++) {
8613         removeField = removeFields[_i];
8614         hasRemoveFields = true;
8615         break;
8616       }
8617     }
8618     if (!hasIdentityData && !hasUserFields && !hasRemoveFields) {
8619       callbacks.failure(this, "all arguments are null or empty");
8620       return;
8621     }
8622     country = userFields != null ? userFields.country : null;
8623     if ((identityData != null) && (identityData.phoneNumber != null) && !this._validateLocalPhoneNumber(identityData.phoneNumber, country)) {
8624       callbacks.failure(this, "needs to provide country for the local phone number");
8625       return;
8626     }
8627     return this.refresh({
8628       failure: (function(_this) {
8629         return function(user, error) {
8630           root.Kii.logger("Failreg");
8631           if (callbacks != null) {
8632             return callbacks.failure(_this, error);
8633           }
8634         };
8635       })(this),
8636       success: (function(_this) {
8637         return function(user) {
8638           var jsonBody, requestCallbacks, url, wrapper, xhr, _j, _len1;
8639           if (user.isPseudoUser() && hasIdentityData) {
8640             if (callbacks != null) {
8641               callbacks.failure(user, "Pseudo user must use putIdentity()");
8642             }
8643             return;
8644           }
8645           data = _this._clone(user._customInfo);
8646           if (identityData != null) {
8647             if (identityData.emailAddress != null) {
8648               data.emailAddress = identityData.emailAddress;
8649             }
8650             if (identityData.phoneNumber != null) {
8651               data.phoneNumber = identityData.phoneNumber;
8652             }
8653             if (identityData.username != null) {
8654               data.loginName = identityData.username;
8655             }
8656           }
8657           if (userFields != null) {
8658             for (key in userFields) {
8659               value = userFields[key];
8660               data[key] = value;
8661             }
8662           }
8663           if (removeFields != null) {
8664             for (_j = 0, _len1 = removeFields.length; _j < _len1; _j++) {
8665               removeField = removeFields[_j];
8666               delete data[removeField];
8667             }
8668           }
8669           url = root.Kii.getBaseURL() + "/apps/" + root.Kii.getAppID() + ("/users/" + _this._uuid);
8670           wrapper = _this._getXhrWrapper("POST", url, false);
8671           xhr = wrapper.xhr;
8672           _this._setAuthHeader(xhr);
8673           xhr.setRequestHeader("Content-Type", "application/vnd.kii.UserUpdateRequest+json");
8674           requestCallbacks = {
8675             success: function() {
8676               var errString, json;
8677               try {
8678                 json = JSON.parse(xhr.responseText);
8679                 if (xhr.status < 300 && xhr.status >= 200) {
8680                   user._setModified(data.modifiedAt);
8681                   user._updateWithIdentityData(identityData);
8682                   user._updateWithUserFields(userFields, removeFields);
8683                   return callbacks.success(user);
8684                 } else {
8685                   errString = xhr.status + " : " + url;
8686                   return callbacks.failure(_this, errString);
8687                 }
8688               } catch (_error) {
8689                 return callbacks.failure(_this, "failed to parse response");
8690               }
8691             },
8692             failure: function() {
8693               var errString, json;
8694               errString = "failed to update user. statusCode: " + xhr.status;
8695               try {
8696                 json = JSON.parse(xhr.responseText);
8697                 if (json.errorCode != null) {
8698                   errString += " error code: " + json.errorCode;
8699                 }
8700                 if (json.message != null) {
8701                   return errString += " error message: " + json.message;
8702                 }
8703               } catch (_error) {
8704 
8705               } finally {
8706                 callbacks.failure(_this, errString);
8707               }
8708             }
8709           };
8710           jsonBody = JSON.stringify(data);
8711           return wrapper.sendData(jsonBody, requestCallbacks);
8712         };
8713       })(this)
8714     });
8715   };
8716 
8717 
8718   /** Update a user's password on the server
8719   
8720   <br><br>Update a user's password with the server. The fromPassword must be equal to the current password associated with the account in order to succeed.
8721   @param {String} fromPassword The user's current password
8722   @param {String} toPassword The user's desired password. Must be at least 4 characters, made up of alphanumeric and/or: @,#,$,%,^,&
8723   @param {Object} [callbacks] An object with callback methods defined
8724   @param {Method} callbacks.success The callback method to call on a successful update password request
8725   @param {Method} callbacks.failure The callback method to call on a failed update password request
8726   @return {Promise} return promise object.
8727     <ul>
8728       <li>fulfill callback function: function(theUser). theUser is KiiUser instance which this method was called on.</li>
8729       <li>reject callback function: function(error). error is an Error instance.
8730         <ul>
8731           <li>error.target is the KiiUser instance which this method was called on.</li>
8732           <li>error.message</li>
8733         </ul>
8734       </li>
8735     </ul>
8736   @example
8737   // example to use callbacks directly
8738   var user = Kii.currentUser();
8739   user.updatePassword("oldpassword", "newpassword", {
8740       success: function(theUser) {
8741           // do something
8742       },
8743   
8744       failure: function(theUser, anErrorString) {
8745           // do something with the error response
8746       }
8747   });
8748   
8749   // example to use Promise
8750   var user = Kii.currentUser();
8751   user.updatePassword("oldpassword", "newpassword").then(
8752       function(theUser) {
8753           // do something
8754       },
8755       function(error) {
8756           // do something with the error response
8757       }
8758   );
8759    */
8760 
8761   KiiUser.prototype.updatePassword = function(fromPassword, toPassword, callbacks) {
8762     return new Promise((function(_this) {
8763       return function(resolve, reject) {
8764         var updatePasswordCallbacks;
8765         updatePasswordCallbacks = {
8766           success: function() {
8767             if (callbacks != null) {
8768               callbacks.success.apply(callbacks, arguments);
8769             }
8770             return resolve(arguments[0]);
8771           },
8772           failure: function() {
8773             if (callbacks != null) {
8774               callbacks.failure.apply(callbacks, arguments);
8775             }
8776             return reject(KiiUtilities._Error(arguments[1], _this));
8777           }
8778         };
8779         return _this._updatePasswordUsingCallbacks(fromPassword, toPassword, updatePasswordCallbacks);
8780       };
8781     })(this));
8782   };
8783 
8784   KiiUser.prototype._updatePasswordUsingCallbacks = function(fromPassword, toPassword, callbacks) {
8785     var data, path, request, updateCallbacks;
8786     root.Kii.logger("Updating password from " + fromPassword + " to " + toPassword);
8787     if (KiiUtilities._validatePassword(toPassword)) {
8788       data = {
8789         oldPassword: fromPassword,
8790         newPassword: toPassword
8791       };
8792       path = "/users/" + this._uuid + "/password";
8793       request = this._getRequest({
8794         path: path,
8795         withApp: true
8796       });
8797       request.setMethod("PUT");
8798       request.setData(data);
8799       request.setContentType("application/vnd.kii.ChangePasswordRequest+json");
8800       updateCallbacks = {
8801         success: (function(_this) {
8802           return function(data, statusCode) {
8803             _this._clearPassword;
8804             if (statusCode < 300 && statusCode >= 200) {
8805               if (callbacks != null) {
8806                 return callbacks.success(_this);
8807               }
8808             } else if (callbacks != null) {
8809               return callbacks.failure(_this, "Unable to change password");
8810             }
8811           };
8812         })(this),
8813         failure: (function(_this) {
8814           return function(error, statusCode) {
8815             _this._clearPassword;
8816             if (callbacks != null) {
8817               return callbacks.failure(_this, error);
8818             }
8819           };
8820         })(this)
8821       };
8822       return request.execute(updateCallbacks, true);
8823     } else if (callbacks != null) {
8824       return callbacks.failure(this, (new root.InvalidPasswordException()).message);
8825     }
8826   };
8827 
8828 
8829   /** Reset a user's password on the server
8830   
8831   <br><br>Reset a user's password on the server. The user is determined by the specified userIdentifier - which is an email address that has already been associated with an account. Reset instructions will be sent to that identifier.
8832   <br><br><b>Please Note:</b> This will reset the user's access token, so if they are currently logged in - their session will no longer be valid.
8833   @param {String} userIdentifier The user's email address
8834   @param {Object} [callbacks] An object with callback methods defined
8835   @param {Method} callbacks.success The callback method to call on a successful update password request
8836   @param {Method} callbacks.failure The callback method to call on a failed update password request
8837   @return {Promise} return promise object.
8838     <ul>
8839       <li>fulfill callback function: function(). No parameter used.</li>
8840       <li>reject callback function: function(error). error is an Error instance.
8841         <ul>
8842           <li>error.message</li>
8843         </ul>
8844       </li>
8845     </ul>
8846   @example
8847   // example to use callbacks directly
8848   KiiUser.resetPassword("johndoe@example.com", {
8849       success: function() {
8850           // do something
8851       },
8852   
8853       failure: function(anErrorString) {
8854           // do something with the error response
8855       }
8856   });
8857   
8858   // example to use Promise
8859   KiiUser.resetPassword("johndoe@example.com").then(
8860       function() {
8861           // do something
8862       },
8863       function(error) {
8864           // do something with the error response
8865       }
8866   );
8867    */
8868 
8869   KiiUser.resetPassword = function(userIdentifier, callbacks) {
8870     return new Promise(function(resolve, reject) {
8871       var resetPasswordCallbacks;
8872       resetPasswordCallbacks = {
8873         success: function() {
8874           if (callbacks != null) {
8875             callbacks.success();
8876           }
8877           return resolve();
8878         },
8879         failure: function() {
8880           if (callbacks != null) {
8881             callbacks.failure(arguments[0]);
8882           }
8883           return reject(KiiUtilities._Error(arguments[0]));
8884         }
8885       };
8886       return KiiUser._resetPasswordUsingCallbacks(userIdentifier, resetPasswordCallbacks);
8887     });
8888   };
8889 
8890   KiiUser._resetPasswordUsingCallbacks = function(userIdentifier, callbacks) {
8891     var accountType, path, request, resetCallbacks;
8892     root.Kii.logger("Resetting password with identifier: " + userIdentifier);
8893     if (KiiUtilities._validateEmail(userIdentifier)) {
8894       accountType = "EMAIL";
8895     } else if (callbacks != null) {
8896       callbacks.failure("Invalid user identifier. Must be a valid email address");
8897       return;
8898     }
8899     if (accountType != null) {
8900       path = "/users/" + accountType + ":" + userIdentifier + "/password/request-reset";
8901       request = new KiiRequest(path, true);
8902       request.setMethod("POST");
8903       request.setAnonymous(true);
8904       resetCallbacks = {
8905         success: function(data, statusCode) {
8906           if (statusCode < 300 && statusCode >= 200 && (callbacks != null)) {
8907             return callbacks.success();
8908           } else if (callbacks != null) {
8909             return callbacks.failure("Unable to reset password");
8910           }
8911         },
8912         failure: function(error, statusCode) {
8913           if (callbacks != null) {
8914             return callbacks.failure(error);
8915           }
8916         }
8917       };
8918       return request.execute(resetCallbacks, true);
8919     }
8920   };
8921 
8922 
8923   /** Reset the password of user <br>
8924   Reset the password of user specified by given identifier. <br>
8925   This api does not execute login after reset password.
8926   @param {String} userIdentifier should be valid email address,
8927       global phone number or user identifier obtained by {@link #getID}.
8928   @param {String} notificationMethod specify the destination of message include link
8929       of resetting password. must one of "EMAIL", "SMS" or "SMS_PIN".
8930       - "EMAIL": Send email include link URL to reset password or password.
8931       (Contents are depends on 'Password Reset Flow' setting in app's
8932       Security settings.)
8933       - "SMS" : Send SMS include link URL to reset password.
8934       - "SMS_PIN" : Send SMS include PIN Code for reset password.
8935       different type of identifier and destination can be used
8936       as long as user have verified email, phone.
8937       (ex. User registers both email and phone. Identifier is email and
8938       notificationMethod is SMS.)
8939   @param {Object} [callbacks] object includes callback functions.
8940   @param {Method} callbacks.success called when operation succeeded.
8941   @param {Method} callbacks.failure called when operation failed.
8942   @return {Promise} return promise object.
8943     <ul>
8944       <li>fulfill callback function: function(). No parameter used.</li>
8945       <li>reject callback function: function(error). error is an Error instance.
8946         <ul>
8947           <li>error.message</li>
8948         </ul>
8949       </li>
8950     </ul>
8951   @example
8952   // example to use callbacks directly
8953   KiiUser.resetPasswordWithNotificationMethod("+819001234567", "SMS", {
8954       success: function() {
8955           // Operation succeeded.
8956       },
8957       failure: function(errString) {
8958           // Handle error.
8959       }
8960   });
8961   
8962   // example to use Promise
8963   KiiUser.resetPasswordWithNotificationMethod("+819001234567", "SMS").then(
8964       function() {
8965           // Operation succeeded.
8966       },
8967       function(error) {
8968           // Handle error.
8969       }
8970   );
8971    */
8972 
8973   KiiUser.resetPasswordWithNotificationMethod = function(userIdentifier, notificationMethod, callbacks) {
8974     return new Promise(function(resolve, reject) {
8975       var resetPasswordWithNotificationMethodCallbacks;
8976       resetPasswordWithNotificationMethodCallbacks = {
8977         success: function() {
8978           if (callbacks != null) {
8979             callbacks.success();
8980           }
8981           return resolve();
8982         },
8983         failure: function() {
8984           if (callbacks != null) {
8985             callbacks.failure(arguments[0]);
8986           }
8987           return reject(KiiUtilities._Error(arguments[0]));
8988         }
8989       };
8990       return KiiUser._resetPasswordWithNotificationMethodUsingCallbacks(userIdentifier, notificationMethod, resetPasswordWithNotificationMethodCallbacks);
8991     });
8992   };
8993 
8994   KiiUser._resetPasswordWithNotificationMethodUsingCallbacks = function(userIdentifier, notificationMethod, callbacks) {
8995     var body, qualifiedID, reqCallbacks, requestUri, wrapper, xhr;
8996     if (typeof userIdentifier !== 'string') {
8997       if (callbacks != null) {
8998         callbacks.failure('given userIdentifier is not string');
8999       }
9000       return;
9001     }
9002     if (userIdentifier === "") {
9003       if (callbacks != null) {
9004         callbacks.failure('given userIdentifier is empty');
9005       }
9006       return;
9007     }
9008     if (notificationMethod !== 'EMAIL' && notificationMethod !== 'SMS' && notificationMethod !== 'SMS_PIN') {
9009       if (callbacks != null) {
9010         callbacks.failure('notificationMethod should be \'EMAIL\' or \'SMS\' or \'SMS_PIN\'');
9011       }
9012       return;
9013     }
9014     if (KiiUtilities._validateEmail(userIdentifier)) {
9015       qualifiedID = "EMAIL:" + userIdentifier;
9016     } else if (KiiUtilities._isGlobalPhoneNumber(userIdentifier)) {
9017       qualifiedID = "PHONE:" + userIdentifier;
9018     } else {
9019       qualifiedID = userIdentifier;
9020     }
9021     qualifiedID = encodeURIComponent(qualifiedID);
9022     body = {
9023       notificationMethod: notificationMethod
9024     };
9025     if (notificationMethod === 'SMS_PIN') {
9026       body.notificationMethod = "SMS";
9027       body.smsResetMethod = "PIN";
9028     }
9029     requestUri = "" + (root.Kii.getBaseURL()) + "/apps/" + (root.Kii.getAppID()) + "/users/" + qualifiedID + "/password/request-reset";
9030     wrapper = KiiXHRWrapperFactory.createXHRWrapper("POST", requestUri);
9031     xhr = wrapper.xhr;
9032     xhr.setRequestHeader("x-kii-appid", root.Kii.getAppID());
9033     xhr.setRequestHeader("x-kii-appkey", root.Kii.getAppKey());
9034     xhr.setRequestHeader("x-kii-sdk", root.KiiSDKClientInfo.getSDKClientInfo());
9035     xhr.setRequestHeader("Content-Type", "application/vnd.kii.ResetPasswordRequest+json");
9036     reqCallbacks = {
9037       success: function() {
9038         return callbacks != null ? callbacks.success() : void 0;
9039       },
9040       failure: function() {
9041         var errString, json;
9042         errString = "failed to reset password. statusCode: " + xhr.status;
9043         try {
9044           json = JSON.parse(xhr.responseText);
9045           if (json.errorCode != null) {
9046             errString += " error code: " + json.errorCode;
9047           }
9048           if (json.message != null) {
9049             return errString += " error message: " + json.message;
9050           }
9051         } catch (_error) {
9052 
9053         } finally {
9054           if (callbacks != null) {
9055             callbacks.failure(errString);
9056           }
9057         }
9058       }
9059     };
9060     return wrapper.sendData(JSON.stringify(body), reqCallbacks);
9061   };
9062 
9063 
9064   /** Reset password with the PIN code in receipt SMS
9065   After {@link KiiUser.resetPasswordWithNotificationMethod} is called with
9066   "SMS_PIN", SMS includes the PIN code will be sent to the user's phone.
9067   User can request the new password for login with the PIN code.
9068   Need to call method for authentication after the new password is determined.
9069   @param {String} userIdentifier should be valid email address,
9070       global phone number or user identifier obtained by {@link #getID}.
9071   @param {String} pinCode Received PIN code.
9072   @param {String} [newPassword] New password for login.
9073   If the 'Password Reset Flow' in app's security setting is set to
9074   'Generate password', it would be ignored and null can be passed.
9075   In this case, new password is generated on Kii Cloud and sent to user's
9076   phone. Otherwise valid password is required.
9077   @param {Object} [callbacks] object includes callback functions.
9078   @return {Promise} return promise object.
9079     <ul>
9080       <li>fulfill callback function: function(). No parameter used.</li>
9081       <li>reject callback function: function(error). error is an Error instance.
9082         <ul>
9083           <li>error.message</li>
9084         </ul>
9085       </li>
9086     </ul>
9087   @example
9088   // Example using callback
9089   KiiUser.completeResetPassword("john.doe@kii.com", "new-password", "223789",
9090   {
9091       success: function() {
9092           // Succeeded.
9093       },
9094       failure: function(error) {
9095           // Handle error here.
9096       }
9097   });
9098   
9099   // Example using Promise
9100   KiiUser.completeResetPassword(
9101       "john.doe@kii.com", "new-password", "223789").then(function() {
9102           // Succeeded.
9103       }).catch(function(error) {
9104           // Handle error here.
9105       });
9106    */
9107 
9108   KiiUser.completeResetPassword = function(userIdentifier, pinCode, newPassword, callbacks) {
9109     return new Promise(function(resolve, reject) {
9110       var completeResetPasswordCallbacks;
9111       completeResetPasswordCallbacks = {
9112         success: function() {
9113           if (callbacks != null) {
9114             callbacks.success();
9115           }
9116           return resolve();
9117         },
9118         failure: function() {
9119           if (callbacks != null) {
9120             callbacks.failure(arguments[0]);
9121           }
9122           return reject(KiiUtilities._Error(arguments[0]));
9123         }
9124       };
9125       return KiiUser._completeResetPasswordUsingCallbacks(userIdentifier, pinCode, newPassword, completeResetPasswordCallbacks);
9126     });
9127   };
9128 
9129   KiiUser._completeResetPasswordUsingCallbacks = function(userIdentifier, pinCode, newPassword, callbacks) {
9130     var body, qualifiedID, reqCallbacks, requestUri, wrapper, xhr;
9131     if (!KiiUtilities._isNonEmptyString(userIdentifier)) {
9132       if (callbacks != null) {
9133         callbacks.failure('given userIdentifier is null or empty');
9134       }
9135       return;
9136     }
9137     if (!KiiUtilities._isNonEmptyString(pinCode)) {
9138       if (callbacks != null) {
9139         callbacks.failure('given pinCode is null or empty');
9140       }
9141       return;
9142     }
9143     if (KiiUtilities._validateEmail(userIdentifier)) {
9144       qualifiedID = "EMAIL:" + userIdentifier;
9145     } else if (KiiUtilities._isGlobalPhoneNumber(userIdentifier)) {
9146       qualifiedID = "PHONE:" + userIdentifier;
9147     } else {
9148       qualifiedID = userIdentifier;
9149     }
9150     qualifiedID = encodeURIComponent(qualifiedID);
9151     body = {
9152       pinCode: pinCode
9153     };
9154     if (KiiUtilities._isNonEmptyString(newPassword)) {
9155       body["newPassword"] = newPassword;
9156     }
9157     requestUri = "" + (root.Kii.getBaseURL()) + "/apps/" + (root.Kii.getAppID()) + "/users/" + qualifiedID + "/password/complete-reset";
9158     wrapper = KiiXHRWrapperFactory.createXHRWrapper("POST", requestUri);
9159     xhr = wrapper.xhr;
9160     xhr.setRequestHeader("x-kii-appid", root.Kii.getAppID());
9161     xhr.setRequestHeader("x-kii-appkey", root.Kii.getAppKey());
9162     xhr.setRequestHeader("x-kii-sdk", root.KiiSDKClientInfo.getSDKClientInfo());
9163     xhr.setRequestHeader("Content-Type", "application/vnd.kii.CompletePasswordResetRequest+json");
9164     reqCallbacks = {
9165       success: function() {
9166         return callbacks != null ? callbacks.success() : void 0;
9167       },
9168       failure: function() {
9169         var errString, json;
9170         errString = "failed to reset password. statusCode: " + xhr.status;
9171         try {
9172           json = JSON.parse(xhr.responseText);
9173           if (json.errorCode != null) {
9174             errString += " error code: " + json.errorCode;
9175           }
9176           if (json.message != null) {
9177             return errString += " error message: " + json.message;
9178           }
9179         } catch (_error) {
9180 
9181         } finally {
9182           if (callbacks != null) {
9183             callbacks.failure(errString);
9184           }
9185         }
9186       }
9187     };
9188     return wrapper.sendData(JSON.stringify(body), reqCallbacks);
9189   };
9190 
9191   KiiUser.prototype.verifyCredentials = function(type, code, callbacks) {
9192     return new Promise((function(_this) {
9193       return function(resolve, reject) {
9194         var verifyCredentialsCallbacks;
9195         verifyCredentialsCallbacks = {
9196           success: function() {
9197             if (callbacks != null) {
9198               callbacks.success.apply(callbacks, arguments);
9199             }
9200             return resolve(arguments[0]);
9201           },
9202           failure: function() {
9203             if (callbacks != null) {
9204               callbacks.failure.apply(callbacks, arguments);
9205             }
9206             return reject(KiiUtilities._Error(arguments[1], _this));
9207           }
9208         };
9209         return _this._verifyCredentialsUsingCallbacks(type, code, verifyCredentialsCallbacks);
9210       };
9211     })(this));
9212   };
9213 
9214   KiiUser.prototype._verifyCredentialsUsingCallbacks = function(type, code, callbacks) {
9215     var path, request, verifyCallbacks;
9216     root.Kii.logger("Verifying " + type + " with code: " + code);
9217     path = "/users/me/" + type + "/verify";
9218     request = this._getRequest({
9219       path: path,
9220       withApp: true
9221     });
9222     request.setMethod("POST");
9223     request.setData({
9224       verificationCode: code
9225     });
9226     request.setContentType("application/vnd.kii.AddressVerificationRequest+json");
9227     verifyCallbacks = {
9228       success: (function(_this) {
9229         return function(data, statusCode) {
9230           if (statusCode < 300 && statusCode >= 200) {
9231             if (type === "email-address") {
9232               _this._setEmailVerified(true);
9233             } else if (type === "phone-number") {
9234               _this._setPhoneVerified(true);
9235             }
9236             if (callbacks != null) {
9237               return callbacks.success(_this);
9238             }
9239           } else if (callbacks != null) {
9240             return callbacks.failure(_this, "Unable to verify " + type);
9241           }
9242         };
9243       })(this),
9244       failure: (function(_this) {
9245         return function(error, statusCode) {
9246           if (callbacks != null) {
9247             return callbacks.failure(_this, error);
9248           }
9249         };
9250       })(this)
9251     };
9252     return request.execute(verifyCallbacks, true);
9253   };
9254 
9255 
9256   /** Verify the current user's phone number
9257   <br><br>This method is used to verify the phone number of user currently
9258   logged in.<br>
9259   Verification code is sent from Kii Cloud when new user is registered with
9260   phone number or user requested to change their phone number in the
9261   application which requires phone verification.<br>
9262   (You can enable/disable phone verification through the console in
9263   developer.kii.com)<br>
9264   After the verification succeeded, new phone number becomes users phone
9265   number and user is able to login with the phone number.<br>
9266   To get the new phone number, please call {@link #refresh()} and call
9267   {@link #getPhoneNumber()}<br>
9268   Before completion of {@link #refresh()}, {@link #getPhoneNumber()} returns
9269   cached phone number. It could be old phone number or undefined.
9270   @param {String} verificationCode The code which verifies the currently logged in user
9271   @param {Object} [callbacks] An object with callback methods defined
9272   @param {Method} callbacks.success The callback method to call on a successful verification request
9273   @param {Method} callbacks.failure The callback method to call on a failed verification request
9274   @return {Promise} return promise object.
9275     <ul>
9276       <li>fulfill callback function: function(theUser). theUser is KiiUser instance which this method was called on.</li>
9277       <li>reject callback function: function(error). error is an Error instance.
9278         <ul>
9279           <li>error.target is the KiiUser instance which this method was called on.</li>
9280           <li>error.message</li>
9281         </ul>
9282       </li>
9283     </ul>
9284   @example
9285   // example to use callbacks directly
9286   var user = Kii.currentUser();
9287   user.verifyPhoneNumber("012345", {
9288       success: function(theUser) {
9289           // do something
9290       },
9291   
9292       failure: function(theUser, anErrorString) {
9293           // do something with the error response
9294       }
9295   });
9296   
9297   // example to use Promise
9298   var user = Kii.currentUser();
9299   user.verifyPhoneNumber("012345").then(
9300       function(theUser) {
9301           // do something
9302       },
9303       function(error) {
9304           // do something with the error response
9305       }
9306   );
9307    */
9308 
9309   KiiUser.prototype.verifyPhoneNumber = function(verificationCode, callbacks) {
9310     return this.verifyCredentials("phone-number", verificationCode, callbacks);
9311   };
9312 
9313   KiiUser.prototype.resendVerification = function(type, callbacks) {
9314     return new Promise((function(_this) {
9315       return function(resolve, reject) {
9316         var resendVerificationCallbacks;
9317         resendVerificationCallbacks = {
9318           success: function() {
9319             if (callbacks != null) {
9320               callbacks.success.apply(callbacks, arguments);
9321             }
9322             return resolve(arguments[0]);
9323           },
9324           failure: function() {
9325             if (callbacks != null) {
9326               callbacks.failure.apply(callbacks, arguments);
9327             }
9328             return reject(KiiUtilities._Error(arguments[1], _this));
9329           }
9330         };
9331         return _this._resendVerificationUsingCallbacks(type, resendVerificationCallbacks);
9332       };
9333     })(this));
9334   };
9335 
9336   KiiUser.prototype._resendVerificationUsingCallbacks = function(type, callbacks) {
9337     var id, path, request, resendCallbacks;
9338     root.Kii.logger("Resending verification " + type);
9339     id = this.getID();
9340     path = "/users/" + id + "/" + type + "/resend-verification";
9341     request = this._getRequest({
9342       path: path,
9343       withApp: true
9344     });
9345     request.setMethod("POST");
9346     resendCallbacks = {
9347       success: (function(_this) {
9348         return function(data, statusCode) {
9349           if (statusCode < 300 && statusCode >= 200 && (callbacks != null)) {
9350             return callbacks.success(_this);
9351           } else if (callbacks != null) {
9352             return callbacks.failure(_this, "Unable to resend " + type + " verification");
9353           }
9354         };
9355       })(this),
9356       failure: (function(_this) {
9357         return function(error, statusCode) {
9358           if (callbacks != null) {
9359             return callbacks.failure(_this, error);
9360           }
9361         };
9362       })(this)
9363     };
9364     return request.execute(resendCallbacks, true);
9365   };
9366 
9367 
9368   /** Resend the email verification code to the user
9369   
9370   <br><br>This method will re-send the email verification to the currently logged in user
9371   @param {Object} [callbacks] An object with callback methods defined
9372   @param {Method} callbacks.success The callback method to call on a successful resend request
9373   @param {Method} callbacks.failure The callback method to call on a failed resend request
9374   @return {Promise} return promise object.
9375     <ul>
9376       <li>fulfill callback function: function(theUser). theUser is KiiUser instance which this method was called on.</li>
9377       <li>reject callback function: function(error). error is an Error instance.
9378         <ul>
9379           <li>error.target is the KiiUser instance which this method was called on.</li>
9380           <li>error.message</li>
9381         </ul>
9382       </li>
9383     </ul>
9384   @example
9385   // example to use callbacks directly
9386   var user = Kii.currentUser();
9387   user.resendEmailVerification({
9388       success: function(theUser) {
9389           // do something
9390       },
9391   
9392       failure: function(theUser, anErrorString) {
9393           // do something with the error response
9394       }
9395   });
9396   
9397   // example to use Promise
9398   var user = Kii.currentUser();
9399   user.resendEmailVerification().then(
9400       function(theUser) {
9401           // do something
9402       },
9403       function(error) {
9404           // do something with the error response
9405       }
9406   );
9407    */
9408 
9409   KiiUser.prototype.resendEmailVerification = function(callbacks) {
9410     return this.resendVerification("email-address", callbacks);
9411   };
9412 
9413 
9414   /** Resend the SMS verification code to the user
9415   
9416   <br><br>This method will re-send the SMS verification to the currently logged in user
9417   @param {Object} [callbacks] An object with callback methods defined
9418   @param {Method} callbacks.success The callback method to call on a successful resend request
9419   @param {Method} callbacks.failure The callback method to call on a failed resend request
9420   @return {Promise} return promise object.
9421     <ul>
9422       <li>fulfill callback function: function(theUser). theUser is KiiUser instance which this method was called on.</li>
9423       <li>reject callback function: function(error). error is an Error instance.
9424         <ul>
9425           <li>error.target is the KiiUser instance which this method was called on.</li>
9426           <li>error.message</li>
9427         </ul>
9428       </li>
9429     </ul>
9430   @example
9431   // example to use callbacks directly
9432   var user = Kii.currentUser();
9433   user.resendPhoneNumberVerification({
9434       success: function(theUser) {
9435           // do something
9436       },
9437   
9438       failure: function(theUser, anErrorString) {
9439           // do something with the error response
9440       }
9441   });
9442   
9443   // example to use Promise
9444   var user = Kii.currentUser();
9445   user.resendPhoneNumberVerification().then(
9446       function(theUser) {
9447           // do something
9448       },
9449       function(error) {
9450           // do something with the error response
9451       }
9452   );
9453    */
9454 
9455   KiiUser.prototype.resendPhoneNumberVerification = function(callbacks) {
9456     return this.resendVerification("phone-number", callbacks);
9457   };
9458 
9459 
9460   /** Retrieve a list of groups which the user is a member of
9461   @param {Object} [callbacks] An object with callback methods defined
9462   @param {Method} callbacks.success The callback method to call on a successful resend request
9463   @param {Method} callbacks.failure The callback method to call on a failed resend request
9464   @return {Promise} return promise object.
9465     <ul>
9466       <li>fulfill callback function: function(params). params is Array instance.
9467         <ul>
9468           <li>params[0] is the KiiUser instance which this method was called on.</li>
9469           <li>params[1] is array of KiiGroup instances.</li>
9470         </ul>
9471       </li>
9472       <li>reject callback function: function(error). error is an Error instance.
9473         <ul>
9474           <li>error.target is the KiiUser instance which this method was called on.</li>
9475           <li>error.message</li>
9476         </ul>
9477       </li>
9478     </ul>
9479   @example
9480   // example to use callbacks directly
9481   var user = Kii.currentUser();
9482   user.memberOfGroups({
9483       success: function(theUser, groupList) {
9484           // do something with the results
9485           for(var i=0; i<groupList.length; i++) {
9486               var g = groupList[i]; // a KiiGroup object
9487           }
9488       },
9489   
9490       failure: function(theUser, anErrorString) {
9491           // do something with the error response
9492       }
9493   });
9494   
9495   // example to use Promise
9496   var user = Kii.currentUser();
9497   user.memberOfGroups().then(
9498       function(params) {
9499           // do something with the results
9500           var theUser = params[0];
9501           var groupList = params[1];
9502           for(var i=0; i<groupList.length; i++) {
9503               var g = groupList[i]; // a KiiGroup object
9504           }
9505       },
9506       function(error) {
9507           // do something with the error response
9508       }
9509   );
9510    */
9511 
9512   KiiUser.prototype.memberOfGroups = function(callbacks) {
9513     return new Promise((function(_this) {
9514       return function(resolve, reject) {
9515         var memberOfGroupsCallbacks;
9516         memberOfGroupsCallbacks = {
9517           success: function() {
9518             if (callbacks != null) {
9519               callbacks.success.apply(callbacks, arguments);
9520             }
9521             return resolve(arguments);
9522           },
9523           failure: function() {
9524             if (callbacks != null) {
9525               callbacks.failure.apply(callbacks, arguments);
9526             }
9527             return reject(KiiUtilities._Error(arguments[1], _this));
9528           }
9529         };
9530         return _this._memberOfGroupsUsingCallbacks(memberOfGroupsCallbacks);
9531       };
9532     })(this));
9533   };
9534 
9535   KiiUser.prototype._memberOfGroupsUsingCallbacks = function(callbacks) {
9536     var memberCallbacks, path, request;
9537     root.Kii.logger("Getting groups for member " + this._uuid);
9538     path = "/groups/?is_member=" + this._uuid;
9539     request = this._getRequest({
9540       path: path,
9541       withApp: true
9542     });
9543     request.setAccept("application/vnd.kii.GroupsRetrievalResponse+json");
9544     memberCallbacks = {
9545       success: (function(_this) {
9546         return function(data, statusCode) {
9547           var group, groupList, _i, _len, _ref;
9548           if (statusCode < 300 && statusCode >= 200) {
9549             groupList = [];
9550             _ref = data.groups;
9551             for (_i = 0, _len = _ref.length; _i < _len; _i++) {
9552               group = _ref[_i];
9553               groupList.push(_this._groupWithJSON(group));
9554             }
9555             if (callbacks != null) {
9556               return callbacks.success(_this, groupList);
9557             }
9558           } else if (callbacks != null) {
9559             return callbacks.failure(_this, "Unable to retrieve groups");
9560           }
9561         };
9562       })(this),
9563       failure: (function(_this) {
9564         return function(error, statusCode) {
9565           if (callbacks != null) {
9566             return callbacks.failure(_this, error);
9567           }
9568         };
9569       })(this)
9570     };
9571     return request.execute(memberCallbacks, false);
9572   };
9573 
9574 
9575   /**Retrieve the groups owned by this user. Group in the groupList
9576   does not contain all the property of group. To get all the
9577   property from cloud, a {@link KiiGroup#refresh(callback)} is necessary.
9578   @param {Object} [callbacks] An object with callback methods defined
9579   @param {Method} callbacks.success The callback method to call on a successful resend request
9580   @param {Method} callbacks.failure The callback method to call on a failed resend request
9581   @return {Promise} return promise object.
9582     <ul>
9583       <li>fulfill callback function: function(params). params is Array instance.
9584         <ul>
9585           <li>params[0] is the KiiUser instance which this method was called on.</li>
9586           <li>params[1] is array of KiiGroup instances.</li>
9587         </ul>
9588       </li>
9589       <li>reject callback function: function(error). error is an Error instance.
9590         <ul>
9591           <li>error.target is the KiiUser instance which this method was called on.</li>
9592           <li>error.message</li>
9593         </ul>
9594       </li>
9595     </ul>
9596   @example
9597   // example to use callbacks directly
9598   var user = Kii.currentUser();
9599   user.ownerOfGroups({
9600       success: function(theUser, groupList) {
9601           // do something with the results
9602           for(var i=0; i<groupList.length; i++) {
9603               var g = groupList[i]; // a KiiGroup object
9604           }
9605       },
9606   
9607       failure: function(theUser, anErrorString) {
9608           // do something with the error response
9609       }
9610   });
9611   
9612   // example to use Promise
9613   var user = Kii.currentUser();
9614   user.ownerOfGroups().then(
9615       function(params) {
9616           // do something with the results
9617           var theUser = params[0];
9618           var groupList = params[1];
9619           for(var i=0; i<groupList.length; i++) {
9620               var g = groupList[i]; // a KiiGroup object
9621           }
9622       },
9623       function(error) {
9624           // do something with the error response
9625       }
9626   );
9627    */
9628 
9629   KiiUser.prototype.ownerOfGroups = function(callbacks) {
9630     return new Promise((function(_this) {
9631       return function(resolve, reject) {
9632         var ownerOfGroupsCallbacks;
9633         ownerOfGroupsCallbacks = {
9634           success: function() {
9635             if (callbacks != null) {
9636               callbacks.success.apply(callbacks, arguments);
9637             }
9638             return resolve(arguments);
9639           },
9640           failure: function() {
9641             if (callbacks != null) {
9642               callbacks.failure.apply(callbacks, arguments);
9643             }
9644             return reject(KiiUtilities._Error(arguments[1], _this));
9645           }
9646         };
9647         return _this._ownerOfGroupsUsingCallbacks(ownerOfGroupsCallbacks);
9648       };
9649     })(this));
9650   };
9651 
9652   KiiUser.prototype._ownerOfGroupsUsingCallbacks = function(callbacks) {
9653     var memberCallbacks, path, request;
9654     root.Kii.logger("Getting groups owned by the user " + this._uuid);
9655     path = "/groups/?owner=" + this._uuid;
9656     request = this._getRequest({
9657       path: path,
9658       withApp: true
9659     });
9660     request.setAccept("application/vnd.kii.GroupsRetrievalResponse+json");
9661     memberCallbacks = {
9662       success: (function(_this) {
9663         return function(data, statusCode) {
9664           var group, groupList, _i, _len, _ref;
9665           if (statusCode < 300 && statusCode >= 200) {
9666             groupList = [];
9667             _ref = data.groups;
9668             for (_i = 0, _len = _ref.length; _i < _len; _i++) {
9669               group = _ref[_i];
9670               groupList.push(_this._groupWithJSON(group));
9671             }
9672             if (callbacks != null) {
9673               return callbacks.success(_this, groupList);
9674             }
9675           } else if (callbacks != null) {
9676             return callbacks.failure(_this, "Unable to retrieve groups");
9677           }
9678         };
9679       })(this),
9680       failure: (function(_this) {
9681         return function(error, statusCode) {
9682           if (callbacks != null) {
9683             return callbacks.failure(_this, error);
9684           }
9685         };
9686       })(this)
9687     };
9688     return request.execute(memberCallbacks, false);
9689   };
9690 
9691 
9692   /** Change phone number of logged in user.
9693   If the phone number verification is required by your app configuration,
9694   User's phone number would not changed to new one until the new phone number verification has been done.
9695   In this case, new phone can be obtained by {@link KiiUser#getPendingPhoneNumber()}.
9696   This API does not refresh the KiiUser automatically.
9697   Please execute {@link KiiUser#refresh()} before checking the value of {@link KiiUser#getPhoneNumber()} or {@link KiiUser#getPendingPhoneNumber()}.
9698   @param {String} newPhoneNumber The new phone number to change to
9699   @param {Object} [callbacks] An object with callback methods defined
9700   @param {Method} callbacks.success The callback method to call on a successful resend request
9701   @param {Method} callbacks.failure The callback method to call on a failed resend request
9702   @return {Promise} return promise object.
9703     <ul>
9704       <li>fulfill callback function: function(theUser). theUser is KiiUser instance which this method was called on.</li>
9705       <li>reject callback function: function(error). error is an Error instance.
9706         <ul>
9707           <li>error.target is the KiiUser instance which this method was called on.</li>
9708           <li>error.message</li>
9709         </ul>
9710       </li>
9711     </ul>
9712   @example
9713   // example to use callbacks directly
9714   var user = Kii.currentUser();
9715   user.changePhone('+19415551234', {
9716       success: function(theUser) {
9717           // do something on success
9718       },
9719   
9720       failure: function(theUser, anErrorString) {
9721           // do something with the error response
9722       }
9723   });
9724   
9725   // example to use Promise
9726   var user = Kii.currentUser();
9727   user.changePhone('+19415551234').then(
9728       function(theUser) {
9729           // do something on success
9730       },
9731       function(error) {
9732           // do something with the error response
9733       }
9734   );
9735    */
9736 
9737   KiiUser.prototype.changePhone = function(newPhoneNumber, callbacks) {
9738     return new Promise((function(_this) {
9739       return function(resolve, reject) {
9740         var changePhoneCallbacks;
9741         changePhoneCallbacks = {
9742           success: function() {
9743             if (callbacks != null) {
9744               callbacks.success.apply(callbacks, arguments);
9745             }
9746             return resolve(arguments[0]);
9747           },
9748           failure: function() {
9749             if (callbacks != null) {
9750               callbacks.failure.apply(callbacks, arguments);
9751             }
9752             return reject(KiiUtilities._Error(arguments[1], _this));
9753           }
9754         };
9755         return _this._changePhoneUsingCallbacks(newPhoneNumber, changePhoneCallbacks);
9756       };
9757     })(this));
9758   };
9759 
9760   KiiUser.prototype._changePhoneUsingCallbacks = function(newPhoneNumber, callbacks) {
9761     var path, request, updateCallbacks;
9762     root.Kii.logger("Updating phone number to " + newPhoneNumber);
9763     path = "/users/" + this._uuid + "/phone-number";
9764     request = this._getRequest({
9765       path: path,
9766       withApp: true
9767     });
9768     request.setMethod("PUT");
9769     request.setContentType("application/vnd.kii.PhoneNumberModificationRequest+json");
9770     request.setData({
9771       phoneNumber: newPhoneNumber
9772     });
9773     updateCallbacks = {
9774       success: (function(_this) {
9775         return function(data, statusCode) {
9776           if (statusCode < 300 && statusCode >= 200 && (callbacks != null)) {
9777             return callbacks.success(_this);
9778           } else if (callbacks != null) {
9779             return callbacks.failure(_this, "Unable to update phone number");
9780           }
9781         };
9782       })(this),
9783       failure: (function(_this) {
9784         return function(error, statusCode) {
9785           if (callbacks != null) {
9786             return callbacks.failure(_this, error);
9787           }
9788         };
9789       })(this)
9790     };
9791     return request.execute(updateCallbacks, true);
9792   };
9793 
9794 
9795   /** Change email of logged in user.
9796   If the email address verification is required by your app configuration,
9797   User's email would not changed to new one until the new email verification has been done.
9798   In this case, new mail address can be obtained by {@link KiiUser#getPendingEmailAddress()}.
9799   This API does not refresh the KiiUser automatically.
9800   Please execute {@link KiiUser#refresh()} before checking the value of {@link KiiUser#getEmailAddress()} or {@link KiiUser#getPendingEmailAddress()}
9801   @param {String} newEmail The new email address to change to
9802   @param {Object} [callbacks] An object with callback methods defined
9803   @param {Method} callbacks.success The callback method to call on a successful resend request
9804   @param {Method} callbacks.failure The callback method to call on a failed resend request
9805   @return {Promise} return promise object.
9806     <ul>
9807       <li>fulfill callback function: function(theUser). theUser is KiiUser instance which this method was called on.</li>
9808       <li>reject callback function: function(error). error is an Error instance.
9809         <ul>
9810           <li>error.target is the KiiUser instance which this method was called on.</li>
9811           <li>error.message</li>
9812         </ul>
9813       </li>
9814     </ul>
9815   @example
9816   // example to use callbacks directly
9817   var user = Kii.currentUser();
9818   user.changeEmail('mynewemail@kii.com', {
9819       success: function(theUser) {
9820           // do something on success
9821       },
9822   
9823       failure: function(theUser, anErrorString) {
9824           // do something with the error response
9825       }
9826   });
9827   
9828   // example to use Promise
9829   var user = Kii.currentUser();
9830   user.changeEmail('mynewemail@kii.com').then(
9831       function(theUser) {
9832           // do something on success
9833       },
9834       function(error) {
9835           // do something with the error response
9836       }
9837   );
9838    */
9839 
9840   KiiUser.prototype.changeEmail = function(newEmail, callbacks) {
9841     return new Promise((function(_this) {
9842       return function(resolve, reject) {
9843         var changeEmailCallbacks;
9844         changeEmailCallbacks = {
9845           success: function() {
9846             if (callbacks != null) {
9847               callbacks.success.apply(callbacks, arguments);
9848             }
9849             return resolve(arguments[0]);
9850           },
9851           failure: function() {
9852             if (callbacks != null) {
9853               callbacks.failure.apply(callbacks, arguments);
9854             }
9855             return reject(KiiUtilities._Error(arguments[1], _this));
9856           }
9857         };
9858         return _this._changeEmailUsingCallbacks(newEmail, changeEmailCallbacks);
9859       };
9860     })(this));
9861   };
9862 
9863   KiiUser.prototype._changeEmailUsingCallbacks = function(newEmail, callbacks) {
9864     var path, request, updateCallbacks;
9865     root.Kii.logger("Updating email address to: " + newEmail);
9866     if (KiiUtilities._validateEmail(newEmail)) {
9867       path = "/users/" + this._uuid + "/email-address";
9868       request = this._getRequest({
9869         path: path,
9870         withApp: true
9871       });
9872       request.setMethod("PUT");
9873       request.setContentType("application/vnd.kii.EmailAddressModificationRequest+json");
9874       request.setData({
9875         emailAddress: newEmail
9876       });
9877       updateCallbacks = {
9878         success: (function(_this) {
9879           return function(data, statusCode) {
9880             if (statusCode < 300 && statusCode >= 200 && (callbacks != null)) {
9881               return callbacks.success(_this);
9882             } else if (callbacks != null) {
9883               return callbacks.failure(_this, "Unable to update email address");
9884             }
9885           };
9886         })(this),
9887         failure: (function(_this) {
9888           return function(error, statusCode) {
9889             if (callbacks != null) {
9890               return callbacks.failure(_this, error);
9891             }
9892           };
9893         })(this)
9894       };
9895       return request.execute(updateCallbacks, true);
9896     } else {
9897       return callbacks.failure(this, "Invalid email address format");
9898     }
9899   };
9900 
9901 
9902   /** Saves the latest user values to the server
9903   
9904   <br><br>If the user does not yet exist, it will NOT be created. Otherwise, the fields that have changed will be updated accordingly.
9905   @param {Object} [callbacks] An object with callback methods defined
9906   @param {Method} callbacks.success The callback method to call on a successful save request
9907   @param {Method} callbacks.failure The callback method to call on a failed save request
9908   @return {Promise} return promise object.
9909     <ul>
9910       <li>fulfill callback function: function(theSavedUser). theSavedUser is KiiUser instance.</li>
9911       <li>reject callback function: function(error). error is an Error instance.
9912         <ul>
9913           <li>error.target is the KiiUser instance which this method was called on.</li>
9914           <li>error.message</li>
9915         </ul>
9916       </li>
9917     </ul>
9918   @example
9919   // example to use callbacks directly
9920   var user = Kii.getCurrentUser(); // a KiiUser
9921   user.save({
9922       success: function(theSavedUser) {
9923           // do something with the saved user
9924       },
9925   
9926       failure: function(theUser, anErrorString) {
9927           // do something with the error response
9928       }
9929   });
9930   
9931   // example to use Promise
9932   var user = Kii.getCurrentUser(); // a KiiUser
9933   user.save().then(
9934       function(theSavedUser) {
9935           // do something with the saved user
9936       },
9937       function(error) {
9938           // do something with the error response
9939       }
9940   );
9941    */
9942 
9943   KiiUser.prototype.save = function(callbacks) {
9944     return new Promise((function(_this) {
9945       return function(resolve, reject) {
9946         var saveCallbacks;
9947         saveCallbacks = {
9948           success: function() {
9949             if (callbacks != null) {
9950               callbacks.success.apply(callbacks, arguments);
9951             }
9952             return resolve(arguments[0]);
9953           },
9954           failure: function() {
9955             if (callbacks != null) {
9956               callbacks.failure.apply(callbacks, arguments);
9957             }
9958             return reject(KiiUtilities._Error(arguments[1], _this));
9959           }
9960         };
9961         return _this._saveUsingCallbacks(saveCallbacks);
9962       };
9963     })(this));
9964   };
9965 
9966   KiiUser.prototype._saveUsingCallbacks = function(callbacks) {
9967     var data, path, request, updateCallbacks;
9968     root.Kii.logger("Saving user: " + this._uuid);
9969     path = "/users/" + this._uuid;
9970     root.Kii.logger("CUSTOMINFO: ");
9971     root.Kii.logger(this._customInfo);
9972     request = this._getRequest({
9973       path: path,
9974       withApp: true
9975     });
9976     request.setMethod("POST");
9977     request.setContentType("application/vnd.kii.UserUpdateRequest+json");
9978     data = this._customInfo;
9979     if (this._country != null) {
9980       data.country = this._country;
9981     }
9982     if (this._locale != null) {
9983       data.locale = this._locale;
9984     }
9985     if (this._displayName != null) {
9986       data.displayName = this._displayName;
9987     }
9988     request.setData(data);
9989     updateCallbacks = {
9990       success: (function(_this) {
9991         return function(data, statusCode) {
9992           if (statusCode < 300 && statusCode >= 200) {
9993             _this._setModified(data.modifiedAt);
9994             if (callbacks != null) {
9995               return callbacks.success(_this);
9996             }
9997           } else if (callbacks != null) {
9998             return callbacks.failure(_this, "Unable to parse response");
9999           }
10000         };
10001       })(this),
10002       failure: (function(_this) {
10003         return function(error, statusCode) {
10004           if (callbacks != null) {
10005             return callbacks.failure(_this, error);
10006           }
10007         };
10008       })(this)
10009     };
10010     return request.execute(updateCallbacks, false);
10011   };
10012 
10013 
10014   /** Updates the local user's data with the user data on the server
10015   
10016   <br><br>The user must exist on the server. Local data will be overwritten.
10017   @param {Object} [callbacks] An object with callback methods defined
10018   @param {Method} callbacks.success The callback method to call on a successful refresh request
10019   @param {Method} callbacks.failure The callback method to call on a failed refresh request
10020   @return {Promise} return promise object.
10021     <ul>
10022       <li>fulfill callback function: function(theRefreshedUser). theRefreshedUser is KiiUser instance.</li>
10023       <li>reject callback function: function(error). error is an Error instance.
10024         <ul>
10025           <li>error.target is the KiiUser instance which this method was called on.</li>
10026           <li>error.message</li>
10027         </ul>
10028       </li>
10029     </ul>
10030   @example
10031   // example to use callbacks directly
10032   var user = Kii.getCurrentUser(); // a KiiUser
10033   user.refresh({
10034       success: function(theRefreshedUser) {
10035           // do something with the refreshed user
10036       },
10037   
10038       failure: function(theUser, anErrorString) {
10039           // do something with the error response
10040       }
10041   });
10042   
10043   // example to use Promise
10044   var user = Kii.getCurrentUser(); // a KiiUser
10045   user.refresh().then(
10046       function(theRefreshedUser) {
10047           // do something with the refreshed user
10048       },
10049       function(error) {
10050           // do something with the error response
10051       }
10052   );
10053    */
10054 
10055   KiiUser.prototype.refresh = function(callbacks) {
10056     return new Promise((function(_this) {
10057       return function(resolve, reject) {
10058         var refreshCallbacks;
10059         refreshCallbacks = {
10060           success: function() {
10061             if (callbacks != null) {
10062               callbacks.success.apply(callbacks, arguments);
10063             }
10064             return resolve(arguments[0]);
10065           },
10066           failure: function() {
10067             if (callbacks != null) {
10068               callbacks.failure.apply(callbacks, arguments);
10069             }
10070             return reject(KiiUtilities._Error(arguments[1], _this));
10071           }
10072         };
10073         return _this._refreshUsingCallbacks(refreshCallbacks);
10074       };
10075     })(this));
10076   };
10077 
10078   KiiUser.prototype._refreshUsingCallbacks = function(callbacks) {
10079     var refreshCallbacks, request;
10080     root.Kii.logger("Refreshing user: " + this._uuid);
10081     request = this._getRequest({
10082       path: "/users/" + this._uuid,
10083       withApp: true
10084     });
10085     refreshCallbacks = {
10086       success: (function(_this) {
10087         return function(data, statusCode) {
10088           if (statusCode < 300 && statusCode >= 200) {
10089             _this._phoneNumberPending = null;
10090             _this._emailAddressPending = null;
10091             _this._updateWithJSON(data);
10092             if (callbacks != null) {
10093               return callbacks.success(_this);
10094             }
10095           } else if (callbacks != null) {
10096             return callbacks.failure(_this, "Unable to parse response");
10097           }
10098         };
10099       })(this),
10100       failure: (function(_this) {
10101         return function(error, statusCode) {
10102           if (callbacks != null) {
10103             return callbacks.failure(_this, error);
10104           }
10105         };
10106       })(this)
10107     };
10108     return request.execute(refreshCallbacks, false);
10109   };
10110 
10111 
10112   /** Delete the user from the server
10113   @name delete
10114   @memberOf root.KiiUser#
10115   @function
10116   @param {Object} [callbacks] An object with callback methods defined
10117   @param {Method} callbacks.success The callback method to call on a successful delete request
10118   @param {Method} callbacks.failure The callback method to call on a failed delete request
10119   @return {Promise} return promise object.
10120     <ul>
10121       <li>fulfill callback function: function(theDeletedUser). theDeletedUser is KiiUser instance.</li>
10122       <li>reject callback function: function(error). error is an Error instance.
10123         <ul>
10124           <li>error.target is the KiiUser instance which this method was called on.</li>
10125           <li>error.message</li>
10126         </ul>
10127       </li>
10128     </ul>
10129   @example
10130   // example to use callbacks directly
10131   var user = Kii.getCurrentUser(); // a KiiUser
10132   user.delete({
10133       success: function(theDeletedUser) {
10134           // do something
10135       },
10136   
10137       failure: function(theUser, anErrorString) {
10138           // do something with the error response
10139       }
10140   });
10141   
10142   // example to use Promise
10143   var user = Kii.getCurrentUser(); // a KiiUser
10144   user.delete().then(
10145       function(theDeletedUser) {
10146           // do something
10147       },
10148       function(error) {
10149           // do something with the error response
10150       }
10151   );
10152    */
10153 
10154   KiiUser.prototype["delete"] = function(callbacks) {
10155     return new Promise((function(_this) {
10156       return function(resolve, reject) {
10157         var deleteCallbacks;
10158         deleteCallbacks = {
10159           success: function() {
10160             if (callbacks != null) {
10161               callbacks.success.apply(callbacks, arguments);
10162             }
10163             return resolve(arguments[0]);
10164           },
10165           failure: function() {
10166             if (callbacks != null) {
10167               callbacks.failure.apply(callbacks, arguments);
10168             }
10169             return reject(KiiUtilities._Error(arguments[1], _this));
10170           }
10171         };
10172         return _this._deleteUsingCallbacks(deleteCallbacks);
10173       };
10174     })(this));
10175   };
10176 
10177   KiiUser.prototype._deleteUsingCallbacks = function(callbacks) {
10178     var refreshCallbacks, request;
10179     root.Kii.logger("Deleting user...");
10180     request = this._getRequest({
10181       path: "/users/" + this._uuid,
10182       withApp: true
10183     });
10184     request.setMethod("DELETE");
10185     refreshCallbacks = {
10186       success: (function(_this) {
10187         return function(data, statusCode) {
10188           if (statusCode < 300 && statusCode >= 200 && (callbacks != null)) {
10189             return callbacks.success(_this);
10190           } else if (callbacks != null) {
10191             return callbacks.failure(_this, "Unable to parse response");
10192           }
10193         };
10194       })(this),
10195       failure: (function(_this) {
10196         return function(error, statusCode) {
10197           if (callbacks != null) {
10198             return callbacks.failure(_this, error);
10199           }
10200         };
10201       })(this)
10202     };
10203     return request.execute(refreshCallbacks, true);
10204   };
10205 
10206 
10207   /**
10208       Logs the currently logged-in user out of the KiiSDK
10209       @example
10210       KiiUser.logOut();
10211    */
10212 
10213   KiiUser.logOut = function() {
10214     return root.Kii.logOut();
10215   };
10216 
10217 
10218   /**
10219       Checks to see if there is a user authenticated with the SDK
10220       @example
10221       if(KiiUser.loggedIn()) {
10222           // do something
10223       }
10224    */
10225 
10226   KiiUser.loggedIn = function() {
10227     return root.Kii.loggedIn();
10228   };
10229 
10230   KiiUser.prototype._updateWithIdentityData = function(identityData) {
10231     if (identityData != null) {
10232       if (identityData["username"] != null) {
10233         this._username = identityData["username"];
10234       }
10235       if (identityData["emailAddress"] != null) {
10236         this._emailAddress = identityData["emailAddress"];
10237       }
10238       if (identityData["phoneNumber"] != null) {
10239         return this._phoneNumber = identityData["phoneNumber"];
10240       }
10241     }
10242   };
10243 
10244   KiiUser.prototype._updateWithUserFields = function(userFields, removeFields) {
10245     var key, removeField, value, _i, _len, _results;
10246     if (userFields != null) {
10247       for (key in userFields) {
10248         value = userFields[key];
10249         if (key === "displayName") {
10250           this._displayName = value;
10251         } else if (key === "country") {
10252           this._country = value;
10253         } else if (key === "locale") {
10254           this._locale = value;
10255         } else if (key === "") {
10256           root.Kii.logger("Setting empty to custom info");
10257           this._customInfo[key] = value;
10258         } else if (key.substring(0, 1) !== "_") {
10259           root.Kii.logger("Setting to custom info");
10260           this._customInfo[key] = value;
10261         }
10262       }
10263     }
10264     if (removeFields != null) {
10265       _results = [];
10266       for (_i = 0, _len = removeFields.length; _i < _len; _i++) {
10267         removeField = removeFields[_i];
10268         _results.push(delete this._customInfo[removeField]);
10269       }
10270       return _results;
10271     }
10272   };
10273 
10274   KiiUser.prototype._validateIdentityData = function(identityData) {
10275     if (identityData != null) {
10276       if (identityData.emailAddress != null) {
10277         if (!KiiUtilities._validateEmail(identityData.emailAddress)) {
10278           throw "invalid email";
10279         }
10280       }
10281       if (identityData.phoneNumber != null) {
10282         if (!KiiUtilities._validatePhoneNumber(identityData.phoneNumber)) {
10283           throw "invalid phone number";
10284         }
10285       }
10286       if (identityData.username != null) {
10287         if (!KiiUtilities._validateUsername(identityData.username)) {
10288           throw "invalid username";
10289         }
10290       }
10291     }
10292   };
10293 
10294   KiiUser.prototype._validateLocalPhoneNumber = function(phone, country) {
10295     if ((phone != null) && !KiiUtilities._isGlobalPhoneNumber(phone)) {
10296       if (country != null) {
10297         return KiiUtilities._validateCountryCode(country);
10298       } else {
10299         return false;
10300       }
10301     }
10302     return true;
10303   };
10304 
10305   KiiUser.prototype._updateWithJSON = function(json) {
10306     var key, temp, value, _results;
10307     root.Kii.logger("Updating with:");
10308     root.Kii.logger(JSON.stringify(json));
10309     this._thirdPartyAccounts = {};
10310     _results = [];
10311     for (key in json) {
10312       value = json[key];
10313       root.Kii.logger("key/val => " + key + "/" + value);
10314       root.Kii.logger("Substr " + (key.substring(0, 1)));
10315       if (key === "userID" || key === "id") {
10316         _results.push(this._uuid = value);
10317       } else if (key === "created" || key === "createdAt" || key === "_created") {
10318         _results.push(this._created = value);
10319       } else if (key === "modified" || key === "modifiedAt" || key === "_modified") {
10320         _results.push(this._modified = value);
10321       } else if (key === "loginName") {
10322         _results.push(this._username = value);
10323       } else if (key === "displayName") {
10324         _results.push(this._displayName = value);
10325       } else if (key === "country") {
10326         root.Kii.logger("Is setting country");
10327         _results.push(this._country = value);
10328       } else if (key === "locale") {
10329         _results.push(this._locale = value);
10330       } else if (key === "emailAddress") {
10331         _results.push(this._emailAddress = value);
10332       } else if (key === "_emailAddressPending") {
10333         _results.push(this._emailAddressPending = value);
10334       } else if (key === "phoneNumber") {
10335         _results.push(this._phoneNumber = value);
10336       } else if (key === "_phoneNumberPending") {
10337         _results.push(this._phoneNumberPending = value);
10338       } else if (key === "emailAddressVerified") {
10339         root.Kii.logger("Email verified: " + value);
10340         _results.push(this._emailVerified = value);
10341       } else if (key === "phoneNumberVerified") {
10342         root.Kii.logger("Phone verified: " + value);
10343         _results.push(this._phoneVerified = value);
10344       } else if (key === "_hasPassword") {
10345         root.Kii.logger("_hasPassword: " + value);
10346         _results.push(this._hasPassword = value);
10347       } else if (key === "_thirdPartyAccounts") {
10348         if (value.hotmail != null) {
10349           temp = value.hotmail;
10350           temp.type = "live";
10351           value.live = temp;
10352           delete value.hotmail;
10353         }
10354         root.Kii.logger("_thirdPartyAccounts: " + value);
10355         _results.push(this._thirdPartyAccounts = value);
10356       } else if (key === "_disabled") {
10357         root.Kii.logger("disabled: " + value);
10358         _results.push(this._disabled = value);
10359       } else if (key === "") {
10360         root.Kii.logger("Setting empty to custom info");
10361         _results.push(this._customInfo[key] = value);
10362       } else if (key.substring(0, 1 !== "_")) {
10363         root.Kii.logger("Setting to custom info");
10364         _results.push(this._customInfo[key] = value);
10365       } else {
10366         _results.push(root.Kii.logger("Doing nothing"));
10367       }
10368     }
10369     return _results;
10370   };
10371 
10372   KiiUser.prototype._getRequest = function(spec) {
10373     var path, request, withApp;
10374     path = spec.path;
10375     withApp = spec.withApp;
10376     request = new KiiRequest(path, withApp);
10377     return request;
10378   };
10379 
10380 
10381   /**
10382   Find registered KiiUser with the email.<br>
10383   If there are no user registers with the specified email or if there are but not verified email yet,
10384   callbacks.failure or reject callback of promise will be called.<br>
10385   <br><br>
10386   <b>Note:</b>
10387   <ul>
10388   <li>If "Expose Full User Data To Others" is enabled in the application console, the response will contain full of the user data.</li>
10389   <li>Otherwise, the response will only contain "userID", "loginName" and "displayName" field values if exist.</li>
10390   </ul>
10391   
10392   @param {String} email The email to find KiiUser who owns it.<br>
10393   Don't add prefix of "EMAIL:" described in REST API documentation. SDK will take care of it.
10394   @param {Object} [callbacks] An object with callback methods defined.
10395   This argument is mandatory and can't be ommited.
10396   @param {Method} callbacks.success The callback method to call on a successful finding request.
10397   @param {Method} callbacks.failure The callback method to call on a failed finding request.
10398   @return {Promise} return promise object.
10399     <ul>
10400       <li>fulfill callback function: function(theMatchedUser). theMatchedUser is KiiUser instance.</li>
10401       <li>reject callback function: function(error). error is an Error instance.
10402         <ul>
10403           <li>error.message</li>
10404         </ul>
10405       </li>
10406     </ul>
10407   @example
10408   // example to use callbacks directly
10409   KiiUser.findUserByEmail("user_to_find@example.com", {
10410       success: function(theMatchedUser) {
10411           // Do something with the found user
10412       },
10413       failure: function(anErrorString) {
10414           // Do something with the error response
10415       }
10416   });
10417   
10418   // example to use Promise
10419   KiiUser.findUserByEmail("user_to_find@example.com").then(
10420       function(theMatchedUser) {
10421           // Do something with the matched user
10422       },
10423       function(error) {
10424           // Do something with the error response
10425       }
10426   );
10427    */
10428 
10429   KiiUser.findUserByEmail = function(email, callbacks) {
10430     var error, errorString;
10431     if ((root.KiiUser.getCurrentUser() == null) || (root.KiiUser.getCurrentUser().getAccessToken() == null)) {
10432       errorString = root.IllegalStateException('User is not logged in');
10433       error = KiiUtilities._Error(errorString);
10434       if (callbacks != null) {
10435         if (typeof callbacks.failure === "function") {
10436           callbacks.failure(errorString);
10437         }
10438       }
10439       return Promise.reject(error);
10440     }
10441     return KiiUser._findUserByEmail(email, callbacks);
10442   };
10443 
10444   KiiUser._findUserByEmail = function(email, callbacks, context) {
10445     var error, errorString, url;
10446     if ((email == null) || email === "") {
10447       errorString = root.InvalidArgumentException('email should not null or empty');
10448       error = KiiUtilities._Error(errorString);
10449       if (context != null) {
10450         if (callbacks != null) {
10451           if (typeof callbacks.failure === "function") {
10452             callbacks.failure(context, errorString);
10453           }
10454         }
10455         error.target = context;
10456       } else {
10457         if (callbacks != null) {
10458           if (typeof callbacks.failure === "function") {
10459             callbacks.failure(errorString);
10460           }
10461         }
10462       }
10463       return Promise.reject(error);
10464     }
10465     url = root.Kii.getBaseURL() + "/apps/" + root.Kii.getAppID() + ("/users/EMAIL:" + email);
10466     return KiiUser._findUserRequestImpl(url, callbacks, context);
10467   };
10468 
10469 
10470   /**
10471   Find registered KiiUser with the phone.<br>
10472   If there are no user registers with the specified phone or if there are but not verified phone yet,
10473   callbacks.failure or reject callback of promise will be called.
10474   <br><br>
10475   <b>Note:</b>
10476   <ul>
10477   <li>If "Expose Full User Data To Others" is enabled in the application console, the response will contain full of the user data.</li>
10478   <li>Otherwise, the response will only contain "userID", "loginName" and "displayName" field values if exist.</li>
10479   </ul>
10480   
10481   @param {String} phone The phone number to find KiiUser who owns it.<br>
10482   Don't add prefix of "PHONE:" described in REST API documentation. SDK will take care of it.
10483   @param {Object} [callbacks] An object with callback methods defined.
10484   This argument is mandatory and can't be ommited.
10485   @param {Method} callbacks.success The callback method to call on a successful finding request.
10486   @param {Method} callbacks.failure The callback method to call on a failed finding request.
10487   @return {Promise} return promise object.
10488     <ul>
10489       <li>fulfill callback function: function(theMatchedUser). theMatchedUser is KiiUser instance.</li>
10490       <li>reject callback function: function(error). error is an Error instance.
10491         <ul>
10492           <li>error.message</li>
10493         </ul>
10494       </li>
10495     </ul>
10496   @example
10497   // example to use callbacks directly
10498   KiiUser.findUserByPhone("phone_number_to_find", {
10499       success: function(theMatchedUser) {
10500           // Do something with the found user
10501       },
10502       failure: function(anErrorString) {
10503           // Do something with the error response
10504       }
10505   });
10506   
10507   // example to use Promise
10508   KiiUser.findUserByPhone("phone_number_to_find").then(
10509       function(theMatchedUser) {
10510           // Do something with the matched user
10511       },
10512       function(error) {
10513           // Do something with the error response
10514       }
10515   );
10516    */
10517 
10518   KiiUser.findUserByPhone = function(phone, callbacks) {
10519     var error, errorString;
10520     if ((root.KiiUser.getCurrentUser() == null) || (root.KiiUser.getCurrentUser().getAccessToken() == null)) {
10521       errorString = root.IllegalStateException('User is not logged in');
10522       error = KiiUtilities._Error(errorString);
10523       if (callbacks != null) {
10524         if (typeof callbacks.failure === "function") {
10525           callbacks.failure(errorString);
10526         }
10527       }
10528       return Promise.reject(error);
10529     }
10530     return KiiUser._findUserByPhone(phone, callbacks);
10531   };
10532 
10533   KiiUser._findUserByPhone = function(phone, callbacks, context) {
10534     var error, errorString, url;
10535     if ((phone == null) || phone === "") {
10536       errorString = root.InvalidArgumentException('phone should not null or empty');
10537       error = KiiUtilities._Error(errorString);
10538       if (context != null) {
10539         if (callbacks != null) {
10540           if (typeof callbacks.failure === "function") {
10541             callbacks.failure(context, errorString);
10542           }
10543         }
10544         error.target = context;
10545       } else {
10546         if (callbacks != null) {
10547           if (typeof callbacks.failure === "function") {
10548             callbacks.failure(errorString);
10549           }
10550         }
10551       }
10552       return Promise.reject(error);
10553     }
10554     url = root.Kii.getBaseURL() + "/apps/" + root.Kii.getAppID() + ("/users/PHONE:" + phone);
10555     return KiiUser._findUserRequestImpl(url, callbacks, context);
10556   };
10557 
10558 
10559   /**
10560   Find registered KiiUser with the user name.<br>
10561   If there are no user registers with the specified user name, callbacks.failure or reject callback of promise will be called.
10562   <br><br>
10563   <b>Note:</b>
10564   <ul>
10565   <li>If "Expose Full User Data To Others" is enabled in the application console, the response will contain full of the user data.</li>
10566   <li>Otherwise, the response will only contain "userID", "loginName" and "displayName" field values if exist.</li>
10567   </ul>
10568   
10569   @param {String} username The user name to find KiiUser who owns it.<br>
10570   Don't add prefix of "LOGIN_NAME:" described in REST API documentation. SDK will take care of it.
10571   @param {Object} [callbacks] An object with callback methods defined.
10572   This argument is mandatory and can't be ommited.
10573   @param {Method} callbacks.success The callback method to call on a successful finding request.
10574   @param {Method} callbacks.failure The callback method to call on a failed finding request.
10575   @return {Promise} return promise object.
10576     <ul>
10577       <li>fulfill callback function: function(theMatchedUser). theMatchedUser is KiiUser instance.</li>
10578       <li>reject callback function: function(error). error is an Error instance.
10579         <ul>
10580           <li>error.message</li>
10581         </ul>
10582       </li>
10583     </ul>
10584   @example
10585   // example to use callbacks directly
10586   KiiUser.findUserByUsername("user_name_to_find", {
10587       success: function(theMatchedUser) {
10588           // Do something with the found user
10589       },
10590       failure: function(anErrorString) {
10591           // Do something with the error response
10592       }
10593   });
10594   
10595   // example to use Promise
10596   KiiUser.findUserByUsername("user_name_to_find").then(
10597       function(theMatchedUser) {
10598           // Do something with the matched user
10599       },
10600       function(error) {
10601           // Do something with the error response
10602       }
10603   );
10604    */
10605 
10606   KiiUser.findUserByUsername = function(username, callbacks) {
10607     var error, errorString;
10608     if ((root.KiiUser.getCurrentUser() == null) || (root.KiiUser.getCurrentUser().getAccessToken() == null)) {
10609       errorString = root.IllegalStateException('User is not logged in');
10610       error = KiiUtilities._Error(errorString);
10611       if (callbacks != null) {
10612         if (typeof callbacks.failure === "function") {
10613           callbacks.failure(errorString);
10614         }
10615       }
10616       return Promise.reject(error);
10617     }
10618     return KiiUser._findUserByUsername(username, callbacks);
10619   };
10620 
10621   KiiUser._findUserByUsername = function(username, callbacks, context) {
10622     var error, errorString, url;
10623     if ((username == null) || username === "") {
10624       errorString = root.InvalidArgumentException('username should not null or empty');
10625       error = KiiUtilities._Error(errorString);
10626       if (context != null) {
10627         if (callbacks != null) {
10628           if (typeof callbacks.failure === "function") {
10629             callbacks.failure(context, errorString);
10630           }
10631         }
10632         error.target = context;
10633       } else {
10634         if (callbacks != null) {
10635           if (typeof callbacks.failure === "function") {
10636             callbacks.failure(errorString);
10637           }
10638         }
10639       }
10640       return Promise.reject(error);
10641     }
10642     url = root.Kii.getBaseURL() + "/apps/" + root.Kii.getAppID() + ("/users/LOGIN_NAME:" + username);
10643     return KiiUser._findUserRequestImpl(url, callbacks, context);
10644   };
10645 
10646   KiiUser._findUserRequestImpl = function(url, callbacks, context) {
10647     return new Promise(function(resolve, reject) {
10648       var findUserRequestImplCallbacks;
10649       findUserRequestImplCallbacks = {
10650         success: function() {
10651           var _ref;
10652           if (callbacks != null) {
10653             if ((_ref = callbacks.success) != null) {
10654               _ref.apply(callbacks, arguments);
10655             }
10656           }
10657           if (context != null) {
10658             return resolve(arguments);
10659           } else {
10660             return resolve(arguments[0]);
10661           }
10662         },
10663         failure: function() {
10664           var _ref;
10665           if (callbacks != null) {
10666             if ((_ref = callbacks.failure) != null) {
10667               _ref.apply(callbacks, arguments);
10668             }
10669           }
10670           if (context != null) {
10671             return reject(KiiUtilities._Error(arguments[1], arguments[0]));
10672           } else {
10673             return reject(KiiUtilities._Error(arguments[0]));
10674           }
10675         }
10676       };
10677       return KiiUser._findUserRequestImplUsingCallbacks(url, findUserRequestImplCallbacks, context);
10678     });
10679   };
10680 
10681   KiiUser._findUserRequestImplUsingCallbacks = function(url, callbacks, context) {
10682     var requestCallbacks, wrapper, xhr;
10683     wrapper = KiiXHRWrapperFactory.createXHRWrapper("GET", url);
10684     xhr = wrapper.xhr;
10685     xhr.setRequestHeader("x-kii-appid", root.Kii.getAppID());
10686     xhr.setRequestHeader("x-kii-appkey", root.Kii.getAppKey());
10687     xhr.setRequestHeader("x-kii-sdk", root.KiiSDKClientInfo.getSDKClientInfo());
10688     if (context != null) {
10689       xhr.setRequestHeader("Authorization", "Bearer " + context._getToken());
10690     } else {
10691       xhr.setRequestHeader("Authorization", "Bearer " + root.KiiUser.getCurrentUser().getAccessToken());
10692     }
10693     requestCallbacks = {
10694       success: function() {
10695         var json, user;
10696         if (callbacks != null) {
10697           try {
10698             json = JSON.parse(xhr.responseText);
10699             if (context != null) {
10700               user = new root.KiiUserWithToken(context._getToken());
10701               user._updateWithJSON(json);
10702               return callbacks.success(context, user);
10703             } else {
10704               user = new root.KiiUser();
10705               user._updateWithJSON(json);
10706               return callbacks.success(user);
10707             }
10708           } catch (_error) {
10709             if (context != null) {
10710               return callbacks.failure(context, "Unable to parse response");
10711             } else {
10712               return callbacks.failure("Unable to parse response");
10713             }
10714           }
10715         }
10716       },
10717       failure: function() {
10718         var errString, json;
10719         if (callbacks != null) {
10720           errString = "Failed to find user. statusCode: " + xhr.status;
10721           try {
10722             json = JSON.parse(xhr.responseText);
10723             if (json.errorCode != null) {
10724               errString += " error code: " + json.errorCode;
10725             }
10726             if (json.message != null) {
10727               return errString += " error message: " + json.message;
10728             }
10729           } finally {
10730             if (context != null) {
10731               callbacks.failure(context, errString);
10732             } else {
10733               callbacks.failure(errString);
10734             }
10735           }
10736         }
10737       }
10738     };
10739     return wrapper.send(requestCallbacks);
10740   };
10741 
10742   KiiUser.prototype._getXhrWrapper = function(method, url) {
10743     var wrapper, xhr;
10744     wrapper = KiiXHRWrapperFactory.createXHRWrapper(method, url);
10745     xhr = wrapper.xhr;
10746     xhr.setRequestHeader("x-kii-appid", root.Kii.getAppID());
10747     xhr.setRequestHeader("x-kii-appkey", root.Kii.getAppKey());
10748     xhr.setRequestHeader("x-kii-sdk", root.KiiSDKClientInfo.getSDKClientInfo());
10749     return wrapper;
10750   };
10751 
10752   KiiUser.prototype._setAuthHeader = function(xhr) {
10753     var user;
10754     user = root.KiiUser.getCurrentUser();
10755     if (user != null) {
10756       return xhr.setRequestHeader("Authorization", "Bearer " + user.getAccessToken());
10757     }
10758   };
10759 
10760   KiiUser.prototype._groupWithJSON = function(json) {
10761     return root.KiiGroup._groupWithJSON(json);
10762   };
10763 
10764 
10765   /**
10766   Instantiate topic belongs to this user.
10767   @param {String} topicName name of the topic. Must be a not empty string.
10768   @return {KiiTopic} topic instance.
10769    */
10770 
10771   KiiUser.prototype.topicWithName = function(topicName) {
10772     var id, puri;
10773     if (typeof topicName !== "string" || topicName === "") {
10774       throw new root.InvalidArgumentException('topicName should not null or empty');
10775     }
10776     id = this.getID();
10777     if (!id) {
10778       throw 'can not instantiate topic from instance which doesn\'t have ID';
10779     }
10780     puri = this._getHttpURI();
10781     return new root.KiiTopic(puri, topicName);
10782   };
10783 
10784 
10785   /** Gets a list of topics in this user scope
10786   @param {Object} [callbacks] An object with callback methods defined
10787   @param {Method} callbacks.success The callback method to call on a successful list request
10788   @param {Method} callbacks.failure The callback method to call on a failed list request
10789   @param {String} [paginationKey] You can specify the pagination key with the nextPaginationKey passed by callbacks.success. If empty string or no string object is provided, this API regards no paginationKey specified.
10790   @return {Promise} return promise object.
10791       <ul>
10792         <li>fulfill callback function: function(params). params is Array instance.
10793           <ul>
10794             <li>params[0] is array of KiiTopic instances.</li>
10795             <li>params[1] is string of nextPaginationKey.</li>
10796           </ul>
10797         </li>
10798         <li>reject callback function: function(error). error is an Error instance.
10799           <ul>
10800             <li>error.target is the KiiUser instance which this method was called on. </li>
10801             <li>error.message</li>
10802           </ul>
10803         </li>
10804       </ul>
10805   @example
10806   // example to use callbacks directly
10807   var user = . . .; // a KiiUser
10808   user.listTopics({
10809       success: function(topicList, nextPaginationKey) {
10810           // do something with the result
10811           for(var i=0; i<topicList.length; i++){
10812               var topic = topicList[i];
10813           }
10814           if (nextPaginationKey != null) {
10815               user.listTopics({
10816                   success: function(topicList, nextPaginationKey) {...},
10817                   failure: function(anErrorString) {...}
10818               }, nextPaginationKey);
10819           }
10820       },
10821       failure: function(anErrorString) {
10822           // do something with the error response
10823       }
10824   });
10825   
10826   // example to use callbacks directly
10827   var user = . . .; // a KiiUser
10828   user.listTopics().then(
10829       function(params) {
10830           var topicList = params[0];
10831           var nextPaginationKey = params[1];
10832           // do something with the result
10833           for(var i=0; i<topicList.length; i++){
10834               var topic = topicList[i];
10835           }
10836           if (nextPaginationKey != null) {
10837               user.listTopics(null, nextPaginationKey).then(
10838                   function(params) {...},
10839                   function(error) {...}
10840               );
10841           }
10842       },
10843       function(error) {
10844           // do something with the error response
10845       }
10846   );
10847    */
10848 
10849   KiiUser.prototype.listTopics = function(callbacks, paginationKey) {
10850     return new Promise((function(_this) {
10851       return function(resolve, reject) {
10852         var listTopicsCallbacks;
10853         listTopicsCallbacks = {
10854           success: function() {
10855             if (callbacks != null) {
10856               callbacks.success.apply(callbacks, arguments);
10857             }
10858             return resolve(arguments);
10859           },
10860           failure: function() {
10861             if (callbacks != null) {
10862               callbacks.failure.apply(callbacks, arguments);
10863             }
10864             return reject(arguments[0]);
10865           }
10866         };
10867         return _this._listTopicsUsingCallbacks(listTopicsCallbacks, paginationKey);
10868       };
10869     })(this));
10870   };
10871 
10872   KiiUser.prototype._listTopicsUsingCallbacks = function(callbacks, paginationKey) {
10873     var listCallbacks, uri, wrapper;
10874     uri = "" + (this._getHttpURI()) + "/topics";
10875     if (typeof paginationKey === "string" && paginationKey !== "") {
10876       uri = uri + "?paginationKey=" + encodeURIComponent(paginationKey);
10877     }
10878     wrapper = KiiXHRWrapperFactory.createXHRWrapper('GET', uri);
10879     wrapper.setKiiHeaders();
10880     this._setAuthToken(wrapper);
10881     listCallbacks = {
10882       success: (function(_this) {
10883         return function() {
10884           var json, topic, topics, _i, _len, _ref;
10885           json = JSON.parse(wrapper.xhr.responseText);
10886           topics = [];
10887           _ref = json.topics;
10888           for (_i = 0, _len = _ref.length; _i < _len; _i++) {
10889             topic = _ref[_i];
10890             topics.push(_this.topicWithName(topic.topicID));
10891           }
10892           return callbacks != null ? callbacks.success(topics, (json.paginationKey === void 0 ? null : json.paginationKey)) : void 0;
10893         };
10894       })(this),
10895       failure: (function(_this) {
10896         return function() {
10897           var errObj, errString;
10898           errString = wrapper.getErrorString("list topics");
10899           errObj = KiiUtilities._Error(errString, _this);
10900           return callbacks != null ? callbacks.failure(errObj) : void 0;
10901         };
10902       })(this)
10903     };
10904     return wrapper.send(listCallbacks);
10905   };
10906 
10907 
10908   /** Instantiate push subscription for this user.
10909   @return {KiiPushSubscription} push subscription object.
10910    */
10911 
10912   KiiUser.prototype.pushSubscription = function() {
10913     return new root.KiiPushSubscription(this);
10914   };
10915 
10916 
10917   /** Instantiate push installation for this user.
10918   @return {KiiPushInstallation} push installation object.
10919    */
10920 
10921   KiiUser.prototype.pushInstallation = function() {
10922     return new root.KiiPushInstallation(this);
10923   };
10924 
10925   KiiUser.prototype._getSubscriberPath = function() {
10926     return "users/" + (this.getID());
10927   };
10928 
10929   KiiUser.prototype._clone = function(obj) {
10930     var key, newInstance;
10931     if ((obj == null) || typeof obj !== 'object') {
10932       return obj;
10933     }
10934     newInstance = new obj.constructor();
10935     for (key in obj) {
10936       newInstance[key] = this._clone(obj[key]);
10937     }
10938     return newInstance;
10939   };
10940 
10941   KiiUser.prototype._getHttpURI = function() {
10942     return "" + (root.Kii.getBaseURL()) + "/apps/" + (root.Kii.getAppID()) + "/users/" + (this.getID());
10943   };
10944 
10945   KiiUser.prototype._setAuthToken = function(wrapper) {
10946     return wrapper.setCurrentUserToken();
10947   };
10948 
10949   return KiiUser;
10950 
10951 })();
10952 
10953 KiiUtilities = (function() {
10954   function KiiUtilities() {}
10955 
10956   KiiUtilities.MAX_DATE_IN_MILLIS = 100000000 * 24 * 60 * 60 * 1000;
10957 
10958   KiiUtilities.MIN_DATE_IN_MILLIS = -100000000 * 24 * 60 * 60 * 1000;
10959 
10960   KiiUtilities._validateEmail = function(value) {
10961     var pattern;
10962     if ((typeof value).toLowerCase() !== "string") {
10963       root.Kii.logger("Not string");
10964       return false;
10965     }
10966     value = KiiUtilities._trim(value);
10967     pattern = /^[^@]+@[^@]+$/;
10968     return pattern.test(value);
10969   };
10970 
10971   KiiUtilities._validatePhoneNumber = function(value) {
10972     var pattern;
10973     value = KiiUtilities._trim(value);
10974     pattern = /^[\\+]?[0-9]{10,}$/i;
10975     if ((typeof value).toLowerCase() !== "string") {
10976       root.Kii.logger("Not string");
10977       return false;
10978     } else if (value.match(pattern)) {
10979       return true;
10980     } else {
10981       return false;
10982     }
10983   };
10984 
10985   KiiUtilities._isGlobalPhoneNumber = function(value) {
10986     var pattern;
10987     value = KiiUtilities._trim(value);
10988     pattern = /^[\\+]{1}[0-9]{2}/;
10989     if ((typeof value).toLowerCase() !== "string") {
10990       root.Kii.logger("Not string");
10991       return false;
10992     } else if (value.match(pattern)) {
10993       return true;
10994     } else {
10995       return false;
10996     }
10997   };
10998 
10999   KiiUtilities._validateLocalPhone = function(value) {
11000     var pattern;
11001     value = KiiUtilities._trim(value);
11002     pattern = /^\d+$/;
11003     if ((typeof value).toLowerCase() !== "string") {
11004       root.Kii.logger("Not string");
11005       return false;
11006     } else if (value.match(pattern)) {
11007       return true;
11008     } else {
11009       root.Kii.logger("Invalid format");
11010       return false;
11011     }
11012   };
11013 
11014   KiiUtilities._assertLocalPhoneIsValid = function(value) {
11015     if (!KiiUtilities._validateLocalPhone(value)) {
11016       throw new root.InvalidLocalPhoneNumberException;
11017     }
11018   };
11019 
11020   KiiUtilities._validateCountryCode = function(value) {
11021     var pattern;
11022     value = KiiUtilities._trim(value);
11023     pattern = /^[a-z]{2}$/i;
11024     if ((typeof value).toLowerCase() !== "string") {
11025       root.Kii.logger("Not string");
11026       return false;
11027     } else if (value.match(pattern)) {
11028       root.Kii.logger("Is true");
11029       return true;
11030     } else {
11031       return false;
11032     }
11033   };
11034 
11035   KiiUtilities._assertCountryCodeIsValid = function(value) {
11036     if (!KiiUtilities._validateCountryCode(value)) {
11037       throw new root.InvalidCountryException;
11038     }
11039   };
11040 
11041   KiiUtilities._validatePassword = function(value) {
11042     var pattern;
11043     root.Kii.logger("Validating password: " + value);
11044     pattern = /^[\x20-\x7E]{4,50}$/;
11045     if ((typeof value).toLowerCase() !== "string") {
11046       root.Kii.logger("not string");
11047       return false;
11048     } else if (value.match(pattern)) {
11049       root.Kii.logger("matched");
11050       return true;
11051     } else {
11052       root.Kii.logger("other exception");
11053       return false;
11054     }
11055   };
11056 
11057   KiiUtilities._assertPasswordIsValid = function(value) {
11058     if (!KiiUtilities._validatePassword(value)) {
11059       throw new root.InvalidPasswordException;
11060     }
11061   };
11062 
11063   KiiUtilities._validateUsername = function(value) {
11064     var pattern;
11065     pattern = /^[a-zA-Z0-9-_\\.]{3,64}$/i;
11066     if ((typeof value).toLowerCase() !== "string") {
11067       return false;
11068     } else if (value.match(pattern)) {
11069       return true;
11070     } else {
11071       return false;
11072     }
11073   };
11074 
11075   KiiUtilities._validateGroupID = function(value) {
11076     var pattern;
11077     pattern = /^[a-z0-9-_.]{1,30}$/;
11078     if ((typeof value).toLowerCase() !== "string") {
11079       return false;
11080     } else if (value.match(pattern)) {
11081       return true;
11082     } else {
11083       return false;
11084     }
11085   };
11086 
11087   KiiUtilities._validateDisplayName = function(value) {
11088     var _ref;
11089     return KiiUtilities._type(value) === "string" && (1 <= (_ref = value.length) && _ref <= 50);
11090   };
11091 
11092   KiiUtilities._trim = function(value) {
11093     var pattern;
11094     pattern = /^(\s|\u00A0)+|(\s|\u00A0)+$/g;
11095     return (value || "").replace(pattern, "");
11096   };
11097 
11098   KiiUtilities._safeAddTicks = function(left, right) {
11099     if ((isNaN(parseInt(left, 10))) || (isNaN(parseInt(right, 10)))) {
11100       throw new root.InvalidArgumentException('Parameters should be a number');
11101     }
11102     if ((Math.abs(left + right)) > KiiUtilities.MAX_DATE_IN_MILLIS) {
11103       throw new root.ArithmeticException("Addition of " + left + " and " + right + " result in long overflow");
11104     }
11105     return left + right;
11106   };
11107 
11108   KiiUtilities._safeMultiplyTicks = function(left, right) {
11109     if ((isNaN(parseInt(left, 10))) || (isNaN(parseInt(right, 10)))) {
11110       throw new root.InvalidArgumentException('Parameters should be a number');
11111     }
11112     if ((Math.abs(left * right)) > KiiUtilities.MAX_DATE_IN_MILLIS) {
11113       throw new root.ArithmeticException("Multiplication of " + left + " and " + right + " result in long overflow");
11114     }
11115     return left * right;
11116   };
11117 
11118   KiiUtilities._safeCalculateExpiresAtAsNumber = function(expirationInSeconds, baseUnixTimeInMills) {
11119     var e, expirationInMillis, expiresAt;
11120     expiresAt = 0;
11121     try {
11122       expirationInMillis = KiiUtilities._safeMultiplyTicks(expirationInSeconds, 1000);
11123       expiresAt = KiiUtilities._safeAddTicks(baseUnixTimeInMills, expirationInMillis);
11124     } catch (_error) {
11125       e = _error;
11126       if (e instanceof root.ArithmeticException) {
11127         expiresAt = KiiUtilities.MAX_DATE_IN_MILLIS;
11128       } else {
11129         throw e;
11130       }
11131     }
11132     return expiresAt;
11133   };
11134 
11135   KiiUtilities._safeCalculateExpiresAtAsDate = function(expirationInSeconds, baseUnixTimeInMills) {
11136     var e, expirationInMillis, expiresAt;
11137     expiresAt = 0;
11138     try {
11139       expirationInMillis = KiiUtilities._safeMultiplyTicks(expirationInSeconds, 1000);
11140       expiresAt = KiiUtilities._safeAddTicks(baseUnixTimeInMills, expirationInMillis);
11141     } catch (_error) {
11142       e = _error;
11143       if (e instanceof root.ArithmeticException) {
11144         expiresAt = KiiUtilities.MAX_DATE_IN_MILLIS;
11145       } else {
11146         throw e;
11147       }
11148     }
11149     return new Date(expiresAt);
11150   };
11151 
11152   KiiUtilities._isJSONType = function(contentType) {
11153     var pattern;
11154     pattern = /\+?json(;.*)?$/i;
11155     return contentType.match(pattern);
11156   };
11157 
11158   KiiUtilities._type = function(obj) {
11159     var classToType;
11160     if (obj === void 0 || obj === null) {
11161       return String(obj);
11162     }
11163     classToType = {
11164       '[object Boolean]': 'boolean',
11165       '[object Number]': 'number',
11166       '[object String]': 'string',
11167       '[object Function]': 'function',
11168       '[object Array]': 'array',
11169       '[object Date]': 'date',
11170       '[object RegExp]': 'regexp',
11171       '[object Object]': 'object'
11172     };
11173     return classToType[Object.prototype.toString.call(obj)];
11174   };
11175 
11176   KiiUtilities._disableCacheURL = function(url) {
11177     if (url.indexOf('?') !== -1) {
11178       url += "&disable_cache=";
11179     } else {
11180       url += "?disable_cache=";
11181     }
11182     url += new Date().getTime();
11183     return url;
11184   };
11185 
11186   KiiUtilities._validateServerCodeEntryName = function(value) {
11187     var pattern;
11188     pattern = /^[a-zA-Z][_a-zA-Z0-9]*$/i;
11189     return KiiUtilities._type(value) === "string" && value.match(pattern);
11190   };
11191 
11192   KiiUtilities._validateServerCodeEntryArgument = function(value) {
11193     return KiiUtilities._type(value) === "null" || (KiiUtilities._type(value) === "object" && Object.keys(value).length > 0);
11194   };
11195 
11196   KiiUtilities._validateServerCodeEnryVersion = function(value) {
11197     return KiiUtilities._type(value) === 'string' && value !== "";
11198   };
11199 
11200   KiiUtilities._isNonEmptyString = function(s) {
11201     if (typeof s !== "string") {
11202       return false;
11203     }
11204     return s.length > 0;
11205   };
11206 
11207   KiiUtilities._Error = function(message, target) {
11208     var e;
11209     e = Error(message);
11210     e.target = target;
11211     return e;
11212   };
11213 
11214   KiiUtilities._clone = function(obj) {
11215     var flags, key, newInstance;
11216     if ((obj == null) || typeof obj !== 'object') {
11217       return obj;
11218     }
11219     if (obj instanceof Date) {
11220       return new Date(obj.getTime());
11221     }
11222     if (obj instanceof RegExp) {
11223       flags = '';
11224       if (obj.global) {
11225         flags += 'g';
11226       }
11227       if (obj.ignoreCase) {
11228         flags += 'i';
11229       }
11230       if (obj.multiline) {
11231         flags += 'm';
11232       }
11233       if (obj.sticky) {
11234         flags += 'y';
11235       }
11236       return new RegExp(obj.source, flags);
11237     }
11238     newInstance = new obj.constructor();
11239     for (key in obj) {
11240       newInstance[key] = KiiUtilities._clone(obj[key]);
11241     }
11242     return newInstance;
11243   };
11244 
11245   return KiiUtilities;
11246 
11247 })();
11248 
11249 
11250 /**
11251     @class Represents a KiiSocialConnect object
11252     @exports root.KiiACL as KiiACL
11253  */
11254 
11255 root.KiiSocialConnect = (function() {
11256   var _instance;
11257 
11258   function KiiSocialConnect() {}
11259 
11260   _instance = null;
11261 
11262 
11263   /** @deprecated You don't have to call this method.
11264   Set up a reference to one of the supported KiiSocialNetworks.
11265   
11266   Set up the network. Need to be called before accessing other methods.
11267               <br><b> Facebook </b>
11268               <table border="1" cellspacing="0">
11269               <thead>
11270               <tr bgcolor="#CCCCFF">
11271                   <th>Argument</th>
11272                   <th>Value Type</th>
11273                   <th>Value</th>
11274                   <th>Note</th>
11275               </tr>
11276               </thead>
11277               <tbody>
11278               <tr>
11279                   <td>networkName</td>
11280                   <td>Number</td>
11281                   <td>KiiSocialNetworkName.FACEBOOK</td>
11282                   <td>Specify Facebook</td>
11283               </tr>
11284               <tr>
11285                   <td>apiKey</td>
11286                   <td>String</td>
11287                   <td>null</td>
11288                   <td>Facebook does not requires this argument.</td>
11289               </tr>
11290               <tr>
11291                   <td>apiSecret</td>
11292                   <td>String</td>
11293                   <td>null</td>
11294                   <td>Facebook does not requires this argument.</td>
11295               </tr>
11296               <tr>
11297                   <td>extras</td>
11298                   <td>Object</td>
11299                   <td>null</td>
11300                   <td>Facebook does not requires this argument.</td>
11301               </tr>
11302               </tbody>
11303               </table>
11304   
11305               <br><b> Twitter </b>
11306               <table border="1" cellspacing="0">
11307               <thead>
11308               <tr bgcolor="#CCCCFF">
11309                   <th>Argument</th>
11310                   <th>Value Type</th>
11311                   <th>Value</th>
11312                   <th>Note</th>
11313               </tr>
11314               </thead>
11315               <tbody>
11316               <tr>
11317                   <td>networkName</td>
11318                   <td>Number</td>
11319                   <td>KiiSocialNetworkName.TWITTER</td>
11320                   <td>Specify Twitter</td>
11321               </tr>
11322               <tr>
11323                   <td>apiKey</td>
11324                   <td>String</td>
11325                   <td>null</td>
11326                   <td>Twitter does not requires this argument.</td>
11327               </tr>
11328               <tr>
11329                   <td>apiSecret</td>
11330                   <td>String</td>
11331                   <td>null</td>
11332                   <td>Twitter does not requires this argument.</td>
11333               </tr>
11334               <tr>
11335                   <td>extras</td>
11336                   <td>Object</td>
11337                   <td>null</td>
11338                   <td>Twitter does not requires this argument.</td>
11339               </tr>
11340               </tbody>
11341               </table>
11342               <br><b> QQ </b>
11343               <table border="1" cellspacing="0">
11344               <thead>
11345               <tr bgcolor="#CCCCFF">
11346                   <th>Argument</th>
11347                   <th>Value Type</th>
11348                   <th>Value</th>
11349                   <th>Note</th>
11350               </tr>
11351               </thead>
11352               <tbody>
11353               <tr>
11354                   <td>networkName</td>
11355                   <td>Number</td>
11356                   <td>KiiSocialNetworkName.QQ</td>
11357                   <td>Specify QQ</td>
11358               </tr>
11359               <tr>
11360                   <td>apiKey</td>
11361                   <td>String</td>
11362                   <td>null</td>
11363                   <td>QQ does not requires this argument.</td>
11364               </tr>
11365               <tr>
11366                   <td>apiSecret</td>
11367                   <td>String</td>
11368                   <td>null</td>
11369                   <td>QQ does not requires this argument.</td>
11370               </tr>
11371               <tr>
11372                   <td>extras</td>
11373                   <td>Object</td>
11374                   <td>null</td>
11375                   <td>QQ does not requires this argument.</td>
11376               </tr>
11377               </tbody>
11378               </table>
11379   
11380    @param {KiiSocialNetworkName} networkName One of the supported KiiSocialNetworkName values
11381    @param {String} apiKey The SDK key assigned by the social network provider. For details refer to the table above.
11382    @param {String} apiSecret The SDK secret assigned by the social network provider. For details refer to the table above.
11383    @param {Object} extras Extra options that should be passed to the SNS. For details refer to the table above.
11384    @throws {InvalidArgumentException} For details refer to the table above
11385    */
11386 
11387   KiiSocialConnect.setupNetwork = function(networkName, apiKey, apiSecret, extras) {};
11388 
11389 
11390   /** Log a user into the social network provided
11391   
11392    This will initiate the login process for the given network. If user has already linked with the specified social network,
11393    sign-in with the social network. Otherwise, this will sign-up and create new user authenticated by the specified social network.
11394    If sign-up successful, the user is cached inside SDK as current user,and accessible via {@link KiiUser.getCurrentUser()}.
11395    User token and token expiration is also cached and can be get by {@link KiiUser#getAccessTokenObject()}.
11396    Access token won't be expired unless you set it explicitly by {@link Kii.setAccessTokenExpiration()}.
11397    The network must already be set up via setupNetwork<br>
11398    If the opitons is invalid, callbacks.failure or reject callback of promise will be called. <br>
11399   
11400    @param networkName One of the supported KiiSocialNetworkName values
11401    @param options A dictionary of key/values to pass to KiiSocialConnect
11402   
11403               <br><b> Facebook </b>
11404               <table border="1" cellspacing="0">
11405               <thead>
11406               <tr bgcolor="#CCCCFF">
11407                   <th>Key</th>
11408                   <th>Value type</th>
11409                   <th>Value</th>
11410                   <th>Note</th>
11411               </tr>
11412               </thead>
11413               <tbody>
11414               <tr>
11415                   <td>access_token</td>
11416                   <td>String</td>
11417                   <td>Access token of Facebook.</td>
11418                   <td>This is mandatory.</td>
11419               </tr>
11420               </tbody>
11421               </table>
11422   
11423               <br><b> Twitter </b>
11424               <table border="1" cellspacing="0">
11425               <thead>
11426               <tr bgcolor="#CCCCFF">
11427                   <th>Key</th>
11428                   <th>Value type</th>
11429                   <th>Value</th>
11430                   <th>Note</th>
11431               </tr>
11432               </thead>
11433               <tbody>
11434               <tr>
11435                   <td>oauth_token</td>
11436                   <td>String</td>
11437                   <td>OAuth access token of twitter.</td>
11438                   <td>This is mandatory. </td>
11439               </tr>
11440               <tr>
11441                   <td>oauth_token_secret</td>
11442                   <td>String</td>
11443                   <td>OAuth access token secret of twitter.</td>
11444                   <td>This is mandatory.</td>
11445               </tr>
11446               </tbody>
11447               </table>
11448   
11449               <br><b> Google </b>
11450               <table border="1" cellspacing="0">
11451               <thead>
11452               <tr bgcolor="#CCCCFF">
11453                   <th>Key</th>
11454                   <th>Value type</th>
11455                   <th>Value</th>
11456                   <th>Note</th>
11457               </tr>
11458               </thead>
11459               <tbody>
11460               <tr>
11461                   <td>access_token</td>
11462                   <td>String</td>
11463                   <td>Access token of Google.</td>
11464                   <td>This is mandatory.</td>
11465               </tr>
11466               </tbody>
11467               </table>
11468   
11469               <br><b> QQ </b>
11470               <table border="1" cellspacing="0">
11471               <thead>
11472               <tr bgcolor="#CCCCFF">
11473                   <th>Key</th>
11474                   <th>Value type</th>
11475                   <th>Value</th>
11476                   <th>Note</th>
11477               </tr>
11478               </thead>
11479               <tbody>
11480               <tr>
11481                   <td>access_token</td>
11482                   <td>String</td>
11483                   <td>Access token of QQ.</td>
11484                   <td>This is mandatory. </td>
11485               </tr>
11486               <tr>
11487                   <td>openID</td>
11488                   <td>String</td>
11489                   <td>OpenID of QQ.</td>
11490                   <td>This is mandatory.</td>
11491               </tr>
11492               </tbody>
11493               </table>
11494   
11495   
11496    @param {Object} [callbacks] An object with callback methods defined
11497    @param {Method} callbacks.success The callback method to call on a successful log in request
11498    @param {Method} callbacks.failure The callback method to call on a failed log in request
11499    @return {Promise} return promise object.
11500     <ul>
11501       <li>fulfill callback function: function(params). params is Array instance.
11502         <ul>
11503           <li>params[0] is a logged in KiiUser instance.</li>
11504           <li>params[1] is the KiiSocialNetworkName used to login.</li>
11505         </ul>
11506       </li>
11507       <li>reject callback function: function(error). error is an Error instance.
11508         <ul>
11509           <li>error.message</li>
11510           <li>error.network is the KiiSocialNetworkName used to login.</li>
11511         </ul>
11512       </li>
11513     </ul>
11514    @example
11515    // example to use callbacks directly
11516    // Example of using no option
11517    KiiSocialConnect.logIn(KiiSocialNetworkName.FACEBOOK, null, {
11518   
11519        success: function(user, network) {
11520            // do something now that the user is logged in
11521        },
11522   
11523        failure: function(user, network, anErrorString) {
11524            // do something with the error response
11525        }
11526    });
11527   
11528    // example to use Promise
11529    KiiSocialConnect.logIn(KiiSocialNetworkName.FACEBOOK, null).then(
11530        function(params) {
11531            // do something now that the user is logged in
11532        },
11533        function(error) {
11534            // do something with the error response
11535        }
11536    );
11537    */
11538 
11539   KiiSocialConnect.logIn = function(networkName, options, callbacks) {
11540     if (_instance == null) {
11541       _instance = new _KiiSocialConnect;
11542     }
11543     return new Promise(function(resolve, reject) {
11544       var error, errorString, logInCallbacks;
11545       logInCallbacks = {
11546         success: function() {
11547           if (callbacks != null) {
11548             callbacks.success.apply(callbacks, arguments);
11549           }
11550           return resolve(arguments);
11551         },
11552         failure: function() {
11553           var error;
11554           if (callbacks != null) {
11555             callbacks.failure.apply(callbacks, arguments);
11556           }
11557           error = KiiUtilities._Error(arguments[2]);
11558           error.network = networkName;
11559           return reject(error);
11560         }
11561       };
11562       try {
11563         return KiiSocialConnect._logInUsingCallbacks(networkName, options, logInCallbacks);
11564       } catch (_error) {
11565         errorString = _error;
11566         if (callbacks != null) {
11567           if (typeof callbacks.failure === "function") {
11568             callbacks.failure(null, networkName, errorString);
11569           }
11570         }
11571         error = KiiUtilities._Error(errorString);
11572         error.network = networkName;
11573         return reject(error);
11574       }
11575     });
11576   };
11577 
11578   KiiSocialConnect._logInUsingCallbacks = function(networkName, options, callbacks) {
11579     var called;
11580     called = false;
11581     if (_instance != null) {
11582       root.Kii.logger("And manager: ");
11583       root.Kii.logger(_instance._getManager(networkName));
11584       if (_instance._getManager(networkName)) {
11585         _instance._getManager(networkName)._logIn(options, callbacks);
11586         called = true;
11587       }
11588     }
11589     root.Kii.logger("Callbacks");
11590     root.Kii.logger(callbacks);
11591     if (!called && (callbacks != null)) {
11592       return callbacks.failure(root.KiiUser.getCurrentUser(), networkName, "Unable to get network. Please ensure the network name is one of the supported KiiSocialNetworkName values");
11593     }
11594   };
11595 
11596 
11597   /** Link the currently logged in user with a social network
11598   
11599    This will initiate the login process for the given network, which for SSO-enabled services like Facebook, will send the user to the Facebook site for authentication. There must be a currently authenticated KiiUser. Otherwise, you can use the logIn: method to create and log in a KiiUser using a network. The network must already be set up via setupNetwork<br>
11600    If there is not logged-in user to link with, callbacks.failure or reject callback of promise will be called. <br>
11601    If the opitons is invalid, callbacks.failure or reject callback of promise will be called. <br>
11602    @param networkName One of the supported KiiSocialNetworkName values
11603    @param options A dictionary of key/values to pass to KiiSocialConnect
11604               <br><b> Facebook </b>
11605               <table border="1" cellspacing="0">
11606               <thead>
11607               <tr bgcolor="#CCCCFF">
11608                   <th>Key</th>
11609                   <th>Value type</th>
11610                   <th>Value</th>
11611                   <th>Note</th>
11612               </tr>
11613               </thead>
11614               <tbody>
11615               <tr>
11616                   <td>access_token</td>
11617                   <td>String</td>
11618                   <td>Access token of Facebook.</td>
11619                   <td>This is mandatory.</td>
11620               </tr>
11621               </tbody>
11622               </table>
11623   
11624               <br><b> Twitter </b>
11625               <table border="1" cellspacing="0">
11626               <thead>
11627               <tr bgcolor="#CCCCFF">
11628                   <th>Key</th>
11629                   <th>Value type</th>
11630                   <th>Value</th>
11631                   <th>Note</th>
11632               </tr>
11633               </thead>
11634               <tbody>
11635               <tr>
11636                   <td>oauth_token</td>
11637                   <td>String</td>
11638                   <td>OAuth access token of twitter.</td>
11639                   <td>This is mandatory.</td>
11640               </tr>
11641               <tr>
11642                   <td>oauth_token_secret</td>
11643                   <td>String</td>
11644                   <td>OAuth access token secret of twitter.</td>
11645                   <td>This is mandatory.</td>
11646               </tr>
11647               </tbody>
11648               </table>
11649   
11650               <br><b> Google </b>
11651               <table border="1" cellspacing="0">
11652               <thead>
11653               <tr bgcolor="#CCCCFF">
11654                   <th>Key</th>
11655                   <th>Value type</th>
11656                   <th>Value</th>
11657                   <th>Note</th>
11658               </tr>
11659               </thead>
11660               <tbody>
11661               <tr>
11662                   <td>access_token</td>
11663                   <td>String</td>
11664                   <td>Access token of Google.</td>
11665                   <td>This is mandatory.</td>
11666               </tr>
11667               </tbody>
11668               </table>
11669   
11670              <br><b> QQ </b>
11671               <table border="1" cellspacing="0">
11672               <thead>
11673               <tr bgcolor="#CCCCFF">
11674                   <th>Key</th>
11675                   <th>Value type</th>
11676                   <th>Value</th>
11677                   <th>Note</th>
11678               </tr>
11679               </thead>
11680               <tbody>
11681               <tr>
11682                   <td>access_token</td>
11683                   <td>String</td>
11684                   <td>Access token of QQ.</td>
11685                   <td>This is mandatory. </td>
11686               </tr>
11687               <tr>
11688                   <td>openID</td>
11689                   <td>String</td>
11690                   <td>OpenID of QQ.</td>
11691                   <td>This is mandatory.</td>
11692               </tr>
11693               </tbody>
11694               </table>
11695   
11696    @param {Object} [callbacks] An object with callback methods defined
11697    @param {Method} callbacks.success The callback method to call on a successful log in request
11698    @param {Method} callbacks.failure The callback method to call on a failed log in request
11699    @return {Promise} return promise object.
11700     <ul>
11701       <li>fulfill callback function: function(params). params is Array instance.
11702         <ul>
11703           <li>params[0] is a linked KiiUser instance.</li>
11704           <li>params[1] is the KiiSocialNetworkName used to link.</li>
11705         </ul>
11706       </li>
11707       <li>reject callback function: function(error). error is an Error instance.
11708         <ul>
11709           <li>error.target is current logged-in KiiUser instance. If there is not logged-in user, it will be null.</li>
11710           <li>error.message</li>
11711           <li>error.network is the KiiSocialNetworkName used to link.</li>
11712         </ul>
11713       </li>
11714     </ul>
11715    @example
11716    // example to use callbacks directly
11717    // Example of using no option
11718    KiiSocialConnect.linkCurrentUserWithNetwork(KiiSocialNetworkName.FACEBOOK, null, {
11719   
11720        success: function(user, network) {
11721            // do something now that the user is linked
11722        },
11723   
11724        failure: function(user, network, anErrorString) {
11725            // do something with the error response
11726        }
11727    });
11728   
11729    // example to use Promise
11730    // Example of using no option
11731    KiiSocialConnect.linkCurrentUserWithNetwork(KiiSocialNetworkName.FACEBOOK, null).then(
11732        function(params) {
11733            // do something now that the user is linked
11734        },
11735        function(error) {
11736            // do something with the error response
11737        }
11738    );
11739    */
11740 
11741   KiiSocialConnect.linkCurrentUserWithNetwork = function(networkName, options, callbacks) {
11742     if (_instance == null) {
11743       _instance = new _KiiSocialConnect;
11744     }
11745     return new Promise(function(resolve, reject) {
11746       var currentUser, error, errorString, linkCurrentUserWithNetworkCallbacks;
11747       linkCurrentUserWithNetworkCallbacks = {
11748         success: function() {
11749           if (callbacks != null) {
11750             callbacks.success.apply(callbacks, arguments);
11751           }
11752           return resolve(arguments);
11753         },
11754         failure: function() {
11755           var error;
11756           if (callbacks != null) {
11757             callbacks.failure.apply(callbacks, arguments);
11758           }
11759           error = KiiUtilities._Error(arguments[2]);
11760           error.target = arguments[0];
11761           error.network = networkName;
11762           return reject(error);
11763         }
11764       };
11765       try {
11766         return KiiSocialConnect._linkCurrentUserWithNetworkUsingCallbacks(networkName, options, linkCurrentUserWithNetworkCallbacks);
11767       } catch (_error) {
11768         errorString = _error;
11769         currentUser = root.KiiUser.getCurrentUser();
11770         if (callbacks != null) {
11771           if (typeof callbacks.failure === "function") {
11772             callbacks.failure(currentUser, networkName, errorString);
11773           }
11774         }
11775         error = KiiUtilities._Error(errorString);
11776         error.target = currentUser;
11777         error.network = networkName;
11778         return reject(error);
11779       }
11780     });
11781   };
11782 
11783   KiiSocialConnect._linkCurrentUserWithNetworkUsingCallbacks = function(networkName, options, callbacks) {
11784     var called;
11785     root.Kii.logger("Trying with instance");
11786     root.Kii.logger(_instance);
11787     called = false;
11788     if (_instance != null) {
11789       root.Kii.logger("And manager: ");
11790       root.Kii.logger(_instance._getManager(networkName));
11791       if (_instance._getManager(networkName)) {
11792         _instance._getManager(networkName)._linkWithCurrentUser(options, callbacks);
11793         called = true;
11794       }
11795     }
11796     root.Kii.logger("Callbacks");
11797     root.Kii.logger(callbacks);
11798     if (!called && (callbacks != null)) {
11799       return callbacks.failure(root.KiiUser.getCurrentUser(), networkName, "Unable to get network. Please ensure the network name is one of the supported KiiSocialNetworkName values");
11800     }
11801   };
11802 
11803 
11804   /** Unlink the currently logged in user with a social network
11805   
11806    The network must already be set up via setupNetwork
11807    @param networkName One of the supported KiiSocialNetworkName values
11808    @param {Object} [callbacks] An object with callback methods defined
11809    @param {Method} callbacks.success The callback method to call on a successful log in request
11810    @param {Method} callbacks.failure The callback method to call on a failed log in request
11811    @return {Promise} return promise object.
11812     <ul>
11813       <li>fulfill callback function: function(params). params is Array instance.
11814         <ul>
11815           <li>params[0] is a unlinked KiiUser instance.</li>
11816           <li>params[1] is the KiiSocialNetworkName used to unlink.</li>
11817         </ul>
11818       </li>
11819       <li>reject callback function: function(error). error is an Error instance.
11820         <ul>
11821           <li>error.target is current logged-in KiiUser instance. If there is not logged-in user, it will be null.</li>
11822           <li>error.message</li>
11823           <li>error.network is the KiiSocialNetworkName used to unlink.</li>
11824         </ul>
11825       </li>
11826     </ul>
11827    @example
11828   
11829    // example to use callbacks directly
11830    KiiSocialConnect.unLinkCurrentUserFromNetwork(KiiSocialNetworkName.FACEBOOK, {
11831   
11832        success: function(user, network) {
11833            // do something now that the user is unlinked
11834        },
11835   
11836        failure: function(user, network, anErrorString) {
11837            // do something with the error response
11838        }
11839    });
11840   
11841    // example to use Promise
11842    KiiSocialConnect.unLinkCurrentUserFromNetwork(KiiSocialNetworkName.FACEBOOK).then(
11843        function(params) {
11844            // do something now that the user is unlinked
11845        },
11846        function(error) {
11847            // do something with the error response
11848        }
11849    );
11850    */
11851 
11852   KiiSocialConnect.unLinkCurrentUserFromNetwork = function(networkName, callbacks) {
11853     if (_instance == null) {
11854       _instance = new _KiiSocialConnect;
11855     }
11856     return new Promise(function(resolve, reject) {
11857       var unLinkCurrentUserWithNetworkCallbacks;
11858       unLinkCurrentUserWithNetworkCallbacks = {
11859         success: function() {
11860           if (callbacks != null) {
11861             callbacks.success.apply(callbacks, arguments);
11862           }
11863           return resolve(arguments);
11864         },
11865         failure: function() {
11866           var error;
11867           if (callbacks != null) {
11868             callbacks.failure.apply(callbacks, arguments);
11869           }
11870           error = KiiUtilities._Error(arguments[2]);
11871           error.target = arguments[0];
11872           error.network = networkName;
11873           return reject(error);
11874         }
11875       };
11876       return KiiSocialConnect._unLinkCurrentUserWithNetworkUsingCallbacks(networkName, unLinkCurrentUserWithNetworkCallbacks);
11877     });
11878   };
11879 
11880   KiiSocialConnect._unLinkCurrentUserWithNetworkUsingCallbacks = function(networkName, callbacks) {
11881     root.Kii.logger("Trying with instance");
11882     root.Kii.logger(_instance);
11883     if (_instance != null) {
11884       root.Kii.logger("And manager: ");
11885       root.Kii.logger(_instance._getManager(networkName));
11886       if (_instance._getManager(networkName)) {
11887         return _instance._getManager(networkName)._unlinkFromCurrentUser(callbacks);
11888       }
11889     } else if (callbacks != null) {
11890       return callbacks.failure(root.KiiUser.getCurrentUser(), networkName, "Unable to get network. Please ensure the network name is one of the supported KiiSocialNetworkName values");
11891     }
11892   };
11893 
11894 
11895   /** Retrieve the current user's access token from a social network
11896   The network must be set up and linked to the current user. It is recommended you save this to preferences for multi-session use.
11897   @param networkName One of the supported KiiSocialNetworkName values
11898   @returns {String} The current access token, null if unavailable
11899   @deprecated Use {@link KiiSocialConnect.getAccessTokenObjectForNetwork} instead.
11900    */
11901 
11902   KiiSocialConnect.getAccessTokenForNetwork = function(networkName) {
11903     return _instance != null ? _instance._getManager(networkName)._getToken() : void 0;
11904   };
11905 
11906 
11907   /** Retrieve the current user's access token expiration date from a social network
11908   
11909   The network must be set up and linked to the current user. It is recommended you save this to preferences for multi-session use.
11910   @param networkName One of the supported KiiSocialNetworkName values
11911   @returns {String} The current access token expiration date, null if unavailable
11912   @deprecated Use {@link KiiSocialConnect.getAccessTokenObjectForNetwork} instead.
11913    */
11914 
11915   KiiSocialConnect.getAccessTokenExpirationForNetwork = function(networkName) {
11916     return _instance != null ? _instance._getManager(networkName)._getTokenExpiration() : void 0;
11917   };
11918 
11919 
11920   /** Retrieve the current user's access token object from a social network
11921   
11922   The network must be set up and linked to the current user.
11923   It is recommended you save this to preferences for multi-session use.<br><br>
11924   Following parameters can be assigned to object.<br><br>
11925   <b>Facebook</b>
11926   <li>access_token</li>
11927   <li>expires_in</li>
11928   <li>kii_new_user</li>
11929   <br>
11930   <b>Twitter</b>
11931   <li>oauth_token</li>
11932   <li>oauth_token_secret</li>
11933   <li>kii_new_user</li>
11934   <br>
11935   <b>Google</b>
11936   <li>access_token</li>
11937   <li>kii_new_user</li>
11938   <br>
11939   <b>QQ</b>
11940   <li>access_token</li>
11941   <li>openID</li>
11942   <li>kii_new_user</li>
11943   @param networkName One of the supported KiiSocialNetworkName values
11944   @returns {Object} tokenObject The current access token object, null if unavailable.
11945    */
11946 
11947   KiiSocialConnect.getAccessTokenObjectForNetwork = function(networkName) {
11948     return _instance != null ? _instance._getManager(networkName)._getTokenObject() : void 0;
11949   };
11950 
11951   KiiSocialConnect.logOutAll = function() {
11952     var fb, google, qq, renren, tw;
11953     if (_instance != null) {
11954       fb = _instance._getManager(root.KiiSocialNetworkName.FACEBOOK);
11955       if (fb != null) {
11956         fb._logOut();
11957       }
11958       tw = _instance._getManager(root.KiiSocialNetworkName.TWITTER);
11959       if (tw != null) {
11960         tw._logOut();
11961       }
11962       qq = _instance._getManager(root.KiiSocialNetworkName.QQ);
11963       if (qq != null) {
11964         qq._logOut();
11965       }
11966       google = _instance._getManager(root.KiiSocialNetworkName.GOOGLEPLUS);
11967       if (google != null) {
11968         google._logOut();
11969       }
11970       renren = _instance._getManager(root.KiiSocialNetworkName.RENREN);
11971       if (renren != null) {
11972         return renren._logOut();
11973       }
11974     }
11975   };
11976 
11977   return KiiSocialConnect;
11978 
11979 })();
11980 
11981 _KiiSocialConnect = (function() {
11982   function _KiiSocialConnect() {
11983     this._getManager = __bind(this._getManager, this);
11984   }
11985 
11986   _KiiSocialConnect.prototype._getManager = function(networkName) {
11987     if (networkName === root.KiiSocialNetworkName.FACEBOOK) {
11988       if (this._facebookManager != null) {
11989         return this._facebookManager;
11990       } else {
11991         return this._facebookManager = new root.KiiSCNFacebook();
11992       }
11993     } else if (networkName === root.KiiSocialNetworkName.TWITTER) {
11994       if (this._twitterManager != null) {
11995         return this._twitterManager;
11996       } else {
11997         return this._twitterManager = new root.KiiSCNTwitter();
11998       }
11999     } else if (networkName === root.KiiSocialNetworkName.QQ) {
12000       if (this._qqManager != null) {
12001         return this._qqManager;
12002       } else {
12003         return this._qqManager = new root.KiiSCNQQ();
12004       }
12005     } else if (networkName === root.KiiSocialNetworkName.GOOGLEPLUS) {
12006       if (this._googleManager != null) {
12007         return this._googleManager;
12008       } else {
12009         return this._googleManager = new root.KiiSCNGoogle();
12010       }
12011     } else if (networkName === root.KiiSocialNetworkName.RENREN) {
12012       if (this._renrenManager != null) {
12013         return this._renrenManager;
12014       } else {
12015         return this._renrenManager = new root.KiiSCNRenRen();
12016       }
12017     }
12018   };
12019 
12020   return _KiiSocialConnect;
12021 
12022 })();
12023 
12024 root.KiiSocialConnectNetwork = (function() {
12025   KiiSocialConnectNetwork.prototype._className = "KiiSocialConnectNetwork";
12026 
12027   KiiSocialConnectNetwork.prototype._setNetwork = function(_network) {
12028     this._network = _network;
12029   };
12030 
12031   KiiSocialConnectNetwork.prototype._getNetwork = function() {
12032     return this._network;
12033   };
12034 
12035   KiiSocialConnectNetwork.prototype._setToken = function(_token) {
12036     this._token = _token;
12037   };
12038 
12039   KiiSocialConnectNetwork.prototype._getToken = function() {
12040     return this._token;
12041   };
12042 
12043   KiiSocialConnectNetwork.prototype._setTokenExpiration = function(_tokenExpiration) {
12044     this._tokenExpiration = _tokenExpiration;
12045   };
12046 
12047   KiiSocialConnectNetwork.prototype._getTokenExpiration = function() {
12048     return this._tokenExpiration;
12049   };
12050 
12051   KiiSocialConnectNetwork.prototype._setTokenObject = function(_tokenObject) {
12052     this._tokenObject = _tokenObject;
12053   };
12054 
12055   KiiSocialConnectNetwork.prototype._getTokenObject = function() {
12056     return this._tokenObject;
12057   };
12058 
12059   function KiiSocialConnectNetwork(_network) {
12060     this._network = _network;
12061     this._unlink = __bind(this._unlink, this);
12062     this._link = __bind(this._link, this);
12063     this._register = __bind(this._register, this);
12064     this._getAccessToken = __bind(this._getAccessToken, this);
12065     this._createTokenObject = __bind(this._createTokenObject, this);
12066     this._unlinkFromCurrentUser = __bind(this._unlinkFromCurrentUser, this);
12067     this._linkWithCurrentUser = __bind(this._linkWithCurrentUser, this);
12068     this._logOut = __bind(this._logOut, this);
12069     this._logIn = __bind(this._logIn, this);
12070     this._isAuthenticated = __bind(this._isAuthenticated, this);
12071     this._getTokenObject = __bind(this._getTokenObject, this);
12072     this._setTokenObject = __bind(this._setTokenObject, this);
12073     this._getTokenExpiration = __bind(this._getTokenExpiration, this);
12074     this._setTokenExpiration = __bind(this._setTokenExpiration, this);
12075     this._getToken = __bind(this._getToken, this);
12076     this._setToken = __bind(this._setToken, this);
12077     this._getNetwork = __bind(this._getNetwork, this);
12078     this._setNetwork = __bind(this._setNetwork, this);
12079     this._tokenExpiration = null;
12080     this._token = null;
12081   }
12082 
12083   KiiSocialConnectNetwork.prototype._isAuthenticated = function() {
12084     return this._tokenObject != null;
12085   };
12086 
12087   KiiSocialConnectNetwork.prototype._logIn = function(options, callbacks) {};
12088 
12089   KiiSocialConnectNetwork.prototype._logOut = function() {
12090     this._token = null;
12091     this._tokenExpiration = null;
12092     return this._tokenObject = null;
12093   };
12094 
12095   KiiSocialConnectNetwork.prototype._linkWithCurrentUser = function(options, callbacks) {};
12096 
12097   KiiSocialConnectNetwork.prototype._unlinkFromCurrentUser = function(callbacks) {};
12098 
12099   KiiSocialConnectNetwork.prototype._createTokenObject = function(options, data) {};
12100 
12101   KiiSocialConnectNetwork.prototype._getAccessToken = function(options) {};
12102 
12103   KiiSocialConnectNetwork.prototype._register = function(providerName, contentType, requestData, options, callbacks) {
12104     var currentTime, now, registrationCallbacks, request, token;
12105     if (root.Kii.getAccessTokenExpiration() > 0) {
12106       now = new Date;
12107       currentTime = now.getTime();
12108       requestData.expiresAt = KiiUtilities._safeCalculateExpiresAtAsNumber(root.Kii.getAccessTokenExpiration(), currentTime);
12109     }
12110     request = new KiiRequest("/integration/" + providerName, true);
12111     request.setMethod("POST");
12112     request.setData(requestData);
12113     request.setAnonymous(true);
12114     request.setContentType(contentType);
12115     token = this._getAccessToken(options);
12116     registrationCallbacks = {
12117       success: (function(_this) {
12118         return function(data) {
12119           var refreshCallback, tokenObject, user, value;
12120           _this._setToken(token);
12121           tokenObject = _this._createTokenObject(options, data);
12122           _this._setTokenObject(tokenObject);
12123           user = new root.KiiUser();
12124           user._updateWithJSON(data);
12125           user._setAccessToken(data['access_token']);
12126           if (data.expires_in != null) {
12127             now = new Date;
12128             currentTime = now.getTime();
12129             value = KiiUtilities._safeCalculateExpiresAtAsDate(data.expires_in, currentTime);
12130             user._setExpiresAt(value);
12131           }
12132           root.Kii.setCurrentUser(user);
12133           refreshCallback = {
12134             success: function(refreshedUser) {
12135               root.Kii.setCurrentUser(refreshedUser);
12136               if (callbacks != null) {
12137                 return callbacks.success(refreshedUser, _this._network);
12138               }
12139             },
12140             failure: function(theUser, error) {
12141               if (callbacks != null) {
12142                 return callbacks.failure(theUser, _this._network, error);
12143               }
12144             }
12145           };
12146           return user.refresh(refreshCallback);
12147         };
12148       })(this),
12149       failure: (function(_this) {
12150         return function(error, statusCode) {
12151           if (callbacks != null) {
12152             return callbacks.failure(null, _this._network, error);
12153           }
12154         };
12155       })(this)
12156     };
12157     return request.execute(registrationCallbacks, false);
12158   };
12159 
12160   KiiSocialConnectNetwork.prototype._link = function(providerName, contentType, requestData, options, callbacks) {
12161     var linkCallbacks, request, token;
12162     request = new KiiRequest("/users/me/" + providerName + "/link", true);
12163     request.setMethod("POST");
12164     request.setData(requestData);
12165     request.setContentType(contentType);
12166     token = this._getAccessToken(options);
12167     linkCallbacks = {
12168       success: (function(_this) {
12169         return function(data) {
12170           var refreshCallback, tokenObject;
12171           _this._setToken(token);
12172           tokenObject = _this._createTokenObject(options, data);
12173           _this._setTokenObject(tokenObject);
12174           refreshCallback = {
12175             success: function(refreshedUser) {
12176               root.Kii.setCurrentUser(refreshedUser);
12177               if (callbacks != null) {
12178                 return callbacks.success(refreshedUser, _this._network);
12179               }
12180             },
12181             failure: function(theUser, error) {
12182               if (callbacks != null) {
12183                 return callbacks.failure(theUser, _this._network, error);
12184               }
12185             }
12186           };
12187           return root.KiiUser.getCurrentUser().refresh(refreshCallback);
12188         };
12189       })(this),
12190       failure: (function(_this) {
12191         return function(error, statusCode) {
12192           if (callbacks != null) {
12193             return callbacks.failure(root.KiiUser.getCurrentUser(), _this._network, error);
12194           }
12195         };
12196       })(this)
12197     };
12198     return request.execute(linkCallbacks, true);
12199   };
12200 
12201   KiiSocialConnectNetwork.prototype._unlink = function(providerName, callbacks) {
12202     var request, unlinkCallbacks;
12203     request = new KiiRequest("/users/me/" + providerName + "/unlink", true);
12204     request.setMethod("POST");
12205     unlinkCallbacks = {
12206       success: (function(_this) {
12207         return function(data) {
12208           var refreshCallback;
12209           _this._setToken(null);
12210           _this._setTokenExpiration(null);
12211           _this._setTokenObject(null);
12212           refreshCallback = {
12213             success: function(refreshedUser) {
12214               root.Kii.setCurrentUser(refreshedUser);
12215               if (callbacks != null) {
12216                 return callbacks.success(refreshedUser, _this._network);
12217               }
12218             },
12219             failure: function(theUser, error) {
12220               if (callbacks != null) {
12221                 return callbacks.failure(theUser, _this._network, error);
12222               }
12223             }
12224           };
12225           return root.KiiUser.getCurrentUser().refresh(refreshCallback);
12226         };
12227       })(this),
12228       failure: (function(_this) {
12229         return function(error, statusCode) {
12230           if (callbacks != null) {
12231             return callbacks.failure(root.KiiUser.getCurrentUser(), _this._network, error);
12232           }
12233         };
12234       })(this)
12235     };
12236     return request.execute(unlinkCallbacks, true);
12237   };
12238 
12239   return KiiSocialConnectNetwork;
12240 
12241 })();
12242 
12243 root.KiiSCNFacebook = (function(_super) {
12244   __extends(KiiSCNFacebook, _super);
12245 
12246   function KiiSCNFacebook() {
12247     this._unlinkFromCurrentUser = __bind(this._unlinkFromCurrentUser, this);
12248     this._linkWithCurrentUser = __bind(this._linkWithCurrentUser, this);
12249     this._logOut = __bind(this._logOut, this);
12250     this._logIn = __bind(this._logIn, this);
12251     this._getAccessToken = __bind(this._getAccessToken, this);
12252     this._createTokenObject = __bind(this._createTokenObject, this);
12253     this._setup = __bind(this._setup, this);
12254     KiiSCNFacebook.__super__.constructor.call(this, root.KiiSocialNetworkName.FACEBOOK);
12255   }
12256 
12257   KiiSCNFacebook.prototype._setup = function(_key, _secret, _extras) {
12258     this._key = _key;
12259     this._secret = _secret;
12260     this._extras = _extras;
12261     return KiiSCNFacebook.__super__._setup.call(this, this._key, this._secret, this._extras);
12262   };
12263 
12264   KiiSCNFacebook.prototype._createTokenObject = function(options, data) {
12265     var tokenObject;
12266     tokenObject = {
12267       "access_token": options.access_token
12268     };
12269     if ((data != null) && (data.new_user_created != null)) {
12270       tokenObject["kii_new_user"] = data.new_user_created;
12271     }
12272     return tokenObject;
12273   };
12274 
12275   KiiSCNFacebook.prototype._getAccessToken = function(options) {
12276     return options.access_token;
12277   };
12278 
12279   KiiSCNFacebook.prototype._logIn = function(options, callbacks) {
12280     var requestData;
12281     root.Kii.logger("should auth fb");
12282     root.Kii.logger("Checking options");
12283     if ((options == null) || !options.access_token) {
12284       throw root.InvalidArgumentException('options.access_token is required');
12285     }
12286     if (root.KiiUser.getCurrentUser() != null) {
12287       root.KiiUser.logOut();
12288     }
12289     requestData = {
12290       "accessToken": options.access_token
12291     };
12292     return this._register("facebook", "application/vnd.kii.AuthTokenFacebookRequest+json", requestData, options, callbacks);
12293   };
12294 
12295   KiiSCNFacebook.prototype._logOut = function() {
12296     KiiSCNFacebook.__super__._logOut.apply(this, arguments);
12297     return root.Kii.logger("Log out fb");
12298   };
12299 
12300   KiiSCNFacebook.prototype._linkWithCurrentUser = function(options, callbacks) {
12301     var requestData;
12302     if (root.KiiUser.getCurrentUser() != null) {
12303       if ((options == null) || !options.access_token) {
12304         throw root.InvalidArgumentException('options.access_token is required');
12305       }
12306       requestData = {
12307         "accessToken": options.access_token
12308       };
12309       return this._link("facebook", "application/vnd.kii.LinkFacebookRequest+json", requestData, options, callbacks);
12310     } else if (callbacks != null) {
12311       return callbacks.failure(null, this._network, "A KiiUser must be logged in before linking to Facebook");
12312     }
12313   };
12314 
12315   KiiSCNFacebook.prototype._unlinkFromCurrentUser = function(callbacks) {
12316     if (root.KiiUser.getCurrentUser() != null) {
12317       return this._unlink("facebook", callbacks);
12318     } else if (callbacks != null) {
12319       return callbacks.failure("A KiiUser must be logged in before unlinking from Facebook");
12320     }
12321   };
12322 
12323   return KiiSCNFacebook;
12324 
12325 })(root.KiiSocialConnectNetwork);
12326 
12327 root.InvalidDisplayNameException = function() {
12328   return this.message = "Unable to set displayName. Must be between 1-50 characters.";
12329 };
12330 
12331 root.InvalidPasswordException = function() {
12332   return this.message = "Unable to set password. Must be between 4-50 characters composed with ascii (exclude control character)";
12333 };
12334 
12335 root.InvalidUsernameException = function() {
12336   return this.message = "Unable to set username. Must be between 3 and 64 characters, which can include alphanumeric characters as well as underscores '_' and periods '.'";
12337 };
12338 
12339 root.InvalidUserIdentifierException = function() {
12340   return this.message = "User identifier should be one of user name, phone number or email";
12341 };
12342 
12343 root.InvalidEmailException = function() {
12344   return this.message = "Unable to set email address. Must be a valid email";
12345 };
12346 
12347 root.InvalidPhoneNumberException = function() {
12348   return this.message = "Unable to set phone number. Must begin with a '+' and be at least 10 digits";
12349 };
12350 
12351 root.InvalidLocalPhoneNumberException = function() {
12352   return this.message = "Unable to set phone number. Must be a sequence of numbers";
12353 };
12354 
12355 root.InvalidCountryException = function() {
12356   return this.message = "Unable to set country code. Must be 2 alphabetic characters. Ex: US, JP, CN";
12357 };
12358 
12359 root.InvalidURIException = function() {
12360   return this.message = "Unable to set URI. Must be of the form kiicloud://some/path/to/object/or/entity";
12361 };
12362 
12363 root.InvalidACLAction = function() {
12364   return this.message = "Unable to set ACL action. Must be one of the permitted values in KiiACLAction";
12365 };
12366 
12367 root.InvalidACLSubject = function() {
12368   return this.message = "Unable to set ACL subject. Must be of type KiiUser or KiiGroup";
12369 };
12370 
12371 root.InvalidACLGrant = function() {
12372   return this.message = "Unable to set ACL grant. Must be a boolean type";
12373 };
12374 
12375 root.InvalidLimitException = function() {
12376   return this.message = "Unable to set query limit. Must be an integer > 0";
12377 };
12378 
12379 root.InvalidArgumentException = function(message) {
12380   return this.message = 'InvalidArgument: ' + message;
12381 };
12382 
12383 root.IllegalStateException = function(message) {
12384   return this.message = 'IllegalState: ' + message;
12385 };
12386 
12387 root.ArithmeticException = function(message) {
12388   return this.message = 'ArithmeticException: ' + message;
12389 };
12390 
12391 root.UnsupportedOperationException = function(message) {
12392   return this.message = 'UnsupportedOperationException: ' + message;
12393 };
12394 
12395 
12396 /**
12397     @class represents the app admin context
12398     <br><br>
12399     <B>This class must not referred from code accessible from browser.
12400     This class is intended to be used by server side code like Node.js.
12401     If you use this class in code accessible by browser, your application client id and client secret could be stolen.
12402     Attacker will be act as application admin and all the data in your application will be suffered.
12403     </B>
12404     Application administrator context. Entities obtained from this class will be manipulated by application admin.
12405     @exports root.KiiAppAdminContext as KiiAppAdminContext
12406  */
12407 
12408 root.KiiAppAdminContext = (function() {
12409   function KiiAppAdminContext(spec) {
12410     this.listTopics = __bind(this.listTopics, this);
12411     this.topicWithName = __bind(this.topicWithName, this);
12412     this.loadThingWithThingID = __bind(this.loadThingWithThingID, this);
12413     this.loadThingWithVendorThingID = __bind(this.loadThingWithVendorThingID, this);
12414     this.registerOwnerWithVendorThingID = __bind(this.registerOwnerWithVendorThingID, this);
12415     this.registerOwnerWithThingID = __bind(this.registerOwnerWithThingID, this);
12416     this.thingWithID = __bind(this.thingWithID, this);
12417     this.registerThing = __bind(this.registerThing, this);
12418     this.registerGroupWithOwnerAndID = __bind(this.registerGroupWithOwnerAndID, this);
12419     this._getToken = __bind(this._getToken, this);
12420     this.getAccessToken = __bind(this.getAccessToken, this);
12421     this._getId = __bind(this._getId, this);
12422     this._objectWithURI = __bind(this._objectWithURI, this);
12423     this._token = spec.token;
12424     this._id = spec.id;
12425   }
12426 
12427 
12428   /**
12429       Creates a reference to a bucket operated by app admin.
12430       <br><br>The bucket will be created/accessed within this app's scope
12431       @param String bucketName The name of the bucket the app should create/access
12432       @returns {KiiBucket} A working KiiBucket object
12433       @example
12434       Kii.authenticateAsAppAdmin("client-id", "client-secret", {
12435           success: function(adminContext) {
12436               var bucket = adminContext.bucketWithName("myBucket");
12437               // KiiBucket operation by app admin is available now.
12438           },
12439           failure: function(errorString, errorCode) {
12440               // auth failed.
12441           }
12442       });
12443    */
12444 
12445   KiiAppAdminContext.prototype.bucketWithName = function(bucketName) {
12446     var adminBucket;
12447     adminBucket = new root.KiiBucketWithToken(bucketName, null, this._token);
12448     return adminBucket;
12449   };
12450 
12451 
12452   /**
12453       Creates a reference to a encrypted bucket operated by app admin.
12454       <br><br>The bucket will be created/accessed within this app's scope
12455       @param String bucketName The name of the bucket the app should create/access
12456       @returns {KiiBucket} A working KiiBucket object
12457       @example
12458       Kii.authenticateAsAppAdmin("client-id", "client-secret", {
12459           success: function(adminContext) {
12460               var bucket = adminContext.encryptedBucketWithName("myBucket");
12461               // KiiBucket operation by app admin is available now.
12462           },
12463           failure: function(errorString, errorCode) {
12464               // auth failed.
12465           }
12466       });
12467    */
12468 
12469   KiiAppAdminContext.prototype.encryptedBucketWithName = function(bucketName) {
12470     var bucket;
12471     bucket = new root.KiiEncryptedBucketWithToken(bucketName, null, this._token);
12472     return bucket;
12473   };
12474 
12475 
12476   /**
12477       Creates a reference to a group operated by app admin.
12478       <br><br>
12479       <b>Note:</b>
12480       Returned instance from this API can not operate existing KiiGroup.<br>
12481       If you want to operate existing KiiGroup, please use {@link KiiAppAdminContext#groupWithURI} or {@link KiiAppAdminContext#groupWithID}.
12482   
12483       @param String group name.
12484       @returns {KiiGroup} A working KiiGroup object
12485       @example
12486       Kii.authenticateAsAppAdmin("client-id", "client-secret", {
12487           success: function(adminContext) {
12488               var group = adminContext.groupWithName("newGroup");
12489               // KiiGroup operation by app admin is available now.
12490           },
12491           failure: function(errorString, errorCode) {
12492               // auth failed.
12493           }
12494       });
12495    */
12496 
12497   KiiAppAdminContext.prototype.groupWithName = function(groupName) {
12498     var group;
12499     group = root.KiiGroupWithToken._groupWithName(groupName, this._token);
12500     return group;
12501   };
12502 
12503 
12504   /**
12505       Creates a reference to a user operated by app admin.
12506       @param String user id.
12507       @returns {KiiUser} A working KiiUser object
12508       @example
12509       Kii.authenticateAsAppAdmin("client-id", "client-secret", {
12510           success: function(adminContext) {
12511               var user = adminContext.userWithID("userid");
12512               // KiiUser operation by app admin is available now.
12513           },
12514           failure: function(errorString, errorCode) {
12515               // auth failed.
12516           }
12517       });
12518    */
12519 
12520   KiiAppAdminContext.prototype.userWithID = function(userid) {
12521     var user;
12522     user = root.KiiUserWithToken._userWithID(userid, this._token);
12523     return user;
12524   };
12525 
12526 
12527   /**
12528       Creates a reference to an object operated by app admin using object`s URI.
12529       @param String object URI.
12530       @returns {KiiObject} A working KiiObject instance
12531       @throws {InvalidURIException} If the URI is null, empty or does not have correct format.
12532    */
12533 
12534   KiiAppAdminContext.prototype.objectWithURI = function(objectURI) {
12535     var object;
12536     object = this._objectWithURI(objectURI);
12537     return object;
12538   };
12539 
12540   KiiAppAdminContext.prototype._userWithLoginName = function(loginName, callbacks) {
12541     var refreshCallbacks, request, user;
12542     user = new root.KiiUserWithToken(this._token);
12543     request = user._getRequest({
12544       path: "/users/LOGIN_NAME:" + loginName,
12545       withApp: true
12546     });
12547     request.setAdminToken(this._token);
12548     refreshCallbacks = {
12549       success: (function(_this) {
12550         return function(data, statusCode) {
12551           if (statusCode < 300 && statusCode >= 200) {
12552             user._updateWithJSON(data);
12553             if (callbacks != null) {
12554               return callbacks.success(user);
12555             }
12556           } else if (callbacks != null) {
12557             return callbacks.failure("Unable to parse response");
12558           }
12559         };
12560       })(this),
12561       failure: (function(_this) {
12562         return function(error, statusCode) {
12563           if (callbacks != null) {
12564             return callbacks.failure(error);
12565           }
12566         };
12567       })(this)
12568     };
12569     return request.execute(refreshCallbacks, false);
12570   };
12571 
12572   KiiAppAdminContext.prototype._objectWithURI = function(objectUri) {
12573     var bucket, bucketIndex, bucketName, compLength, components, newURI, obj, subject, valid;
12574     if (!objectUri) {
12575       throw new root.InvalidURIException;
12576     }
12577     valid = (objectUri.indexOf("kiicloud://")) === 0;
12578     newURI = objectUri.substr("kiicloud://".length);
12579     components = newURI.split("/");
12580     compLength = components.length;
12581     if (compLength >= 4 && valid) {
12582       bucketIndex = compLength === 4 ? 1 : 3;
12583       bucketName = components[bucketIndex];
12584       subject = null;
12585       if (components[0] === "groups" && compLength === 6) {
12586         subject = new root.KiiGroupWithToken._groupWithID(components[1], this._token);
12587       } else if (components[0] === "users" && compLength === 6) {
12588         subject = root.KiiUserWithToken._userWithID(components[1], this._token);
12589       } else if (components[0] === "things" && compLength === 6) {
12590         subject = root.KiiThingWithToken.thingWithID(components[1], this._token);
12591       } else if (compLength !== 4) {
12592         throw new root.InvalidURIException;
12593       }
12594       bucket = new root.KiiBucketWithToken(bucketName, subject, this._token);
12595       obj = bucket.createObject();
12596       obj._setUUID(components[compLength - 1]);
12597     } else {
12598       throw new root.InvalidURIException;
12599     }
12600     return obj;
12601   };
12602 
12603   KiiAppAdminContext.prototype._getId = function() {
12604     return this._id;
12605   };
12606 
12607 
12608   /**
12609       Get access token published for app admin.
12610       @return {String} access token published for app admin.
12611    */
12612 
12613   KiiAppAdminContext.prototype.getAccessToken = function() {
12614     return this._getToken();
12615   };
12616 
12617   KiiAppAdminContext.prototype._getToken = function() {
12618     return this._token;
12619   };
12620 
12621 
12622   /**
12623       Creates a reference to a group operated by app admin using group's ID.
12624       <br><br>
12625       <b>Note:</b>
12626       Returned instance from this API can operate existing KiiGroup.<br>
12627       If you want to create a new KiiGroup, please use {@link KiiAppAdminContext#groupWithName}.
12628   
12629       @param String group ID.
12630       @returns {KiiGroup} A working KiiGroup object
12631       @throws {InvalidArgumentException} Thrown if passed groupID is null or empty.
12632       @example
12633       Kii.authenticateAsAppAdmin("client-id", "client-secret", {
12634           success: function(adminContext) {
12635               var groupID = "0123456789abcdefghijklmno";
12636               var group = adminContext.groupWithID(groupID);
12637               // KiiGroup operation by app admin is available now.
12638           },
12639           failure: function(errorString, errorCode) {
12640               // auth failed.
12641           }
12642       });
12643    */
12644 
12645   KiiAppAdminContext.prototype.groupWithID = function(groupID) {
12646     var group;
12647     if ((groupID == null) || groupID === "") {
12648       throw new root.InvalidArgumentException('groupID should not null or empty');
12649     }
12650     group = root.KiiGroupWithToken._groupWithID(groupID, this._token);
12651     return group;
12652   };
12653 
12654 
12655   /** Register new group own by specified user on Kii Cloud with specified ID.
12656   This method can be used only by app admin.
12657   
12658   <br><br>If the group that has specified id already exists, registration will be failed.
12659   
12660   @param {String} groupID ID of the KiiGroup
12661   @param {String} groupName Name of the KiiGroup
12662   @param {String} user id of owner
12663   @param {Array} members An array of KiiUser objects to add to the group
12664   @return {Promise} return promise object.
12665         <ul>
12666           <li>fulfill callback function: function(theSavedGroup). theSavedGroup is KiiGroup instance.</li>
12667           <li>reject callback function: function(error). error is an Error instance.
12668             <ul>
12669               <li>error.target is the KiiGroup instance which this method was called on.</li>
12670               <li>error.message</li>
12671               <li>error.addMembersArray is array of KiiUser to be added as memebers of this group.</li>
12672               <li>error.removeMembersArray is array of KiiUser to be removed from the memebers list of this group.</li>
12673             </ul>
12674           </li>
12675         </ul>
12676   @example
12677   // example to use callbacks directly
12678   Kii.authenticateAsAppAdmin("client-id", "client-secret", {
12679       success: function(adminContext) {
12680           var members = [];
12681           members.push(KiiUser.userWithID("Member User Id"));
12682           adminContext.registerGroupWithOwnerAndID("Group ID", "Group Name", "Owner User ID", members, {
12683               success: function(theSavedGroup) {
12684                   // do something with the saved group
12685               },
12686               failure: function(theGroup, anErrorString, addMembersArray, removeMembersArray) {
12687                   // do something with the error response
12688               }
12689           });
12690       },
12691       failure: function(errorString, errorCode) {
12692           // auth failed.
12693       }
12694   });
12695   // example to use Promise
12696   Kii.authenticateAsAppAdmin("client-id", "client-secret").then(
12697       function(adminContext) {
12698           var members = [];
12699           members.push(KiiUser.userWithID("Member User Id"));
12700           return adminContext.registerGroupWithOwnerAndID("Group ID", "Group Name", "Owner User ID", members);
12701       }
12702   ).then(
12703       function(group) {
12704           // do something with the saved group
12705       }
12706   );
12707    */
12708 
12709   KiiAppAdminContext.prototype.registerGroupWithOwnerAndID = function(groupID, groupName, owner, members, callbacks) {
12710     return new Promise((function(_this) {
12711       return function(resolve, reject) {
12712         var registerGroupWithIDCallbacks;
12713         registerGroupWithIDCallbacks = {
12714           success: function() {
12715             if (callbacks != null) {
12716               callbacks.success.apply(callbacks, arguments);
12717             }
12718             return resolve(arguments[0]);
12719           },
12720           failure: function() {
12721             var error;
12722             if (callbacks != null) {
12723               callbacks.failure.apply(callbacks, arguments);
12724             }
12725             error = KiiUtilities._Error(arguments[1], arguments[0]);
12726             error.addMembersArray = arguments[2];
12727             error.removeMembersArray = arguments[3];
12728             return reject(error);
12729           }
12730         };
12731         return root.KiiGroup._registerGroupWithIDUsingCallbacks(_this._token, groupID, groupName, owner, members, registerGroupWithIDCallbacks);
12732       };
12733     })(this));
12734   };
12735 
12736 
12737   /**
12738       Creates a reference to a group operated by app admin using group's URI.
12739       <br><br>
12740       <b>Note:</b>
12741       Returned instance from this API can operate existing KiiGroup.<br>
12742       If you want to create a new KiiGroup, please use {@link KiiAppAdminContext#groupWithName}.
12743   
12744       @param String group URI.
12745       @returns {KiiGroup} A working KiiGroup object
12746       @throws {InvalidURIException} Thrown if the URI is null, empty or does not have correct format.
12747       @example
12748       Kii.authenticateAsAppAdmin("client-id", "client-secret", {
12749           success: function(adminContext) {
12750               var groupUri = ...; // KiiGroup's URI
12751               var group = adminContext.groupWithURI(groupUri);
12752               // KiiGroup operation by app admin is available now.
12753           },
12754           failure: function(errorString, errorCode) {
12755               // auth failed.
12756           }
12757       });
12758    */
12759 
12760   KiiAppAdminContext.prototype.groupWithURI = function(groupUri) {
12761     var components, group, newURI;
12762     if (groupUri == null) {
12763       throw new root.InvalidURIException;
12764     }
12765     if ((groupUri.indexOf("kiicloud://")) !== 0) {
12766       throw new root.InvalidURIException;
12767     }
12768     newURI = groupUri.substr("kiicloud://".length);
12769     components = newURI.split("/");
12770     if (components.length !== 2 || components[0] !== "groups") {
12771       throw new root.InvalidURIException;
12772     }
12773     group = root.KiiGroupWithToken._groupWithID(components[1], this._token);
12774     return group;
12775   };
12776 
12777 
12778   /**
12779   Find registered KiiUser with the email.<br>
12780   If there are no user registers with the specified email or if there are but not verified email yet,
12781   callbacks.failure or reject callback of promise will be called.<br>
12782   If the email is null or empty, callbacks.failure or reject callback of promise will be callded.
12783   <br><br>
12784   <b>Note:</b>
12785   <ul>
12786   <li>If "Expose Full User Data To Others" is enabled in the application console, the response will contain full of the user data.</li>
12787   <li>Otherwise, the response will only contain "userID", "loginName" and "displayName" field values if exist.</li>
12788   </ul>
12789   
12790   @param {String} email The email to find KiiUser who owns it.<br>
12791   Don't add prefix of "EMAIL:" described in REST API documentation. SDK will take care of it.
12792   @param {Object} [callbacks] An object with callback methods defined.
12793   This argument is mandatory and can't be omitted.
12794   @param {Method} callbacks.success The callback method to call on a successful finding request.
12795   @param {Method} callbacks.failure The callback method to call on a failed finding request.
12796   @return {Promise} return promise object.
12797     <ul>
12798       <li>fulfill callback function: function(params). params is Array instance.
12799         <ul>
12800           <li>params[0] is a KiiAppAdminContext instance which this method was called on.</li>
12801           <li>params[1] is a found KiiUser instance.</li>
12802         </ul>
12803       </li>
12804       <li>reject callback function: function(error). error is an Error instance.
12805         <ul>
12806           <li>error.target is a KiiAppAdminContext instance which this method was called on.</li>
12807           <li>error.message</li>
12808         </ul>
12809       </li>
12810     </ul>
12811   @example
12812   // example to use callbacks directly
12813   Kii.authenticateAsAppAdmin("client-id", "client-secret", {
12814       success: function(adminContext) {
12815           adminContext.findUserByEmail("user_to_find@example.com", {
12816               success: function(adminContext, theMatchedUser) {
12817                   // Do something with the found user
12818               },
12819               failure: function(adminContext, anErrorString) {
12820                   // Do something with the error response
12821               }
12822           });
12823       },
12824       failure: function(errorString, errorCode) {
12825           // Auth failed.
12826       }
12827   });
12828   
12829   // example to use Promise
12830   Kii.authenticateAsAppAdmin("client-id", "client-secret").then(
12831       function(adminContext) {
12832           adminContext.findUserByEmail("user_to_find@example.com").then(
12833               function(params) { // fullfill callback function
12834                   var adminContext = params[0];
12835                   var theMatchedUser = params[1];
12836                   // Do something with the found user
12837               },
12838               function(error) { // reject callback function
12839                   var adminContext = error.target;
12840                   var anErrorString = error.message;
12841                   // Do something with the error response
12842               }
12843           );
12844       },
12845       function(error) {
12846         // Auth failed.
12847       }
12848   );
12849    */
12850 
12851   KiiAppAdminContext.prototype.findUserByEmail = function(email, callbacks) {
12852     return root.KiiUser._findUserByEmail(email, callbacks, this);
12853   };
12854 
12855 
12856   /**
12857   Find registered KiiUser with the phone.<br>
12858   If there are no user registers with the specified phone or if there are but not verified phone yet,
12859   callbacks.failure or reject callback of promise will be called.<br>
12860   If the phone is null or empty, callbacks.failure or reject callback of promise will be called.
12861   <br><br>
12862   <b>Note:</b>
12863   <ul>
12864   <li>If "Expose Full User Data To Others" is enabled in the application console, the response will contain full of the user data.</li>
12865   <li>Otherwise, the response will only contain "userID", "loginName" and "displayName" field values if exist.</li>
12866   </ul>
12867   
12868   @param {String} phone The phone number to find KiiUser who owns it.<br>
12869   Don't add prefix of "PHONE:" described in REST API documentation. SDK will take care of it.
12870   @param {Object} [callbacks] An object with callback methods defined.
12871   This argument is mandatory and can't be omitted.
12872   @param {Method} callbacks.success The callback method to call on a successful finding request.
12873   @param {Method} callbacks.failure The callback method to call on a failed finding request.
12874   @return {Promise} return promise object.
12875     <ul>
12876       <li>fulfill callback function: function(params). params is Array instance.
12877         <ul>
12878           <li>params[0] is a KiiAppAdminContext instance which this method was called on.</li>
12879           <li>params[1] is a found KiiUser instance.</li>
12880         </ul>
12881       </li>
12882       <li>reject callback function: function(error). error is an Error instance.
12883         <ul>
12884           <li>error.target is a KiiAppAdminContext instance which this method was called on.</li>
12885           <li>error.message</li>
12886         </ul>
12887       </li>
12888     </ul>
12889   @example
12890   // example to use callbacks directly
12891   Kii.authenticateAsAppAdmin("client-id", "client-secret", {
12892       success: function(adminContext) {
12893           adminContext.findUserByPhone("phone_number_to_find", {
12894               success: function(adminContext, theMatchedUser) {
12895                   // Do something with the found user
12896               },
12897               failure: function(adminContext, anErrorString) {
12898                   // Do something with the error response
12899               }
12900           });
12901       },
12902       failure: function(errorString, errorCode) {
12903           // Auth failed.
12904       }
12905   });
12906   
12907   // example to use Promise
12908   Kii.authenticateAsAppAdmin("client-id", "client-secret").then(
12909       function(adminContext) {
12910           adminContext.findUserByPhone("phone_number_to_find").then(
12911               function(params) { // fullfill callback function
12912                   var adminContext = params[0];
12913                   var theMatchedUser = params[1];
12914                   // Do something with the found user
12915               },
12916               function(error) { // reject callback function
12917                   var adminContext = error.target;
12918                   var anErrorString = error.message;
12919                   // Do something with the error response
12920               }
12921           );
12922       },
12923       function(error) {
12924         // Auth failed.
12925       }
12926   );
12927    */
12928 
12929   KiiAppAdminContext.prototype.findUserByPhone = function(phone, callbacks) {
12930     return root.KiiUser._findUserByPhone(phone, callbacks, this);
12931   };
12932 
12933 
12934   /**
12935   Find registered KiiUser with the user name.<br>
12936   If there are no user registers with the specified user name, callbacks.failure or reject callback of promise will be called.<br>
12937   If the user name is null or empty, callbacks.failure or reject callback of promise will be called.
12938   <br><br>
12939   <b>Note:</b>
12940   <ul>
12941   <li>If "Expose Full User Data To Others" is enabled in the application console, the response will contain full of the user data.</li>
12942   <li>Otherwise, the response will only contain "userID", "loginName" and "displayName" field values if exist.</li>
12943   </ul>
12944   
12945   @param {String} username The user name to find KiiUser who owns it.<br>
12946   Don't add prefix of "LOGIN_NAME:" described in REST API documentation. SDK will take care of it.
12947   @param {Object} [callbacks] An object with callback methods defined.
12948   This argument is mandatory and can't be omitted.
12949   @param {Method} callbacks.success The callback method to call on a successful finding request.
12950   @param {Method} callbacks.failure The callback method to call on a failed finding request.
12951   @return {Promise} return promise object.
12952     <ul>
12953       <li>fulfill callback function: function(params). params is Array instance.
12954         <ul>
12955           <li>params[0] is a KiiAppAdminContext instance which this method was called on.</li>
12956           <li>params[1] is a found KiiUser instance.</li>
12957         </ul>
12958       </li>
12959       <li>reject callback function: function(error). error is an Error instance.
12960         <ul>
12961           <li>error.target is a KiiAppAdminContext instance which this method was called on.</li>
12962           <li>error.message</li>
12963         </ul>
12964       </li>
12965     </ul>
12966   @example
12967   // example to use callbacks directly
12968   Kii.authenticateAsAppAdmin("client-id", "client-secret", {
12969       success: function(adminContext) {
12970           adminContext.findUserByUsername("user_name_to_find", {
12971               success: function(adminContext, theMatchedUser) {
12972                   // Do something with the found user
12973               },
12974               failure: function(adminContext, anErrorString) {
12975                   // Do something with the error response
12976               }
12977           });
12978       },
12979       failure: function(errorString, errorCode) {
12980           // Auth failed.
12981       }
12982   });
12983   // example to use Promise
12984   Kii.authenticateAsAppAdmin("client-id", "client-secret").then(
12985       function(adminContext) {
12986           adminContext.findUserByUsername("user_name_to_find").then(
12987               function(params) { // fullfill callback function
12988                   var adminContext = params[0];
12989                   var theMatchedUser = params[1];
12990                   // Do something with the found user
12991               },
12992               function(error) { // reject callback function
12993                   var adminContext = error.target;
12994                   var anErrorString = error.message;
12995                   // Do something with the error response
12996               }
12997           );
12998       },
12999       function(error) {
13000         // Auth failed.
13001       }
13002   );
13003    */
13004 
13005   KiiAppAdminContext.prototype.findUserByUsername = function(username, callbacks) {
13006     return root.KiiUser._findUserByUsername(username, callbacks, this);
13007   };
13008 
13009 
13010   /**
13011   Register thing by app admin.
13012   Method interface is same as {@link KiiThing#register()}.
13013   Please refer to KiiThing document for details.
13014   @param {Object} fields of the thing to be registered. Please refer to {@link KiiThing#register()} for the details of fields.
13015   @param {Object} [callbacks] object holds callback functions.
13016   @param {Function} callbacks.success callback called when operation succeeded.
13017   @param {Function} callbacks.failure callback called when operation failed.
13018   @return {Promise} return promise object.
13019     <ul>
13020       <li>fulfill callback function: function(thing). thing is KiiThing instance with adminToken.</li>
13021       <li>reject callback function: function(error). error is an Error instance.
13022         <ul>
13023           <li>error.message</li>
13024         </ul>
13025       </li>
13026     </ul>
13027   @example
13028   // example to use callbacks directly
13029   // Assume you already have adminContext instance.
13030   adminContext.registerThing(
13031       {
13032           _vendorThingID: "thing-XXXX-YYYY-ZZZZZ",
13033           _password: "thing-password",
13034           _thingType: "thermometer",
13035           yourCustomObj: // Arbitrary key can be used.
13036           { // Object, Array, Number, String can be used. Should be compatible with JSON.
13037               yourCustomKey1: "value",
13038               yourCustomKey2: 100
13039           }
13040       },
13041       {
13042           success: function(thing) {
13043               // Register Thing succeeded.
13044               // Operation using thing instance in the parameter
13045               // is authored by app admin.
13046           },
13047           failure: function(error) {
13048               // Handle error.
13049           }
13050       }
13051   );
13052   
13053   // example to use Promise
13054   // Assume you already have adminContext instance.
13055   adminContext.registerThing(
13056       {
13057           _vendorThingID: "thing-XXXX-YYYY-ZZZZZ",
13058           _password: "thing-password",
13059           _thingType: "thermometer",
13060           yourCustomObj: // Arbitrary key can be used.
13061           { // Object, Array, Number, String can be used. Should be compatible with JSON.
13062               yourCustomKey1: "value",
13063               yourCustomKey2: 100
13064           }
13065       }
13066   ).then(
13067       function(thing) {
13068           // Register Thing succeeded.
13069           // Operation using thing instance in the parameter
13070           // is authored by app admin.
13071       },
13072       function(error) {
13073           // Handle error.
13074       }
13075   );
13076    */
13077 
13078   KiiAppAdminContext.prototype.registerThing = function(fields, callbacks) {
13079     return root.KiiThingWithToken.register(fields, callbacks, this._token);
13080   };
13081 
13082 
13083   /**
13084       Creates a reference to a thing operated by app admin.
13085       @param String thing id.
13086       @returns {KiiThing} A working KiiThing object
13087       @example
13088       // Assume you already have adminContext instance.
13089       adminContext.thingWithID(thingID);
13090    */
13091 
13092   KiiAppAdminContext.prototype.thingWithID = function(thingID) {
13093     return root.KiiThingWithToken.thingWithID(thingID, this._token);
13094   };
13095 
13096 
13097   /**
13098   Register user/group as owner of specified thing by app admin.
13099   
13100   @param {String} thingID The ID of thing
13101   @param {KiiUser or KiiGroup} owner instnce of KiiUser/KiiGroup to be registered as owner.
13102   @param {Object} [callbacks] object holds callback functions.
13103   @param {Function} callbacks.success callback called when operation succeeded.
13104   <br>1st argument: user/group object registered as owner.
13105   @param {Function} callbacks.failure callback called when operation failed.
13106   <br>argument is Error object.
13107   @return {Promise} return promise object.
13108     <ul>
13109       <li>fulfill callback function: function(params). params is an Array instance.
13110         <ul>
13111           <li>params[0] is a KiiUser/KiiGroup instance.</li>
13112         </ul>
13113       </li>
13114       <li>reject callback function: function(error). error is an Error instance.
13115         <ul>
13116           <li>error.message</li>
13117         </ul>
13118       </li>
13119     </ul>
13120   @example
13121   // example to use callbacks directly
13122   // assume thing/group is already registered.
13123   var group = KiiGroup.groupWithURI("kiicloud://groups/xxxyyyy");
13124   // example to use Promise
13125   // Assume you already have adminContext instance.
13126   adminContext.registerOwnerWithThingID("th.xxxx-yyyy-zzzz", group, {
13127       success: function(group) {
13128           // Register owner succeeded.
13129       },
13130       failure: function(error) {
13131           // Handle error.
13132       }
13133   });
13134   
13135   // example to use Promise
13136   // assume thing/group is already registered.
13137   var group = KiiGroup.groupWithURI("kiicloud://groups/xxxyyyy");
13138   // example to use Promise
13139   // Assume you already have adminContext instance.
13140   adminContext.registerOwnerWithThingID("th.xxxx-yyyy-zzzz", group).then(
13141       function(params) {
13142           // Register owner succeeded.
13143           var group = params[0];
13144       },
13145       function(error) {
13146           // Handle error.
13147       }
13148   );
13149    */
13150 
13151   KiiAppAdminContext.prototype.registerOwnerWithThingID = function(thingID, owner, callbacks) {
13152     return root.KiiThingWithToken.registerOwnerWithThingID(thingID, owner, callbacks, this._token);
13153   };
13154 
13155 
13156   /**
13157   Register user/group as owner of specified thing by app admin.
13158   
13159   @param {String} vendorThingID The vendor thing ID of thing
13160   @param {KiiUser or KiiGroup} owner instance of KiiUser/KiiGroupd to be registered as owner.
13161   @param {Object} [callbacks] object holds callback functions.
13162   @param {Function} callbacks.success callback called when operation succeeded.
13163   <br>1st argument: user/group object registered as owner.
13164   @param {Function} callbacks.failure callback called when operation failed.
13165   <br>argument is Error object.
13166   @return {Promise} return promise object.
13167     <ul>
13168       <li>fulfill callback function: function(params). params is an Array instance.
13169         <ul>
13170           <li>params[0] is a KiiUser/KiiGroup instance.</li>
13171         </ul>
13172       </li>
13173       <li>reject callback function: function(error). error is an Error instance.
13174         <ul>
13175           <li>error.message</li>
13176         </ul>
13177       </li>
13178     </ul>
13179   @example
13180   // example to use callbacks directly
13181   // assume thing/group is already registered.
13182   var group = KiiGroup.groupWithURI("kiicloud://groups/xxxyyyy");
13183   // example to use Promise
13184   // Assume you already have adminContext instance.
13185   adminContext.registerOwnerWithVendorThingID("xxxx-yyyy-zzzz", group, {
13186       success: function(group) {
13187           // Register owner succeeded.
13188       },
13189       failure: function(error) {
13190           // Handle error.
13191       }
13192   });
13193   
13194   // example to use Promise
13195   // assume thing/group is already registered.
13196   var group = KiiGroup.groupWithURI("kiicloud://groups/xxxyyyy");
13197   // example to use Promise
13198   // Assume you already have adminContext instance.
13199   adminContext.registerOwnerWithVendorThingID("xxxx-yyyy-zzzz", group).then(
13200       function(group) {
13201           // Register owner succeeded.
13202       },
13203       function(error) {
13204           // Handle error.
13205       }
13206   );
13207    */
13208 
13209   KiiAppAdminContext.prototype.registerOwnerWithVendorThingID = function(vendorThingID, owner, callbacks) {
13210     return root.KiiThingWithToken.registerOwnerWithVendorThingID(vendorThingID, owner, callbacks, this._token);
13211   };
13212 
13213 
13214   /**
13215   Creates a reference to a thing operated by app admin.
13216   @param String thing id.
13217   @returns {KiiThing} A working KiiThing object
13218   @example
13219   Kii.authenticateAsAppAdmin("client-id", "client-secret", {
13220       success: function(adminContext) {
13221          var thing = adminContext.thingWithID("th.xxxx-yyyy");
13222           // KiiThing operation by app admin is available now.
13223       },
13224       failure: function(errorString, errorCode) {
13225           // auth failed.
13226       }
13227   });
13228    */
13229 
13230   KiiAppAdminContext.prototype.thingWithID = function(thingID) {
13231     return root.KiiThingWithToken.thingWithID(thingID, this._token);
13232   };
13233 
13234 
13235   /**
13236   Load thing with vendor thing ID by app admin.
13237   Method interface is same as {@link KiiThing#loadWithVendorThingID()}.
13238   Please refer to KiiThing document for details.
13239   @param {String} vendorThingID registered vendor thing id.
13240   @param {Object} [callbacks] object holds callback functions.
13241   @param {Function} callbacks.success callback called when operation succeeded.
13242   @param {Function} callbacks.failure callback called when operation failed.
13243   @return {Promise} return promise object.
13244     <ul>
13245       <li>fulfill callback function: function(thing). thing is KiiThing instance with adminToken.</li>
13246       <li>reject callback function: function(error). error is an Error instance.
13247         <ul>
13248           <li>error.message</li>
13249         </ul>
13250       </li>
13251     </ul>
13252   @example
13253   // example to use callbacks directly
13254   // Assume you already have adminContext instance.
13255   adminContext.loadThingWithVendorThingID("thing-xxxx-yyyy",{
13256       success: function(thing) {
13257           // Load succeeded.
13258           // Operation using thing instance in the parameter
13259           // is authored by app admin.
13260       },
13261       failure: function(error) {
13262           // Handle error.
13263       }
13264   });
13265   
13266   // example to use Promise
13267   // Assume you already have adminContext instance.
13268   adminContext.loadThingWithVendorThingID("thing-xxxx-yyyy").then(
13269       function(thing) {
13270           // Load succeeded.
13271           // Operation using thing instance in the parameter
13272           // is authored by app admin.
13273       },
13274       function(error) {
13275           // Handle error.
13276       }
13277   );
13278    */
13279 
13280   KiiAppAdminContext.prototype.loadThingWithVendorThingID = function(vendorThingID, callbacks) {
13281     return root.KiiThingWithToken.loadWithVendorThingID(vendorThingID, callbacks, this._token);
13282   };
13283 
13284 
13285   /**
13286   Load thing with thing ID by app admin.
13287   Method interface is same as {@link KiiThing#loadWithThingID()}.
13288   Please refer to KiiThing document for details.
13289   @param {String} thingID registered thing id.
13290   @param {Object} [callbacks] object holds callback functions.
13291   @param {Function} callbacks.success callback called when operation succeeded.
13292   @param {Function} callbacks.failure callback called when operation failed.
13293   @return {Promise} return promise object.
13294     <ul>
13295       <li>fulfill callback function: function(thing). thing is KiiThing instance with adminToken.</li>
13296       <li>reject callback function: function(error). error is an Error instance.
13297         <ul>
13298           <li>error.message</li>
13299         </ul>
13300       </li>
13301     </ul>
13302   @example
13303   // example to use callbacks directly
13304   // Assume you already have adminContext instance.
13305   adminContext.loadThingWithThingID("thing-xxxx-yyyy",{
13306       success: function(thing) {
13307           // Load succeeded.
13308           // Operation using thing instance in the parameter
13309           // is authored by app admin.
13310       },
13311       failure: function(error) {
13312           // Handle error.
13313       }
13314   });
13315   
13316   // example to use Promise
13317   // Assume you already have adminContext instance.
13318   adminContext.loadThingWithThingID("thing-xxxx-yyyy").then(
13319       function(thing) {
13320           // Load succeeded.
13321           // Operation using thing instance in the parameter
13322           // is authored by app admin.
13323       },
13324       function(error) {
13325           // Handle error.
13326       }
13327   );
13328    */
13329 
13330   KiiAppAdminContext.prototype.loadThingWithThingID = function(thingID, callbacks) {
13331     return root.KiiThingWithToken.loadWithThingID(thingID, callbacks, this._token);
13332   };
13333 
13334 
13335   /**
13336   Creates a reference to a topic operated by app admin
13337   @param {String} topicName name of the topic. Must be a not empty string.
13338   @return {KiiTopic} topic instance.
13339    */
13340 
13341   KiiAppAdminContext.prototype.topicWithName = function(topicName) {
13342     if (typeof topicName !== "string" || topicName === "") {
13343       throw new root.InvalidArgumentException('topicName should not null or empty');
13344     }
13345     return new root.KiiTopicWithToken("" + (root.Kii.getBaseURL()) + "/apps/" + (root.Kii.getAppID()), topicName, this._token);
13346   };
13347 
13348 
13349   /** Gets a list of topics in app scope
13350   @param {Object} callbacks An object with callback methods defined
13351   @param {Method} callbacks.success The callback method to call on a successful list request
13352   @param {Method} callbacks.failure The callback method to call on a failed list request
13353   @param {String} paginationKey You can specify the pagination key with the nextPaginationKey passed by callbacks.success. If empty string or no string object is provided, this API regards no paginationKey specified.
13354   @return {Promise} return promise object.
13355       <ul>
13356         <li>fulfill callback function: function(params). params is Array instance.
13357           <ul>
13358             <li>params[0] is array of KiiTopic instances.</li>
13359             <li>params[1] is string of nextPaginationKey.</li>
13360           </ul>
13361         </li>
13362         <li>reject callback function: function(error). error is an Error instance.
13363           <ul>
13364             <li>error.target is a KiiAppAdminContext instance which this method was called on.</li>
13365             <li>error.message</li>
13366           </ul>
13367         </li>
13368       </ul>
13369   @example
13370   // example to use callbacks directly
13371   // Assume you already have adminContext instance.
13372   adminContext.listTopics({
13373       success: function(topicList, nextPaginationKey) {
13374           // do something with the result
13375           for(var i=0; i<topicList.length; i++){
13376               var topic = topicList[i];
13377           }
13378           if (nextPaginationKey != null) {
13379               Kii.listTopics({
13380                   success: function(topicList, nextPaginationKey) {...},
13381                   failure: function(anErrorString) {...}
13382               }, nextPaginationKey);
13383           }
13384       },
13385       failure: function(anErrorString) {
13386           // do something with the error response
13387       }
13388   });
13389   
13390   // example to use Promise
13391   // Assume you already have adminContext instance.
13392   adminContext.listTopics().then(
13393       function(params) {
13394           var topicList = params[0];
13395           var nextPaginationKey = params[1];
13396           // do something with the result
13397           for(var i=0; i<topicList.length; i++){
13398               var topic = topicList[i];
13399           }
13400           if (nextPaginationKey != null) {
13401               adminContext.listTopics(null, nextPaginationKey).then(
13402                   function(params) {...},
13403                   function(error) {...}
13404               );
13405           }
13406       },
13407       function(error) {
13408           // do something with the error response
13409       }
13410   );
13411    */
13412 
13413   KiiAppAdminContext.prototype.listTopics = function(callbacks, paginationKey) {
13414     return root.Kii._listTopics(callbacks, paginationKey, this);
13415   };
13416 
13417   return KiiAppAdminContext;
13418 
13419 })();
13420 
13421 root.KiiACLWithToken = (function(_super) {
13422   __extends(KiiACLWithToken, _super);
13423 
13424   function KiiACLWithToken(parent, authToken) {
13425     this._userWithID = __bind(this._userWithID, this);
13426     this._groupWithID = __bind(this._groupWithID, this);
13427     this._getRequest = __bind(this._getRequest, this);
13428     KiiACLWithToken.__super__.constructor.call(this);
13429     this._setParent(parent);
13430     this._authToken = authToken;
13431   }
13432 
13433   KiiACLWithToken.prototype._getRequest = function(spec) {
13434     var request;
13435     request = KiiACLWithToken.__super__._getRequest.call(this, spec);
13436     request.setAdminToken(this._authToken);
13437     return request;
13438   };
13439 
13440   KiiACLWithToken.prototype._groupWithID = function(id) {
13441     var group;
13442     group = root.KiiGroupWithToken._groupWithID(id, this._authToken);
13443     return group;
13444   };
13445 
13446   KiiACLWithToken.prototype._userWithID = function(id) {
13447     var user;
13448     user = root.KiiUserWithToken._userWithID(id, this._authToken);
13449     return user;
13450   };
13451 
13452   return KiiACLWithToken;
13453 
13454 })(root.KiiACL);
13455 
13456 root.KiiGroupWithToken = (function(_super) {
13457   __extends(KiiGroupWithToken, _super);
13458 
13459   function KiiGroupWithToken(authToken) {
13460     this.topicWithName = __bind(this.topicWithName, this);
13461     this._setAuthToken = __bind(this._setAuthToken, this);
13462     this._setOwnerFromContext = __bind(this._setOwnerFromContext, this);
13463     this._userWithID = __bind(this._userWithID, this);
13464     this.bucketWithName = __bind(this.bucketWithName, this);
13465     this._getRequest = __bind(this._getRequest, this);
13466     KiiGroupWithToken.__super__.constructor.call(this);
13467     this._authToken = authToken;
13468   }
13469 
13470   KiiGroupWithToken.prototype._getRequest = function(spec) {
13471     var request;
13472     request = KiiGroupWithToken.__super__._getRequest.call(this, spec);
13473     request.setAdminToken(this._authToken);
13474     return request;
13475   };
13476 
13477   KiiGroupWithToken._groupWithName = function(groupName, authToken) {
13478     return root.KiiGroupWithToken._groupWithNameAndMembers(groupName, null, authToken);
13479   };
13480 
13481   KiiGroupWithToken._groupWithNameAndMembers = function(groupName, members, authToken) {
13482     var group;
13483     group = new root.KiiGroupWithToken(authToken);
13484     group._setName(groupName);
13485     group._setAddMembers(members);
13486     return group;
13487   };
13488 
13489   KiiGroupWithToken._groupWithID = function(id, authToken) {
13490     var group;
13491     group = new root.KiiGroupWithToken(authToken);
13492     group._setUUID(id);
13493     return group;
13494   };
13495 
13496   KiiGroupWithToken.prototype.bucketWithName = function(name) {
13497     var bucket;
13498     bucket = new root.KiiBucketWithToken(name, this, this._authToken);
13499     return bucket;
13500   };
13501 
13502   KiiGroupWithToken.prototype.encryptedBucketWithName = function(name) {
13503     var bucket;
13504     bucket = new root.KiiEncryptedBucketWithToken(name, this, this._authToken);
13505     return bucket;
13506   };
13507 
13508   KiiGroupWithToken.prototype._userWithID = function(id) {
13509     var user;
13510     user = root.KiiUserWithToken._userWithID(id, this._authToken);
13511     return user;
13512   };
13513 
13514   KiiGroupWithToken.prototype._setOwnerFromContext = function(data) {};
13515 
13516   KiiGroupWithToken._groupWithJSON = function(json, authToken) {
13517     var group;
13518     group = new root.KiiGroupWithToken(authToken);
13519     if (json.groupID != null) {
13520       group._setUUID(json.groupID);
13521     }
13522     if (json.name != null) {
13523       group._setName(json.name);
13524     }
13525     if (json.owner != null) {
13526       group._setOwner(root.KiiUserWithToken._userWithID(json.owner, authToken));
13527     }
13528     return group;
13529   };
13530 
13531   KiiGroupWithToken.prototype._setAuthToken = function(wrapper) {
13532     return wrapper.setAuthToken(this._authToken);
13533   };
13534 
13535   KiiGroupWithToken.prototype.topicWithName = function(topicName) {
13536     var id, puri;
13537     if (typeof topicName !== "string" || topicName === "") {
13538       throw new root.InvalidArgumentException('topicName should not null or empty');
13539     }
13540     id = this.getID();
13541     if (!id) {
13542       throw 'can not instantiate topic from instance which doesn\'t have ID';
13543     }
13544     puri = this._getHttpURI();
13545     return new root.KiiTopicWithToken(puri, topicName, this._authToken);
13546   };
13547 
13548   return KiiGroupWithToken;
13549 
13550 })(root.KiiGroup);
13551 
13552 root.KiiObjectWithToken = (function(_super) {
13553   __extends(KiiObjectWithToken, _super);
13554 
13555   function KiiObjectWithToken(token) {
13556     this._userWithID = __bind(this._userWithID, this);
13557     this.objectACL = __bind(this.objectACL, this);
13558     this._getToken = __bind(this._getToken, this);
13559     this._getRequest = __bind(this._getRequest, this);
13560     KiiObjectWithToken.__super__.constructor.call(this);
13561     this._authToken = token;
13562   }
13563 
13564   KiiObjectWithToken.prototype._getRequest = function(spec) {
13565     var request;
13566     root.Kii.logger("admin req: " + this._authToken);
13567     request = KiiObjectWithToken.__super__._getRequest.call(this, spec);
13568     request.setAdminToken(this._authToken);
13569     return request;
13570   };
13571 
13572   KiiObjectWithToken.prototype._getToken = function() {
13573     if (this._authToken) {
13574       return this._authToken;
13575     } else {
13576       return null;
13577     }
13578   };
13579 
13580   KiiObjectWithToken.objectWithBucket = function(bucket, type, authToken) {
13581     var obj;
13582     root.Kii.logger("Creating object w type: " + type);
13583     obj = new root.KiiObjectWithToken(authToken);
13584     obj._setBucket(bucket);
13585     obj._setObjectType(type);
13586     root.Kii.logger(obj);
13587     return obj;
13588   };
13589 
13590   KiiObjectWithToken.objectWithID = function(bucket, id, authToken) {
13591     var obj;
13592     root.Kii.logger("Creating object w id: " + id);
13593     obj = new root.KiiObjectWithToken(authToken);
13594     obj._setBucket(bucket);
13595     obj._setUUID(id);
13596     root.Kii.logger(obj);
13597     return obj;
13598   };
13599 
13600   KiiObjectWithToken.prototype.objectACL = function() {
13601     var acl;
13602     acl = new root.KiiACLWithToken(this, this._authToken);
13603     return acl;
13604   };
13605 
13606   KiiObjectWithToken.prototype._userWithID = function(id) {
13607     var user;
13608     user = root.KiiUserWithToken._userWithID(id, this._authToken);
13609     return user;
13610   };
13611 
13612   return KiiObjectWithToken;
13613 
13614 })(root.KiiObject);
13615 
13616 root.KiiUserWithToken = (function(_super) {
13617   __extends(KiiUserWithToken, _super);
13618 
13619   function KiiUserWithToken(authToken) {
13620     this.pushInstallation = __bind(this.pushInstallation, this);
13621     this.topicWithName = __bind(this.topicWithName, this);
13622     this.pushSubscription = __bind(this.pushSubscription, this);
13623     this._groupWithJSON = __bind(this._groupWithJSON, this);
13624     this.bucketWithName = __bind(this.bucketWithName, this);
13625     this._setAuthHeader = __bind(this._setAuthHeader, this);
13626     this._setAuthToken = __bind(this._setAuthToken, this);
13627     this._getRequest = __bind(this._getRequest, this);
13628     KiiUserWithToken.__super__.constructor.call(this);
13629     this._authToken = authToken;
13630   }
13631 
13632   KiiUserWithToken._userWithID = function(id, authToken) {
13633     var user;
13634     user = new root.KiiUserWithToken(authToken);
13635     user._setUUID(id);
13636     return user;
13637   };
13638 
13639   KiiUserWithToken.prototype._getRequest = function(spec) {
13640     var request;
13641     request = KiiUserWithToken.__super__._getRequest.call(this, spec);
13642     request.setAdminToken(this._authToken);
13643     return request;
13644   };
13645 
13646   KiiUserWithToken.prototype._setAuthToken = function(wrapper) {
13647     return wrapper.setAuthToken(this._authToken);
13648   };
13649 
13650   KiiUserWithToken.prototype._setAuthHeader = function(xhr) {
13651     return xhr.setRequestHeader("Authorization", "Bearer " + this._authToken);
13652   };
13653 
13654   KiiUserWithToken.prototype.bucketWithName = function(bucketName) {
13655     var bucket;
13656     bucket = new root.KiiBucketWithToken(bucketName, this, this._authToken);
13657     return bucket;
13658   };
13659 
13660   KiiUserWithToken.prototype.encryptedBucketWithName = function(bucketName) {
13661     var bucket;
13662     bucket = new root.KiiEncryptedBucketWithToken(bucketName, this, this._authToken);
13663     return bucket;
13664   };
13665 
13666   KiiUserWithToken.prototype._groupWithJSON = function(json) {
13667     var group;
13668     group = new root.KiiGroupWithToken._groupWithJSON(json, this._authToken);
13669     return group;
13670   };
13671 
13672   KiiUserWithToken.prototype.pushSubscription = function() {
13673     return new root.KiiPushSubscriptionWithToken(this, this._authToken);
13674   };
13675 
13676   KiiUserWithToken.prototype.topicWithName = function(topicName) {
13677     var id;
13678     if (typeof topicName !== "string" || topicName === "") {
13679       throw new root.InvalidArgumentException('topicName should not null or empty');
13680     }
13681     id = this.getID();
13682     if (!id) {
13683       throw 'can not instantiate topic from instance which doesn\'t have ID';
13684     }
13685     return new root.KiiTopicWithToken(this._getHttpURI(), topicName, this._authToken);
13686   };
13687 
13688   KiiUserWithToken.prototype.pushInstallation = function() {
13689     throw new root.UnsupportedOperationException('Push installation is not supported by admin context');
13690   };
13691 
13692   return KiiUserWithToken;
13693 
13694 })(root.KiiUser);
13695 
13696 
13697 /**
13698 	@class Represent an anonymous user for setting the ACL of an object. This will include anyone using the application but have not signed up or authenticated as registered user.
13699 
13700 	When retrieving ACL from an object, test for this class to determine the subject type.
13701     @example
13702     var entry = ... // Retrieved ACL entry
13703     if(entry.getSubject() instanceof KiiAnonymousUser) {
13704         // the ACL is set for anonymous users
13705     }
13706 
13707     @exports root.KiiAnonymousUser as KiiAnonymousUser
13708  */
13709 
13710 root.KiiAnonymousUser = (function() {
13711   function KiiAnonymousUser() {
13712     this.getID = __bind(this.getID, this);
13713   }
13714 
13715 
13716   /** 
13717     Returns the ID of Anonymous user.
13718    */
13719 
13720   KiiAnonymousUser.prototype.getID = function() {
13721     return 'ANONYMOUS_USER';
13722   };
13723 
13724   return KiiAnonymousUser;
13725 
13726 })();
13727 
13728 
13729 /**
13730 	@class Represent any authenticated user for setting the ACL of an object. This will include anyone using the application who has registered and authenticated in the current session.
13731 
13732 	When retrieving ACL from an object, test for this class to determine the subject type. Example:
13733 
13734     @example
13735     var entry = ... // Retrieved ACL entry
13736     if(entry.getSubject() instanceof KiiAnyAuthenticatedUser) {
13737         // the ACL is set for authenticated users
13738     }
13739 
13740     @exports root.KiiAnyAuthenticatedUser as KiiAnyAuthenticatedUser
13741  */
13742 
13743 root.KiiAnyAuthenticatedUser = (function() {
13744   function KiiAnyAuthenticatedUser() {
13745     this.getID = __bind(this.getID, this);
13746   }
13747 
13748 
13749   /** 
13750     Returns the ID of AuthenticatedUser user.
13751    */
13752 
13753   KiiAnyAuthenticatedUser.prototype.getID = function() {
13754     return 'ANY_AUTHENTICATED_USER';
13755   };
13756 
13757   return KiiAnyAuthenticatedUser;
13758 
13759 })();
13760 
13761 root.KiiSDKClientInfo = (function() {
13762   function KiiSDKClientInfo() {}
13763 
13764   KiiSDKClientInfo.getSDKClientInfo = function() {
13765     if (KiiSDKClientInfo._clientInfo == null) {
13766       KiiSDKClientInfo._clientInfo = "sn=jss;sv=" + root.Kii.getSDKVersion();
13767     }
13768     return KiiSDKClientInfo._clientInfo;
13769   };
13770 
13771   return KiiSDKClientInfo;
13772 
13773 })();
13774 
13775 root.KiiSCNTwitter = (function(_super) {
13776   __extends(KiiSCNTwitter, _super);
13777 
13778   function KiiSCNTwitter() {
13779     this._unlinkFromCurrentUser = __bind(this._unlinkFromCurrentUser, this);
13780     this._linkWithCurrentUser = __bind(this._linkWithCurrentUser, this);
13781     this._logOut = __bind(this._logOut, this);
13782     this._logIn = __bind(this._logIn, this);
13783     this._getAccessToken = __bind(this._getAccessToken, this);
13784     this._createTokenObject = __bind(this._createTokenObject, this);
13785     this._setup = __bind(this._setup, this);
13786     KiiSCNTwitter.__super__.constructor.call(this, root.KiiSocialNetworkName.TWITTER);
13787   }
13788 
13789   KiiSCNTwitter.prototype._setup = function(_key, _secret, _extras) {
13790     this._key = _key;
13791     this._secret = _secret;
13792     this._extras = _extras;
13793     return KiiSCNTwitter.__super__._setup.call(this, this._key, this._secret, this._extras);
13794   };
13795 
13796   KiiSCNTwitter.prototype._createTokenObject = function(options, data) {
13797     var tokenObject;
13798     tokenObject = {
13799       "oauth_token": options.oauth_token,
13800       "oauth_token_secret": options.oauth_token_secret
13801     };
13802     if ((data != null) && (data.new_user_created != null)) {
13803       tokenObject["kii_new_user"] = data.new_user_created;
13804     }
13805     return tokenObject;
13806   };
13807 
13808   KiiSCNTwitter.prototype._getAccessToken = function(options) {
13809     return options.oauth_token;
13810   };
13811 
13812   KiiSCNTwitter.prototype._logIn = function(options, callbacks) {
13813     var requestData;
13814     root.Kii.logger("Checking options");
13815     root.Kii.logger(options);
13816     if ((options == null) || (!options.oauth_token && !options.oauth_token_secret)) {
13817       throw root.InvalidArgumentException('Both options.oauth_token and options.oauth_token_secret are required');
13818     } else if (!options.oauth_token) {
13819       throw root.InvalidArgumentException('options.oauth_token is required');
13820     } else if (!options.oauth_token_secret) {
13821       throw root.InvalidArgumentException('options.oauth_token_secret is required');
13822     }
13823     if (root.KiiUser.getCurrentUser() != null) {
13824       root.KiiUser.logOut();
13825     }
13826     requestData = {
13827       accessToken: options.oauth_token,
13828       accessTokenSecret: options.oauth_token_secret
13829     };
13830     return this._register("twitter", "application/vnd.kii.AuthTokenTwitterRequest+json", requestData, options, callbacks);
13831   };
13832 
13833   KiiSCNTwitter.prototype._logOut = function() {
13834     KiiSCNTwitter.__super__._logOut.apply(this, arguments);
13835     return root.Kii.logger("Log out twitter");
13836   };
13837 
13838   KiiSCNTwitter.prototype._linkWithCurrentUser = function(options, callbacks) {
13839     var requestData;
13840     if (root.KiiUser.getCurrentUser() == null) {
13841       callbacks.failure(null, this._network, "No user logged in");
13842       return;
13843     }
13844     if ((options == null) || (!options.oauth_token && !options.oauth_token_secret)) {
13845       throw root.InvalidArgumentException('Both options.oauth_token and options.oauth_token_secret are required');
13846     } else if (!options.oauth_token) {
13847       throw root.InvalidArgumentException('options.oauth_token is required');
13848     } else if (!options.oauth_token_secret) {
13849       throw root.InvalidArgumentException('options.oauth_token_secret is required');
13850     }
13851     requestData = {
13852       accessToken: options.oauth_token,
13853       accessTokenSecret: options.oauth_token_secret
13854     };
13855     return this._link("twitter", "application/vnd.kii.LinkTwitterRequest+json", requestData, options, callbacks);
13856   };
13857 
13858   KiiSCNTwitter.prototype._unlinkFromCurrentUser = function(callbacks) {
13859     if (root.KiiUser.getCurrentUser() == null) {
13860       callbacks.failure(null, this._network, "No user logged in");
13861       return;
13862     }
13863     return this._unlink("twitter", callbacks);
13864   };
13865 
13866   return KiiSCNTwitter;
13867 
13868 })(root.KiiSocialConnectNetwork);
13869 
13870 
13871 /**
13872     @class Represents Geo Point.
13873     @exports root.KiiGeoPoint as KiiGeoPoint
13874  */
13875 
13876 root.KiiGeoPoint = (function() {
13877   function KiiGeoPoint(_latitude, _longitude) {
13878     var inRange;
13879     this._latitude = _latitude;
13880     this._longitude = _longitude;
13881     this._toDict = __bind(this._toDict, this);
13882     this.getLongitude = __bind(this.getLongitude, this);
13883     this.getLatitude = __bind(this.getLatitude, this);
13884     inRange = function(min, max, num) {
13885       return (num > min) && (num < max) && (!isNaN(num));
13886     };
13887     if (!inRange(-90, 90, this._latitude) || !inRange(-180, 180, this._longitude)) {
13888       throw root.InvalidArgumentException("Specified latitide or longitude is invalid");
13889     }
13890   }
13891 
13892 
13893   /**
13894       Return the latitide of this point.
13895    */
13896 
13897   KiiGeoPoint.prototype.getLatitude = function() {
13898     return this._latitude;
13899   };
13900 
13901 
13902   /**
13903       Return the longitude of this point.
13904    */
13905 
13906   KiiGeoPoint.prototype.getLongitude = function() {
13907     return this._longitude;
13908   };
13909 
13910 
13911   /**
13912       Create a geo point with the given latitude and longitude.
13913       @param {Number} latitude Latitude of the point in degrees. Valid if the value is greater than -90 degrees and less than +90 degrees.
13914       @param {Number} longitude Longitude of the point in degrees. Valid if the value is greater than -180 degrees and less than +180 degrees.
13915       @throws {String} Specified latitude or longitude is invalid.
13916       @return {KiiGeoPoint} A new reference of KiiGeoPoint.
13917       @example
13918       var point = KiiGeoPoint.geoPoint(35.07, 139.02);
13919    */
13920 
13921   KiiGeoPoint.geoPoint = function(latitude, longitude) {
13922     return new root.KiiGeoPoint(latitude, longitude);
13923   };
13924 
13925   KiiGeoPoint.prototype._toDict = function() {
13926     var dict;
13927     dict = {
13928       _type: 'point',
13929       lat: this._latitude,
13930       lon: this._longitude
13931     };
13932     return dict;
13933   };
13934 
13935   return KiiGeoPoint;
13936 
13937 })();
13938 
13939 KiiJQueryHttpRequest = (function() {
13940   function KiiJQueryHttpRequest(method, url, callbacks) {
13941     this.xhr = $.ajaxSettings.xhr();
13942     url = KiiUtilities._disableCacheURL(url);
13943     this.xhr.open(method, url, true);
13944     this.xhr.onreadystatechange = callbacks.onComplete;
13945   }
13946 
13947   return KiiJQueryHttpRequest;
13948 
13949 })();
13950 
13951 KiiXMLHttpRequest = (function() {
13952   function KiiXMLHttpRequest(method, url, callbacks) {
13953     url = KiiUtilities._disableCacheURL(url);
13954     this.xhr = new XMLHttpRequest;
13955     if ("withCredentials" in this.xhr) {
13956       this.xhr.open(method, url, true);
13957       this.xhr.onreadystatechange = callbacks.onComplete;
13958     } else {
13959       this.xhr = null;
13960     }
13961   }
13962 
13963   return KiiXMLHttpRequest;
13964 
13965 })();
13966 
13967 KiiTitaniumHttpRequest = (function() {
13968   function KiiTitaniumHttpRequest(method, url, callbacks) {
13969     this.xhr = Ti.Network.createHTTPClient();
13970     url = KiiUtilities._disableCacheURL(url);
13971     this.xhr.open(method, url, true);
13972     this.xhr.onload = callbacks.onComplete;
13973     this.xhr.onerror = callbacks.onError;
13974   }
13975 
13976   return KiiTitaniumHttpRequest;
13977 
13978 })();
13979 
13980 KiiXHRWrapperFactory = (function() {
13981   function KiiXHRWrapperFactory() {}
13982 
13983   KiiXHRWrapperFactory.createXHRWrapper = function(method, url) {
13984     var wrapper;
13985     wrapper = null;
13986     if (root.Kii._getHttpRequestType() === null) {
13987       if (typeof jQuery !== 'undefined') {
13988         root.Kii.logger("Use jQuery " + method + ":" + url);
13989         wrapper = new KiiJQXHRWrapper(method, url);
13990       } else if (typeof XMLHttpRequest !== 'undefined') {
13991         root.Kii.logger("Use XMLHttpRequest " + method + ":" + url);
13992         wrapper = new KiiXHRWrapper(method, url);
13993       } else if (typeof Titanium !== 'undefined') {
13994         root.Kii.logger("Use Titanium " + method + ":" + url);
13995         wrapper = new KiiTiXHRWrapper(method, url);
13996       }
13997     } else {
13998       root.Kii.logger("Use http request backdoor");
13999       if (root.Kii._getHttpRequestType() === root._KiiHttpRequestType.jQuery) {
14000         root.Kii.logger("Use jQuery " + method + ":" + url);
14001         wrapper = new KiiJQXHRWrapper(method, url);
14002       } else if (root.Kii._getHttpRequestType() === root._KiiHttpRequestType.XMLHttpRequest) {
14003         root.Kii.logger("Use XMLHttpRequest " + method + ":" + url);
14004         wrapper = new KiiXHRWrapper(method, url);
14005       } else if (root.Kii._getHttpRequestType() === root._KiiHttpRequestType.Titanium) {
14006         root.Kii.logger("Use Titanium " + method + ":" + url);
14007         wrapper = new KiiTiXHRWrapper(method, url);
14008       }
14009     }
14010     return wrapper;
14011   };
14012 
14013   return KiiXHRWrapperFactory;
14014 
14015 })();
14016 
14017 KiiXHRWrapper = (function() {
14018   KiiXHRWrapper.prototype.getAppID = function() {
14019     return root.Kii.getAppID();
14020   };
14021 
14022   KiiXHRWrapper.prototype.getAppKey = function() {
14023     return root.Kii.getAppKey();
14024   };
14025 
14026   KiiXHRWrapper.prototype.getLogger = function() {
14027     return root.Kii.logger();
14028   };
14029 
14030   function KiiXHRWrapper(method, url) {
14031     this.setAuthToken = __bind(this.setAuthToken, this);
14032     this.setAdminOrUserToken = __bind(this.setAdminOrUserToken, this);
14033     this.setCurrentUserToken = __bind(this.setCurrentUserToken, this);
14034     this.setContentType = __bind(this.setContentType, this);
14035     this.setKiiHeaders = __bind(this.setKiiHeaders, this);
14036     this.getErrorCode = __bind(this.getErrorCode, this);
14037     this.getErrorString = __bind(this.getErrorString, this);
14038     this.sendData = __bind(this.sendData, this);
14039     this.send = __bind(this.send, this);
14040     this._setUpCallbacks = __bind(this._setUpCallbacks, this);
14041     var hs, k, v;
14042     url = KiiUtilities._disableCacheURL(url);
14043     this.xhr = new XMLHttpRequest;
14044     this.method = method;
14045     if ("withCredentials" in this.xhr) {
14046       this.xhr.open(method, url, true);
14047       hs = root.Kii.getAdditionalHeaders();
14048       if (hs != null) {
14049         for (k in hs) {
14050           v = hs[k];
14051           this.xhr.setRequestHeader(k, v);
14052         }
14053       }
14054     } else {
14055       this.xhr = null;
14056     }
14057   }
14058 
14059   KiiXHRWrapper.prototype._setUpCallbacks = function(callback) {
14060     if (callback && callback.progress) {
14061       if (this.method === "PUT") {
14062         return this.xhr.upload.addEventListener("progress", callback.progress, false);
14063       } else {
14064         return this.xhr.addEventListener("progress", callback.progress, false);
14065       }
14066     }
14067   };
14068 
14069   KiiXHRWrapper.prototype.send = function(sendCallbacks) {
14070     var requestCallback;
14071     this._setUpCallbacks(sendCallbacks);
14072     requestCallback = {
14073       onComplete: (function(_this) {
14074         return function() {
14075           var _ref;
14076           if (_this.xhr.readyState === 4) {
14077             if ((200 <= (_ref = _this.xhr.status) && _ref < 400)) {
14078               _this.getLogger("Completed Request[" + _this.xhr.status + "]");
14079               if (sendCallbacks != null) {
14080                 return sendCallbacks.success();
14081               }
14082             } else {
14083               _this.getLogger('Error loading data...');
14084               _this.getLogger('callback : ' + sendCallbacks);
14085               if (sendCallbacks != null) {
14086                 return sendCallbacks.failure();
14087               }
14088             }
14089           }
14090         };
14091       })(this)
14092     };
14093     this.xhr.onreadystatechange = requestCallback.onComplete;
14094     return this.xhr.send();
14095   };
14096 
14097   KiiXHRWrapper.prototype.sendData = function(data, sendCallbacks) {
14098     var requestCallback;
14099     this.getLogger("SENDING:");
14100     this.getLogger(JSON.stringify(data));
14101     this._setUpCallbacks(sendCallbacks);
14102     requestCallback = {
14103       onComplete: (function(_this) {
14104         return function() {
14105           var _ref;
14106           if (_this.xhr.readyState === 4) {
14107             if ((200 <= (_ref = _this.xhr.status) && _ref < 400)) {
14108               _this.getLogger("Completed Request[" + _this.xhr.status + "]");
14109               if (sendCallbacks != null) {
14110                 return sendCallbacks.success();
14111               }
14112             } else {
14113               _this.getLogger('Error loading data...');
14114               if (sendCallbacks != null) {
14115                 return sendCallbacks.failure();
14116               }
14117             }
14118           }
14119         };
14120       })(this)
14121     };
14122     this.xhr.onreadystatechange = requestCallback.onComplete;
14123     return this.xhr.send(data);
14124   };
14125 
14126   KiiXHRWrapper.prototype.getErrorString = function(actionString) {
14127     var errString, json;
14128     errString = "" + actionString + " failed. statusCode: " + this.xhr.status;
14129     try {
14130       json = JSON.parse(decodeURIComponent(this.xhr.responseText));
14131       if (json.errorCode != null) {
14132         errString += " error code: " + json.errorCode;
14133       }
14134       if (json.message != null) {
14135         errString += " message: " + json.message;
14136       }
14137       return errString;
14138     } catch (_error) {
14139       return errString;
14140     }
14141   };
14142 
14143   KiiXHRWrapper.prototype.getErrorCode = function() {
14144     var json;
14145     try {
14146       json = JSON.parse(decodeURIComponent(this.xhr.responseText));
14147       return json.errorCode;
14148     } catch (_error) {
14149       return null;
14150     }
14151   };
14152 
14153   KiiXHRWrapper.prototype.setKiiHeaders = function() {
14154     this.xhr.setRequestHeader("x-kii-appid", this.getAppID());
14155     this.xhr.setRequestHeader("x-kii-appkey", this.getAppKey());
14156     return this.xhr.setRequestHeader("x-kii-sdk", root.KiiSDKClientInfo.getSDKClientInfo());
14157   };
14158 
14159   KiiXHRWrapper.prototype.setContentType = function(contentType) {
14160     return this.xhr.setRequestHeader("Content-Type", contentType);
14161   };
14162 
14163   KiiXHRWrapper.prototype.setCurrentUserToken = function() {
14164     var token, _ref;
14165     token = (_ref = this.getCurrentUser()) != null ? _ref.getAccessToken() : void 0;
14166     if (token != null) {
14167       this.xhr.setRequestHeader("authorization", "bearer " + token);
14168       return true;
14169     }
14170     return false;
14171   };
14172 
14173   KiiXHRWrapper.prototype.setAdminOrUserToken = function(adminContext) {
14174     var token, _ref;
14175     if (adminContext != null) {
14176       token = adminContext._getToken();
14177     } else {
14178       token = (_ref = this.getCurrentUser()) != null ? _ref.getAccessToken() : void 0;
14179     }
14180     if (token != null) {
14181       this.xhr.setRequestHeader("authorization", "bearer " + token);
14182       return true;
14183     }
14184     return false;
14185   };
14186 
14187   KiiXHRWrapper.prototype.setAuthToken = function(authToken) {
14188     if (authToken != null) {
14189       return this.xhr.setRequestHeader("authorization", "bearer " + authToken);
14190     }
14191   };
14192 
14193   KiiXHRWrapper.prototype.getCurrentUser = function() {
14194     return root.KiiUser.getCurrentUser();
14195   };
14196 
14197   return KiiXHRWrapper;
14198 
14199 })();
14200 
14201 KiiTiXHRWrapper = (function(_super) {
14202   __extends(KiiTiXHRWrapper, _super);
14203 
14204   function KiiTiXHRWrapper(method, url) {
14205     this.sendData = __bind(this.sendData, this);
14206     this.send = __bind(this.send, this);
14207     var hs, k, v;
14208     url = KiiUtilities._disableCacheURL(url);
14209     this.xhr = Ti.Network.createHTTPClient();
14210     this.method = method;
14211     this.xhr.open(method, url, true);
14212     hs = root.Kii.getAdditionalHeaders();
14213     if (hs != null) {
14214       for (k in hs) {
14215         v = hs[k];
14216         this.xhr.setRequestHeader(k, v);
14217       }
14218     }
14219   }
14220 
14221   KiiTiXHRWrapper.prototype.send = function(sendCallbacks) {
14222     var requestCallback;
14223     this._setUpCallbacks(sendCallbacks);
14224     requestCallback = {
14225       onComplete: (function(_this) {
14226         return function() {
14227           var _ref;
14228           if (_this.xhr.readyState === 4) {
14229             if ((200 <= (_ref = _this.xhr.status) && _ref < 400)) {
14230               root.Kii.logger("Completed Request[" + _this.xhr.status + "]");
14231               if (sendCallbacks != null) {
14232                 return sendCallbacks.success();
14233               }
14234             } else {
14235               root.Kii.logger('Error loading data...');
14236               root.Kii.logger('callback : ' + sendCallbacks);
14237               if (sendCallbacks != null) {
14238                 return sendCallbacks.failure();
14239               }
14240             }
14241           }
14242         };
14243       })(this),
14244       onError: (function(_this) {
14245         return function() {
14246           root.Kii.logger('Error loading data...');
14247           root.Kii.logger('callback : ' + sendCallbacks);
14248           if (sendCallbacks != null) {
14249             return sendCallbacks.failure();
14250           }
14251         };
14252       })(this)
14253     };
14254     this.xhr.onload = requestCallback.onComplete;
14255     this.xhr.onerror = requestCallback.onError;
14256     return this.xhr.send();
14257   };
14258 
14259   KiiTiXHRWrapper.prototype.sendData = function(data, sendCallbacks) {
14260     var requestCallback;
14261     this._setUpCallbacks(sendCallbacks);
14262     requestCallback = {
14263       onComplete: (function(_this) {
14264         return function() {
14265           var _ref;
14266           if (_this.xhr.readyState === 4) {
14267             if ((200 <= (_ref = _this.xhr.status) && _ref < 400)) {
14268               root.Kii.logger("Completed Request[" + _this.xhr.status + "]");
14269               if (sendCallbacks != null) {
14270                 return sendCallbacks.success();
14271               }
14272             } else {
14273               root.Kii.logger('Error loading data...');
14274               if (sendCallbacks != null) {
14275                 return sendCallbacks.failure();
14276               }
14277             }
14278           }
14279         };
14280       })(this),
14281       onError: (function(_this) {
14282         return function() {
14283           root.Kii.logger('Error loading data...');
14284           root.Kii.logger('callback : ' + sendCallbacks);
14285           if (sendCallbacks != null) {
14286             return sendCallbacks.failure();
14287           }
14288         };
14289       })(this)
14290     };
14291     this.xhr.onload = requestCallback.onComplete;
14292     this.xhr.onerror = requestCallback.onError;
14293     return this.xhr.send(data);
14294   };
14295 
14296   return KiiTiXHRWrapper;
14297 
14298 })(KiiXHRWrapper);
14299 
14300 KiiJQXHRWrapper = (function(_super) {
14301   __extends(KiiJQXHRWrapper, _super);
14302 
14303   function KiiJQXHRWrapper(method, url) {
14304     var hs, k, v;
14305     url = KiiUtilities._disableCacheURL(url);
14306     this.xhr = $.ajaxSettings.xhr();
14307     this.xhr.open(method, url, true);
14308     this.method = method;
14309     hs = root.Kii.getAdditionalHeaders();
14310     if (hs != null) {
14311       for (k in hs) {
14312         v = hs[k];
14313         this.xhr.setRequestHeader(k, v);
14314       }
14315     }
14316   }
14317 
14318   return KiiJQXHRWrapper;
14319 
14320 })(KiiXHRWrapper);
14321 
14322 root.KiiSCNQQ = (function(_super) {
14323   __extends(KiiSCNQQ, _super);
14324 
14325   function KiiSCNQQ() {
14326     this._unlinkFromCurrentUser = __bind(this._unlinkFromCurrentUser, this);
14327     this._linkWithCurrentUser = __bind(this._linkWithCurrentUser, this);
14328     this._logOut = __bind(this._logOut, this);
14329     this._logIn = __bind(this._logIn, this);
14330     this._getAccessToken = __bind(this._getAccessToken, this);
14331     this._createTokenObject = __bind(this._createTokenObject, this);
14332     this._setup = __bind(this._setup, this);
14333     KiiSCNQQ.__super__.constructor.call(this, root.KiiSocialNetworkName.QQ);
14334   }
14335 
14336   KiiSCNQQ.prototype._setup = function(_key, _secret, _extras) {
14337     this._key = _key;
14338     this._secret = _secret;
14339     this._extras = _extras;
14340     return KiiSCNQQ.__super__._setup.call(this, this._key, this._secret, this._extras);
14341   };
14342 
14343   KiiSCNQQ.prototype._createTokenObject = function(options, data) {
14344     var tokenObject;
14345     tokenObject = {
14346       "access_token": options.access_token,
14347       "openID": options.openID
14348     };
14349     if ((data != null) && (data.new_user_created != null)) {
14350       tokenObject["kii_new_user"] = data.new_user_created;
14351     }
14352     return tokenObject;
14353   };
14354 
14355   KiiSCNQQ.prototype._getAccessToken = function(options) {
14356     return options.access_token;
14357   };
14358 
14359   KiiSCNQQ.prototype._logIn = function(options, callbacks) {
14360     var requestData;
14361     root.Kii.logger("Checking options");
14362     root.Kii.logger(options);
14363     if ((options == null) || (!options.access_token && !options.openID)) {
14364       throw root.InvalidArgumentException('Both options.access_token and options.openID are required');
14365     } else if (!options.access_token) {
14366       throw root.InvalidArgumentException('options.access_token is required');
14367     } else if (!options.openID) {
14368       throw root.InvalidArgumentException('options.openID is required');
14369     }
14370     if (root.KiiUser.getCurrentUser() != null) {
14371       root.KiiUser.logOut();
14372     }
14373     requestData = {
14374       accessToken: options.access_token,
14375       openID: options.openID
14376     };
14377     return this._register("qq", "application/vnd.kii.AuthTokenQQRequest+json", requestData, options, callbacks);
14378   };
14379 
14380   KiiSCNQQ.prototype._logOut = function() {
14381     KiiSCNQQ.__super__._logOut.apply(this, arguments);
14382     return root.Kii.logger("Log out qq");
14383   };
14384 
14385   KiiSCNQQ.prototype._linkWithCurrentUser = function(options, callbacks) {
14386     var requestData;
14387     if (root.KiiUser.getCurrentUser() == null) {
14388       callbacks.failure(null, this._network, "No user logged in");
14389       return;
14390     }
14391     if ((options == null) || (!options.access_token && !options.openID)) {
14392       throw root.InvalidArgumentException('Both options.access_token and options.openID are required');
14393     } else if (!options.access_token) {
14394       throw root.InvalidArgumentException('options.access_token is required');
14395     } else if (!options.openID) {
14396       throw root.InvalidArgumentException('options.openID is required');
14397     }
14398     requestData = {
14399       accessToken: options.access_token,
14400       openID: options.openID
14401     };
14402     return this._link("qq", "application/vnd.kii.LinkQQRequest+json", requestData, options, callbacks);
14403   };
14404 
14405   KiiSCNQQ.prototype._unlinkFromCurrentUser = function(callbacks) {
14406     if (root.KiiUser.getCurrentUser() == null) {
14407       callbacks.failure(null, this._network, "No user logged in");
14408       return;
14409     }
14410     return this._unlink("qq", callbacks);
14411   };
14412 
14413   return KiiSCNQQ;
14414 
14415 })(root.KiiSocialConnectNetwork);
14416 
14417 
14418 /**
14419     @class Represents a server side code entry in KiiCloud.
14420  */
14421 
14422 root.KiiServerCodeEntry = (function() {
14423   function KiiServerCodeEntry(entryName, version, environmentVersion) {
14424     this.entryName = entryName;
14425     this.version = version;
14426     this.environmentVersion = environmentVersion;
14427   }
14428 
14429 
14430   /**
14431    Execute this server code entry.<br>
14432    If argument is an empty object or not type of Object, callbacks.failure or reject callback of promise will be called.<br>
14433    @param {Object} argument pass to the entry of script in the cloud.
14434       If null is specified, no argument pass to the script.
14435    @param {Object} [callbacks] called on completion of execution.
14436    @param {Function} callbacks.success callback called when operation succeeded.
14437    <br>1st argument: the KiiServerCodeEntry instance which this method was called on
14438    <br>2nd argument: the passed argument object
14439    <br>3rd argument: a KiiServerCodeExecResult instance
14440    @param {Function} callbacks.failure callback called when operation failed.
14441    <br>1st argument: the KiiServerCodeEntry instance which this method was called on
14442    <br>2nd argument: the passed argument object
14443    <br>3rd argument: executed result, which is null
14444    <br>4th argument: error string
14445    @return {Promise} return promise object.
14446     <ul>
14447       <li>fulfill callback function: function(params). params is Array instance.
14448         <ul>
14449           <li>params[0] is the KiiServerCodeEntry instance which this method was called on.</li>
14450           <li>params[1] is the passed argument object.</li>
14451           <li>params[2] is a KiiServerCodeExecResult instance.</li>
14452         </ul>
14453       </li>
14454       <li>reject callback function: function(error). error is an Error instance.
14455         <ul>
14456           <li>error.target is the KiiServerCodeEntry instance which this method was called on.</li>
14457           <li>error.message</li>
14458           <li>error.argument is passed argument object. </li>
14459         </ul>
14460       </li>
14461     </ul>
14462    @example
14463   // example to use callbacks directly
14464   // Instantiate with the endpoint.
14465   var entry = Kii.serverCodeEntry("main");
14466   
14467   // Set the custom parameters.
14468   var arg = {"username":"name_of_my_friend", "password":"password_for_my_friend"};
14469   
14470   // Example of executing the Server Code
14471   entry.execute(arg, {
14472   
14473      success: function(entry, argument, execResult) {
14474          // do something now that the user is logged in
14475      },
14476   
14477      failure: function(entry, argument, execResult, anErrorString) {
14478          // do something with the error response
14479      }
14480   });
14481   
14482   // example to use Promise
14483   // Instantiate with the endpoint.
14484   var entry = Kii.serverCodeEntry("main");
14485   
14486   // Set the custom parameters.
14487   var arg = {"username":"name_of_my_friend", "password":"password_for_my_friend"};
14488   
14489   // Example of executing the Server Code
14490   entry.execute(arg).then(
14491       function(params) {
14492           var entry = params[0];
14493           var argument = params[1];
14494           var execResult = params[2];
14495          // do something
14496       },
14497       function(error) {
14498          // do something with the error response
14499       }
14500   );
14501    */
14502 
14503   KiiServerCodeEntry.prototype.execute = function(argument, callbacks) {
14504     return new Promise((function(_this) {
14505       return function(resolve, reject) {
14506         var executeCallbacks;
14507         executeCallbacks = {
14508           success: function() {
14509             if (callbacks != null) {
14510               callbacks.success.apply(callbacks, arguments);
14511             }
14512             return resolve(arguments);
14513           },
14514           failure: function() {
14515             var error;
14516             if (callbacks != null) {
14517               callbacks.failure.apply(callbacks, arguments);
14518             }
14519             error = KiiUtilities._Error(arguments[3], _this);
14520             error.argument = arguments[1];
14521             return reject(error);
14522           }
14523         };
14524         return _this._executeUsingCallbacks(argument, executeCallbacks);
14525       };
14526     })(this));
14527   };
14528 
14529   KiiServerCodeEntry.prototype._executeUsingCallbacks = function(argument, callbacks) {
14530     var jsonBody, requestData, serverCodeExecutionCallBacks, url, versionName, wrapper, xhr, _ref;
14531     if (!(KiiUtilities._validateServerCodeEntryArgument(argument))) {
14532       return callbacks.failure(this, argument, null, root.InvalidArgumentException('arugment is invalid'));
14533     }
14534     requestData = argument != null ? argument : {};
14535     versionName = (_ref = this.version) != null ? _ref : "current";
14536     jsonBody = JSON.stringify(requestData);
14537     url = root.Kii.getBaseURL() + "/apps/" + root.Kii.getAppID() + ("/server-code/versions/" + versionName + "/" + this.entryName);
14538     if (this.environmentVersion) {
14539       url += "?environment-version=" + this.environmentVersion;
14540     }
14541     wrapper = KiiXHRWrapperFactory.createXHRWrapper("POST", url);
14542     xhr = wrapper.xhr;
14543     xhr.setRequestHeader("x-kii-appid", root.Kii.getAppID());
14544     xhr.setRequestHeader("x-kii-appkey", root.Kii.getAppKey());
14545     xhr.setRequestHeader("x-kii-sdk", root.KiiSDKClientInfo.getSDKClientInfo());
14546     xhr.setRequestHeader("Content-Type", "application/json");
14547     if (root.KiiUser.getCurrentUser() != null) {
14548       xhr.setRequestHeader("Authorization", "Bearer " + (root.KiiUser.getCurrentUser().getAccessToken()));
14549     }
14550     serverCodeExecutionCallBacks = {
14551       success: (function(_this) {
14552         return function() {
14553           var environmentVersion, errorString, execResult, returnObject, stepCount;
14554           stepCount = xhr.getResponseHeader("x-step-count");
14555           environmentVersion = xhr.getResponseHeader("x-environment-version");
14556           try {
14557             returnObject = JSON.parse(xhr.responseText);
14558             execResult = new root.KiiServerCodeExecResult(returnObject, stepCount, environmentVersion);
14559             if (callbacks != null) {
14560               return callbacks.success(_this, argument, execResult);
14561             }
14562           } catch (_error) {
14563             if (callbacks != null) {
14564               errorString = "fail to parse response. statusCode: " + xhr.status + " executedSteps: " + stepCount + " error code: failed_to_parse_response response: " + xhr.responseText;
14565               return callbacks.failure(_this, argument, null, errorString);
14566             }
14567           }
14568         };
14569       })(this),
14570       failure: (function(_this) {
14571         return function() {
14572           var errorMessage, errorString, json, stepCount;
14573           stepCount = xhr.getResponseHeader("x-step-count");
14574           errorMessage = {
14575             statusCode: xhr.status,
14576             executedSteps: stepCount
14577           };
14578           errorString = "fail to execute server code. statusCode: " + xhr.status + " executedSteps: " + stepCount;
14579           try {
14580             json = JSON.parse(xhr.responseText);
14581             if (json.errorCode != null) {
14582               errorString += " error code: " + json.errorCode;
14583             }
14584             if (json.message != null) {
14585               errorString += " message: " + json.message;
14586             }
14587             if ((json.details != null) && (json.details.message != null)) {
14588               return errorString += " detailMessage: " + json.details.message;
14589             }
14590           } catch (_error) {
14591             return errorString += " error code: failed_to_parse_response message: " + xhr.responseText;
14592           } finally {
14593             if (callbacks != null) {
14594               callbacks.failure(_this, argument, null, errorString);
14595             }
14596           }
14597         };
14598       })(this)
14599     };
14600     return wrapper.sendData(jsonBody, serverCodeExecutionCallBacks);
14601   };
14602 
14603 
14604   /**
14605       Get the entryName of this server code entry.
14606       @returns {String} entryName.
14607    */
14608 
14609   KiiServerCodeEntry.prototype.getEntryName = function() {
14610     return this.entryName;
14611   };
14612 
14613   return KiiServerCodeEntry;
14614 
14615 })();
14616 
14617 
14618 /**
14619     @class Represents a server side code execution result in KiiCloud.
14620  */
14621 
14622 root.KiiServerCodeExecResult = (function() {
14623   function KiiServerCodeExecResult(returnObject, exeSteps, environmentVersion) {
14624     this.returnObject = returnObject;
14625     this.exeSteps = exeSteps;
14626     this.environmentVersion = environmentVersion;
14627   }
14628 
14629 
14630   /**
14631       Get calculated number of executed steps.
14632       @returns {Number} calculated number of executed steps
14633    */
14634 
14635   KiiServerCodeExecResult.prototype.getExecutedSteps = function() {
14636     return this.exeSteps;
14637   };
14638 
14639 
14640   /**
14641       Get the version of Node.js which the server code was executed.
14642       @returns {String} version of Node.js
14643    */
14644 
14645   KiiServerCodeExecResult.prototype.getEnvironmentVersion = function() {
14646     return this.environmentVersion;
14647   };
14648 
14649 
14650   /**
14651       Get Object returned by server code entry.
14652       @returns {Object} returned by server code entry.
14653    */
14654 
14655   KiiServerCodeExecResult.prototype.getReturnedValue = function() {
14656     return this.returnObject;
14657   };
14658 
14659   return KiiServerCodeExecResult;
14660 
14661 })();
14662 
14663 
14664 /**
14665 @class Represents a Thing object
14666 @note KiiThing does not support removal of fields from Server.
14667 @property {Object} fields of this thing.
14668 For details refer to {@link KiiThing.register}
14669 @exports root.KiiThing as KiiThing
14670  */
14671 
14672 root.KiiThing = (function() {
14673   function KiiThing(fields) {
14674     this.fields = fields;
14675     this._getSubscriberPath = __bind(this._getSubscriberPath, this);
14676     this._setAuthToken = __bind(this._setAuthToken, this);
14677     this._getHttpURI = __bind(this._getHttpURI, this);
14678     this.pushSubscription = __bind(this.pushSubscription, this);
14679     this._listTopicsUsingCallbacks = __bind(this._listTopicsUsingCallbacks, this);
14680     this.listTopics = __bind(this.listTopics, this);
14681     this.topicWithName = __bind(this.topicWithName, this);
14682     this.encryptedBucketWithName = __bind(this.encryptedBucketWithName, this);
14683     this.bucketWithName = __bind(this.bucketWithName, this);
14684     this.updatePassword = __bind(this.updatePassword, this);
14685     this._changeStatus = __bind(this._changeStatus, this);
14686     this.enable = __bind(this.enable, this);
14687     this.disable = __bind(this.disable, this);
14688     this.unregisterOwner = __bind(this.unregisterOwner, this);
14689     this._getOwnerURL = __bind(this._getOwnerURL, this);
14690     this.registerOwnerWithPassword = __bind(this.registerOwnerWithPassword, this);
14691     this.registerOwner = __bind(this.registerOwner, this);
14692     this.isOwner = __bind(this.isOwner, this);
14693     this.deleteThing = __bind(this.deleteThing, this);
14694     this.update = __bind(this.update, this);
14695     this._refresh = __bind(this._refresh, this);
14696     this.refresh = __bind(this.refresh, this);
14697     this.getOnlineStatusModifiedAt = __bind(this.getOnlineStatusModifiedAt, this);
14698     this.isOnline = __bind(this.isOnline, this);
14699     this.getDisabled = __bind(this.getDisabled, this);
14700     this.getCreated = __bind(this.getCreated, this);
14701     this.getAccessToken = __bind(this.getAccessToken, this);
14702     this.getVendorThingID = __bind(this.getVendorThingID, this);
14703     this.getThingID = __bind(this.getThingID, this);
14704     this._renewThingFields = __bind(this._renewThingFields, this);
14705     if (this.fields != null) {
14706       this._renewThingFields(this.fields);
14707     }
14708   }
14709 
14710   KiiThing.prototype._renewThingFields = function(respJson) {
14711     this._online = null;
14712     this._onlineStatusModifiedAt = null;
14713     this.fields = respJson;
14714     this._thingID = respJson._thingID;
14715     this._vendorThingID = respJson._vendorThingID;
14716     this._accessToken = respJson._accessToken;
14717     this._created = new Date(respJson._created);
14718     this._disabled = respJson._disabled;
14719     if (respJson._online != null) {
14720       this._online = respJson._online;
14721     }
14722     if (respJson._onlineStatusModifiedAt != null) {
14723       this._onlineStatusModifiedAt = new Date(respJson._onlineStatusModifiedAt);
14724     }
14725     delete this.fields._thingID;
14726     delete this.fields._vendorThingID;
14727     delete this.fields._accessToken;
14728     delete this.fields._created;
14729     return delete this.fields._disabled;
14730   };
14731 
14732 
14733   /** Get thing ID.
14734   @return {String} thing id
14735    */
14736 
14737   KiiThing.prototype.getThingID = function() {
14738     return this._thingID;
14739   };
14740 
14741 
14742   /** Get vendor thing ID.
14743   @return {String} vendor thing id
14744    */
14745 
14746   KiiThing.prototype.getVendorThingID = function() {
14747     return this._vendorThingID;
14748   };
14749 
14750 
14751   /** Get access token of this thing.
14752   @return {String} access token of this thing.
14753    */
14754 
14755   KiiThing.prototype.getAccessToken = function() {
14756     return this._accessToken;
14757   };
14758 
14759 
14760   /** Get created time of this thing.
14761   @return {Date} created time of this thing.
14762    */
14763 
14764   KiiThing.prototype.getCreated = function() {
14765     return this._created;
14766   };
14767 
14768 
14769   /** Get disabled status of this thing.
14770   @return {Boolean} true if thing is disabled, false otherwise.
14771    */
14772 
14773   KiiThing.prototype.getDisabled = function() {
14774     return this._disabled;
14775   };
14776 
14777 
14778   /** Get online status of the thing.
14779   @return {Boolean} true if the thing is online, false otherwise. The return value will be null initially until the thing is connected for the first time.
14780    */
14781 
14782   KiiThing.prototype.isOnline = function() {
14783     return this._online;
14784   };
14785 
14786 
14787   /** Get online status modified date of the thing.
14788   @return {Date} online status modified time of this thing. The date will be null initially until the thing is connected for the first time.
14789    */
14790 
14791   KiiThing.prototype.getOnlineStatusModifiedAt = function() {
14792     return this._onlineStatusModifiedAt;
14793   };
14794 
14795 
14796   /** Register thing in KiiCloud.<br>
14797   This API doesnt require users login Anonymous user can register thing.
14798   <br>
14799   Propertis started with '_' in the fields is reserved by Kii Cloud.<br>
14800   Those properties are indexed in Kii Cloud storage.<br>
14801   Properties not started with '_' is custom properties defined by developer.<br>
14802   Custom properties are not indexed in KiiCloud storage.<br>
14803   Following properties are readonly and ignored on creation/{@link #update} of thing.<br>
14804   '_thingID', '_created', '_accessToken' <br>
14805   Following properties are readonly after creation and will be ignored on {@link #update} of thing.<br>
14806   '_vendorThingID', '_password'<br>
14807   As Property prefixed with '_' is reserved by Kii Cloud,
14808   properties other than ones described in the parameter secion
14809   and '_layoutPosition' are ignored on creation/{@link #update} of thing.<br>
14810   Those ignored properties won't be removed from fields object passed as argument.
14811   However it won't be reflected to fields object property of created/updated Thing.
14812   @param {Object} fields of the thing to be registered.
14813   @param {String} fields._vendorThingID thing identifier given by thing vendor.
14814   @param {String} fields._password thing password given by thing vendor.
14815   @param {String} [fields._thingType] thing type given by thing vendor.
14816   @param {String} [fields._vendor] vendor identifier given by thing vendor.
14817   @param {String} [fields._firmwareVersion] firmware version given by thing vendor.
14818   @param {String} [fields._lot] lot identifier given by thing vendor.
14819   @param {String} [fields._productName] product name given by thing vendor.
14820   @param {String} [fields._stringField1] arbitrary string field.
14821   @param {String} [fields._stringField2] arbitrary string field.
14822   @param {String} [fields._stringField3] arbitrary string field.
14823   @param {String} [fields._stringField4] arbitrary string field.
14824   @param {String} [fields._stringField5] arbitrary string field.
14825   @param {Number} [fields._numberField1] arbitrary number field.
14826   @param {Number} [fields._numberField2] arbitrary number field.
14827   @param {Number} [fields._numberField3] arbitrary number field.
14828   @param {Number} [fields._numberField4] arbitrary number field.
14829   @param {Number} [fields._numberField5] arbitrary number field.
14830   @param {Object} [callbacks] object holds callback functions.
14831   @param {Function} callbacks.success callback called when operation succeeded.
14832   <br>argument is registered thing.
14833   @param {Function} callbacks.failure callback called when operation failed.
14834   <br>argument is Error object.
14835   @return {Promise} return promise object.
14836     <ul>
14837       <li>fulfill callback function: function(thing). thing is a KiiThing instance.</li>
14838       <li>reject callback function: function(error). error is an Error instance.
14839         <ul>
14840           <li>error.target is the KiiThing instance.</li>
14841           <li>error.message</li>
14842         </ul>
14843       </li>
14844     </ul>
14845   @example
14846   // example to use callbacks directly
14847   KiiThing.register(
14848       {
14849           _vendorThingID: "thing-XXXX-YYYY-ZZZZZ",
14850           _password: "thing-password",
14851           _thingType: "thermometer",
14852           yourCustomObj: // Arbitrary key can be used.
14853           { // Object, Array, Number, String can be used. Should be compatible with JSON.
14854               yourCustomKey1: "value",
14855               yourCustomKey2: 100
14856           }
14857       },
14858       {
14859           success: function(thing) {
14860               // Register Thing succeeded.
14861           },
14862           failure: function(error) {
14863               // Handle error.
14864           }
14865       }
14866   );
14867   
14868   // example to use Promise
14869   KiiThing.register(
14870       {
14871           _vendorThingID: "thing-XXXX-YYYY-ZZZZZ",
14872           _password: "thing-password",
14873           _thingType: "thermometer",
14874           yourCustomObj: // Arbitrary key can be used.
14875           { // Object, Array, Number, String can be used. Should be compatible with JSON.
14876               yourCustomKey1: "value",
14877               yourCustomKey2: 100
14878           }
14879       }
14880   ).then(
14881       function(thing) {
14882           // Register Thing succeeded.
14883       },
14884       function(error) {
14885           // Handle error.
14886       }
14887   );
14888    */
14889 
14890   KiiThing.register = function(fields, callbacks) {
14891     return new Promise(function(resolve, reject) {
14892       var sendCallbacks, wrapper;
14893       wrapper = KiiXHRWrapperFactory.createXHRWrapper('POST', "" + (root.Kii.getBaseURL()) + "/apps/" + (root.Kii.getAppID()) + "/things");
14894       wrapper.setKiiHeaders();
14895       wrapper.setContentType("application/vnd.kii.ThingRegistrationAndAuthorizationRequest+json");
14896       sendCallbacks = {
14897         success: function() {
14898           var respJson, thing;
14899           respJson = JSON.parse(decodeURIComponent(wrapper.xhr.responseText));
14900           thing = new root.KiiThing(respJson);
14901           if (callbacks != null) {
14902             callbacks.success(thing);
14903           }
14904           return resolve(thing);
14905         },
14906         failure: function() {
14907           var errObj, errString;
14908           errString = wrapper.getErrorString("register thing");
14909           errObj = KiiUtilities._Error(errString);
14910           if (callbacks != null) {
14911             callbacks.failure(errObj);
14912           }
14913           return reject(errObj);
14914         }
14915       };
14916       return wrapper.sendData(JSON.stringify(fields), sendCallbacks);
14917     });
14918   };
14919 
14920 
14921   /** Perform a query to get the owned things.
14922   
14923   <br><br>The query will be executed against the server, returning a result set.
14924   @param KiiThingQuery thingQuery thingQuery.
14925   @param Object callbacks An object with callback methods defined
14926   @param {Function} callbacks.success The callback method to call on a successful query request
14927   @param {Function} callbacks.failure The callback method to call on a failed query request
14928   @return {Promise} return promise object.
14929     <ul>
14930       <li>fulfill callback function: function(result). result is KiiThingQueryResult instance.</li>
14931       <li>reject callback function: function(error). error is an Error instance.
14932         <ul>
14933           <li>error.target is the KiiThing instance.</li>
14934           <li>error.message</li>
14935         </ul>
14936       </li>
14937     </ul>
14938    */
14939 
14940   KiiThing.executeQuery = function(thingQuery, callbacks) {
14941     return new Promise(function(resolve, reject) {
14942       var errObj, sendCallbacks, wrapper;
14943       if (thingQuery == null) {
14944         errObj = KiiUtilities._Error("thingQuery is null");
14945         if (callbacks != null) {
14946           callbacks.failure(errObj);
14947         }
14948         reject(errObj);
14949         return;
14950       }
14951       wrapper = KiiXHRWrapperFactory.createXHRWrapper('POST', "" + (root.Kii.getBaseURL()) + "/apps/" + (root.Kii.getAppID()) + "/things/query");
14952       wrapper.setKiiHeaders();
14953       wrapper.setCurrentUserToken();
14954       wrapper.setContentType("application/vnd.kii.ThingQueryRequest+json");
14955       sendCallbacks = {
14956         success: function() {
14957           var queryResult, respJson, result, things, _i, _len, _ref;
14958           respJson = JSON.parse(decodeURIComponent(wrapper.xhr.responseText));
14959           things = [];
14960           _ref = respJson.results;
14961           for (_i = 0, _len = _ref.length; _i < _len; _i++) {
14962             result = _ref[_i];
14963             things.push(new root.KiiThing(result));
14964           }
14965           queryResult = new root.KiiThingQueryResult(thingQuery, things, respJson.nextPaginationKey);
14966           if (callbacks != null) {
14967             callbacks.success(queryResult);
14968           }
14969           return resolve(queryResult);
14970         },
14971         failure: function() {
14972           var errString;
14973           errString = wrapper.getErrorString("query thing");
14974           errObj = KiiUtilities._Error(errString);
14975           if (callbacks != null) {
14976             callbacks.failure(errObj);
14977           }
14978           return reject(errObj);
14979         }
14980       };
14981       return wrapper.sendData(JSON.stringify(thingQuery._dictValue()), sendCallbacks);
14982     });
14983   };
14984 
14985 
14986   /**
14987   Retrieve the latest thing information from KiiCloud.
14988   <br>This API is authorized by owner of thing.
14989   <br>Need user login who owns this thing before execute this API.
14990   <br>To let users to own thing, please call {@link KiiThing#registerOwner}
14991   <br>Note: if you obtain thing instance from {@link KiiAppAdminContext},
14992   API is authorized by app admin.<br>
14993   @param {Object} [callbacks] object holds callback functions.
14994   @param {Function} callbacks.success callback called when operation succeeded.
14995   <br>argument is refreshed thing.
14996   @param {Function} callbacks.failure callback called when operation failed.
14997   <br>argument is Error object.
14998   @return {Promise} return promise object.
14999     <ul>
15000       <li>fulfill callback function: function(thing). thing is KiiThing instance.</li>
15001       <li>reject callback function: function(error). error is an Error instance.
15002         <ul>
15003           <li>error.target is the KiiThing instance which this method was called on.</li>
15004           <li>error.message</li>
15005         </ul>
15006       </li>
15007     </ul>
15008   @example
15009   // example to use callbacks directly
15010   // assume thing is already registered.
15011   thing.refresh({
15012       success: function(thing) {
15013           // Refresh succeeded.
15014       },
15015       failure: function(error) {
15016           // Handle error.
15017       }
15018   });
15019   
15020   // example to use Promise
15021   // assume thing is already registered.
15022   thing.refresh().then(
15023       function(thing) {
15024           // Refresh succeeded.
15025       },
15026       function(error) {
15027           // Handle error.
15028       }
15029   );
15030    */
15031 
15032   KiiThing.prototype.refresh = function(callbacks) {
15033     return new Promise((function(_this) {
15034       return function(resolve, reject) {
15035         var _refreshCallbacks;
15036         _refreshCallbacks = {
15037           success: function(respJson) {
15038             _this._renewThingFields(respJson);
15039             if (callbacks != null) {
15040               callbacks.success(_this);
15041             }
15042             return resolve(_this);
15043           },
15044           failure: function(errString) {
15045             var errObj;
15046             errObj = KiiUtilities._Error(errString, _this);
15047             if (callbacks != null) {
15048               callbacks.failure(errObj);
15049             }
15050             return reject(errObj);
15051           }
15052         };
15053         return _this._refresh(_refreshCallbacks);
15054       };
15055     })(this));
15056   };
15057 
15058   KiiThing.prototype._refresh = function(callbacks) {
15059     var qualifiedID, sendCallbacks, wrapper;
15060     if (this._thingID != null) {
15061       qualifiedID = this._thingID;
15062     } else {
15063       qualifiedID = "VENDOR_THING_ID:" + this._vendorThingID;
15064     }
15065     wrapper = KiiXHRWrapperFactory.createXHRWrapper('GET', "" + (root.Kii.getBaseURL()) + "/apps/" + (root.Kii.getAppID()) + "/things/" + qualifiedID);
15066     wrapper.setKiiHeaders();
15067     this._setAuthToken(wrapper);
15068     sendCallbacks = {
15069       success: (function(_this) {
15070         return function() {
15071           var respJson;
15072           respJson = JSON.parse(decodeURIComponent(wrapper.xhr.responseText));
15073           return callbacks.success(respJson);
15074         };
15075       })(this),
15076       failure: (function(_this) {
15077         return function() {
15078           var errString;
15079           errString = wrapper.getErrorString("refresh thing");
15080           return callbacks.failure(errString);
15081         };
15082       })(this)
15083     };
15084     return wrapper.send(sendCallbacks);
15085   };
15086 
15087 
15088   /**
15089   Update registered thing information in Kii Cloud
15090   <br>This API is authorized by owner of thing.
15091   <br>Need user login who owns this thing before execute this API.
15092   <br>To let users to own thing, please call {@link KiiThing#registerOwner}
15093   <br>Note: if you obtain thing instance from {@link KiiAppAdminContext},
15094   API is authorized by app admin.<br>
15095   
15096   @param {Object} [callbacks] object holds callback functions.
15097   @param {Function} callbacks.success callback called when operation succeeded.
15098   <br>argument is updated thing.
15099   @param {Function} callbacks.failure callback called when operation failed.
15100   <br>argument is Error object.
15101   @return {Promise} return promise object.
15102     <ul>
15103       <li>fulfill callback function: function(thing). thing is a KiiThing instance.</li>
15104       <li>reject callback function: function(error). error is an Error instance.
15105         <ul>
15106           <li>error.target is the KiiThing instance which this method was called on.</li>
15107           <li>error.message</li>
15108         </ul>
15109       </li>
15110     </ul>
15111   @see KiiThing.register
15112   @example
15113   // example to use callbacks directly
15114   // assume thing is already registered.
15115   thing.fields._stringField1 = "new string value";
15116   thing.fields.customObject = {
15117       "customField1" : "abcd",
15118       "customField2" : 123
15119   };
15120   thing.update({
15121       success: function(thing) {
15122           // Update succeeded.
15123       },
15124       failure: function(error) {
15125           // Handle error.
15126       }
15127   });
15128   
15129   // example to use Promise
15130   // assume thing is already registered.
15131   thing.fields._stringField1 = "new string value";
15132   thing.fields.customObject = {
15133       "customField1" : "abcd",
15134       "customField2" : 123
15135   };
15136   thing.update().then(
15137       function(thing) {
15138           // Update succeeded.
15139       },
15140       function(error) {
15141           // Handle error.
15142       }
15143   );
15144    */
15145 
15146   KiiThing.prototype.update = function(callbacks) {
15147     return new Promise((function(_this) {
15148       return function(resolve, reject) {
15149         var _refreshCallbacks;
15150         _refreshCallbacks = {
15151           success: function(respJson) {
15152             var k, sendCallbacks, v, wrapper, _ref;
15153             _ref = _this.fields;
15154             for (k in _ref) {
15155               v = _ref[k];
15156               respJson[k] = v;
15157             }
15158             _this.fields = respJson;
15159             wrapper = KiiXHRWrapperFactory.createXHRWrapper('PATCH', "" + (root.Kii.getBaseURL()) + "/apps/" + (root.Kii.getAppID()) + "/things/" + _this._thingID);
15160             wrapper.setKiiHeaders();
15161             wrapper.setContentType("application/vnd.kii.ThingUpdateRequest+json");
15162             _this._setAuthToken(wrapper);
15163             sendCallbacks = {
15164               success: function() {
15165                 if (callbacks != null) {
15166                   callbacks.success(_this);
15167                 }
15168                 return resolve(_this);
15169               },
15170               failure: function() {
15171                 var errObj, errString;
15172                 errString = wrapper.getErrorString("update thing");
15173                 errObj = KiiUtilities._Error(errString, _this);
15174                 if (callbacks != null) {
15175                   callbacks.failure(errObj);
15176                 }
15177                 return reject(errObj);
15178               }
15179             };
15180             wrapper.sendData(JSON.stringify(_this.fields), sendCallbacks);
15181             return typeof _this._testOnUpdateRequest === "function" ? _this._testOnUpdateRequest() : void 0;
15182           },
15183           failure: function(errString) {
15184             var errObj;
15185             errObj = KiiUtilities._Error(errString, _this);
15186             if (callbacks != null) {
15187               callbacks.failure(errObj);
15188             }
15189             return reject(errObj);
15190           }
15191         };
15192         return _this._refresh(_refreshCallbacks);
15193       };
15194     })(this));
15195   };
15196 
15197 
15198   /**
15199   Delete registered thing in Kii Cloud.
15200   <br>This API is authorized by owner of thing.
15201   <br>Need user login who owns this thing before execute this API.
15202   <br>To let users to own thing, please call {@link KiiThing#registerOwner}
15203   <br>Note: if you obtain thing instance from {@link KiiAppAdminContext},
15204   API is authorized by app admin.<br>
15205   
15206   It will delete bucket, topic which belongs to this thing,
15207   entity belongs to the bucket/topic and all ownership information of thing.
15208   This operation can not be reverted. Please carefully use this.
15209   @param {Object} [callbacks] object holds callback functions.
15210   @param {Function} callbacks.success callback called when operation succeeded.
15211   <br>argument is updated thing.
15212   @param {Function} callbacks.failure callback called when operation failed.
15213   <br>argument is Error object.
15214   @return {Promise} return promise object.
15215     <ul>
15216       <li>fulfill callback function: function(thing). thing is a KiiThing instance.</li>
15217       <li>reject callback function: function(error). error is an Error instance.
15218         <ul>
15219           <li>error.target is the KiiThing instance which this method was called on.</li>
15220           <li>error.message</li>
15221         </ul>
15222       </li>
15223     </ul>
15224   @example
15225   // example to use callbacks directly
15226   // assume thing is already registered.
15227   thing.deleteThing({
15228       success: function(thing) {
15229           // Delete succeeded.
15230       },
15231       failure: function(error) {
15232           // Handle error.
15233       }
15234   });
15235   
15236   // example to use Promise
15237   // assume thing is already registered.
15238   thing.deleteThing().then(
15239       function(thing) {
15240           // Delete succeeded.
15241       },
15242       function(error) {
15243           // Handle error.
15244       }
15245   );
15246    */
15247 
15248   KiiThing.prototype.deleteThing = function(callbacks) {
15249     return new Promise((function(_this) {
15250       return function(resolve, reject) {
15251         var sendCallbacks, wrapper;
15252         wrapper = KiiXHRWrapperFactory.createXHRWrapper('DELETE', "" + (root.Kii.getBaseURL()) + "/apps/" + (root.Kii.getAppID()) + "/things/" + _this._thingID);
15253         wrapper.setKiiHeaders();
15254         _this._setAuthToken(wrapper);
15255         sendCallbacks = {
15256           success: function() {
15257             if (callbacks != null) {
15258               callbacks.success(_this);
15259             }
15260             return resolve(_this);
15261           },
15262           failure: function() {
15263             var errObj, errString;
15264             errString = wrapper.getErrorString("delete thing");
15265             errObj = KiiUtilities._Error(errString, _this);
15266             if (callbacks != null) {
15267               callbacks.failure(errObj);
15268             }
15269             return reject(errObj);
15270           }
15271         };
15272         return wrapper.send(sendCallbacks);
15273       };
15274     })(this));
15275   };
15276 
15277 
15278   /**
15279   Check if user/ group is owner of the thing.
15280   <br>This API is authorized by owner of thing.
15281   <br>Need user login before execute this API.
15282   <br>To let users to own Thing, please call {@link KiiThing#registerOwner}
15283   <br>Note: if you obtain thing instance from {@link KiiAppAdminContext},
15284   API is authorized by app admin.<br>
15285   
15286   @param {KiiUser or KiiGroup} owner whether the instance is owner of thing or not.
15287   @param {Object} [callbacks] object holds callback functions.
15288   @param {Function} callbacks.success callback called when operation succeeded.
15289   <br>1st argument: thing object.
15290   <br>2nd argument: user/group object.
15291   <br>3rd argument: result whether the user/group owns this thing.
15292   @param {Function} callbacks.failure callback called when operation failed.
15293   <br>argument is Error object.
15294   @return {Promise} return promise object.
15295     <ul>
15296       <li>fulfill callback function: function(params). params is an Array instance.
15297         <ul>
15298           <li>params[0] is the KiiThing instance which this method was called on.</li>
15299           <li>params[1] is a KiiUser/KiiGroup instance.</li>
15300           <li>params[2] is Boolean value, true is the user/group is owner of the thing, otherwise false.</li>
15301         </ul>
15302       </li>
15303       <li>reject callback function: function(error). error is an Error instance.
15304         <ul>
15305           <li>error.target is the KiiThing instance which this method was called on.</li>
15306           <li>error.message</li>
15307         </ul>
15308       </li>
15309     </ul>
15310   @example
15311   // example to use callbacks directly
15312   // assume thing/user is already registered.
15313   var user = KiiUser.userWithURI("kiicloud://users/xxxyyyy");
15314   thing.isOwner(user, {
15315       success: function(thing, user, isOwner) {
15316           if (isOwner) {
15317               // user is owner of the thing.
15318           } else {
15319               // user is not owner of the thing.
15320           }
15321       },
15322       failure: function(error) {
15323           // Handle error.
15324       }
15325   });
15326   
15327   // example to use Promise
15328   // assume thing/user is already registered.
15329   var user = KiiUser.userWithURI("kiicloud://users/xxxyyyy");
15330   thing.isOwner(user).then(
15331       function(params) {
15332           var thing = params[0];
15333           var user = params[1];
15334           var isOwner = params[2];
15335           if (isOwner) {
15336               // user is owner of the thing.
15337           } else {
15338               // user is not owner of the thing.
15339           }
15340       },
15341       function(error) {
15342           // Handle error.
15343       }
15344   );
15345    */
15346 
15347   KiiThing.prototype.isOwner = function(owner, callbacks) {
15348     return new Promise((function(_this) {
15349       return function(resolve, reject) {
15350         var errObj, message, ownerUrl, sendCallbacks, wrapper;
15351         try {
15352           ownerUrl = _this._getOwnerURL(_this._thingID, owner);
15353         } catch (_error) {
15354           message = _error;
15355           errObj = KiiUtilities._Error(message, _this);
15356           if (callbacks != null) {
15357             callbacks.failure(errObj);
15358           }
15359           reject(errObj);
15360           return;
15361         }
15362         wrapper = KiiXHRWrapperFactory.createXHRWrapper('HEAD', ownerUrl);
15363         wrapper.setKiiHeaders();
15364         _this._setAuthToken(wrapper);
15365         sendCallbacks = {
15366           success: function() {
15367             if (callbacks != null) {
15368               callbacks.success(_this, owner, true);
15369             }
15370             return resolve([_this, owner, true]);
15371           },
15372           failure: function() {
15373             var errString;
15374             if (wrapper.xhr.status === 404) {
15375               if (callbacks != null) {
15376                 callbacks.success(_this, owner, false);
15377               }
15378               resolve([_this, owner, false]);
15379               return;
15380             }
15381             errString = wrapper.getErrorString("register owner");
15382             errObj = KiiUtilities._Error(errString, _this);
15383             if (callbacks != null) {
15384               callbacks.failure(errObj);
15385             }
15386             return reject(errObj);
15387           }
15388         };
15389         return wrapper.send(sendCallbacks);
15390       };
15391     })(this));
15392   };
15393 
15394 
15395   /**
15396   Register user/group as owner of this thing.
15397   <br>Need user login before execute this API.
15398   <br>Note: if you obtain thing instance from {@link KiiAppAdminContext},
15399   API is authorized by app admin.<br>
15400   
15401   @param {KiiUser or KiiGroup} owner to be registered as owner.
15402   @param {Object} [callbacks] object holds callback functions.
15403   @param {Function} callbacks.success callback called when operation succeeded.
15404   <br>1st argument: thing object.
15405   <br>2nd argument: user/group object registered as owner.
15406   @param {Function} callbacks.failure callback called when operation failed.
15407   <br>argument is Error object.
15408   @return {Promise} return promise object.
15409     <ul>
15410       <li>fulfill callback function: function(params). params is an Array instance.
15411         <ul>
15412           <li>params[0] is the KiiThing instance which this method was called on.</li>
15413           <li>params[1] is a KiiUser/KiiGroup instance.</li>
15414         </ul>
15415       </li>
15416       <li>reject callback function: function(error). error is an Error instance.
15417         <ul>
15418           <li>error.target is the KiiThing instance which this method was called on.</li>
15419           <li>error.message</li>
15420         </ul>
15421       </li>
15422     </ul>
15423   @deprecated Use {@link KiiThing.registerOwnerWithPassword} instead.
15424   @example
15425   // example to use callbacks directly
15426   // assume thing/group is already registered.
15427   var group = KiiGroup.groupWithURI("kiicloud://groups/xxxyyyy");
15428   thing.registerOwner(group, {
15429       success: function(thing, group) {
15430           // Register owner succeeded.
15431       },
15432       failure: function(error) {
15433           // Handle error.
15434       }
15435   });
15436   
15437   // example to use Promise
15438   // assume thing/group is already registered.
15439   var group = KiiGroup.groupWithURI("kiicloud://groups/xxxyyyy");
15440   thing.registerOwner(group).then(
15441       function(params) {
15442           // Register owner succeeded.
15443           var thing = params[0];
15444           var group = params[1];
15445       },
15446       function(error) {
15447           // Handle error.
15448       }
15449   );
15450    */
15451 
15452   KiiThing.prototype.registerOwner = function(owner, callbacks) {
15453     return new Promise((function(_this) {
15454       return function(resolve, reject) {
15455         var errObj, message, ownerUrl, sendCallbacks, wrapper;
15456         try {
15457           ownerUrl = _this._getOwnerURL(_this._thingID, owner);
15458         } catch (_error) {
15459           message = _error;
15460           errObj = KiiUtilities._Error(message, _this);
15461           if (callbacks != null) {
15462             callbacks.failure(errObj);
15463           }
15464           reject(errObj);
15465           return;
15466         }
15467         wrapper = KiiXHRWrapperFactory.createXHRWrapper('PUT', ownerUrl);
15468         wrapper.setKiiHeaders();
15469         _this._setAuthToken(wrapper);
15470         sendCallbacks = {
15471           success: function() {
15472             if (callbacks != null) {
15473               callbacks.success(_this, owner);
15474             }
15475             return resolve([_this, owner]);
15476           },
15477           failure: function() {
15478             var errString;
15479             errString = wrapper.getErrorString("register owner");
15480             errObj = KiiUtilities._Error(errString, _this);
15481             if (callbacks != null) {
15482               callbacks.failure(errObj);
15483             }
15484             return reject(errObj);
15485           }
15486         };
15487         return wrapper.send(sendCallbacks);
15488       };
15489     })(this));
15490   };
15491 
15492 
15493   /**
15494   Register user/group as owner of this thing.
15495   <br>Need user login before execute this API.
15496   <br>Note: if you obtain thing instance from {@link KiiAppAdminContext},
15497   API is authorized by app admin.<br>
15498   
15499   @param {KiiUser or KiiGroup} owner to be registered as owner.
15500   @param {String} [password] the thing password
15501   @param {Object} [callbacks] object holds callback functions.
15502   @param {Function} callbacks.success callback called when operation succeeded.
15503   <br>1st argument: thing object.
15504   <br>2nd argument: user/group object registered as owner.
15505   @param {Function} callbacks.failure callback called when operation failed.
15506   <br>argument is Error object.
15507   @return {Promise} return promise object.
15508     <ul>
15509       <li>fulfill callback function: function(params). params is an Array instance.
15510         <ul>
15511           <li>params[0] is the KiiThing instance which this method was called on.</li>
15512           <li>params[1] is a KiiUser/KiiGroup instance.</li>
15513         </ul>
15514       </li>
15515       <li>reject callback function: function(error). error is an Error instance.
15516         <ul>
15517           <li>error.target is the KiiThing instance which this method was called on.</li>
15518           <li>error.message</li>
15519         </ul>
15520       </li>
15521     </ul>
15522   @example
15523   // example to use callbacks directly
15524   // assume thing/group is already registered.
15525   var group = KiiGroup.groupWithURI("kiicloud://groups/xxxyyyy");
15526   thing.registerOwnerWithPassword(group, "Thing password", {
15527       success: function(thing, group) {
15528           // Register owner succeeded.
15529       },
15530       failure: function(error) {
15531           // Handle error.
15532       }
15533   });
15534   
15535   // example to use Promise
15536   // assume thing/group is already registered.
15537   var group = KiiGroup.groupWithURI("kiicloud://groups/xxxyyyy");
15538   thing.registerOwnerWithPassword(group, "Thing password").then(
15539       function(params) {
15540           // Register owner succeeded.
15541           var thing = params[0];
15542           var group = params[1];
15543       },
15544       function(error) {
15545           // Handle error.
15546       }
15547   );
15548    */
15549 
15550   KiiThing.prototype.registerOwnerWithPassword = function(owner, password, callbacks) {
15551     return new Promise((function(_this) {
15552       return function(resolve, reject) {
15553         var registerCallbacks;
15554         registerCallbacks = {
15555           success: function() {
15556             if (callbacks != null) {
15557               callbacks.success(_this, owner);
15558             }
15559             return resolve([_this, owner]);
15560           },
15561           failure: function(error) {
15562             if (callbacks != null) {
15563               callbacks.failure(error);
15564             }
15565             return reject(error);
15566           }
15567         };
15568         return root.KiiThing._registerOwnerWithIdentifierAndPassword(_this._thingID, owner, password, registerCallbacks);
15569       };
15570     })(this));
15571   };
15572 
15573 
15574   /**
15575   Register user/group as owner of specified thing.
15576   <br>Need user login before execute this API.
15577   <br>Note: if you obtain thing instance from {@link KiiAppAdminContext},
15578   API is authorized by app admin.<br>
15579   
15580   @param {String} thingID The ID of thing
15581   @param {KiiUser or KiiGroup} owner instance of KiiUser/KiiGroup to be registered as owner.
15582   @param {Object} [callbacks] object holds callback functions.
15583   @param {Function} callbacks.success callback called when operation succeeded.
15584   <br>1st argument: user/group object registered as owner.
15585   @param {Function} callbacks.failure callback called when operation failed.
15586   <br>argument is Error object.
15587   @return {Promise} return promise object.
15588     <ul>
15589       <li>fulfill callback function: function(params). params is an Array instance.
15590         <ul>
15591           <li>params[0] is a KiiUser/KiiGroup instance.</li>
15592         </ul>
15593       </li>
15594       <li>reject callback function: function(error). error is an Error instance.
15595         <ul>
15596           <li>error.message</li>
15597         </ul>
15598       </li>
15599     </ul>
15600   @deprecated Use {@link KiiThing.registerOwnerWithThingIDAndPassword} instead.
15601   @example
15602   // example to use callbacks directly
15603   // assume thing/group is already registered.
15604   var group = KiiGroup.groupWithURI("kiicloud://groups/xxxyyyy");
15605   KiiThing.registerOwnerWithThingID("th.xxxx-yyyy-zzzz", group, {
15606       success: function(group) {
15607           // Register owner succeeded.
15608       },
15609       failure: function(error) {
15610           // Handle error.
15611       }
15612   });
15613   
15614   // example to use Promise
15615   // assume thing/group is already registered.
15616   var group = KiiGroup.groupWithURI("kiicloud://groups/xxxyyyy");
15617   KiiThing.registerOwnerWithThingID("th.xxxx-yyyy-zzzz", group).then(
15618       function(params) {
15619           // Register owner succeeded.
15620           var group = params[0];
15621       },
15622       function(error) {
15623           // Handle error.
15624       }
15625   );
15626    */
15627 
15628   KiiThing.registerOwnerWithThingID = function(thingID, owner, callbacks) {
15629     return root.KiiThing._registerOwnerWithIdentifier(thingID, owner, callbacks);
15630   };
15631 
15632 
15633   /**
15634   Register user/group as owner of specified thing.
15635   <br>Need user login before execute this API.
15636   <br>Note: if you obtain thing instance from {@link KiiAppAdminContext},
15637   API is authorized by app admin.<br>
15638   
15639   @param {String} thingID The ID of thing
15640   @param {KiiUser or KiiGroup} owner instance of KiiUser/KiiGroup to be registered as owner.
15641   @param {String} [password] the thing password
15642   @param {Object} [callbacks] object holds callback functions.
15643   @param {Function} callbacks.success callback called when operation succeeded.
15644   <br>1st argument: user/group object registered as owner.
15645   @param {Function} callbacks.failure callback called when operation failed.
15646   <br>argument is Error object.
15647   @return {Promise} return promise object.
15648     <ul>
15649       <li>fulfill callback function: function(owner).
15650         <ul>
15651           <li>owner is a KiiUser/KiiGroup instance.</li>
15652         </ul>
15653       </li>
15654       <li>reject callback function: function(error). error is an Error instance.
15655         <ul>
15656           <li>error.message</li>
15657         </ul>
15658       </li>
15659     </ul>
15660   @example
15661   // example to use callbacks directly
15662   // assume thing/group is already registered.
15663   var group = KiiGroup.groupWithURI("kiicloud://groups/xxxyyyy");
15664   KiiThing.registerOwnerWithThingIDAndPassword("th.xxxx-yyyy-zzzz", group, "Thing password", {
15665       success: function(owner) {
15666           // Register owner succeeded.
15667       },
15668       failure: function(error) {
15669           // Handle error.
15670       }
15671   });
15672   
15673   // example to use Promise
15674   // assume thing/group is already registered.
15675   var group = KiiGroup.groupWithURI("kiicloud://groups/xxxyyyy");
15676   KiiThing.registerOwnerWithThingIDAndPassword("th.xxxx-yyyy-zzzz", group, "Thing password").then(
15677       function(owner) {
15678           // Register owner succeeded.
15679       },
15680       function(error) {
15681           // Handle error.
15682       }
15683   );
15684    */
15685 
15686   KiiThing.registerOwnerWithThingIDAndPassword = function(thingID, owner, password, callbacks) {
15687     return root.KiiThing._registerOwnerWithIdentifierAndPassword(thingID, owner, password, callbacks);
15688   };
15689 
15690 
15691   /**
15692   Register user/group as owner of specified thing.
15693   <br>Need user login before execute this API.
15694   <br>Note: if you obtain thing instance from {@link KiiAppAdminContext},
15695   API is authorized by app admin.<br>
15696   
15697   @param {String} vendorThingID The vendor thing ID of thing
15698   @param {KiiUser or KiiGroup} owner instance of KiiUser/KiiGroup to be registered as owner.
15699   @param {Object} [callbacks] object holds callback functions.
15700   @param {Function} callbacks.success callback called when operation succeeded.
15701   <br>1st argument: user/group object registered as owner.
15702   @param {Function} callbacks.failure callback called when operation failed.
15703   <br>argument is Error object.
15704   @return {Promise} return promise object.
15705     <ul>
15706       <li>fulfill callback function: function(params). params is an Array instance.
15707         <ul>
15708           <li>params[0] is a KiiUser/KiiGroup instance.</li>
15709         </ul>
15710       </li>
15711       <li>reject callback function: function(error). error is an Error instance.
15712         <ul>
15713           <li>error.message</li>
15714         </ul>
15715       </li>
15716     </ul>
15717   @deprecated Use {@link KiiThing.registerOwnerWithVendorThingIDAndPassword} instead.
15718   @example
15719   // example to use callbacks directly
15720   // assume thing/group is already registered.
15721   var group = KiiGroup.groupWithURI("kiicloud://groups/xxxyyyy");
15722   KiiThing.registerOwnerWithVendorThingID("xxxx-yyyy-zzzz", group, {
15723       success: function(group) {
15724           // Register owner succeeded.
15725       },
15726       failure: function(error) {
15727           // Handle error.
15728       }
15729   });
15730   
15731   // example to use Promise
15732   // assume thing/group is already registered.
15733   var group = KiiGroup.groupWithURI("kiicloud://groups/xxxyyyy");
15734   KiiThing.registerOwnerWithVendorThingID("xxxx-yyyy-zzzz", group).then(
15735       function(group) {
15736           // Register owner succeeded.
15737       },
15738       function(error) {
15739           // Handle error.
15740       }
15741   );
15742    */
15743 
15744   KiiThing.registerOwnerWithVendorThingID = function(vendorThingID, owner, callbacks) {
15745     if (!KiiUtilities._isNonEmptyString(vendorThingID)) {
15746       return root.KiiThing._registerOwnerWithIdentifier(null, owner, callbacks);
15747     }
15748     return root.KiiThing._registerOwnerWithIdentifier("VENDOR_THING_ID:" + vendorThingID, owner, callbacks);
15749   };
15750 
15751 
15752   /**
15753   Register user/group as owner of specified thing.
15754   <br>Need user login before execute this API.
15755   <br>Note: if you obtain thing instance from {@link KiiAppAdminContext},
15756   API is authorized by app admin.<br>
15757   
15758   @param {String} vendorThingID The vendor thing ID of thing
15759   @param {KiiUser or KiiGroup} owner instance of KiiUser/KiiGroup to be registered as owner.
15760   @param {String} [password] the thing password
15761   @param {Object} [callbacks] object holds callback functions.
15762   @param {Function} callbacks.success callback called when operation succeeded.
15763   <br>1st argument: user/group object registered as owner.
15764   @param {Function} callbacks.failure callback called when operation failed.
15765   <br>argument is Error object.
15766   @return {Promise} return promise object.
15767     <ul>
15768       <li>fulfill callback function: function(owner).
15769         <ul>
15770           <li>owner is a KiiUser/KiiGroup instance.</li>
15771         </ul>
15772       </li>
15773       <li>reject callback function: function(error). error is an Error instance.
15774         <ul>
15775           <li>error.message</li>
15776         </ul>
15777       </li>
15778     </ul>
15779   @example
15780   // example to use callbacks directly
15781   // assume thing/group is already registered.
15782   var group = KiiGroup.groupWithURI("kiicloud://groups/xxxyyyy");
15783   KiiThing.registerOwnerWithVendorThingIDAndPassword("xxxx-yyyy-zzzz", group, "Thing password", {
15784       success: function(owner) {
15785           // Register owner succeeded.
15786       },
15787       failure: function(error) {
15788           // Handle error.
15789       }
15790   });
15791   
15792   // example to use Promise
15793   // assume thing/group is already registered.
15794   var group = KiiGroup.groupWithURI("kiicloud://groups/xxxyyyy");
15795   KiiThing.registerOwnerWithVendorThingIDAndPassword("xxxx-yyyy-zzzz", group, "Thing password").then(
15796       function(owner) {
15797           // Register owner succeeded.
15798       },
15799       function(error) {
15800           // Handle error.
15801       }
15802   );
15803    */
15804 
15805   KiiThing.registerOwnerWithVendorThingIDAndPassword = function(vendorThingID, owner, password, callbacks) {
15806     if (!KiiUtilities._isNonEmptyString(vendorThingID)) {
15807       return root.KiiThing._registerOwnerWithIdentifierAndPassword(null, owner, password, callbacks);
15808     }
15809     return root.KiiThing._registerOwnerWithIdentifierAndPassword("VENDOR_THING_ID:" + vendorThingID, owner, password, callbacks);
15810   };
15811 
15812   KiiThing._registerOwnerWithIdentifier = function(identifier, owner, callbacks) {
15813     return new Promise(function(resolve, reject) {
15814       var errObj, message, ownerUrl, sendCallbacks, wrapper;
15815       if (!KiiUtilities._isNonEmptyString(identifier)) {
15816         errObj = KiiUtilities._Error("identifier is null or empty");
15817         if (callbacks != null) {
15818           callbacks.failure(errObj);
15819         }
15820         reject(errObj);
15821         return;
15822       }
15823       if (owner == null) {
15824         errObj = KiiUtilities._Error("owner is null");
15825         if (callbacks != null) {
15826           callbacks.failure(errObj);
15827         }
15828         reject(errObj);
15829         return;
15830       }
15831       try {
15832         ownerUrl = root.KiiThing.prototype._getOwnerURL(identifier, owner);
15833       } catch (_error) {
15834         message = _error;
15835         errObj = KiiUtilities._Error(message);
15836         if (callbacks != null) {
15837           callbacks.failure(errObj);
15838         }
15839         reject(errObj);
15840         return;
15841       }
15842       wrapper = KiiXHRWrapperFactory.createXHRWrapper('PUT', ownerUrl);
15843       wrapper.setKiiHeaders();
15844       root.KiiThing.prototype._setAuthToken(wrapper);
15845       sendCallbacks = {
15846         success: function() {
15847           if (callbacks != null) {
15848             callbacks.success(owner);
15849           }
15850           return resolve([owner]);
15851         },
15852         failure: function() {
15853           var errString;
15854           errString = wrapper.getErrorString("register owner");
15855           errObj = KiiUtilities._Error(errString);
15856           if (callbacks != null) {
15857             callbacks.failure(errObj);
15858           }
15859           return reject(errObj);
15860         }
15861       };
15862       return wrapper.send(sendCallbacks);
15863     });
15864   };
15865 
15866   KiiThing._registerOwnerWithIdentifierAndPassword = function(identifier, owner, password, callbacks) {
15867     return new Promise(function(resolve, reject) {
15868       var errObj, requestBody, sendCallbacks, url, wrapper;
15869       if (!KiiUtilities._isNonEmptyString(identifier)) {
15870         errObj = KiiUtilities._Error("identifier is null or empty");
15871         if (callbacks != null) {
15872           callbacks.failure(errObj);
15873         }
15874         reject(errObj);
15875         return;
15876       }
15877       if (owner == null) {
15878         errObj = KiiUtilities._Error("owner is null");
15879         if (callbacks != null) {
15880           callbacks.failure(errObj);
15881         }
15882         reject(errObj);
15883         return;
15884       }
15885       if (!KiiUtilities._isNonEmptyString(password)) {
15886         errObj = KiiUtilities._Error("password is null or empty");
15887         if (callbacks != null) {
15888           callbacks.failure(errObj);
15889         }
15890         reject(errObj);
15891         return;
15892       }
15893       url = "" + (root.Kii.getBaseURL()) + "/apps/" + (root.Kii.getAppID()) + "/things/" + identifier + "/ownership";
15894       wrapper = KiiXHRWrapperFactory.createXHRWrapper('POST', url);
15895       wrapper.setKiiHeaders();
15896       wrapper.setContentType("application/vnd.kii.ThingOwnershipRequest+json");
15897       root.KiiThing.prototype._setAuthToken(wrapper);
15898       requestBody = {
15899         thingPassword: password
15900       };
15901       if (owner instanceof root.KiiUser) {
15902         requestBody.userID = owner.getID();
15903       } else if (owner instanceof root.KiiGroup) {
15904         requestBody.groupID = owner.getID();
15905       } else {
15906         errObj = KiiUtilities._Error("owner should be instance of KiiUser or KiiGroup");
15907         if (callbacks != null) {
15908           callbacks.failure(errObj);
15909         }
15910         reject(errObj);
15911         return;
15912       }
15913       sendCallbacks = {
15914         success: function() {
15915           if (callbacks != null) {
15916             callbacks.success(owner);
15917           }
15918           return resolve(owner);
15919         },
15920         failure: function() {
15921           var errString;
15922           errString = wrapper.getErrorString("register owner");
15923           errObj = KiiUtilities._Error(errString);
15924           if (callbacks != null) {
15925             callbacks.failure(errObj);
15926           }
15927           return reject(errObj);
15928         }
15929       };
15930       return wrapper.sendData(JSON.stringify(requestBody), sendCallbacks);
15931     });
15932   };
15933 
15934   KiiThing.prototype._getOwnerURL = function(identifier, owner) {
15935     var oid, type;
15936     if (owner instanceof root.KiiUser) {
15937       oid = owner.getID();
15938       type = 'user';
15939     } else if (owner instanceof root.KiiGroup) {
15940       oid = owner.getID();
15941       type = 'group';
15942     } else {
15943       throw 'owner should be instance of user or group';
15944     }
15945     if (oid == null) {
15946       throw 'owner instance does not have id';
15947     }
15948     return "" + (root.Kii.getBaseURL()) + "/apps/" + (root.Kii.getAppID()) + "/things/" + identifier + "/ownership/" + type + ":" + oid;
15949   };
15950 
15951 
15952   /**
15953   Remove ownership of thing from specified user/group.
15954   <br>This API is authorized by owner of thing.
15955   <br>Need user login who owns this thing before execute this API.
15956   <br>Note: if you obtain thing instance from {@link KiiAppAdminContext},
15957   API is authorized by app admin.<br>
15958   
15959   @param {KiiUser or KiiGroup} owner to be unregistered.
15960   @param {Object} [callbacks] object holds callback functions.
15961   @param {Function} callbacks.success callback called when operation succeeded.
15962   <br>1st argument: thing object
15963   <br>2nd argument: unregistered owner
15964   @param {Function} callbacks.failure callback called when operation failed.
15965   <br>argument is Error object
15966   @return {Promise} return promise object.
15967     <ul>
15968       <li>fulfill callback function: function(params). params is an Array instance.
15969         <ul>
15970           <li>params[0] is the KiiThing instance which this method was called on.</li>
15971           <li>params[1] is a KiiUser/KiiGroup instance which had ownership of the thing removed.</li>
15972         </ul>
15973       </li>
15974       <li>reject callback function: function(error). error is an Error instance.
15975         <ul>
15976           <li>error.target is the KiiThing instance which this method was called on.</li>
15977           <li>error.message</li>
15978         </ul>
15979       </li>
15980     </ul>
15981   @example
15982   // example to use callbacks directly
15983   // assume thing/group is already registered.
15984   var group = KiiGroup.groupWithURI("kiicloud://groups/xxxyyyy");
15985   thing.unregisterOwner(group, {
15986       success: function(thing, group) {
15987           // Unregister owner succeeded.
15988       },
15989       failure: function(error) {
15990           // Handle error.
15991       }
15992   });
15993   
15994   // example to use Promise
15995   // assume thing/group is already registered.
15996   var group = KiiGroup.groupWithURI("kiicloud://groups/xxxyyyy");
15997   thing.unregisterOwner(group).then(
15998       function(params) {
15999           // Unregister owner succeeded.
16000       },
16001       function(error) {
16002           // Handle error.
16003       }
16004   );
16005    */
16006 
16007   KiiThing.prototype.unregisterOwner = function(owner, callbacks) {
16008     return new Promise((function(_this) {
16009       return function(resolve, reject) {
16010         var errObj, message, ownerUrl, sendCallbacks, wrapper;
16011         try {
16012           ownerUrl = _this._getOwnerURL(_this._thingID, owner);
16013         } catch (_error) {
16014           message = _error;
16015           errObj = KiiUtilities._Error(message, _this);
16016           if (callbacks != null) {
16017             callbacks.failure(errObj);
16018           }
16019           reject(errObj);
16020           return;
16021         }
16022         wrapper = KiiXHRWrapperFactory.createXHRWrapper('DELETE', ownerUrl);
16023         wrapper.setKiiHeaders();
16024         _this._setAuthToken(wrapper);
16025         sendCallbacks = {
16026           success: function() {
16027             if (callbacks != null) {
16028               callbacks.success(_this, owner);
16029             }
16030             return resolve([_this, owner]);
16031           },
16032           failure: function() {
16033             var errString;
16034             errString = wrapper.getErrorString("unregister owner");
16035             errObj = KiiUtilities._Error(errString, _this);
16036             if (callbacks != null) {
16037               callbacks.failure(errObj);
16038             }
16039             return reject(errObj);
16040           }
16041         };
16042         return wrapper.send(sendCallbacks);
16043       };
16044     })(this));
16045   };
16046 
16047 
16048   /**
16049   Disable the thing.
16050   <br>This API is authorized by owner of thing.
16051   <br>Need user login who owns this thing before execute this API.
16052   <br>To let users to own Thing, please call {@link KiiThing#registerOwner}
16053   <br>Note: if you obtain thing instance from {@link KiiAppAdminContext},
16054   API is authorized by app admin.<br>
16055   
16056   After succeeded, access token published for thing is disabled.
16057   In a result, only the app administrator and owners of thing can access the thing.
16058   Used when user lost the thing and avoid using by unknown users.
16059   It doesn't throw error when the thing is already disabled.
16060   @param {Object} [callbacks] object holds callback functions.
16061   @param {Function} callbacks.success callback called when operation succeeded.
16062   <br>argument is disabled thing
16063   @param {Function} callbacks.failure callback called when operation failed.
16064   <br>argument is Error object
16065   @return {Promise} return promise object.
16066     <ul>
16067       <li>fulfill callback function: function(thing). thing is a KiiThing instance.</li>
16068       <li>reject callback function: function(error). error is an Error instance.
16069         <ul>
16070           <li>error.target is the KiiThing instance which this method was called on.</li>
16071           <li>error.message</li>
16072         </ul>
16073       </li>
16074     </ul>
16075   @example
16076   // example to use callbacks directly
16077   // assume thing is already registered.
16078   thing.disable({
16079       success: function(thing) {
16080           // Disable succeeded.
16081       },
16082       failure: function(error) {
16083           // Handle error.
16084       }
16085   });
16086   
16087   // example to use Promise
16088   // assume thing is already registered.
16089   thing.disable().then(
16090       function(thing) {
16091           // Disable succeeded.
16092       },
16093       function(error) {
16094           // Handle error.
16095       }
16096   );
16097    */
16098 
16099   KiiThing.prototype.disable = function(callbacks) {
16100     return this._changeStatus(true, callbacks);
16101   };
16102 
16103 
16104   /**
16105   Enable the thing.
16106   <br>This API is authorized by owner of thing.
16107   <br>Need user login who owns this thing before execute this API.
16108   <br>To let users to own Thing, please call {@link KiiThing#registerOwner}
16109   <br>Note: if you obtain thing instance from {@link KiiAppAdminContext},
16110   API is authorized by app admin.<br>
16111   
16112   After succeeded, If thing is registered with "persistentToken" option,
16113   token should be recovered (Access token which is used before disabling can be available).
16114   Otherwise, it does not recovered.
16115   It doesn't throw error when the thing is already enabled.
16116   @param {Object} [callbacks] object holds callback functions.
16117   @param {Function} callbacks.success callback called when operation succeeded.
16118   <br>argument is enabled thing
16119   @param {Function} callbacks.failure callback called when operation failed.
16120   <br>argument is Error object
16121   @return {Promise} return promise object.
16122     <ul>
16123       <li>fulfill callback function: function(thing). thing is a KiiThing instance.</li>
16124       <li>reject callback function: function(error). error is an Error instance.
16125         <ul>
16126           <li>error.target is the KiiThing instance which this method was called on.</li>
16127           <li>error.message</li>
16128         </ul>
16129       </li>
16130     </ul>
16131   @example
16132   // example to use callbacks directly
16133   // assume thing is already registered.
16134   thing.enable({
16135       success: function(thing) {
16136           // Enable succeeded.
16137       },
16138       failure: function(error) {
16139           // Handle error.
16140       }
16141   });
16142   
16143   // example to use Promise
16144   // assume thing is already registered.
16145   thing.enable().then(
16146       function(thing) {
16147           // Disable succeeded.
16148       },
16149       function(error) {
16150           // Handle error.
16151       }
16152   );
16153    */
16154 
16155   KiiThing.prototype.enable = function(callbacks) {
16156     return this._changeStatus(false, callbacks);
16157   };
16158 
16159   KiiThing.prototype._changeStatus = function(disable, callbacks) {
16160     return new Promise((function(_this) {
16161       return function(resolve, reject) {
16162         var data, sendCallbacks, wrapper;
16163         wrapper = KiiXHRWrapperFactory.createXHRWrapper('PUT', "" + (root.Kii.getBaseURL()) + "/apps/" + (root.Kii.getAppID()) + "/things/" + _this._thingID + "/status");
16164         wrapper.setKiiHeaders();
16165         _this._setAuthToken(wrapper);
16166         wrapper.setContentType('application/vnd.kii.ThingStatusUpdateRequest+json');
16167         sendCallbacks = {
16168           success: function() {
16169             _this._disabled = disable;
16170             if (callbacks != null) {
16171               callbacks.success(_this);
16172             }
16173             return resolve(_this);
16174           },
16175           failure: function() {
16176             var errObj, errString;
16177             errString = wrapper.getErrorString("disable thing " + disable);
16178             errObj = KiiUtilities._Error(errString, _this);
16179             if (callbacks != null) {
16180               callbacks.failure(errObj);
16181             }
16182             return reject(errObj);
16183           }
16184         };
16185         data = {
16186           disabled: disable
16187         };
16188         return wrapper.sendData(JSON.stringify(data), sendCallbacks);
16189       };
16190     })(this));
16191   };
16192 
16193 
16194   /** Updates thing password. This method can be used only by app admin.
16195   
16196   <br>
16197   @param {String} newPassword new password
16198   @param {Object} [callbacks] object holds callback functions.
16199   @param {Function} callbacks.success callback called when operation succeeded.
16200   <br>argument is this thing.
16201   @param {Function} callbacks.failure callback called when operation failed.
16202   <br>argument is Error object.
16203   @return {Promise} return promise object.
16204     <ul>
16205       <li>fulfill callback function: function(thing). thing is a KiiThing instance.</li>
16206       <li>reject callback function: function(error). error is an Error instance.
16207         <ul>
16208           <li>error.target is the KiiThing instance which this method was called on.</li>
16209           <li>error.message</li>
16210         </ul>
16211       </li>
16212     </ul>
16213   @example
16214   // example to use callbacks directly
16215   // assume thing is already registered and you had an adminContext.
16216   adminContext.thingWithID(thing.getThingID()).updatePassword("new password", {
16217     success: function(thing) {
16218       // Update succeeded.
16219     },
16220     failure: function(error) {
16221       // Handle error.
16222     }
16223   });
16224   // example to use Promise
16225   // assume thing is already registered and you had an adminContext.
16226   adminContext.thingWithID(thing.getThingID()).updatePassword("new password").then(
16227       function(thing) {
16228           // Update succeeded.
16229       },
16230       function(error) {
16231           // Handle error.
16232       }
16233   );
16234    */
16235 
16236   KiiThing.prototype.updatePassword = function(newPassword, callbacks) {
16237     var errObj;
16238     errObj = KiiUtilities._Error("updatePassword can be used only by app admin.");
16239     if (callbacks != null) {
16240       callbacks.failure(errObj);
16241     }
16242     return Promise.reject(errObj);
16243   };
16244 
16245 
16246   /**
16247   Load thing with given vendor thing id.
16248   <br>This API is authorized by owner of thing.
16249   <br>Need user login who owns this thing before execute this API.
16250   <br>To let users to own Thing, please call {@link KiiThing#registerOwner}
16251   <br>Note: if you obtain thing instance from {@link KiiAppAdminContext},
16252   API is authorized by app admin.<br>
16253   
16254   @param {String} vendorThingID registered vendor thing id.
16255   @param {Object} [callbacks] object holds callback functions.
16256   @param {Function} callbacks.success callback called when operation succeeded.
16257   @param {Function} callbacks.failure callback called when operation failed.
16258   @return {Promise} return promise object.
16259     <ul>
16260       <li>fulfill callback function: function(thing). thing is a KiiThing instance.</li>
16261       <li>reject callback function: function(error). error is an Error instance.
16262         <ul>
16263           <li>error.message</li>
16264         </ul>
16265       </li>
16266     </ul>
16267   @example
16268   // example to use callbacks directly
16269   KiiThing.loadWithVendorThingID("thing-xxxx-yyyy",{
16270       success: function(thing) {
16271           // Load succeeded.
16272       },
16273       failure: function(error) {
16274           // Handle error.
16275       }
16276   });
16277   
16278   // example to use Promise
16279   KiiThing.loadWithVendorThingID("thing-xxxx-yyyy").then(
16280       function(thing) {
16281           // Load succeeded.
16282       },
16283       function(error) {
16284           // Handle error.
16285       }
16286   );
16287    */
16288 
16289   KiiThing.loadWithVendorThingID = function(vendorThingID, callbacks) {
16290     var qualifiedID;
16291     qualifiedID = "VENDOR_THING_ID:" + vendorThingID;
16292     return root.KiiThing._load(qualifiedID, callbacks);
16293   };
16294 
16295 
16296   /**
16297   Load thing with thing id given by Kii Cloud.
16298   <br>This API is authorized by owner of thing.
16299   <br>Need user login who owns this thing before execute this API.
16300   <br>To let users to own Thing, please call {@link KiiThing#registerOwner}
16301   <br>Note: if you obtain thing instance from {@link KiiAppAdminContext},
16302   API is authorized by app admin.<br>
16303   
16304   thing id can be obtained by {@link thingID}
16305   @param {String} thingID registered thing id.
16306   @param {Object} [callbacks] object holds callback functions.
16307   @param {Function} callbacks.success callback called when operation succeeded.
16308   <br>argument is loaded thing.
16309   @param {Function} callbacks.failure callback called when operation failed.
16310   <br>argument is Error object.
16311   @return {Promise} return promise object.
16312     <ul>
16313       <li>fulfill callback function: function(thing). thing is a KiiThing instance.</li>
16314       <li>reject callback function: function(error). error is an Error instance.
16315         <ul>
16316           <li>error.message</li>
16317         </ul>
16318       </li>
16319     </ul>
16320   @example
16321   // example to use callbacks directly
16322   KiiThing.loadWithThingID("thing-xxxx-yyyy",{
16323       success: function(thing) {
16324           // Load succeeded.
16325       },
16326       failure: function(error) {
16327           // Handle error.
16328       }
16329   });
16330   
16331   // example to use Promise
16332   KiiThing.loadWithVendorThingID("thing-xxxx-yyyy").then(
16333       function(thing) {
16334           // Load succeeded.
16335       },
16336       function(error) {
16337           // Handle error.
16338       }
16339   );
16340    */
16341 
16342   KiiThing.loadWithThingID = function(thingID, callbacks) {
16343     return root.KiiThing._load(thingID, callbacks);
16344   };
16345 
16346   KiiThing._load = function(qualifiedID, callbacks) {
16347     return new Promise(function(resolve, reject) {
16348       var sendCallbacks, wrapper;
16349       wrapper = KiiXHRWrapperFactory.createXHRWrapper('GET', "" + (root.Kii.getBaseURL()) + "/apps/" + (root.Kii.getAppID()) + "/things/" + qualifiedID);
16350       wrapper.setKiiHeaders();
16351       root.KiiThing.prototype._setAuthToken(wrapper);
16352       sendCallbacks = {
16353         success: function() {
16354           var respJson, thing;
16355           respJson = JSON.parse(decodeURIComponent(wrapper.xhr.responseText));
16356           thing = new root.KiiThing(respJson);
16357           if (callbacks != null) {
16358             callbacks.success(thing);
16359           }
16360           return resolve(thing);
16361         },
16362         failure: function() {
16363           var errObj, errString;
16364           errString = wrapper.getErrorString("load thing");
16365           errObj = KiiUtilities._Error(errString);
16366           if (callbacks != null) {
16367             callbacks.failure(errObj);
16368           }
16369           return reject(errObj);
16370         }
16371       };
16372       return wrapper.send(sendCallbacks);
16373     });
16374   };
16375 
16376 
16377   /**
16378   Instantiate bucket belongs to this thing.
16379   @param {String} bucketName name of the bucket.
16380   @return {KiiBucket} bucket instance.
16381    */
16382 
16383   KiiThing.prototype.bucketWithName = function(bucketName) {
16384     return new root.KiiBucket._bucketWithName(bucketName, this);
16385   };
16386 
16387 
16388   /** Creates a reference to a encrypted bucket for this thing
16389   
16390   <br><br>The bucket will be created/accessed within this thing's scope
16391   @param {String} bucketName The name of the bucket the user should create/access
16392   @returns {KiiEncryptedBucket} A working KiiEncryptedBucket object
16393   @example
16394   var thing = . . .; // a KiiThing
16395   var bucket = thing.encryptedBucketWithName("myBucket");
16396    */
16397 
16398   KiiThing.prototype.encryptedBucketWithName = function(bucketName) {
16399     return new root.KiiEncryptedBucket(bucketName, this);
16400   };
16401 
16402 
16403   /**
16404   Instantiate topic belongs to this thing.
16405   @param {String} topicName name of the topic. Must be a not empty string.
16406   @return {KiiTopic} topic instance.
16407    */
16408 
16409   KiiThing.prototype.topicWithName = function(topicName) {
16410     if (typeof topicName !== "string" || topicName === "") {
16411       throw new root.InvalidArgumentException('topicName should not null or empty');
16412     }
16413     return new root.KiiTopic(this._getHttpURI(), topicName);
16414   };
16415 
16416 
16417   /** Gets a list of topics in this thing scope
16418   @param {Object} [callbacks] An object with callback methods defined
16419   @param {Method} callbacks.success The callback method to call on a successful list request
16420   @param {Method} callbacks.failure The callback method to call on a failed list request
16421   @param {String} [paginationKey] You can specify the pagination key with the nextPaginationKey passed by callbacks.success. If empty string or no string object is provided, this API regards no paginationKey specified.
16422   @return {Promise} return promise object.
16423       <ul>
16424         <li>fulfill callback function: function(params). params is Array instance.
16425           <ul>
16426             <li>params[0] is array of KiiTopic instances.</li>
16427             <li>params[1] is string of nextPaginationKey.</li>
16428           </ul>
16429         </li>
16430         <li>reject callback function: function(error). error is an Error instance.
16431           <ul>
16432             <li>error.target is the KiiThing instance which this method was called on. </li>
16433             <li>error.message</li>
16434           </ul>
16435         </li>
16436       </ul>
16437   @example
16438   // example to use callbacks directly
16439   var thing = . . .; // a KiiThing
16440   thing.listTopics({
16441       success: function(topicList, nextPaginationKey) {
16442           // do something with the result
16443           for(var i=0; i<topicList.length; i++){
16444               var topic = topicList[i];
16445           }
16446           if (nextPaginationKey != null) {
16447               thing.listTopics({
16448                   success: function(topicList, nextPaginationKey) {...},
16449                   failure: function(anErrorString) {...}
16450               }, nextPaginationKey);
16451           }
16452       },
16453       failure: function(anErrorString) {
16454           // do something with the error response
16455       }
16456   });
16457   
16458   // example to use promise
16459   var thing = . . .; // a KiiThing
16460   thing.listTopics().then(
16461       function(params) {
16462           var topicList = params[0];
16463           var nextPaginationKey = params[1];
16464           // do something with the result
16465           for(var i=0; i<topicList.length; i++){
16466               var topic = topicList[i];
16467           }
16468           if (nextPaginationKey != null) {
16469               thing.listTopics(null, nextPaginationKey).then(
16470                   function(params) {...},
16471                   function(error) {...}
16472               );
16473           }
16474       },
16475       function(error) {
16476           // do something with the error response
16477       }
16478   );
16479    */
16480 
16481   KiiThing.prototype.listTopics = function(callbacks, paginationKey) {
16482     return new Promise((function(_this) {
16483       return function(resolve, reject) {
16484         var listTopicsCallbacks;
16485         listTopicsCallbacks = {
16486           success: function() {
16487             if (callbacks != null) {
16488               callbacks.success.apply(callbacks, arguments);
16489             }
16490             return resolve(arguments);
16491           },
16492           failure: function() {
16493             if (callbacks != null) {
16494               callbacks.failure.apply(callbacks, arguments);
16495             }
16496             return reject(arguments[0]);
16497           }
16498         };
16499         return _this._listTopicsUsingCallbacks(listTopicsCallbacks, paginationKey);
16500       };
16501     })(this));
16502   };
16503 
16504   KiiThing.prototype._listTopicsUsingCallbacks = function(callbacks, paginationKey) {
16505     var listCallbacks, uri, wrapper;
16506     uri = "" + (this._getHttpURI()) + "/topics";
16507     if (typeof paginationKey === "string" && paginationKey !== "") {
16508       uri = uri + "?paginationKey=" + encodeURIComponent(paginationKey);
16509     }
16510     wrapper = KiiXHRWrapperFactory.createXHRWrapper('GET', uri);
16511     wrapper.setKiiHeaders();
16512     this._setAuthToken(wrapper);
16513     listCallbacks = {
16514       success: (function(_this) {
16515         return function() {
16516           var json, topic, topics, _i, _len, _ref;
16517           json = JSON.parse(wrapper.xhr.responseText);
16518           topics = [];
16519           _ref = json.topics;
16520           for (_i = 0, _len = _ref.length; _i < _len; _i++) {
16521             topic = _ref[_i];
16522             topics.push(_this.topicWithName(topic.topicID));
16523           }
16524           return callbacks != null ? callbacks.success(topics, (json.paginationKey === void 0 ? null : json.paginationKey)) : void 0;
16525         };
16526       })(this),
16527       failure: (function(_this) {
16528         return function() {
16529           var errObj, errString;
16530           errString = wrapper.getErrorString("list topics");
16531           errObj = KiiUtilities._Error(errString, _this);
16532           return callbacks != null ? callbacks.failure(errObj) : void 0;
16533         };
16534       })(this)
16535     };
16536     return wrapper.send(listCallbacks);
16537   };
16538 
16539 
16540   /** Instantiate push subscription for this thing.
16541   @return {KiiPushSubscription} push subscription object.
16542    */
16543 
16544   KiiThing.prototype.pushSubscription = function() {
16545     return new root.KiiPushSubscription(this);
16546   };
16547 
16548   KiiThing.prototype._getHttpURI = function() {
16549     return "" + (root.Kii.getBaseURL()) + "/apps/" + (root.Kii.getAppID()) + "/things/" + (this.getThingID());
16550   };
16551 
16552   KiiThing.thingWithID = function(thingID) {
16553     var thing;
16554     if ((thingID == null) || thingID === "") {
16555       throw new root.InvalidArgumentException('thingID should not null or empty');
16556     }
16557     thing = new root.KiiThing();
16558     thing._thingID = thingID;
16559     return thing;
16560   };
16561 
16562   KiiThing.prototype._setAuthToken = function(wrapper) {
16563     return wrapper.setCurrentUserToken();
16564   };
16565 
16566   KiiThing.prototype._getSubscriberPath = function() {
16567     return "things/" + (this.getThingID());
16568   };
16569 
16570   return KiiThing;
16571 
16572 })();
16573 
16574 
16575 /**
16576 @class Represents a Topic object.
16577 @exports root.KiiTopic as KiiTopic
16578  */
16579 
16580 root.KiiTopic = (function() {
16581   function KiiTopic(parentUri, topicName) {
16582     this._getHttpUri = __bind(this._getHttpUri, this);
16583     this._setAuthToken = __bind(this._setAuthToken, this);
16584     this.acl = __bind(this.acl, this);
16585     this.deleteTopic = __bind(this.deleteTopic, this);
16586     this.sendMessage = __bind(this.sendMessage, this);
16587     this.save = __bind(this.save, this);
16588     this.exists = __bind(this.exists, this);
16589     this.getName = __bind(this.getName, this);
16590     this._uri = "" + parentUri + "/topics/" + topicName;
16591     this._name = topicName;
16592   }
16593 
16594 
16595   /** get name of this topic
16596   @return {String} name of this topic.
16597    */
16598 
16599   KiiTopic.prototype.getName = function() {
16600     return this._name;
16601   };
16602 
16603 
16604   /** Checks whether the topic already exists or not.
16605   @param {Object} [callbacks] An object with callback methods defined
16606   @param {Method} callbacks.success callback called when operation succeeded.
16607   <br>argument is boolean.
16608   @param {Method} callbacks.failure callback called when operation failed.
16609   <br>argument is error object.
16610   @return {Promise} return promise object.
16611     <ul>
16612       <li>fulfill callback function: function(existed). true if the topic exists.</li>
16613       <li>reject callback function: function(error). error is an Error instance.
16614         <ul>
16615           <li>error.target is the KiiTopic instance which this method was called on.</li>
16616           <li>error.message</li>
16617         </ul>
16618       </li>
16619     </ul>
16620   @example
16621   // example to use callbacks directly
16622   // assume topic is already instantiated.
16623   topic.exists({
16624       success: function(existed) {
16625       },
16626       failure: function(error) {
16627           // Handle error.
16628       }
16629   });
16630   
16631   // example to use Promise
16632   // assume topic is already instantiated.
16633   topic.exists().then(
16634       function(existed){
16635       },
16636       function(error){
16637           // Handle error.
16638       });
16639    */
16640 
16641   KiiTopic.prototype.exists = function(callbacks) {
16642     return new Promise((function(_this) {
16643       return function(resolve, reject) {
16644         var existsCallbacks, wrapper;
16645         wrapper = KiiXHRWrapperFactory.createXHRWrapper('HEAD', _this._uri);
16646         wrapper.setKiiHeaders();
16647         _this._setAuthToken(wrapper);
16648         existsCallbacks = {
16649           success: function() {
16650             if (callbacks != null) {
16651               callbacks.success(true);
16652             }
16653             return resolve(true);
16654           },
16655           failure: function() {
16656             var errObj, errString;
16657             if (wrapper.xhr.status === 404) {
16658               if (callbacks != null) {
16659                 callbacks.success(false);
16660               }
16661               resolve(false);
16662               return;
16663             }
16664             errString = wrapper.getErrorString("check topic");
16665             errObj = KiiUtilities._Error(errString, _this);
16666             if (callbacks != null) {
16667               callbacks.failure(errObj);
16668             }
16669             return reject(errObj);
16670           }
16671         };
16672         return wrapper.send(existsCallbacks);
16673       };
16674     })(this));
16675   };
16676 
16677 
16678   /** Save this topic on Kii Cloud.
16679   Note that only app admin can save application scope topic.
16680   @param {Object} [callbacks] callback functions.
16681   @param {Function} callbacks.success callback called when operation succeeded.
16682   <br>argument is saved topic.
16683   @param {Function} callbacks.failure callback called when operation failed.
16684   <br>argument is error object.
16685   @return {Promise} return promise object.
16686     <ul>
16687       <li>fulfill callback function: function(theSavedTopic). theSavedTopic is a KiiTopic instance.</li>
16688       <li>reject callback function: function(error). error is an Error instance.
16689         <ul>
16690           <li>error.target is the KiiTopic instance which this method was called on.</li>
16691           <li>error.message</li>
16692         </ul>
16693       </li>
16694     </ul>
16695   @example
16696   // example to use callbacks directly
16697   // assume topic is already instantiated.
16698   topic.save({
16699       success: function(topic) {
16700           // Save topic succeeded.
16701       },
16702       failure: function(error) {
16703           // Handle error.
16704       }
16705   });
16706   
16707   // example to use Promise
16708   // assume topic is already instantiated.
16709   topic.save().then(
16710       function(topic) {
16711           // Save topic succeeded.
16712       },
16713       function(error) {
16714           // Handle error.
16715       }
16716   );
16717    */
16718 
16719   KiiTopic.prototype.save = function(callbacks) {
16720     return new Promise((function(_this) {
16721       return function(resolve, reject) {
16722         var sendCallbacks, wrapper;
16723         wrapper = KiiXHRWrapperFactory.createXHRWrapper('PUT', _this._uri);
16724         wrapper.setKiiHeaders();
16725         _this._setAuthToken(wrapper);
16726         sendCallbacks = {
16727           success: function() {
16728             if (callbacks != null) {
16729               callbacks.success(_this);
16730             }
16731             return resolve(_this);
16732           },
16733           failure: function() {
16734             var errObj, errString;
16735             errString = wrapper.getErrorString("save topic");
16736             errObj = KiiUtilities._Error(errString, _this);
16737             if (callbacks != null) {
16738               callbacks.failure(errObj);
16739             }
16740             return reject(errObj);
16741           }
16742         };
16743         return wrapper.send(sendCallbacks);
16744       };
16745     })(this));
16746   };
16747 
16748 
16749   /** Send message to the topic.
16750   @param {Object} message to be sent.
16751   @param {Object} [callbacks] callback functions.
16752   @param {Function} callbacks.success callback called when operation succeeded.
16753   <br>1st argument: topic object.
16754   <br>2nd argument: message object.
16755   @param {Function} callbacks.failure callback called when operation failed.
16756   <br>argument is Error object.
16757   @return {Promise} return promise object.
16758     <ul>
16759       <li>fulfill callback function: function(params). params is an Array instance.
16760         <ul>
16761           <li>params[0] is the KiiTopic instance which this method was called on.</li>
16762           <li>params[1] is the message object to send.</li>
16763         </ul>
16764       </li>
16765       <li>reject callback function: function(error). error is an Error instance.
16766         <ul>
16767           <li>error.target is the KiiTopic instance which this method was called on.</li>
16768           <li>error.message</li>
16769         </ul>
16770       </li>
16771     </ul>
16772   @example
16773   // example to use callbacks directly
16774   // assume topic is already instantiated.
16775   var contents = {
16776       message : "hello push!"
16777   };
16778   var message = new KiiPushMessageBuilder(contents).build();
16779   topic.sendMessage(message, {
16780       success: function(topic, message) {
16781           // Send message succeeded.
16782       },
16783       failure: function(error) {
16784           // Handle error.
16785       }
16786   });
16787   
16788   // example to use Promise
16789   // assume topic is already instantiated.
16790   var contents = {
16791       message : "hello push!"
16792   };
16793   var message = new KiiPushMessageBuilder(contents).build();
16794   topic.sendMessage(message).then(
16795       function(params) {
16796           // Send message succeeded.
16797       },
16798       function(error) {
16799           // Handle error.
16800       }
16801   );
16802    */
16803 
16804   KiiTopic.prototype.sendMessage = function(message, callbacks) {
16805     return new Promise((function(_this) {
16806       return function(resolve, reject) {
16807         var sendCallbacks, wrapper;
16808         wrapper = KiiXHRWrapperFactory.createXHRWrapper('POST', "" + _this._uri + "/push/messages");
16809         wrapper.setKiiHeaders();
16810         _this._setAuthToken(wrapper);
16811         wrapper.setContentType("application/vnd.kii.SendPushMessageRequest+json");
16812         sendCallbacks = {
16813           success: function() {
16814             if (callbacks != null) {
16815               callbacks.success(_this, message);
16816             }
16817             return resolve([_this, message]);
16818           },
16819           failure: function() {
16820             var errObj, errString;
16821             errString = wrapper.getErrorString("send messages");
16822             errObj = KiiUtilities._Error(errString, _this);
16823             if (callbacks != null) {
16824               callbacks.failure(errObj);
16825             }
16826             return reject(errObj);
16827           }
16828         };
16829         return wrapper.sendData(JSON.stringify(message), sendCallbacks);
16830       };
16831     })(this));
16832   };
16833 
16834 
16835   /** Delete the topic.
16836   @param {Object} [callbacks] callback functions.
16837   @param {Function} callbacks.success callback called when operation succeeded.
16838   <br>argument is topic object.
16839   @param {Function} callbacks.failure callback called when operation failed.
16840   <br>argument is Error object.
16841   @return {Promise} return promise object.
16842     <ul>
16843       <li>fulfill callback function: function(theDeletedTopic). theDeletedTopic is a KiiTopic instance.</li>
16844       <li>reject callback function: function(error). error is an Error instance.
16845         <ul>
16846           <li>error.target is the KiiTopic instance which this method was called on.</li>
16847           <li>error.message</li>
16848         </ul>
16849       </li>
16850     </ul>
16851   @example
16852   // example to use callbacks directly
16853   // assume topic is already instantiated.
16854   topic.deleteTopic({
16855       success: function(topic) {
16856           // Delete topic succeeded.
16857       },
16858       failure: function(error) {
16859           // Handle error.
16860       }
16861   });
16862   
16863   // example to use Promise
16864   // assume topic is already instantiated.
16865   topic.deleteTopic().then(
16866       function(topic) {
16867           // Delete topic succeeded.
16868       },
16869       function(error) {
16870           // Handle error.
16871       }
16872   );
16873    */
16874 
16875   KiiTopic.prototype.deleteTopic = function(callbacks) {
16876     return new Promise((function(_this) {
16877       return function(resolve, reject) {
16878         var sendCallbacks, wrapper;
16879         wrapper = KiiXHRWrapperFactory.createXHRWrapper('DELETE', _this._uri);
16880         wrapper.setKiiHeaders();
16881         _this._setAuthToken(wrapper);
16882         sendCallbacks = {
16883           success: function() {
16884             if (callbacks != null) {
16885               callbacks.success(_this);
16886             }
16887             return resolve(_this);
16888           },
16889           failure: function() {
16890             var errObj, errString;
16891             errString = wrapper.getErrorString("delete topic");
16892             errObj = KiiUtilities._Error(errString, _this);
16893             if (callbacks != null) {
16894               callbacks.failure(errObj);
16895             }
16896             return reject(errObj);
16897           }
16898         };
16899         return wrapper.send(sendCallbacks);
16900       };
16901     })(this));
16902   };
16903 
16904 
16905   /** Get ACL object of this topic.
16906   Access to topic can be configured by adding/removing KiiACLEntry
16907   to/from obtained acl object.
16908   @return {KiiACL} acl object of this topic.
16909    */
16910 
16911   KiiTopic.prototype.acl = function() {
16912     return root.KiiACL.aclWithParent(this);
16913   };
16914 
16915   KiiTopic.prototype._setAuthToken = function(wrapper) {
16916     return wrapper.setCurrentUserToken();
16917   };
16918 
16919   KiiTopic.prototype._getHttpUri = function() {
16920     return this._uri;
16921   };
16922 
16923   return KiiTopic;
16924 
16925 })();
16926 
16927 
16928 /**
16929 @class Builder of push message
16930 @exports root.KiiPushMessageBuilder as KiiPushMessageBuilder
16931  */
16932 
16933 root.KiiPushMessageBuilder = (function() {
16934 
16935   /** instantiate builder with push message data.
16936   By default all push channels (gcm, apns, jpush, mqtt) is enabled.
16937   All other properties configured by method of this class won't be set and default
16938   value would be applied.<br>
16939   Details of properties of message and its default value, please refer to
16940   http://documentation.kii.com/rest/#notification_management-leverage__push_to_users__notification-group_scope-send_messages-send_a_push_message_to_the_current_topic
16941   @param {Object} data sent to all push channels (gcm, apns, jpush, mqtt).
16942    */
16943   function KiiPushMessageBuilder(data) {
16944     this.data = data;
16945     this.mqttData = __bind(this.mqttData, this);
16946     this.jpushData = __bind(this.jpushData, this);
16947     this.apnsMutableContent = __bind(this.apnsMutableContent, this);
16948     this.apnsCategory = __bind(this.apnsCategory, this);
16949     this.apnsContentAvailable = __bind(this.apnsContentAvailable, this);
16950     this.apnsBadge = __bind(this.apnsBadge, this);
16951     this.apnsSound = __bind(this.apnsSound, this);
16952     this.apnsAlert = __bind(this.apnsAlert, this);
16953     this.apnsData = __bind(this.apnsData, this);
16954     this.gcmRestrictedPackageName = __bind(this.gcmRestrictedPackageName, this);
16955     this.gcmTimeToLive = __bind(this.gcmTimeToLive, this);
16956     this.gcmDelayWhileIdle = __bind(this.gcmDelayWhileIdle, this);
16957     this.gcmCollapseKey = __bind(this.gcmCollapseKey, this);
16958     this.gcmData = __bind(this.gcmData, this);
16959     this.enableMqtt = __bind(this.enableMqtt, this);
16960     this.enableJpush = __bind(this.enableJpush, this);
16961     this.enableApns = __bind(this.enableApns, this);
16962     this.enableGcm = __bind(this.enableGcm, this);
16963     this.setSendToProduction = __bind(this.setSendToProduction, this);
16964     this.setSendToDevelopment = __bind(this.setSendToDevelopment, this);
16965     this.build = __bind(this.build, this);
16966     this.gcm = {};
16967     this.apns = {};
16968     this.jpush = {};
16969     this.mqtt = {};
16970     this.gcm.enabled = true;
16971     this.apns.enabled = true;
16972     this.jpush.enabled = true;
16973     this.mqtt.enabled = true;
16974   }
16975 
16976 
16977   /** build push message.
16978   @return {Object} push message object. Can be used in {@link KiiTopic#sendMessage()}
16979    */
16980 
16981   KiiPushMessageBuilder.prototype.build = function() {
16982     var ret;
16983     ret = {};
16984     ret.data = this.data;
16985     ret.gcm = this.gcm;
16986     ret.apns = this.apns;
16987     ret.jpush = this.jpush;
16988     ret.mqtt = this.mqtt;
16989     if (this.sendToDevelopment != null) {
16990       ret.sendToDevelopment = this.sendToDevelopment;
16991     }
16992     if (this.sendToProduction != null) {
16993       ret.sendToProduction = this.sendToProduction;
16994     }
16995     return ret;
16996   };
16997 
16998 
16999   /** Indicate whether send this message to development environment.
17000   If this method is not called, true will be applied as default.
17001   @param {boolean} flag indicate whether send this message to development env.
17002   @return builder instance.
17003    */
17004 
17005   KiiPushMessageBuilder.prototype.setSendToDevelopment = function(flag) {
17006     this.sendToDevelopment = flag;
17007     return this;
17008   };
17009 
17010 
17011   /** Indicate whether send this message to production environment.
17012   If this method is not called, true will be applied as default.
17013   @param {boolean} flag indicate whether send this message to production env.
17014   @return {Object} builder instance.
17015    */
17016 
17017   KiiPushMessageBuilder.prototype.setSendToProduction = function(flag) {
17018     this.sendToProduction = flag;
17019     return this;
17020   };
17021 
17022 
17023   /** Enable/ Disable message distribution via GCM.
17024   If this method is not called, true will be applied as default.
17025   @param {boolean} enable flag indicate whether distribute this message to GCM subscribers.
17026   @return {Object} builder instance.
17027    */
17028 
17029   KiiPushMessageBuilder.prototype.enableGcm = function(enable) {
17030     this.gcm.enabled = enable;
17031     return this;
17032   };
17033 
17034 
17035   /** Enable/ Disable message distribution via APNS.
17036   If this method is not called, true will be applied as default.
17037   @param {boolean} enable flag indicate whether distribute this message to APNS subscribers.
17038   @return {Object} builder instance.
17039    */
17040 
17041   KiiPushMessageBuilder.prototype.enableApns = function(enable) {
17042     this.apns.enabled = enable;
17043     return this;
17044   };
17045 
17046 
17047   /** Enable/ Disable message distribution via JPush.
17048   If this method is not called, true will be applied as default.
17049   @param {boolean} enable flag indicate whether distribute this message to JPush subscribers.
17050   @return {Object} builder instance.
17051    */
17052 
17053   KiiPushMessageBuilder.prototype.enableJpush = function(enable) {
17054     this.jpush.enabled = enable;
17055     return this;
17056   };
17057 
17058 
17059   /** Enable/ Disable message distribution via MQTT.
17060   If this method is not called, true will be applied as default.
17061   @param {boolean} enable flag indicate whether distribute this message to MQTT subscribers.
17062   @return {Object} builder instance.
17063    */
17064 
17065   KiiPushMessageBuilder.prototype.enableMqtt = function(enable) {
17066     this.mqtt.enabled = enable;
17067     return this;
17068   };
17069 
17070 
17071   /** Set specific data for GCM subscribers.
17072   If this method is not called, no specific data is not applied
17073   and data passed to the constructor would be sent to subscribers.
17074   @param {Object} data specific data applied to only GCM subscribers.
17075   Contents should be JSON Object with only one-level of nesting,
17076   and only strings in values
17077   @return {Object} builder instance.
17078    */
17079 
17080   KiiPushMessageBuilder.prototype.gcmData = function(data) {
17081     this.gcm.data = data;
17082     return this;
17083   };
17084 
17085 
17086   /** Set collapse_key for GCM subscribers.
17087   If this method is not called, no collapse_key is applied.
17088   For details please refer to GCM document of collapse_key.
17089   @param {String} collapseKey
17090   @return {Object} builder instance.
17091    */
17092 
17093   KiiPushMessageBuilder.prototype.gcmCollapseKey = function(collapseKey) {
17094     this.gcm.collapseKey = collapseKey;
17095     return this;
17096   };
17097 
17098 
17099   /** Set delay_while_idle for GCM subscribers.
17100   If this method is not called, no delay_while_idle is applied.
17101   For details please refer to GCM document of delay_while_idle.
17102   @param {boolean} delayWhileIdle
17103   @return {Object} builder instance.
17104    */
17105 
17106   KiiPushMessageBuilder.prototype.gcmDelayWhileIdle = function(delayWhileIdle) {
17107     this.gcm.delayWhileIdle = delayWhileIdle;
17108     return this;
17109   };
17110 
17111 
17112   /** Set time_to_live for GCM subscribers.
17113   If this method is not called, no time_to_live is applied.
17114   For details please refer to GCM document of time_to_live.
17115   @param {Number} timeToLive
17116   @return {Object} builder instance.
17117    */
17118 
17119   KiiPushMessageBuilder.prototype.gcmTimeToLive = function(timeToLive) {
17120     this.gcm.timeToLive = timeToLive;
17121     return this;
17122   };
17123 
17124 
17125   /** Set restricted_package_name for GCM subscribers.
17126   If this method is not called, no restricted_package_name is applied.
17127   For details please refer to GCM document of restricted_package_name.
17128   @param {String} restrictedPackageName.
17129   @return {Object} builder instance.
17130    */
17131 
17132   KiiPushMessageBuilder.prototype.gcmRestrictedPackageName = function(restrictedPackageName) {
17133     this.gcm.restrictedPackageName = restrictedPackageName;
17134     return this;
17135   };
17136 
17137 
17138   /** Set specific data for APNS subscribers.
17139   If this method is not called, no specific data is not applied
17140   and data passed to the constructor would be sent to subscribers.
17141   @param {Object} data specific data applied to only APNS subscribers.
17142   Contents should be JSON Object with only one-level of nesting,
17143   and only strings, integers, booleans or doubles in the values.
17144   @return {Object} builder instance.
17145    */
17146 
17147   KiiPushMessageBuilder.prototype.apnsData = function(data) {
17148     this.apns.data = data;
17149     return this;
17150   };
17151 
17152 
17153   /** Set alert for APNS subscribers.
17154   If this method is not called, no alert is applied.
17155   For details please refer to APNS document of alert.
17156   @param {Object} alert alert object
17157   @return {Object} builder instance.
17158    */
17159 
17160   KiiPushMessageBuilder.prototype.apnsAlert = function(alert) {
17161     this.apns.alert = alert;
17162     return this;
17163   };
17164 
17165 
17166   /** Set sound for APNS subscribers.
17167   If this method is not called, no sound is applied.
17168   For details please refer to APNS document of sound.
17169   @param {String} sound
17170   @return {Object} builder instance.
17171    */
17172 
17173   KiiPushMessageBuilder.prototype.apnsSound = function(sound) {
17174     this.apns.sound = sound;
17175     return this;
17176   };
17177 
17178 
17179   /** Set badge for APNS subscribers.
17180   If this method is not called, no badge is applied.
17181   For details please refer to APNS document of badge.
17182   @param {Number} badge
17183   @return {Object} builder instance.
17184    */
17185 
17186   KiiPushMessageBuilder.prototype.apnsBadge = function(badge) {
17187     this.apns.badge = badge;
17188     return this;
17189   };
17190 
17191 
17192   /** Set content-available for APNS subscribers.
17193   If this method is not called, no content-available is applied.
17194   @param {Number} contentAvailable If eqaul or less than 0
17195   or this method is not invoked,
17196   content-available payload is not delivered.
17197   Otherwise, content-available=1 payload is delivered.
17198   @return {Object} builder instance.
17199    */
17200 
17201   KiiPushMessageBuilder.prototype.apnsContentAvailable = function(contentAvailable) {
17202     if (contentAvailable > 0) {
17203       this.apns.contentAvailable = true;
17204     } else {
17205       delete this.apns.contentAvailable;
17206     }
17207     return this;
17208   };
17209 
17210 
17211   /** Set category for APNS subscribers.
17212   If this method is not called, no category is applied.
17213   For details please refer to APNS document of category.
17214   @param {String} category
17215   @return {Object} builder instance.
17216    */
17217 
17218   KiiPushMessageBuilder.prototype.apnsCategory = function(category) {
17219     this.apns.category = category;
17220     return this;
17221   };
17222 
17223 
17224   /** Set mutable-content for APNS subscribers.
17225   If this method is not called, no mutable-content is applied.
17226   @param {Number} mutableContent If equal or less than 0
17227   or this method is not invoked,
17228   mutable-content payload is not delivered.
17229   Otherwise, mutable-content=1 payload is delivered.
17230   @return {Object} builder instance.
17231    */
17232 
17233   KiiPushMessageBuilder.prototype.apnsMutableContent = function(mutableContent) {
17234     if (mutableContent > 0) {
17235       this.apns.mutableContent = true;
17236     } else {
17237       delete this.apns.mutableContent;
17238     }
17239     return this;
17240   };
17241 
17242 
17243   /** Set specific data for JPush subscribers.
17244   If this method is not called, no specific data is not applied
17245   and data passed to the constructor would be sent to subscribers.
17246   @param {Object} data specific data applied to only JPush subscribers.
17247   Contents should be JSON Object with only one-level of nesting,
17248   and only strings, integers, booleans or doubles in the values.
17249   @return {Object} builder instance.
17250    */
17251 
17252   KiiPushMessageBuilder.prototype.jpushData = function(data) {
17253     this.jpush.data = data;
17254     return this;
17255   };
17256 
17257 
17258   /** Set specific data for MQTT subscribers.
17259   If this method is not called, no specific data is not applied
17260   and data passed to the constructor would be sent to subscribers.
17261   @param {Object} data specific data applied to only MQTT subscribers.
17262   Contents should be JSON Object with only one-level of nesting,
17263   and only strings in the values.
17264   @return {Object} builder instance.
17265    */
17266 
17267   KiiPushMessageBuilder.prototype.mqttData = function(data) {
17268     this.mqtt.data = data;
17269     return this;
17270   };
17271 
17272   return KiiPushMessageBuilder;
17273 
17274 })();
17275 
17276 
17277 /**
17278 @class Represents a KiiPushSubscription.
17279 @exports root.KiiPushSubscription as KiiPushSubscription
17280  */
17281 
17282 root.KiiPushSubscription = (function() {
17283   KiiPushSubscription.prototype.getSubscriber = function() {
17284     return this._subscriber;
17285   };
17286 
17287   function KiiPushSubscription(_subscriber) {
17288     this._subscriber = _subscriber;
17289     this._setAuthToken = __bind(this._setAuthToken, this);
17290     this._getRequestHTTPURI = __bind(this._getRequestHTTPURI, this);
17291     this._validateTarget = __bind(this._validateTarget, this);
17292     this.isSubscribed = __bind(this.isSubscribed, this);
17293     this.unsubscribe = __bind(this.unsubscribe, this);
17294     this.subscribe = __bind(this.subscribe, this);
17295   }
17296 
17297 
17298   /** Subscribe to bucket or topic.
17299   @param {Object} target to be subscribed. KiiBucket or KiiTopic instance.
17300   @param {Object} [callbacks] object contains callback functions.
17301   @param {Function} callbacks.success callback called when operation succeeded.
17302   <br>1st argument: KiiPushSubscription object
17303   <br>2nd argument: target object
17304   @param {Function} callbacks.failure callback called when operation failed.
17305   <br>argument is Error object.
17306   @return {Promise} return promise object.
17307     <ul>
17308       <li>fulfill callback function: function(params). params is an Array instance.
17309         <ul>
17310           <li>params[0] is a KiiPushSubscription instance.</li>
17311           <li>params[1] is the KiiTopic instance to subscribe.</li>
17312         </ul>
17313       </li>
17314       <li>reject callback function: function(error). error is an Error instance.
17315         <ul>
17316           <li>error.target is a KiiPushSubscription instance.</li>
17317           <li>error.message</li>
17318         </ul>
17319       </li>
17320     </ul>
17321   @example
17322   // example to use callbacks directly
17323   var topic = Kii.topicWithName("myAppTopic");
17324   var user = KiiUser.getCurrentUser();
17325   user.pushSubscription().subscribe(topic, {
17326       success: function(subscription, topic) {
17327           // Succeeded.
17328       },
17329       failure: function(error) {
17330           // Handle error.
17331       }
17332   });
17333   
17334   // example to use Promise
17335   var topic = Kii.topicWithName("myAppTopic");
17336   var user = KiiUser.getCurrentUser();
17337   user.pushSubscription().subscribe(topic).then(
17338       function(params) {
17339           var subscription = params[0];
17340           var topic = params[1];
17341           // Succeeded.
17342       },
17343       function(error) {
17344           // Handle error.
17345       }
17346   );
17347    */
17348 
17349   KiiPushSubscription.prototype.subscribe = function(target, callbacks) {
17350     return new Promise((function(_this) {
17351       return function(resolve, reject) {
17352         var requestUri, sendCallbacks, wrapper;
17353         if (!_this._validateTarget(target)) {
17354           if (callbacks != null) {
17355             callbacks.failure(root.InvalidArgumentException("target is invalid"));
17356           }
17357           reject(KiiUtilities._Error(root.InvalidArgumentException("target is invalid"), _this));
17358           return;
17359         }
17360         requestUri = _this._getRequestHTTPURI(target);
17361         wrapper = KiiXHRWrapperFactory.createXHRWrapper('PUT', requestUri);
17362         wrapper.setKiiHeaders();
17363         _this._setAuthToken(wrapper);
17364         sendCallbacks = {
17365           success: function() {
17366             if (callbacks != null) {
17367               callbacks.success(_this, target);
17368             }
17369             return resolve([_this, target]);
17370           },
17371           failure: function() {
17372             var errObj, errString;
17373             errString = wrapper.getErrorString("subscribe");
17374             errObj = KiiUtilities._Error(errString, _this);
17375             if (callbacks != null) {
17376               callbacks.failure(errObj);
17377             }
17378             return reject(errObj);
17379           }
17380         };
17381         return wrapper.send(sendCallbacks);
17382       };
17383     })(this));
17384   };
17385 
17386 
17387   /** Unsubscribe to bucket or topic.
17388   @param {Object} target to be unsubscribed. KiiBucket or KiiTopic instance.
17389   @param {Object} [callbacks] object contains callback functions.
17390   @param {Function} callbacks.success callback called when operation succeeded.
17391   <br>1st argument: KiiPushSubscription object
17392   <br>2nd argument: target object
17393   @param {Function} callbacks.failure callback called when operation failed.
17394   <br>argument is Error object.
17395   @return {Promise} return promise object.
17396     <ul>
17397       <li>fulfill callback function: function(params). params is an Array instance.
17398         <ul>
17399           <li>params[0] is a KiiPushSubscription instance.</li>
17400           <li>params[1] is the KiiTopic instance to unsubscribe.</li>
17401         </ul>
17402       </li>
17403       <li>reject callback function: function(error). error is an Error instance.
17404         <ul>
17405           <li>error.target is a KiiPushSubscription instance.</li>
17406           <li>error.message</li>
17407         </ul>
17408       </li>
17409     </ul>
17410   @example
17411   // example to use callbacks directly
17412   var topic = Kii.topicWithName("myAppTopic");
17413   var user = KiiUser.getCurrentUser();
17414   user.pushSubscription().unsubscribe(topic, {
17415       success: function(subscription, topic) {
17416           // Succeeded.
17417       },
17418       failure: function(error) {
17419           // Handle error.
17420       }
17421   });
17422   
17423   // example to use Promise
17424   var topic = Kii.topicWithName("myAppTopic");
17425   var user = KiiUser.getCurrentUser();
17426   user.pushSubscription().unsubscribe(topic).then(
17427       function(params) {
17428           var subscription = params[0];
17429           var topic = params[1];
17430           // Succeeded.
17431       },
17432       function(error) {
17433           // Handle error.
17434       }
17435   );
17436    */
17437 
17438   KiiPushSubscription.prototype.unsubscribe = function(target, callbacks) {
17439     return new Promise((function(_this) {
17440       return function(resolve, reject) {
17441         var requestUri, sendCallbacks, wrapper;
17442         if (!_this._validateTarget(target)) {
17443           if (callbacks != null) {
17444             callbacks.failure(root.InvalidArgumentException("target is invalid"));
17445           }
17446           reject(KiiUtilities._Error(root.InvalidArgumentException("target is invalid"), _this));
17447           return;
17448         }
17449         requestUri = _this._getRequestHTTPURI(target);
17450         wrapper = KiiXHRWrapperFactory.createXHRWrapper('DELETE', requestUri);
17451         wrapper.setKiiHeaders();
17452         _this._setAuthToken(wrapper);
17453         sendCallbacks = {
17454           success: function() {
17455             if (callbacks != null) {
17456               callbacks.success(_this, target);
17457             }
17458             return resolve([_this, target]);
17459           },
17460           failure: function() {
17461             var errObj, errString;
17462             errString = wrapper.getErrorString("unsubscribe");
17463             errObj = KiiUtilities._Error(errString, _this);
17464             if (callbacks != null) {
17465               callbacks.failure(errObj);
17466             }
17467             return reject(errObj);
17468           }
17469         };
17470         return wrapper.send(sendCallbacks);
17471       };
17472     })(this));
17473   };
17474 
17475 
17476   /** Check subscription of bucket, topic.
17477   @param {Object} target to check subscription. KiiBucket or KiiTopic instance.
17478   @param {Object} [callbacks] object contains callback functions.
17479   @param {Function} callbacks.success callback called when operation succeeded.
17480   <br>1st argument: KiiPushSubscription object
17481   <br>2nd argument: target object
17482   <br>3rd argument: flag indicate whether the target object is subscirbed.
17483   @param {Function} callbacks.failure callback called when operation failed.
17484   <br>argument is Error object.
17485   @return {Promise} return promise object.
17486     <ul>
17487       <li>fulfill callback function: function(params). params is an Array instance.
17488         <ul>
17489           <li>params[0] is a KiiPushSubscription instance.</li>
17490           <li>params[1] is the KiiTopic instance to subscribe.</li>
17491           <li>params[2] is Boolean value. true if subscirbed, otherwise false.</li>
17492         </ul>
17493       </li>
17494       <li>reject callback function: function(error). error is an Error instance.
17495         <ul>
17496           <li>error.target is a KiiPushSubscription instance.</li>
17497           <li>error.message</li>
17498         </ul>
17499       </li>
17500     </ul>
17501   @example
17502   // example to use callbacks directly
17503   var topic = Kii.topicWithName("myAppTopic");
17504   var user = KiiUser.getCurrentUser();
17505   user.pushSubscription().isSubscribed(topic, {
17506       success: function(subscription, topic, isSubscribed) {
17507           // Succeeded.
17508           if (isSubscribed) {
17509               // The topic is subscribed by current user.
17510           } else {
17511               // The topic is not subscribed by current user.
17512           }
17513       },
17514       failure: function(error) {
17515           // Handle error.
17516       }
17517   });
17518   
17519   // example to use Promise
17520   var topic = Kii.topicWithName("myAppTopic");
17521   var user = KiiUser.getCurrentUser();
17522   user.pushSubscription().isSubscribed(topic).then(
17523       function(params) {
17524           // Succeeded.
17525           var subscription = params[0];
17526           var topic = params[1];
17527           var isSubscribed = params[2];
17528           if (isSubscribed) {
17529               // The topic is subscribed by current user.
17530           } else {
17531               // The topic is not subscribed by current user.
17532           }
17533       },
17534       function(error) {
17535           // Handle error.
17536       }
17537   );
17538    */
17539 
17540   KiiPushSubscription.prototype.isSubscribed = function(target, callbacks) {
17541     return new Promise((function(_this) {
17542       return function(resolve, reject) {
17543         var requestUri, sendCallbacks, wrapper;
17544         if (!_this._validateTarget(target)) {
17545           if (callbacks != null) {
17546             callbacks.failure(root.InvalidArgumentException("target is invalid"));
17547           }
17548           reject(KiiUtilities._Error(root.InvalidArgumentException("target is invalid"), _this));
17549           return;
17550         }
17551         requestUri = _this._getRequestHTTPURI(target);
17552         wrapper = KiiXHRWrapperFactory.createXHRWrapper('GET', requestUri);
17553         wrapper.setKiiHeaders();
17554         _this._setAuthToken(wrapper);
17555         sendCallbacks = {
17556           success: function() {
17557             if (callbacks != null) {
17558               callbacks.success(_this, target, true);
17559             }
17560             return resolve([_this, target, true]);
17561           },
17562           failure: function() {
17563             var errObj, errString, errorCode;
17564             errorCode = wrapper.getErrorCode();
17565             if (errorCode === "FILTER_NOT_FOUND" || errorCode === "PUSH_SUBSCRIPTION_NOT_FOUND") {
17566               if (callbacks != null) {
17567                 callbacks.success(_this, target, false);
17568               }
17569               return resolve([_this, target, false]);
17570             } else {
17571               errString = wrapper.getErrorString("Check is subscribed");
17572               errObj = KiiUtilities._Error(errString, _this);
17573               if (callbacks != null) {
17574                 callbacks.failure(errObj);
17575               }
17576               return reject(errObj);
17577             }
17578           }
17579         };
17580         return wrapper.send(sendCallbacks);
17581       };
17582     })(this));
17583   };
17584 
17585   KiiPushSubscription.prototype._validateTarget = function(target) {
17586     return (target != null) && (target instanceof root.KiiBucket || target instanceof root.KiiTopic);
17587   };
17588 
17589   KiiPushSubscription.prototype._getRequestHTTPURI = function(target) {
17590     var requestUri;
17591     if (target instanceof root.KiiBucket) {
17592       return requestUri = "" + (target._getHttpUri()) + "/filters/all/push/subscriptions/" + (this._subscriber._getSubscriberPath());
17593     } else if (target instanceof root.KiiTopic) {
17594       return requestUri = "" + (target._getHttpUri()) + "/push/subscriptions/" + (this._subscriber._getSubscriberPath());
17595     }
17596   };
17597 
17598   KiiPushSubscription.prototype._setAuthToken = function(wrapper) {
17599     return wrapper.setCurrentUserToken();
17600   };
17601 
17602   return KiiPushSubscription;
17603 
17604 })();
17605 
17606 root.KiiThingWithToken = (function(_super) {
17607   __extends(KiiThingWithToken, _super);
17608 
17609   function KiiThingWithToken(fields, thingID, vendorThingID, _adminToken) {
17610     this._adminToken = _adminToken;
17611     this._getIdentifier = __bind(this._getIdentifier, this);
17612     this.updatePassword = __bind(this.updatePassword, this);
17613     this.topicWithName = __bind(this.topicWithName, this);
17614     this.bucketWithName = __bind(this.bucketWithName, this);
17615     this.pushSubscription = __bind(this.pushSubscription, this);
17616     this._setAuthToken = __bind(this._setAuthToken, this);
17617     KiiThingWithToken.__super__.constructor.call(this, fields);
17618     if (thingID != null) {
17619       this._thingID = thingID;
17620     }
17621     if (vendorThingID != null) {
17622       this._vendorThingID = vendorThingID;
17623     }
17624   }
17625 
17626   KiiThingWithToken.register = function(fields, callbacks, accessToken) {
17627     return new Promise(function(resolve, reject) {
17628       var sendCallbacks, wrapper;
17629       wrapper = KiiXHRWrapperFactory.createXHRWrapper('POST', "" + (root.Kii.getBaseURL()) + "/apps/" + (root.Kii.getAppID()) + "/things");
17630       wrapper.setKiiHeaders();
17631       wrapper.setContentType("application/vnd.kii.ThingRegistrationAndAuthorizationRequest+json");
17632       wrapper.setAuthToken(accessToken);
17633       sendCallbacks = {
17634         success: function() {
17635           var respJson, thing;
17636           respJson = JSON.parse(decodeURIComponent(wrapper.xhr.responseText));
17637           thing = new root.KiiThingWithToken(respJson, null, null, accessToken);
17638           if (callbacks != null) {
17639             callbacks.success(thing);
17640           }
17641           return resolve(thing);
17642         },
17643         failure: function() {
17644           var errObj, errString;
17645           errString = wrapper.getErrorString("register thing");
17646           errObj = KiiUtilities._Error(errString);
17647           if (callbacks != null) {
17648             callbacks.failure(errObj);
17649           }
17650           return reject(errObj);
17651         }
17652       };
17653       return wrapper.sendData(JSON.stringify(fields), sendCallbacks);
17654     });
17655   };
17656 
17657   KiiThingWithToken.registerOwnerWithThingID = function(thingID, owner, callbacks, accessToken) {
17658     return root.KiiThingWithToken._registerOwnerWithIdentifier(thingID, owner, callbacks, accessToken);
17659   };
17660 
17661   KiiThingWithToken.registerOwnerWithVendorThingID = function(vendorThingID, owner, callbacks, accessToken) {
17662     return root.KiiThingWithToken._registerOwnerWithIdentifier("VENDOR_THING_ID:" + vendorThingID, owner, callbacks, accessToken);
17663   };
17664 
17665   KiiThingWithToken._registerOwnerWithIdentifier = function(identifier, owner, callbacks, accessToken) {
17666     return new Promise(function(resolve, reject) {
17667       var oid, sendCallbacks, type, wrapper;
17668       if (owner instanceof root.KiiUser) {
17669         oid = owner.getID();
17670         type = 'user';
17671       } else if (owner instanceof root.KiiGroup) {
17672         oid = owner.getID();
17673         type = 'group';
17674       } else {
17675         throw 'owner should be instance of user or group';
17676       }
17677       if (oid == null) {
17678         throw 'owner instance does not have id';
17679       }
17680       wrapper = KiiXHRWrapperFactory.createXHRWrapper('PUT', "" + (root.Kii.getBaseURL()) + "/apps/" + (root.Kii.getAppID()) + "/things/" + identifier + "/ownership/" + type + ":" + oid);
17681       wrapper.setKiiHeaders();
17682       wrapper.setAuthToken(accessToken);
17683       sendCallbacks = {
17684         success: function() {
17685           if (callbacks != null) {
17686             callbacks.success(owner);
17687           }
17688           return resolve([owner]);
17689         },
17690         failure: function() {
17691           var errObj, errString;
17692           errString = wrapper.getErrorString("register owner");
17693           errObj = KiiUtilities._Error(errString);
17694           if (callbacks != null) {
17695             callbacks.failure(errObj);
17696           }
17697           return reject(errObj);
17698         }
17699       };
17700       return wrapper.send(sendCallbacks);
17701     });
17702   };
17703 
17704   KiiThingWithToken.loadWithVendorThingID = function(vendorThingID, callbacks, adminToken) {
17705     var thingAdmin;
17706     thingAdmin = new root.KiiThingWithToken(null, null, vendorThingID, adminToken);
17707     return thingAdmin.refresh(callbacks);
17708   };
17709 
17710   KiiThingWithToken.loadWithThingID = function(thingID, callbacks, adminToken) {
17711     var thingAdmin;
17712     thingAdmin = new root.KiiThingWithToken(null, thingID, null, adminToken);
17713     return thingAdmin.refresh(callbacks);
17714   };
17715 
17716   KiiThingWithToken.prototype._setAuthToken = function(wrapper) {
17717     return wrapper.setAuthToken(this._adminToken);
17718   };
17719 
17720   KiiThingWithToken.prototype.pushSubscription = function() {
17721     return new root.KiiPushSubscriptionWithToken(this, this._adminToken);
17722   };
17723 
17724   KiiThingWithToken.prototype.bucketWithName = function(bucketName) {
17725     return new root.KiiBucketWithToken(bucketName, this, this._adminToken);
17726   };
17727 
17728   KiiThingWithToken.prototype.encryptedBucketWithName = function(bucketName) {
17729     return new root.KiiEncryptedBucketWithToken(bucketName, this, this._adminToken);
17730   };
17731 
17732   KiiThingWithToken.prototype.topicWithName = function(topicName) {
17733     if (typeof topicName !== "string" || topicName === "") {
17734       throw new root.InvalidArgumentException('topicName should not null or empty');
17735     }
17736     return new root.KiiTopicWithToken(this._getHttpURI(), topicName, this._adminToken);
17737   };
17738 
17739   KiiThingWithToken.prototype.updatePassword = function(newPassword, callbacks) {
17740     return new Promise((function(_this) {
17741       return function(resolve, reject) {
17742         var errObj, requestBody, sendCallbacks, wrapper;
17743         if (!KiiUtilities._isNonEmptyString(newPassword)) {
17744           errObj = KiiUtilities._Error("newPassword is null or empty");
17745           if (callbacks != null) {
17746             callbacks.failure(errObj);
17747           }
17748           reject(errObj);
17749           return;
17750         }
17751         requestBody = {
17752           newPassword: newPassword
17753         };
17754         wrapper = KiiXHRWrapperFactory.createXHRWrapper('PUT', "" + (root.Kii.getBaseURL()) + "/apps/" + (root.Kii.getAppID()) + "/things/" + (_this._getIdentifier()) + "/password");
17755         wrapper.setKiiHeaders();
17756         wrapper.setAuthToken(_this._adminToken);
17757         wrapper.setContentType("application/vnd.kii.ChangeThingPasswordRequest+json");
17758         sendCallbacks = {
17759           success: function() {
17760             if (callbacks != null) {
17761               callbacks.success(_this);
17762             }
17763             return resolve(_this);
17764           },
17765           failure: function() {
17766             var errString;
17767             errString = wrapper.getErrorString("changing thing password");
17768             errObj = KiiUtilities._Error(errString);
17769             if (callbacks != null) {
17770               callbacks.failure(errObj);
17771             }
17772             return reject(errObj);
17773           }
17774         };
17775         return wrapper.sendData(JSON.stringify(requestBody), sendCallbacks);
17776       };
17777     })(this));
17778   };
17779 
17780   KiiThingWithToken.prototype._getIdentifier = function() {
17781     if (this._thingID != null) {
17782       return this._thingID;
17783     }
17784     if (this._vendorThingID != null) {
17785       return "VENDOR_THING_ID:" + this._vendorThingID;
17786     }
17787     return null;
17788   };
17789 
17790   KiiThingWithToken.thingWithID = function(thingID, adminToken) {
17791     var thingAdmin;
17792     thingAdmin = new root.KiiThingWithToken(null, thingID, null, adminToken);
17793     return thingAdmin;
17794   };
17795 
17796   return KiiThingWithToken;
17797 
17798 })(root.KiiThing);
17799 
17800 root.KiiTopicWithToken = (function(_super) {
17801   __extends(KiiTopicWithToken, _super);
17802 
17803   function KiiTopicWithToken(parentUri, topicName, _authToken) {
17804     this._authToken = _authToken;
17805     this.acl = __bind(this.acl, this);
17806     this._setAuthToken = __bind(this._setAuthToken, this);
17807     KiiTopicWithToken.__super__.constructor.call(this, parentUri, topicName);
17808   }
17809 
17810   KiiTopicWithToken.prototype._setAuthToken = function(wrapper) {
17811     return wrapper.setAuthToken(this._authToken);
17812   };
17813 
17814   KiiTopicWithToken.prototype.acl = function() {
17815     return new root.KiiACLWithToken(this, this._authToken);
17816   };
17817 
17818   return KiiTopicWithToken;
17819 
17820 })(root.KiiTopic);
17821 
17822 root.KiiPushSubscriptionWithToken = (function(_super) {
17823   __extends(KiiPushSubscriptionWithToken, _super);
17824 
17825   function KiiPushSubscriptionWithToken(subscriber, _authToken) {
17826     this._authToken = _authToken;
17827     this._setAuthToken = __bind(this._setAuthToken, this);
17828     KiiPushSubscriptionWithToken.__super__.constructor.call(this, subscriber);
17829   }
17830 
17831   KiiPushSubscriptionWithToken.prototype._setAuthToken = function(wrapper) {
17832     return wrapper.setAuthToken(this._authToken);
17833   };
17834 
17835   return KiiPushSubscriptionWithToken;
17836 
17837 })(root.KiiPushSubscription);
17838 
17839 root.KiiSCNGoogle = (function(_super) {
17840   __extends(KiiSCNGoogle, _super);
17841 
17842   function KiiSCNGoogle() {
17843     this._unlinkFromCurrentUser = __bind(this._unlinkFromCurrentUser, this);
17844     this._linkWithCurrentUser = __bind(this._linkWithCurrentUser, this);
17845     this._logOut = __bind(this._logOut, this);
17846     this._logIn = __bind(this._logIn, this);
17847     this._getAccessToken = __bind(this._getAccessToken, this);
17848     this._createTokenObject = __bind(this._createTokenObject, this);
17849     this._setup = __bind(this._setup, this);
17850     KiiSCNGoogle.__super__.constructor.call(this, root.KiiSocialNetworkName.GOOGLEPLUS);
17851   }
17852 
17853   KiiSCNGoogle.prototype._setup = function(_key, _secret, _extras) {
17854     this._key = _key;
17855     this._secret = _secret;
17856     this._extras = _extras;
17857     return KiiSCNGoogle.__super__._setup.call(this, this._key, this._secret, this._extras);
17858   };
17859 
17860   KiiSCNGoogle.prototype._createTokenObject = function(options, data) {
17861     var tokenObject;
17862     tokenObject = {
17863       "access_token": options.access_token
17864     };
17865     if ((data != null) && (data.new_user_created != null)) {
17866       tokenObject["kii_new_user"] = data.new_user_created;
17867     }
17868     return tokenObject;
17869   };
17870 
17871   KiiSCNGoogle.prototype._getAccessToken = function(options) {
17872     return options.access_token;
17873   };
17874 
17875   KiiSCNGoogle.prototype._logIn = function(options, callbacks) {
17876     var requestData;
17877     root.Kii.logger("should auth google");
17878     root.Kii.logger("Checking options");
17879     if ((options == null) || !options.access_token) {
17880       throw root.InvalidArgumentException('options.access_token is required');
17881     }
17882     if (root.KiiUser.getCurrentUser() != null) {
17883       root.KiiUser.logOut();
17884     }
17885     requestData = {
17886       "accessToken": options.access_token
17887     };
17888     return this._register("google", "application/vnd.kii.AuthTokenGoogleRequest+json", requestData, options, callbacks);
17889   };
17890 
17891   KiiSCNGoogle.prototype._logOut = function() {
17892     KiiSCNGoogle.__super__._logOut.apply(this, arguments);
17893     return root.Kii.logger("Log out google");
17894   };
17895 
17896   KiiSCNGoogle.prototype._linkWithCurrentUser = function(options, callbacks) {
17897     var requestData;
17898     if (root.KiiUser.getCurrentUser() != null) {
17899       if ((options == null) || !options.access_token) {
17900         throw root.InvalidArgumentException('options.access_token is required');
17901       }
17902       requestData = {
17903         "accessToken": options.access_token
17904       };
17905       return this._link("google", "application/vnd.kii.LinkGoogleRequest+json", requestData, options, callbacks);
17906     } else if (callbacks != null) {
17907       return callbacks.failure(null, this._network, "A KiiUser must be logged in before linking to Google");
17908     }
17909   };
17910 
17911   KiiSCNGoogle.prototype._unlinkFromCurrentUser = function(callbacks) {
17912     if (root.KiiUser.getCurrentUser() != null) {
17913       return this._unlink("google", callbacks);
17914     } else if (callbacks != null) {
17915       return callbacks.failure("A KiiUser must be logged in before unlinking from Google");
17916     }
17917   };
17918 
17919   return KiiSCNGoogle;
17920 
17921 })(root.KiiSocialConnectNetwork);
17922 
17923 root.KiiSCNRenRen = (function(_super) {
17924   __extends(KiiSCNRenRen, _super);
17925 
17926   function KiiSCNRenRen() {
17927     this._unlinkFromCurrentUser = __bind(this._unlinkFromCurrentUser, this);
17928     this._linkWithCurrentUser = __bind(this._linkWithCurrentUser, this);
17929     this._logOut = __bind(this._logOut, this);
17930     this._logIn = __bind(this._logIn, this);
17931     this._getAccessToken = __bind(this._getAccessToken, this);
17932     this._createTokenObject = __bind(this._createTokenObject, this);
17933     this._setup = __bind(this._setup, this);
17934     KiiSCNRenRen.__super__.constructor.call(this, root.KiiSocialNetworkName.RENREN);
17935   }
17936 
17937   KiiSCNRenRen.prototype._setup = function(_key, _secret, _extras) {
17938     this._key = _key;
17939     this._secret = _secret;
17940     this._extras = _extras;
17941     return KiiSCNRenRen.__super__._setup.call(this, this._key, this._secret, this._extras);
17942   };
17943 
17944   KiiSCNRenRen.prototype._createTokenObject = function(options, data) {
17945     var tokenObject;
17946     tokenObject = {
17947       "access_token": options.access_token
17948     };
17949     if ((data != null) && (data.new_user_created != null)) {
17950       tokenObject["kii_new_user"] = data.new_user_created;
17951     }
17952     return tokenObject;
17953   };
17954 
17955   KiiSCNRenRen.prototype._getAccessToken = function(options) {
17956     return options.access_token;
17957   };
17958 
17959   KiiSCNRenRen.prototype._logIn = function(options, callbacks) {
17960     var requestData;
17961     root.Kii.logger("should auth renren");
17962     root.Kii.logger("Checking options");
17963     if ((options == null) || !options.access_token) {
17964       throw root.InvalidArgumentException('options.access_token is required');
17965     }
17966     if (root.KiiUser.getCurrentUser() != null) {
17967       root.KiiUser.logOut();
17968     }
17969     requestData = {
17970       "accessToken": options.access_token
17971     };
17972     return this._register("renren", "application/vnd.kii.AuthTokenRenRenRequest+json", requestData, options, callbacks);
17973   };
17974 
17975   KiiSCNRenRen.prototype._logOut = function() {
17976     KiiSCNRenRen.__super__._logOut.apply(this, arguments);
17977     return root.Kii.logger("Log out renren");
17978   };
17979 
17980   KiiSCNRenRen.prototype._linkWithCurrentUser = function(options, callbacks) {
17981     var requestData;
17982     if (root.KiiUser.getCurrentUser() != null) {
17983       if ((options == null) || !options.access_token) {
17984         throw root.InvalidArgumentException('options.access_token is required');
17985       }
17986       requestData = {
17987         "accessToken": options.access_token
17988       };
17989       return this._link("renren", "application/vnd.kii.LinkRenRenRequest+json", requestData, options, callbacks);
17990     } else if (callbacks != null) {
17991       return callbacks.failure(null, this._network, "A KiiUser must be logged in before linking to RenRen");
17992     }
17993   };
17994 
17995   KiiSCNRenRen.prototype._unlinkFromCurrentUser = function(callbacks) {
17996     if (root.KiiUser.getCurrentUser() != null) {
17997       return this._unlink("renren", callbacks);
17998     } else if (callbacks != null) {
17999       return callbacks.failure("A KiiUser must be logged in before unlinking from RenRen");
18000     }
18001   };
18002 
18003   return KiiSCNRenRen;
18004 
18005 })(root.KiiSocialConnectNetwork);
18006 
18007 
18008 /**
18009     @class represents a KiiThingContext object
18010     @exports root.KiiThingContext as KiiThingContext
18011  */
18012 
18013 root.KiiThingContext = (function() {
18014   function KiiThingContext(spec) {
18015     this._objectWithURI = __bind(this._objectWithURI, this);
18016     this._getToken = __bind(this._getToken, this);
18017     this.pushInstallation = __bind(this.pushInstallation, this);
18018     this.getAuthenticatedThing = __bind(this.getAuthenticatedThing, this);
18019     this.listTopics = __bind(this.listTopics, this);
18020     this.topicWithName = __bind(this.topicWithName, this);
18021     this._token = spec.token;
18022     this._thingId = spec.thingId;
18023     if (spec.vendorThingID != null) {
18024       this._vendorThingID = spec.vendorThingID;
18025     }
18026   }
18027 
18028 
18029   /**
18030       Creates a reference to a bucket in App scope operated by thing.
18031       @param String bucketName The name of the bucket the app should create/access
18032       @returns {KiiBucket} A working KiiBucket object
18033       @example
18034       Kii.authenticateAsThing("vendorThingID", "password", {
18035           success: function(thingAuthContext) {
18036               var bucket = thingAuthContext.bucketWithName("myAppBucket");
18037           },
18038           failure: function(errorString, errorCode) {
18039               // auth failed.
18040           }
18041       });
18042    */
18043 
18044   KiiThingContext.prototype.bucketWithName = function(bucketName) {
18045     var adminBucket;
18046     adminBucket = new root.KiiBucketWithToken(bucketName, null, this._token);
18047     return adminBucket;
18048   };
18049 
18050 
18051   /**
18052       Creates a reference to a encrypted bucket in App scope operated by thing.
18053       <br><br>The bucket will be created/accessed within this app's scope
18054       @param String bucketName The name of the bucket the app should create/access
18055       @returns {KiiBucket} A working KiiBucket object
18056       @example
18057       Kii.authenticateAsThing("vendorThingID", "password", {
18058           success: function(thingAuthContext) {
18059               var bucket = thingAuthContext.encryptedBucketWithName("myAppBucket");
18060           },
18061           failure: function(errorString, errorCode) {
18062               // auth failed.
18063           }
18064       });
18065    */
18066 
18067   KiiThingContext.prototype.encryptedBucketWithName = function(bucketName) {
18068     var bucket;
18069     bucket = new root.KiiEncryptedBucketWithToken(bucketName, null, this._token);
18070     return bucket;
18071   };
18072 
18073 
18074   /**
18075       Creates a reference to an object operated by thing using object`s URI.
18076       @param String object URI.
18077       @returns {KiiObject} A working KiiObject instance
18078       @throws {InvalidURIException} If the URI is null, empty or does not have correct format.
18079    */
18080 
18081   KiiThingContext.prototype.objectWithURI = function(objectURI) {
18082     var object;
18083     object = this._objectWithURI(objectURI);
18084     return object;
18085   };
18086 
18087 
18088   /**
18089   Creates a reference to a topic in App scope operated by thing.
18090   <br><br>The Topic will be created/accessed within this app's scope
18091   @param {String} topicName name of the topic. Must be a not empty string.
18092   @return {KiiTopic} topic instance.
18093    */
18094 
18095   KiiThingContext.prototype.topicWithName = function(topicName) {
18096     if (typeof topicName !== "string" || topicName === "") {
18097       throw new root.InvalidArgumentException('topicName should not null or empty');
18098     }
18099     return new root.KiiTopicWithToken("" + (root.Kii.getBaseURL()) + "/apps/" + (root.Kii.getAppID()), topicName, this._token);
18100   };
18101 
18102 
18103   /** Gets a list of topics in app scope
18104   @param {Object} callbacks An object with callback methods defined
18105   @param {Method} callbacks.success The callback method to call on a successful list request
18106   @param {Method} callbacks.failure The callback method to call on a failed list request
18107   @param {String} paginationKey You can specify the pagination key with the nextPaginationKey passed by callbacks.success. If empty string or no string object is provided, this API regards no paginationKey specified.
18108   @return {Promise} return promise object.
18109       <ul>
18110         <li>fulfill callback function: function(params). params is Array instance.
18111           <ul>
18112             <li>params[0] is array of KiiTopic instances.</li>
18113             <li>params[1] is string of nextPaginationKey.</li>
18114           </ul>
18115         </li>
18116         <li>reject callback function: function(error). error is an Error instance.
18117           <ul>
18118             <li>error.target is a KiiAppAdminContext instance which this method was called on.</li>
18119             <li>error.message</li>
18120           </ul>
18121         </li>
18122       </ul>
18123   @example
18124   // example to use callbacks directly
18125   // Assume you already have thingAuthContext instance.
18126   thingAuthContext.listTopics({
18127       success: function(topicList, nextPaginationKey) {
18128           // do something with the result
18129           for(var i=0; i<topicList.length; i++){
18130               var topic = topicList[i];
18131           }
18132           if (nextPaginationKey != null) {
18133               thingAuthContext.listTopics({
18134                   success: function(topicList, nextPaginationKey) {...},
18135                   failure: function(anErrorString) {...}
18136               }, nextPaginationKey);
18137           }
18138       },
18139       failure: function(anErrorString) {
18140           // do something with the error response
18141       }
18142   });
18143   
18144   // example to use Promise
18145   // Assume you already have thingAuthContext instance.
18146   thingAuthContext.listTopics().then(
18147       function(params) {
18148           var topicList = params[0];
18149           var nextPaginationKey = params[1];
18150           // do something with the result
18151           for(var i=0; i<topicList.length; i++){
18152               var topic = topicList[i];
18153           }
18154           if (nextPaginationKey != null) {
18155               thingAuthContext.listTopics(null, nextPaginationKey).then(
18156                   function(params) {...},
18157                   function(error) {...}
18158               );
18159           }
18160       },
18161       function(error) {
18162           // do something with the error response
18163       }
18164   );
18165    */
18166 
18167   KiiThingContext.prototype.listTopics = function(callbacks, paginationKey) {
18168     return root.Kii._listTopics(callbacks, paginationKey, this);
18169   };
18170 
18171 
18172   /** Gets authenticated KiiThing instance.
18173   <br>Returned thing instance only have thingID, vendorThingID and accessToken.
18174   (vendorThingID is not included when you used
18175   {@link Kii.authenticateAsThingWithToken()} to obtain KiiThingContext.)
18176   <br>Please execute {@link KiiThing#refresh()} to obtain other properties.
18177   @return {KiiThing} return authenticated KiiThing instance.
18178    */
18179 
18180   KiiThingContext.prototype.getAuthenticatedThing = function() {
18181     var thingContext;
18182     thingContext = root.KiiThingWithToken.thingWithID(this._thingId, this._token);
18183     thingContext._accessToken = this._token;
18184     thingContext._vendorThingID = this._vendorThingID;
18185     return thingContext;
18186   };
18187 
18188 
18189   /** Instantiate push installation for this thing.
18190   @return {KiiPushInstallation} push installation object.
18191    */
18192 
18193   KiiThingContext.prototype.pushInstallation = function() {
18194     return new root.KiiPushInstallationWithToken(this._token);
18195   };
18196 
18197   KiiThingContext.prototype._getToken = function() {
18198     return this._token;
18199   };
18200 
18201   KiiThingContext.prototype._objectWithURI = function(objectUri) {
18202     var bucket, bucketIndex, bucketName, compLength, components, newURI, obj, subject, valid;
18203     if (!objectUri) {
18204       throw new root.InvalidURIException;
18205     }
18206     valid = (objectUri.indexOf("kiicloud://")) === 0;
18207     newURI = objectUri.substr("kiicloud://".length);
18208     components = newURI.split("/");
18209     compLength = components.length;
18210     if (compLength >= 4 && valid) {
18211       bucketIndex = compLength === 4 ? 1 : 3;
18212       bucketName = components[bucketIndex];
18213       subject = null;
18214       if (components[0] === "groups" && compLength === 6) {
18215         subject = new root.KiiGroupWithToken._groupWithID(components[1], this._token);
18216       } else if (components[0] === "users" && compLength === 6) {
18217         subject = root.KiiUserWithToken._userWithID(components[1], this._token);
18218       } else if (components[0] === "things" && compLength === 6) {
18219         subject = root.KiiThingWithToken.thingWithID(components[1], this._token);
18220       } else if (compLength !== 4) {
18221         throw new root.InvalidURIException;
18222       }
18223       bucket = new root.KiiBucketWithToken(bucketName, subject, this._token);
18224       obj = bucket.createObject();
18225       obj._setUUID(components[compLength - 1]);
18226     } else {
18227       throw new root.InvalidURIException;
18228     }
18229     return obj;
18230   };
18231 
18232   return KiiThingContext;
18233 
18234 })();
18235 
18236 
18237 /**
18238     @class Represents a KiiUser builder
18239     @exports root.KiiUserBuilder as KiiUserBuilder
18240  */
18241 
18242 root.KiiUserBuilder = (function() {
18243   function KiiUserBuilder() {
18244     this._password = null;
18245     this._username = null;
18246     this._emailAddress = null;
18247     this._phoneNumber = null;
18248     this._country = null;
18249   }
18250 
18251 
18252   /** Create a KiiUser builder with identifier.
18253   
18254   <br><br>Create a KiiUser builder. This constructor is received
18255   identifier. The identifier is one of user name, email address or
18256   phone number. This constructor automatically identity What is
18257   identifier and build proper KiiUser object on build method.
18258   
18259   <br><br> Some strings can be accepted as both user name and phone
18260   number. If such string is passed to this constructor as
18261   identifier, then phone number is prior to user name. String of
18262   email address is in different class against user name and phone
18263   number. So Email address is always identified correctly.
18264   
18265   @param {String} identifier The user's user name, email address or phone
18266   number. Must be string. Must not be null or undefined.
18267   @param {String} password for the user. Must be string. Must not be null or
18268   undefined.
18269   @returns {KiiUserBuilder} KiiUser object builder.
18270   @throws {InvalidArgumentException} If Identifier is not user name,
18271   email address or phone number.
18272   @throws {InvalidPasswordException} If the password is not in the
18273   proper format
18274    */
18275 
18276   KiiUserBuilder.builderWithIdentifier = function(identifier, password) {
18277     var builder, trimmed;
18278     if (identifier == null) {
18279       throw new root.InvalidArgumentException("Identifier must not be null or undefined");
18280     }
18281     if (!KiiUtilities._validatePassword(password)) {
18282       throw new root.InvalidPasswordException;
18283     }
18284     builder = new root.KiiUserBuilder();
18285     builder._password = password;
18286     if (KiiUtilities._validatePhoneNumber(identifier)) {
18287       builder._phoneNumber = identifier;
18288     } else {
18289       trimmed = KiiUtilities._trim(identifier);
18290       if (KiiUtilities._validateEmail(trimmed)) {
18291         builder._emailAddress = trimmed;
18292       } else if (KiiUtilities._validateUsername(trimmed)) {
18293         builder._username = trimmed;
18294       } else {
18295         throw new root.InvalidArgumentException;
18296       }
18297     }
18298     return builder;
18299   };
18300 
18301 
18302   /** Create KiiUser builder with email address
18303   
18304   <br><br>Create a KiiUser builder with email address.
18305   
18306   @param {String} emailAddress email address.
18307   @param {String} password for the user. Must be string. Must not be null or
18308   undefined.
18309   @returns {KiiUserBuilder} KiiUser object builder.
18310   @throws {InvalidEmailException} If the email address is not in the proper format
18311   @throws {InvalidPasswordException} If the password is not in the
18312   proper format
18313    */
18314 
18315   KiiUserBuilder.builderWithEmailAddress = function(emailAddress, password) {
18316     var builder;
18317     if (!KiiUtilities._validateEmail(emailAddress)) {
18318       throw new root.InvalidEmailException;
18319     }
18320     if (!KiiUtilities._validatePassword(password)) {
18321       throw new root.InvalidPasswordException;
18322     }
18323     builder = new root.KiiUserBuilder();
18324     builder._emailAddress = KiiUtilities._trim(emailAddress);
18325     builder._password = password;
18326     return builder;
18327   };
18328 
18329 
18330   /** Create KiiUser builder with global phone number
18331   
18332   <br><br>Create a KiiUser builder with global phone number.
18333   
18334   @param {String} phoneNumber global phone number.
18335   @returns {KiiUserBuilder} KiiUser object builder.
18336   @throws {InvalidPhoneNumberException} If the phone number is not in the proper format
18337    */
18338 
18339   KiiUserBuilder.builderWithGlobalPhoneNumber = function(phoneNumber, password) {
18340     var builder;
18341     if (!KiiUtilities._validatePhoneNumber(phoneNumber)) {
18342       throw new root.InvalidPhoneNumberException;
18343     }
18344     if (!KiiUtilities._isGlobalPhoneNumber(phoneNumber)) {
18345       throw new root.InvalidPhoneNumberException;
18346     }
18347     if (!KiiUtilities._validatePassword(password)) {
18348       throw new root.InvalidPasswordException;
18349     }
18350     builder = new root.KiiUserBuilder();
18351     builder._phoneNumber = phoneNumber;
18352     builder._password = password;
18353     return builder;
18354   };
18355 
18356 
18357   /** Create KiiUser builder with local phone number
18358   
18359   <br><br>Create a KiiUser builder with local phone number.
18360   
18361   @param {String} phoneNumber local phone number.
18362   @param {String} country country code
18363   @param {String} password for the user. Must be string. Must not be null or
18364   undefined.
18365   @returns {KiiUserBuilder} KiiUser object builder.
18366   @throws {InvalidPhoneNumberException} If the phone number is not in the proper format
18367   @throws {InvalidCountryException} If the country code is not a valid format
18368   @throws {InvalidPasswordException} If the password is not in the
18369   proper format
18370    */
18371 
18372   KiiUserBuilder.builderWithLocalPhoneNumber = function(phoneNumber, country, password) {
18373     var builder;
18374     if (!KiiUtilities._validateLocalPhone(phoneNumber)) {
18375       throw new root.InvalidPhoneNumberException;
18376     }
18377     if (!KiiUtilities._validateCountryCode(country)) {
18378       throw new root.InvalidCountryException;
18379     }
18380     if (!KiiUtilities._validatePassword(password)) {
18381       throw new root.InvalidPasswordException;
18382     }
18383     builder = new root.KiiUserBuilder();
18384     builder._phoneNumber = phoneNumber;
18385     builder._country = country;
18386     builder._password = password;
18387     return builder;
18388   };
18389 
18390 
18391   /** Create KiiUser builder with user name
18392   
18393   <br><br>Create a KiiUser builder with user name.
18394   
18395   @param {String} username user name.
18396   @param {String} password for the user. Must be string. Must not be null or
18397   undefined.
18398   @returns {KiiUserBuilder} KiiUser object builder.
18399   @throws {InvalidUsernameException} If the username is not in the proper format
18400   @throws {InvalidPasswordException} If the password is not in the
18401   proper format
18402    */
18403 
18404   KiiUserBuilder.builderWithUsername = function(username, password) {
18405     var builder, trimmed;
18406     trimmed = KiiUtilities._trim(username);
18407     if (!KiiUtilities._validateUsername(trimmed)) {
18408       throw new root.InvalidUsernameException;
18409     }
18410     if (!KiiUtilities._validatePassword(password)) {
18411       throw new root.InvalidPasswordException;
18412     }
18413     builder = new root.KiiUserBuilder();
18414     builder._username = trimmed;
18415     builder._password = password;
18416     return builder;
18417   };
18418 
18419 
18420   /** Set user name.
18421   
18422   <br><br>Set user name. If null or undefined is passed. It is
18423   ignored. Previous user name is remained.
18424   @param {String} username user name.
18425   @returns {KiiUserBuilder} this builder object.
18426   @throws {InvalidUsernameException} If the username is not in the
18427   proper format
18428    */
18429 
18430   KiiUserBuilder.prototype.setUsername = function(username) {
18431     var trimmed;
18432     if (username != null) {
18433       trimmed = KiiUtilities._trim(username);
18434       if (KiiUtilities._validateUsername(trimmed)) {
18435         this._username = trimmed;
18436       } else {
18437         throw new root.InvalidUsernameException;
18438       }
18439     }
18440     return this;
18441   };
18442 
18443 
18444   /** Set email address.
18445   
18446   <br><br>Set email address. If null or undefined is passed. It is
18447   ignored. Previous email address is remained.
18448   @param {String} emailAddress email address.
18449   @returns {KiiUserBuilder} this builder object.
18450   @throws {InvalidEmailException} If the email address is not in the
18451   proper format
18452    */
18453 
18454   KiiUserBuilder.prototype.setEmailAddress = function(emailAddress) {
18455     var trimmed;
18456     if (emailAddress != null) {
18457       trimmed = KiiUtilities._trim(emailAddress);
18458       if (KiiUtilities._validateEmail(trimmed)) {
18459         this._emailAddress = trimmed;
18460       } else {
18461         throw new root.InvalidEmailException;
18462       }
18463     }
18464     return this;
18465   };
18466 
18467 
18468   /** Set global phone number.
18469   
18470   <br><br>Set global phone number. If null or undefined is
18471   passed. It is ignored. Previous phone number is remained.
18472   @param {String} phoneNumber global phone number.
18473   @returns {KiiUserBuilder} this builder object.
18474   @throws {InvalidPhoneNumberException} If the phone number is not
18475   in the proper format
18476    */
18477 
18478   KiiUserBuilder.prototype.setGlobalPhoneNumber = function(phoneNumber) {
18479     if (phoneNumber != null) {
18480       if (KiiUtilities._validatePhoneNumber(phoneNumber)) {
18481         this._phoneNumber = phoneNumber;
18482         this._country = null;
18483       } else {
18484         throw new root.InvalidPhoneNumberException;
18485       }
18486     }
18487     return this;
18488   };
18489 
18490 
18491   /** Set local phone number.
18492   
18493   <br><br>Set local phone number. If null or undefined is
18494   passed. It is ignored. Previous phone number is remained.
18495   @param {String} phoneNumber local phone number.
18496   @param {String} country country code
18497   @returns {KiiUserBuilder} this builder object.
18498   @throws {InvalidPhoneNumberException} If the phone number is not
18499   in the proper format
18500   @throws {InvalidCountryException} If the country code is not a valid format
18501    */
18502 
18503   KiiUserBuilder.prototype.setLocalPhoneNumber = function(phoneNumber, country) {
18504     if ((phoneNumber != null) && !KiiUtilities._validateLocalPhone(phoneNumber)) {
18505       throw new root.InvalidPhoneNumberException;
18506     }
18507     if ((country != null) && !KiiUtilities._validateCountryCode(country)) {
18508       throw new root.InvalidCountryException;
18509     }
18510     if (phoneNumber != null) {
18511       this._phoneNumber = phoneNumber;
18512     }
18513     if (country != null) {
18514       this._country = country;
18515     }
18516     return this;
18517   };
18518 
18519 
18520   /** Build KiiUser object.
18521   
18522   <br><br> Build KiiUser object. This method verify set values.
18523   @returns {KiiUser} a working KiiUser object.
18524    */
18525 
18526   KiiUserBuilder.prototype.build = function() {
18527     var kiiUser;
18528     kiiUser = new root.KiiUser;
18529     if (this._username != null) {
18530       kiiUser._setUsername(this._username);
18531     }
18532     if (this._emailAddress != null) {
18533       kiiUser._setEmailAddress(this._emailAddress);
18534     }
18535     if (this._country != null) {
18536       kiiUser._setLocalPhone(this._phoneNumber, this._country);
18537     } else if (this._phoneNumber != null) {
18538       kiiUser._setPhoneNumber(this._phoneNumber);
18539     }
18540     kiiUser._setPassword(this._password);
18541     return kiiUser;
18542   };
18543 
18544   return KiiUserBuilder;
18545 
18546 })();
18547 
18548 
18549 /**
18550     @class Represents a KiiPushInstallation object
18551     @exports root.KiiPushInstallation as KiiPushInstallation
18552  */
18553 
18554 root.KiiPushInstallation = (function() {
18555   function KiiPushInstallation(user) {
18556     this._setAuthToken = __bind(this._setAuthToken, this);
18557     this.uninstallByInstallationID = __bind(this.uninstallByInstallationID, this);
18558     this.uninstall = __bind(this.uninstall, this);
18559     this._getMqttEndpoint = __bind(this._getMqttEndpoint, this);
18560     this.getMqttEndpoint = __bind(this.getMqttEndpoint, this);
18561     this._install = __bind(this._install, this);
18562     this.installMqtt = __bind(this.installMqtt, this);
18563     this.installApns = __bind(this.installApns, this);
18564     this.installGcm = __bind(this.installGcm, this);
18565     this._user = user;
18566   }
18567 
18568 
18569   /** Register the id issued by GCM to the Kii cloud for current logged in user.
18570   @param {String} installationRegistrationID The ID of registration that identifies the installation externally.
18571   @param {Boolean} development Indicates if the installation is for development or production environment.
18572   @param {Object} [callbacks] An object with callback methods defined
18573   @param {Method} callbacks.success The callback method to call on a successful resend request
18574   <br>argument is response object. response.installationID is ID of the installation in the platform.
18575   @param {Method} callbacks.failure The callback method to call on a failed resend request
18576   <br>argument is Error object.
18577   @return {Promise} return promise object.
18578     <ul>
18579       <li>fulfill callback function: function(response).
18580         <ul>
18581           <li>response.installationID is ID of the installation in the platform.</li>
18582         </ul>
18583       </li>
18584       <li>reject callback function: function(error). error is an Error instance.
18585         <ul>
18586           <li>error.message</li>
18587         </ul>
18588       </li>
18589     </ul>
18590   @example
18591    */
18592 
18593   KiiPushInstallation.prototype.installGcm = function(installationRegistrationID, development, callbacks) {
18594     if (!KiiUtilities._isNonEmptyString(installationRegistrationID)) {
18595       return new Promise((function(_this) {
18596         return function(resolve, reject) {
18597           var errObj;
18598           errObj = KiiUtilities._Error("installationRegistrationID must not be null or empty.", _this);
18599           if (callbacks != null) {
18600             callbacks.failure(errObj);
18601           }
18602           return reject(errObj);
18603         };
18604       })(this));
18605     }
18606     return this._install(installationRegistrationID, "ANDROID", development, callbacks);
18607   };
18608 
18609 
18610   /** Register the id issued by APNS to the Kii cloud for current logged in user.
18611   @param {String} deviceToken The ID of registration that identifies the installation externally.
18612   @param {Boolean} development Indicates if the installation is for development or production environment.
18613   @param {Object} [callbacks] An object with callback methods defined
18614   @param {Method} callbacks.success The callback method to call on a successful resend request
18615   <br>argument is response object. response.installationID is ID of the installation in the platform.
18616   @param {Method} callbacks.failure The callback method to call on a failed resend request
18617   <br>argument is Error object.
18618   @return {Promise} return promise object.
18619     <ul>
18620       <li>fulfill callback function: function(response).
18621         <ul>
18622           <li>response.installationID is ID of the installation in the platform.</li>
18623         </ul>
18624       </li>
18625       <li>reject callback function: function(error). error is an Error instance.
18626         <ul>
18627           <li>error.message</li>
18628         </ul>
18629       </li>
18630     </ul>
18631   @example
18632    */
18633 
18634   KiiPushInstallation.prototype.installApns = function(deviceToken, development, callbacks) {
18635     if (!KiiUtilities._isNonEmptyString(deviceToken)) {
18636       return new Promise((function(_this) {
18637         return function(resolve, reject) {
18638           var errObj;
18639           errObj = KiiUtilities._Error("deviceToken must not be null or empty.", _this);
18640           if (callbacks != null) {
18641             callbacks.failure(errObj);
18642           }
18643           return reject(errObj);
18644         };
18645       })(this));
18646     }
18647     return this._install(deviceToken, "IOS", development, callbacks);
18648   };
18649 
18650 
18651   /** Register a MQTT installation to the Kii cloud for current logged in user.
18652   @param {Boolean} development Indicates if the installation is for development or production environment.
18653   @param {Object} [callbacks] An object with callback methods defined
18654   @param {Method} callbacks.success The callback method to call on a successful resend request
18655   <br>argument is response object. response.installationID is ID of the installation in the platform.
18656   @param {Method} callbacks.failure The callback method to call on a failed resend request
18657   <br>argument is Error object.
18658   @return {Promise} return promise object.
18659     <ul>
18660       <li>fulfill callback function: function(response).
18661         <ul>
18662           <li>response.installationID is ID of the installation in the platform.</li>
18663           <li>response.installationRegistrationID is ID of registration that identifies the installation externally.</li>
18664         </ul>
18665       </li>
18666       <li>reject callback function: function(error). error is an Error instance.
18667         <ul>
18668           <li>error.message</li>
18669         </ul>
18670       </li>
18671     </ul>
18672   @example
18673    */
18674 
18675   KiiPushInstallation.prototype.installMqtt = function(development, callbacks) {
18676     return this._install(null, "MQTT", development, callbacks);
18677   };
18678 
18679   KiiPushInstallation.prototype._install = function(installationRegistrationID, deviceType, development, callbacks) {
18680     return new Promise((function(_this) {
18681       return function(resolve, reject) {
18682         var errObj, requestBody, sendCallbacks, wrapper;
18683         if (typeof development !== 'boolean') {
18684           errObj = KiiUtilities._Error("type of development must be boolean.", _this);
18685           if (callbacks != null) {
18686             callbacks.failure(errObj);
18687           }
18688           reject(errObj);
18689         }
18690         wrapper = KiiXHRWrapperFactory.createXHRWrapper('POST', "" + (root.Kii.getBaseURL()) + "/apps/" + (root.Kii.getAppID()) + "/installations");
18691         wrapper.setKiiHeaders();
18692         _this._setAuthToken(wrapper);
18693         wrapper.setContentType("application/vnd.kii.InstallationCreationRequest+json");
18694         requestBody = {
18695           "deviceType": deviceType,
18696           "development": development
18697         };
18698         if (installationRegistrationID != null) {
18699           requestBody["installationRegistrationID"] = installationRegistrationID;
18700         }
18701         sendCallbacks = {
18702           success: function() {
18703             var respJson;
18704             respJson = JSON.parse(decodeURIComponent(wrapper.xhr.responseText));
18705             if (callbacks != null) {
18706               callbacks.success(respJson);
18707             }
18708             return resolve(respJson);
18709           },
18710           failure: function() {
18711             var errString;
18712             errString = wrapper.getErrorString("install push");
18713             errObj = KiiUtilities._Error(errString, _this);
18714             if (callbacks != null) {
18715               callbacks.failure(errObj);
18716             }
18717             return reject(errObj);
18718           }
18719         };
18720         return wrapper.sendData(JSON.stringify(requestBody), sendCallbacks);
18721       };
18722     })(this));
18723   };
18724 
18725 
18726   /** Get MQTT endpoint.
18727   If the MQTT endpoint is not ready, this method retries request up to three times.
18728   <br><br>
18729   Note that only MQTT over tls is supported currently.<br>
18730   Don't use portSSL, portWS or portWSS until we support it.
18731   @param {String} installationID The ID of the installation in the platform.
18732   @param {Object} [callbacks] An object with callback methods defined
18733   @param {Method} callbacks.success The callback method to call on a successful resend request
18734   <br>argument is response object. response.installationID is ID of the installation in the platform.
18735   @param {Method} callbacks.failure The callback method to call on a failed resend request
18736   <br>argument is Error object.
18737   @return {Promise} return promise object.
18738     <ul>
18739       <li>fulfill callback function: function(response).
18740         <ul>
18741           <li>response.installationID is ID of the installation in the platform.</li>
18742           <li>response.username is username to use for connecting to the MQTT broker.</li>
18743           <li>response.password is assword to use for connecting to the MQTT broker.</li>
18744           <li>response.mqttTopic is topic to subscribe in the MQTT broker.</li>
18745           <li>response.host is hostname of the MQTT broker.</li>
18746           <li>response.X-MQTT-TTL is the amount of time in seconds that specifies how long the mqttTopic will be valid, after that the client needs to request new MQTT endpoint info.</li>
18747           <li>response.portTCP is port to connect using plain TCP.</li>
18748           <li>response.portSSL is port to connect using SSL/TLS.</li>
18749           <li>response.portWS is port to connect using plain Websocket.</li>
18750           <li>response.portWSS is port to connect using SSL/TLS Websocket.</li>
18751         </ul>
18752       </li>
18753       <li>reject callback function: function(error). error is an Error instance.
18754         <ul>
18755           <li>error.message</li>
18756         </ul>
18757       </li>
18758     </ul>
18759   @example
18760    */
18761 
18762   KiiPushInstallation.prototype.getMqttEndpoint = function(installationID, callbacks) {
18763     return new Promise((function(_this) {
18764       return function(resolve, reject) {
18765         var errObj, getMqttEndpointCallback;
18766         if (!KiiUtilities._isNonEmptyString(installationID)) {
18767           errObj = KiiUtilities._Error("installationID must not be null or empty.", _this);
18768           if (callbacks != null) {
18769             callbacks.failure(errObj);
18770           }
18771           reject(errObj);
18772         }
18773         getMqttEndpointCallback = {
18774           success: function(respJson) {
18775             if (callbacks != null) {
18776               callbacks.success(respJson);
18777             }
18778             return resolve(respJson);
18779           },
18780           failure: function(err) {
18781             if (callbacks != null) {
18782               callbacks.failure(err);
18783             }
18784             return reject(err);
18785           }
18786         };
18787         return _this._getMqttEndpoint(installationID, 3, getMqttEndpointCallback);
18788       };
18789     })(this));
18790   };
18791 
18792   KiiPushInstallation.prototype._getMqttEndpoint = function(installationID, retry, callbacks) {
18793     var instance, requestCallback, wrapper;
18794     instance = this;
18795     wrapper = KiiXHRWrapperFactory.createXHRWrapper('GET', "" + (root.Kii.getBaseURL()) + "/apps/" + (root.Kii.getAppID()) + "/installations/" + installationID + "/mqtt-endpoint");
18796     wrapper.setKiiHeaders();
18797     this._setAuthToken(wrapper);
18798     requestCallback = {
18799       success: (function(_this) {
18800         return function() {
18801           var respJson;
18802           respJson = JSON.parse(decodeURIComponent(wrapper.xhr.responseText));
18803           return callbacks.success(respJson);
18804         };
18805       })(this),
18806       failure: (function(_this) {
18807         return function() {
18808           var errObj, errString;
18809           if (wrapper.xhr.status === 503) {
18810             retry--;
18811             if (retry <= 0) {
18812               errString = wrapper.getErrorString("get mqtt endpoint");
18813               errObj = KiiUtilities._Error(errString, instance);
18814               return callbacks.failure(errObj);
18815             } else {
18816               return setTimeout(function() {
18817                 return instance._getMqttEndpoint(installationID, retry, callbacks);
18818               }, 1000);
18819             }
18820           } else {
18821             errString = wrapper.getErrorString("get mqtt endpoint");
18822             errObj = KiiUtilities._Error(errString, instance);
18823             return callbacks.failure(errObj);
18824           }
18825         };
18826       })(this)
18827     };
18828     return wrapper.send(requestCallback);
18829   };
18830 
18831 
18832   /** Unregister the push settings by the id(issued by push provider) that is used for installation.
18833   @param {String} installationRegistrationID The ID of registration that identifies the installation externally.
18834   @param {String} deviceType The type of the installation. Supported types are "ANDROID", "IOS" and "MQTT".
18835   @param {Object} [callbacks] An object with callback methods defined
18836   @param {Method} callbacks.success The callback method to call on a successful resend request
18837   @param {Method} callbacks.failure The callback method to call on a failed resend request
18838   <br>argument is Error object.
18839   @return {Promise} return promise object.
18840     <ul>
18841       <li>fulfill callback function: function().</li>
18842       <li>reject callback function: function(error). error is an Error instance.
18843         <ul>
18844           <li>error.message</li>
18845         </ul>
18846       </li>
18847     </ul>
18848   @example
18849    */
18850 
18851   KiiPushInstallation.prototype.uninstall = function(installationRegistrationID, deviceType, callbacks) {
18852     return new Promise((function(_this) {
18853       return function(resolve, reject) {
18854         var errObj, sendCallbacks, wrapper;
18855         if (!KiiUtilities._isNonEmptyString(installationRegistrationID)) {
18856           errObj = KiiUtilities._Error("installationRegistrationID must not be null or empty.", _this);
18857           if (callbacks != null) {
18858             callbacks.failure(errObj);
18859           }
18860           reject(errObj);
18861         }
18862         if (!root.KiiPushInstallation._validateDeviceType(deviceType)) {
18863           errObj = KiiUtilities._Error("Unsupported deviceType " + deviceType, _this);
18864           if (callbacks != null) {
18865             callbacks.failure(errObj);
18866           }
18867           reject(errObj);
18868         }
18869         wrapper = KiiXHRWrapperFactory.createXHRWrapper('DELETE', "" + (root.Kii.getBaseURL()) + "/apps/" + (root.Kii.getAppID()) + "/installations/" + deviceType + ":" + installationRegistrationID);
18870         wrapper.setKiiHeaders();
18871         _this._setAuthToken(wrapper);
18872         sendCallbacks = {
18873           success: function() {
18874             if (callbacks != null) {
18875               callbacks.success();
18876             }
18877             return resolve();
18878           },
18879           failure: function() {
18880             var errString;
18881             errString = wrapper.getErrorString("uninstall push");
18882             errObj = KiiUtilities._Error(errString, _this);
18883             if (callbacks != null) {
18884               callbacks.failure(errObj);
18885             }
18886             return reject(errObj);
18887           }
18888         };
18889         return wrapper.send(sendCallbacks);
18890       };
18891     })(this));
18892   };
18893 
18894 
18895   /** Unregister the push settings by the id(issued by KiiCloud) that is used for installation.
18896   @param {String} installationID The ID of the installation issued by KiiCloud.
18897   @param {Object} [callbacks] An object with callback methods defined
18898   @param {Method} callbacks.success The callback method to call on a successful resend request
18899   @param {Method} callbacks.failure The callback method to call on a failed resend request
18900   <br>argument is Error object.
18901   @return {Promise} return promise object.
18902     <ul>
18903       <li>fulfill callback function: function().</li>
18904       <li>reject callback function: function(error). error is an Error instance.
18905         <ul>
18906           <li>error.message</li>
18907         </ul>
18908       </li>
18909     </ul>
18910   @example
18911    */
18912 
18913   KiiPushInstallation.prototype.uninstallByInstallationID = function(installationID, callbacks) {
18914     return new Promise((function(_this) {
18915       return function(resolve, reject) {
18916         var errObj, sendCallbacks, wrapper;
18917         if (!KiiUtilities._isNonEmptyString(installationID)) {
18918           errObj = KiiUtilities._Error("installationID must not be null or empty.", _this);
18919           if (callbacks != null) {
18920             callbacks.failure(errObj);
18921           }
18922           reject(errObj);
18923         }
18924         wrapper = KiiXHRWrapperFactory.createXHRWrapper('DELETE', "" + (root.Kii.getBaseURL()) + "/apps/" + (root.Kii.getAppID()) + "/installations/" + installationID);
18925         wrapper.setKiiHeaders();
18926         _this._setAuthToken(wrapper);
18927         sendCallbacks = {
18928           success: function() {
18929             if (callbacks != null) {
18930               callbacks.success();
18931             }
18932             return resolve();
18933           },
18934           failure: function() {
18935             var errString;
18936             errString = wrapper.getErrorString("uninstall push");
18937             errObj = KiiUtilities._Error(errString, _this);
18938             if (callbacks != null) {
18939               callbacks.failure(errObj);
18940             }
18941             return reject(errObj);
18942           }
18943         };
18944         return wrapper.send(sendCallbacks);
18945       };
18946     })(this));
18947   };
18948 
18949   KiiPushInstallation._validateDeviceType = function(deviceType) {
18950     return deviceType === "ANDROID" || deviceType === "MQTT" || deviceType === "IOS";
18951   };
18952 
18953   KiiPushInstallation.prototype._setAuthToken = function(wrapper) {
18954     return wrapper.setCurrentUserToken();
18955   };
18956 
18957   return KiiPushInstallation;
18958 
18959 })();
18960 
18961 root.KiiPushInstallationWithToken = (function(_super) {
18962   __extends(KiiPushInstallationWithToken, _super);
18963 
18964   function KiiPushInstallationWithToken(_authToken) {
18965     this._authToken = _authToken;
18966     this._setAuthToken = __bind(this._setAuthToken, this);
18967   }
18968 
18969   KiiPushInstallationWithToken.prototype._setAuthToken = function(wrapper) {
18970     return wrapper.setAuthToken(this._authToken);
18971   };
18972 
18973   return KiiPushInstallationWithToken;
18974 
18975 })(root.KiiPushInstallation);
18976 
18977 
18978 /**
18979     @class A Parser for error string or error object returned by SDK.
18980     @exports root.KiiErrorParser as KiiErrorParser
18981  */
18982 
18983 root.KiiErrorParser = (function() {
18984   var REG_NETWORK_ERROR, REG_SERVER_ERROR_KII_REQUEST, REG_SERVER_ERROR_KII_SERVER_CODE, REG_SERVER_ERROR_KII_SERVER_CODE_VERSION_NOT_FOUND, REG_SERVER_ERROR_KII_USER_OR_OBJECT, REG_SERVER_ERROR_KII_XHR_WRAPPER, SERVER_ERROR_CODES;
18985 
18986   function KiiErrorParser() {}
18987 
18988   SERVER_ERROR_CODES = {
18989     APP_NOT_FOUND: 404,
18990     APP_DISABLED: 403,
18991     UNAUTHORIZED: 401,
18992     USER_NOT_FOUND: 404,
18993     THING_NOT_FOUND: 404,
18994     THING_DISABLED: 401,
18995     THING_ALREADY_EXISTS: 409,
18996     THING_TYPE_NOT_FOUND: 404,
18997     FIRMWARE_VERSION_NOT_FOUND: 404,
18998     WRONG_TOKEN: 403,
18999     WRONG_REFRESH_TOKEN: 403,
19000     INVALID_BUCKET: 400,
19001     OPERATION_NOT_ALLOWED: 409,
19002     OPERATION_NOT_SUPPORTED: 403,
19003     AUTHENTICATION_FAILED: 401,
19004     USER_DISABLED: 401,
19005     INVALID_DATA_TYPE: 400,
19006     INVALID_INPUT_DATA: 400,
19007     INVALID_JSON: 400,
19008     INVALID_JSON_SCHEMA: 400,
19009     MISSING_DATA: 400,
19010     RESOURCE_TEMPORARILY_UNAVAILABLE: 503,
19011     WRONG_PASSWORD: 401,
19012     OAUTH2_ERROR: 400,
19013     THING_END_NODE_DOES_NOT_BELONG_TO_GATEWAY: 404,
19014     THING_END_NODE_ALREADY_BELONGS_TO_GATEWAY: 409,
19015     UNDEFINED_ERROR: 500,
19016     OPERATION_NOT_IMPLEMENTED: 501,
19017     LOCK_FAILED: 503,
19018     QUERY_NOT_SUPPORTED: 400,
19019     QUERY_TIMEOUT: 503,
19020     TEMPORARY_UNAVAILABLE_ERROR: 503,
19021     APP_ALREADY_EXISTS: 409,
19022     BUCKET_ALREADY_EXISTS: 409,
19023     BUCKET_NOT_FOUND: 404,
19024     FILTER_NOT_FOUND: 404,
19025     INVALID_ACCOUNT_STATUS: 400,
19026     INVALID_OBJECT_ID: 400,
19027     INVALID_VERIFICATION_CODE: 403,
19028     OBJECT_NOT_FOUND: 404,
19029     OBJECT_VERSION_IS_STALE: 409,
19030     OBJECT_ALREADY_EXISTS: 409,
19031     OBJECT_CONFLICT: 409,
19032     PUBLICATION_NOT_FOUND: 404,
19033     PUBLICATION_EXPIRED: 410,
19034     USER_ALREADY_EXISTS: 409,
19035     USER_ADDRESS_NOT_FOUND: 404,
19036     VERIFICATION_CODE_NOT_FOUND: 404,
19037     ACCOUNT_TYPE_NOT_SUPPORTED: 400,
19038     OBJECT_BODY_NOT_FOUND: 404,
19039     OBJECT_BODY_RANGE_NOT_SATISFIABLE: 416,
19040     OBJECT_BODY_INTEGRITY_NOT_ASSURED: 412,
19041     OBJECT_BODY_UPLOAD_NOT_FOUND: 404,
19042     OBJECT_BODY_UPLOAD_ALREADY_EXISTS: 409,
19043     BUCKET_TYPE_NOT_SUPPORTED: 400,
19044     GROUP_NOT_FOUND: 404,
19045     GROUP_ALREADY_EXISTS: 409,
19046     INSTALLATION_NOT_FOUND: 404,
19047     INSTALLATION_ALREADY_EXISTS: 409,
19048     ACL_NOT_FOUND: 404,
19049     ACL_ALREADY_EXISTS: 409,
19050     VERSIONED_UPDATES_NOT_SUPPORTED: 400,
19051     NO_ACCOUNT_PROVIDED: 400,
19052     FACEBOOK_USER_ALREADY_LINKED: 409,
19053     QQ_USER_ALREADY_LINKED: 409,
19054     GOOGLE_USER_ALREADY_LINKED: 409,
19055     USER_ALREADY_LINKED: 409,
19056     USER_NOT_LINKED: 409,
19057     UNIQUE_CONSTRAINT_VIOLATED: 409,
19058     GCMKEY_ALREADY_EXISTS: 409,
19059     GCMKEY_NOT_FOUND: 404,
19060     APNSKEY_NOT_FOUND: 404,
19061     JSON_WEB_KEY_NOT_FOUND: 404,
19062     JPUSHKEY_NOT_FOUND: 404,
19063     PUSH_SUBSCRIPTION_ALREADY_EXISTS: 409,
19064     PUSH_SUBSCRIPTION_NOT_FOUND: 404,
19065     TOPIC_ALREADY_EXISTS: 409,
19066     TOPIC_NOT_FOUND: 404,
19067     USER_LOCALE_NOT_FOUND: 404,
19068     TEMPLATE_NOT_FOUND: 404,
19069     USER_COUNTRY_NOT_FOUND: 404,
19070     USER_DISPLAY_NAME_NOT_FOUND: 404,
19071     SERVER_CODE_VERSION_NOT_FOUND: 404,
19072     SERVER_CODE_HOOK_VERSION_NOT_FOUND: 404,
19073     SCHEDULE_EXECUTION_NOT_FOUND: 404,
19074     ENDPOINT_INVOCATION_ERROR: 400,
19075     SERVER_CODE_VERIFICATION_ERROR: 400,
19076     PAYLOAD_ID_NOT_FOUND: 404,
19077     REPLACEMENT_SQL_QUERY_NOT_FOUND: 404,
19078     APP_CONFIG_PARAMETER_NOT_FOUND: 404,
19079     TRANSACTION_ID_NOT_FOUND: 404,
19080     TRANSACTION_ID_ALREADY_EXISTS: 409,
19081     CLIENT_CREDENTIALS_NOT_FOUND: 404,
19082     ACCESS_CODE_NOT_FOUND: 404,
19083     THING_OWNERSHIP_NOT_FOUND: 404,
19084     THING_OWNERSHIP_ALREADY_EXISTS: 409,
19085     INVALID_THING_OWNERSHIP_CODE: 409,
19086     MQTT_ENDPOINT_NOT_FOUND: 404,
19087     TASK_NOT_FOUND: 404,
19088     TASK_NOT_RECURRENT: 400,
19089     INVALID_STATUS: 409,
19090     PHONE_NUMBER_VERIFICATION_CODE_EXPIRED: 410,
19091     PIN_CODE_EXPIRED: 410,
19092     ADDRESS_VERIFICATION_CODE_NOT_FOUND: 404,
19093     MQTT_ENDPOINT_NOT_READY: 503,
19094     INDEX_FAILED: 500
19095   };
19096 
19097   REG_SERVER_ERROR_KII_REQUEST = new RegExp("(^[A-Z_]+): (.*)");
19098 
19099   REG_SERVER_ERROR_KII_XHR_WRAPPER = new RegExp(" statusCode: (\\d{3}) error code: ([A-Z_]+) message: (.*)$");
19100 
19101   REG_SERVER_ERROR_KII_USER_OR_OBJECT = new RegExp(" statusCode: (\\d{3}) error code: ([A-Z_]+) error message: (.*)$");
19102 
19103   REG_SERVER_ERROR_KII_SERVER_CODE = new RegExp(" statusCode: (\\d{3}) executedSteps: \\d+ error code: ([A-Z_]+) message: (.*) detailMessage: (.*)$");
19104 
19105   REG_SERVER_ERROR_KII_SERVER_CODE_VERSION_NOT_FOUND = new RegExp(" statusCode: (\\d{3}) executedSteps: null error code: ([A-Z_]+) message: (.*)$");
19106 
19107   REG_NETWORK_ERROR = new RegExp("statusCode: (\\d{1,3})$");
19108 
19109 
19110   /** Parse an error string or error object returned by SDK.
19111   @param {Object} error An error string or error object
19112   @return {Object} return parsed error object.
19113   @example
19114   var err = KiiErrorParser.parse(errorString);
19115   var httpStatus = err.status;
19116   if (httpStatus == 0) {
19117       // NetworkError
19118   } else if (httpStatus == -1) {
19119       // Error is not related the http error. eg. argument error, illegal state error, etc.
19120   } else if (httpStatus == -2) {
19121       // Unknown error is detected.
19122       // Please confirm that you are using the latest version of SDK.
19123   } else if (httpStatus >= 400 && httpStatus < 600) {
19124       // Http error
19125   }
19126   var errorCode = err.code;
19127   var errorMessage = err.message;
19128    */
19129 
19130   KiiErrorParser.parse = function(error) {
19131     var arr, code, errorString, message, regex, status, _i, _len, _ref;
19132     if ((typeof error).toLowerCase() === "string") {
19133       errorString = error;
19134     } else {
19135       errorString = error.message;
19136     }
19137     if (!errorString) {
19138       return null;
19139     }
19140     if (errorString.indexOf('0 : http') === 0) {
19141       return {
19142         status: 0,
19143         code: null,
19144         message: "Network Error"
19145       };
19146     } else if (errorString.indexOf('429 : http') === 0) {
19147       return {
19148         status: 429,
19149         code: "TOO_MANY_REQUESTS",
19150         message: "Number of requests exceeds the limit."
19151       };
19152     } else if (errorString.indexOf('fail to execute server code. statusCode: 0') === 0) {
19153       return {
19154         status: 0,
19155         code: null,
19156         message: "Network Error"
19157       };
19158     } else if (errorString.indexOf('invalid_grant: ') === 0) {
19159       arr = errorString.split(':', 2);
19160       return {
19161         status: 400,
19162         code: "invalid_grant",
19163         message: arr[1].substr(1)
19164       };
19165     } else {
19166       arr = REG_NETWORK_ERROR.exec(errorString);
19167       if (arr) {
19168         status = Number(arr[1]);
19169         if (status === 429) {
19170           return {
19171             status: 429,
19172             code: "TOO_MANY_REQUESTS",
19173             message: "Number of requests exceeds the limit."
19174           };
19175         } else {
19176           return {
19177             status: 0,
19178             code: null,
19179             message: "Network Error"
19180           };
19181         }
19182       }
19183       arr = REG_SERVER_ERROR_KII_REQUEST.exec(errorString);
19184       if (arr) {
19185         code = arr[1];
19186         message = arr[2];
19187         status = SERVER_ERROR_CODES[code];
19188         if (!status) {
19189           status = -2;
19190         }
19191         return {
19192           status: status,
19193           code: code,
19194           message: message
19195         };
19196       }
19197       _ref = [REG_SERVER_ERROR_KII_XHR_WRAPPER, REG_SERVER_ERROR_KII_USER_OR_OBJECT, REG_SERVER_ERROR_KII_SERVER_CODE, REG_SERVER_ERROR_KII_SERVER_CODE_VERSION_NOT_FOUND];
19198       for (_i = 0, _len = _ref.length; _i < _len; _i++) {
19199         regex = _ref[_i];
19200         arr = regex.exec(errorString);
19201         if (arr) {
19202           status = Number(arr[1]);
19203           code = arr[2];
19204           message = arr[3];
19205           return {
19206             status: status,
19207             code: code,
19208             message: message
19209           };
19210         }
19211       }
19212     }
19213     return {
19214       status: -1,
19215       code: null,
19216       message: errorString
19217     };
19218   };
19219 
19220   return KiiErrorParser;
19221 
19222 })();
19223 
19224 
19225 /**
19226     @class Represents a KiiThingQuery object
19227     @exports root.KiiThingQuery as KiiThingQuery
19228  */
19229 
19230 root.KiiThingQuery = (function() {
19231   function KiiThingQuery(owner, groups) {
19232     this._dictValue = __bind(this._dictValue, this);
19233     this.clone = __bind(this.clone, this);
19234     this.getPaginationKey = __bind(this.getPaginationKey, this);
19235     this.setPaginationKey = __bind(this.setPaginationKey, this);
19236     this.getThingType = __bind(this.getThingType, this);
19237     this.setThingType = __bind(this.setThingType, this);
19238     this.getLimit = __bind(this.getLimit, this);
19239     this.setLimit = __bind(this.setLimit, this);
19240     if ((owner == null) && ((groups == null) || groups.length === 0)) {
19241       throw root.InvalidArgumentException('Both the owner and groups parameter are optional, but at least one of them must be supplied.');
19242     }
19243     this._owner = owner;
19244     this._groups = groups;
19245     this._limit = 0;
19246   }
19247 
19248 
19249   /** Construct KiiThingQuery.<br>
19250   Both an owner and groups parameters are optional,
19251   but at least one of them must be supplied.
19252   @param {KiiUser} [owner] of the thing. The user must be same as 
19253   Login user or causes unauthorized error.
19254   @param {KiiGroup[]} [groups] owns the thing. Login user must belongs
19255   to all groups or causes unauthorized error.
19256   @throws {InvalidArgumentException}
19257   neither an owner nor groups parameters are supplied.
19258    */
19259 
19260   KiiThingQuery.thingQuery = function(owner, groups) {
19261     return new root.KiiThingQuery(owner, groups);
19262   };
19263 
19264 
19265   /** Set the limit of the given query
19266   @param limit The maximum number of items obtained in one request.<br>
19267   If specified limit is <= 0, 0 will be applied.
19268   This limit behaves in a best effort way. Actual number of returned result
19269   can be smaller than the requested number.<br>
19270   If the specified limit is greater than the limit of the server or limit is
19271   set to 0, limit defined in server will be applied.
19272    */
19273 
19274   KiiThingQuery.prototype.setLimit = function(limit) {
19275     if (limit > 0) {
19276       return this._limit = limit;
19277     } else {
19278       return this._limit = 0;
19279     }
19280   };
19281 
19282 
19283   /** Get the limit of the current query
19284   @returns {Number}
19285    */
19286 
19287   KiiThingQuery.prototype.getLimit = function() {
19288     return this._limit;
19289   };
19290 
19291 
19292   /** Set the thing type to filter the results.
19293   @param thingType Thing type
19294    */
19295 
19296   KiiThingQuery.prototype.setThingType = function(thingType) {
19297     return this._thingType = thingType;
19298   };
19299 
19300 
19301   /** Get the thing type
19302   @returns {String}
19303    */
19304 
19305   KiiThingQuery.prototype.getThingType = function() {
19306     return this._thingType;
19307   };
19308 
19309 
19310   /** Set the pagination key.
19311   @param paginationKey Pagination key
19312    */
19313 
19314   KiiThingQuery.prototype.setPaginationKey = function(paginationKey) {
19315     return this._paginationKey = paginationKey;
19316   };
19317 
19318 
19319   /** Get the pagination key.
19320   @returns {String}
19321    */
19322 
19323   KiiThingQuery.prototype.getPaginationKey = function() {
19324     return this._paginationKey;
19325   };
19326 
19327   KiiThingQuery.prototype.clone = function() {
19328     var clone;
19329     clone = new root.KiiThingQuery(root.KiiThingQuery._clone(this._owner), root.KiiThingQuery._clone(this._groups));
19330     clone._limit = this._limit;
19331     clone._thingType = this._thingType;
19332     clone._paginationKey = this._paginationKey;
19333     return clone;
19334   };
19335 
19336   KiiThingQuery._clone = function(obj) {
19337     var key, newInstance;
19338     if ((obj == null) || typeof obj !== 'object') {
19339       return obj;
19340     }
19341     newInstance = new obj.constructor();
19342     for (key in obj) {
19343       newInstance[key] = KiiThingQuery._clone(obj[key]);
19344     }
19345     return newInstance;
19346   };
19347 
19348   KiiThingQuery.prototype._dictValue = function() {
19349     var groupOwner, groupOwnerClause, ownerClause, ownerClauses, query, thingQuery, userOwnerClause, _i, _len, _ref;
19350     query = {};
19351     if ((this._limit != null) && this._limit > 0) {
19352       query.bestEffortLimit = this._limit;
19353     }
19354     if (this._paginationKey != null) {
19355       query.paginationKey = this._paginationKey;
19356     }
19357     ownerClauses = [];
19358     if (this._owner != null) {
19359       userOwnerClause = {
19360         "type": "contains",
19361         "field": "userOwners",
19362         "value": this._owner.getID()
19363       };
19364       ownerClauses.push(userOwnerClause);
19365     }
19366     if ((this._groups != null) && this._groups.length > 0) {
19367       _ref = this._groups;
19368       for (_i = 0, _len = _ref.length; _i < _len; _i++) {
19369         groupOwner = _ref[_i];
19370         groupOwnerClause = {
19371           "type": "contains",
19372           "field": "groupOwners",
19373           "value": groupOwner.getID()
19374         };
19375         ownerClauses.push(groupOwnerClause);
19376       }
19377     }
19378     if (ownerClauses.length === 0) {
19379       throw root.InvalidArgumentException("Query clause must include the 'contains' clause.");
19380     } else if (ownerClauses.length === 1) {
19381       ownerClause = ownerClauses[0];
19382     } else {
19383       ownerClause = {
19384         "type": "or",
19385         "clauses": ownerClauses
19386       };
19387     }
19388     if (this._thingType != null) {
19389       thingQuery = {
19390         "clause": {
19391           "type": "and",
19392           "clauses": [
19393             {
19394               "type": "eq",
19395               "field": "_thingType",
19396               "value": this._thingType
19397             }, ownerClause
19398           ]
19399         }
19400       };
19401     } else {
19402       thingQuery = {
19403         "clause": ownerClause
19404       };
19405     }
19406     query.thingQuery = thingQuery;
19407     return query;
19408   };
19409 
19410   return KiiThingQuery;
19411 
19412 })();
19413 
19414 
19415 /**
19416     @class Represents a KiiThingQueryResult object
19417     @exports root.KiiThingQueryResult as KiiThingQueryResult
19418  */
19419 
19420 root.KiiThingQueryResult = (function() {
19421   function KiiThingQueryResult(query, results, paginationKey) {
19422     this.getNextResult = __bind(this.getNextResult, this);
19423     this.getNextKiiThingQuery = __bind(this.getNextKiiThingQuery, this);
19424     this.hasNext = __bind(this.hasNext, this);
19425     this.getResult = __bind(this.getResult, this);
19426     this._query = query;
19427     this._results = results;
19428     this._paginationKey = paginationKey;
19429   }
19430 
19431 
19432   /** Get the list of KiiThing that matches the query
19433   @returns {Array} An array of KiiThing objects
19434    */
19435 
19436   KiiThingQueryResult.prototype.getResult = function() {
19437     return this._results;
19438   };
19439 
19440 
19441   /** When there are many result of query or data in result is large, Query result would be divided into several pages.
19442   @returns {Boolean} true if there are pending result of the Query to be retrieved.
19443    */
19444 
19445   KiiThingQueryResult.prototype.hasNext = function() {
19446     return this._paginationKey != null;
19447   };
19448 
19449 
19450   /** Get the KiiThingQuery to get next page of the result.
19451   @returns {KiiThingQuery} KiiThingQuery to get next page of the query. null when this result is the last part of the query.
19452    */
19453 
19454   KiiThingQueryResult.prototype.getNextKiiThingQuery = function() {
19455     var nextQuery;
19456     if (!this.hasNext()) {
19457       return null;
19458     }
19459     nextQuery = this._query.clone();
19460     nextQuery.setPaginationKey(this._paginationKey);
19461     return nextQuery;
19462   };
19463 
19464 
19465   /** Fetch the query result of next page.
19466   
19467   <br><br>The query will be executed against the server, returning a result set.
19468   When the state that #hasNext() is false,
19469   method execution is failed and Promise returned by the method is rejected
19470   and failure callback is called if the callback is given.
19471   @param Object callbacks An object with callback methods defined
19472   @param {Function} callbacks.success The callback method to call on a successful query request
19473   @param {Function} callbacks.failure The callback method to call on a failed query request
19474   @return {Promise} return promise object.
19475     <ul>
19476       <li>fulfill callback function: function(result). result is KiiThingQueryResult instance.</li>
19477       <li>reject callback function: function(error). error is an Error instance.
19478         <ul>
19479           <li>error.target is the KiiThing instance.</li>
19480           <li>error.message</li>
19481         </ul>
19482       </li>
19483     </ul>
19484    */
19485 
19486   KiiThingQueryResult.prototype.getNextResult = function(callbacks) {
19487     if (!this.hasNext()) {
19488       return new Promise((function(_this) {
19489         return function(resolve, reject) {
19490           var errObj, message;
19491           message = "No more pages to fetch";
19492           errObj = KiiUtilities._Error(message, _this);
19493           if (callbacks != null) {
19494             callbacks.failure(errObj);
19495           }
19496           return reject(errObj);
19497         };
19498       })(this));
19499     } else {
19500       return root.KiiThing.executeQuery(this.getNextKiiThingQuery(), callbacks);
19501     }
19502   };
19503 
19504   return KiiThingQueryResult;
19505 
19506 })();
19507 
19508 
19509 return root;
19510 });  // generated by build.sh for running on Node.js
19511 
19512 // Following code was generated by build.sh for running on Node.js
19513 (function() {
19514 var b = ((typeof module) !== "undefined") && (module !== null);
19515 if (b && module.exports) {
19516   module.exports = {
19517     exportedClasses: ['ForTest', 'Kii', 'KiiACL', 'KiiACLEntry', 'KiiACLWithToken', 'KiiAnonymousUser', 'KiiAnyAuthenticatedUser', 'KiiAppAdminContext', 'KiiBucket', 'KiiBucketWithToken', 'KiiClause', 'KiiEncryptedBucket', 'KiiEncryptedBucketWithToken', 'KiiErrorParser', 'KiiGeoPoint', 'KiiGroup', 'KiiGroupWithToken', 'KiiObject', 'KiiObjectWithToken', 'KiiPushInstallation', 'KiiPushInstallationWithToken', 'KiiPushSubscription', 'KiiPushSubscriptionWithToken', 'KiiQuery', 'KiiSCNFacebook', 'KiiSCNGoogle', 'KiiSCNQQ', 'KiiSCNRenRen', 'KiiSCNTwitter', 'KiiSDKClientInfo', 'KiiServerCodeEntry', 'KiiServerCodeExecResult', 'KiiSocialConnect', 'KiiSocialConnectNetwork', 'KiiThing', 'KiiThingContext', 'KiiThingQuery', 'KiiThingQueryResult', 'KiiThingWithToken', 'KiiTopic', 'KiiPushMessageBuilder', 'KiiTopicWithToken', 'KiiUser', 'KiiUserBuilder', 'KiiUserWithToken', 'KiiSocialNetworkName', 'KiiSite', 'KiiServerCodeEnvironmentVersion', '_KiiHttpRequestType', 'KiiACLAction', 'InvalidDisplayNameException', 'InvalidPasswordException', 'InvalidUsernameException', 'InvalidUserIdentifierException', 'InvalidEmailException', 'InvalidPhoneNumberException', 'InvalidLocalPhoneNumberException', 'InvalidCountryException', 'InvalidURIException', 'InvalidACLAction', 'InvalidACLSubject', 'InvalidACLGrant', 'InvalidLimitException', 'InvalidArgumentException', 'IllegalStateException', 'ArithmeticException', 'UnsupportedOperationException'],
19518     create: function() {
19519       return ctor.call(this);
19520     }
19521   };
19522 } else {
19523   ctor();
19524 }
19525 })();
19526 })();
19527