You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@usergrid.apache.org by sn...@apache.org on 2014/02/13 15:20:58 UTC
[14/51] [abbrv] lots of updates
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/9dfc5628/sdks/html5-javascript/lib/Usergrid.js
----------------------------------------------------------------------
diff --git a/sdks/html5-javascript/lib/Usergrid.js b/sdks/html5-javascript/lib/Usergrid.js
index 3805057..1a4e5dd 100644
--- a/sdks/html5-javascript/lib/Usergrid.js
+++ b/sdks/html5-javascript/lib/Usergrid.js
@@ -27,12 +27,52 @@
window.console = window.console || {};
window.console.log = window.console.log || function() {};
+
+function extend(subClass, superClass) {
+ var F = function() {};
+ F.prototype = superClass.prototype;
+ subClass.prototype = new F();
+ subClass.prototype.constructor = subClass;
+
+ subClass.superclass = superClass.prototype;
+ if(superClass.prototype.constructor == Object.prototype.constructor) {
+ superClass.prototype.constructor = superClass;
+ }
+ return subClass;
+}
+
+function NOOP(){}
+
//Usergrid namespace encapsulates this SDK
/*window.Usergrid = window.Usergrid || {};
Usergrid = Usergrid || {};
Usergrid.USERGRID_SDK_VERSION = '0.10.07';*/
+function isValidUrl(url) {
+ if (!url) return false;
+ var doc, base, anchor, isValid=false;
+ try{
+ doc = document.implementation.createHTMLDocument('');
+ base = doc.createElement('base');
+ base.href = base || window.lo;
+ doc.head.appendChild(base);
+ anchor = doc.createElement('a');
+ anchor.href = url;
+ doc.body.appendChild(anchor);
+ isValid=!(anchor.href === '')
+ }catch(e){
+ console.error(e);
+ }finally{
+ doc.head.removeChild(base);
+ doc.body.removeChild(anchor);
+ base=null;
+ anchor=null;
+ doc=null;
+ return isValid;
+ }
+}
+
/*
* Tests if the string is a uuid
*
@@ -55,34 +95,21 @@ function isUUID(uuid) {
* @return {string} Returns the encoded string
*/
function encodeParams(params) {
- var tail = [];
- var item = [];
- var i;
- if (params instanceof Array) {
- for (i in params) {
- item = params[i];
- if ((item instanceof Array) && (item.length > 1)) {
- tail.push(item[0] + "=" + encodeURIComponent(item[1]));
- }
- }
- } else {
- for (var key in params) {
- if (params.hasOwnProperty(key)) {
- var value = params[key];
- if (value instanceof Array) {
- for (i in value) {
- item = value[i];
- tail.push(key + "=" + encodeURIComponent(item));
- }
- } else {
- tail.push(key + "=" + encodeURIComponent(value));
- }
- }
- }
- }
- return tail.join("&");
+ var queryString;
+ if(params && Object.keys(params)){
+ queryString = [].slice.call(arguments)
+ .reduce(function(a, b) {return a.concat((b instanceof Array)?b:[b]);},[])
+ .filter(function(c){return "object"===typeof c})
+ .reduce(function(p,c){(!(c instanceof Array)) ? p= p.concat(Object.keys(c).map(function(key){return [key,c[key]]})): p.push(c); return p;},[])
+ .reduce(function(p,c){((c.length===2) ? p.push(c) : p= p.concat(c)); return p;},[])
+ .reduce(function(p,c){(c[1] instanceof Array) ? c[1].forEach(function(v){p.push([c[0],v])}): p.push(c); return p;},[])
+ .map(function(c){c[1]=encodeURIComponent(c[1]); return c.join('=')})
+ .join('&');
+ }
+ return queryString;
}
+
/*
* method to determine whether or not the passed variable is a function
*
@@ -122,490 +149,381 @@ function doCallback(callback, params, context) {
return returnValue;
}
-Function.prototype.extend = function(superClass) {
- var subClass=this,F = function() {};
- F.prototype = superClass.prototype;
- subClass.prototype = new F();
- subClass.prototype.constructor = subClass;
-
- subClass.superclass = superClass.prototype;
- if(superClass.prototype.constructor == Object.prototype.constructor) {
- superClass.prototype.constructor = superClass;
- }
- return subClass;
-}
-//Logger
-(function() {
- var name = 'Logger', global = this, overwrittenName = global[name], exports;
- /* logging */
- exports = (function() {
- function Logger(name) {
- function tr(m) {
- return {
- 'E': 'End',
- '%': 'group',
- '#': 'profile',
- '!': 'time'
- }[m];
- }
- var logEnabled = true,
- methods = "log error warn info debug assert clear count dir dirxml exception % %Collapsed %E # #E table ! !E trace".replace(/([E%#!])/g, tr).split(' '),
- con = window.console;
- if(!name){
- name="UNKNOWN";
- }
- function createLogMethod(method) {
- return function() {
- var args=[].slice.call(arguments);
- var prepend='['+method.toUpperCase()+']['+name+']:';
- if("string"===typeof args[0]){
- args[0]=prepend+args[0];
- }else{
- args.unshift(prepend);
- }
- logEnabled && con && con[method] && con[method].apply(con, args);
- }
- }
- for (var i = 0; i < methods.length; i++) {
- var method = methods[i];
- this[method] = createLogMethod(method);
- }
- }
- return Logger;
- }());
+//noinspection ThisExpressionReferencesGlobalObjectJS
+(function(global) {
+ var name = 'Usergrid', overwrittenName = global[name];
- global[name] = exports;
- global[name].noConflict = function() {
- if(overwrittenName){
- global[name] = overwrittenName;
- }
- return exports;
- };
- return global[name];
-}());
-//Promise
-(function() {
- var name = 'Promise', global = this, overwrittenName = global[name], exports;
-
- exports = (function(global) {
- function Promise() {
- this.complete = false;
- this.error = null;
- this.result = null;
- this.callbacks = [];
- }
- Promise.prototype.create = function() {
- return new Promise()
- };
- Promise.prototype.then = function(callback, context) {
- var f = function() {
- return callback.apply(context, arguments)
- };
- if (this.complete) {
- f(this.error, this.result);
- } else {
- this.callbacks.push(f);
- }
- };
- Promise.prototype.done = function(error, result) {
- this.complete = true;
- this.error = error;
- this.result = result;
- for (var i = 0; i < this.callbacks.length; i++) this.callbacks[i](error, result);
- this.callbacks.length = 0;
- };
- Promise.join = function(promises) {
- var p = new Promise(),
- total = promises.length,
- completed = 0,
- errors = [],
- results = [];
-
- function notifier(i) {
- return function(error, result) {
- completed += 1;
- errors[i] = error;
- results[i] = result;
- if (completed === total) {
- p.done(errors, results);
- }
- };
- }
- for (var i = 0; i < total; i++) {
- promises[i]().then(notifier(i));
- }
- return p;
- };
- Promise.chain = function(promises, error, result) {
- var p = new Promise();
- if (promises===null||promises.length === 0) {
- p.done(error, result);
- } else {
- promises[0](error, result).then(function(res, err) {
- promises.splice(0, 1);
- //self.logger.info(promises.length)
- if(promises){
- Promise.chain(promises, res, err).then(function(r, e) {
- p.done(r, e);
- });
- }else{
- p.done(res, err);
- }
- });
- }
- return p;
- };
- return Promise;
- }(window));
+ function Usergrid() {
+ this.logger = new Logger(name);
+ }
+ Usergrid.isValidEndpoint = function (endpoint) {
+ //TODO actually implement this
+ return true;
+ };
+ var VALID_REQUEST_METHODS = ['GET', 'POST', 'PUT', 'DELETE'];
+ Usergrid.Request = function (method, endpoint, query_params, data, callback) {
+ var p = new Promise();
+ /*
+ Create a logger
+ */
+ this.logger = new global.Logger("Usergrid.Request");
+ this.logger.time("process request " + method + " " + endpoint);
+ /*
+ Validate our input
+ */
+ this.endpoint=endpoint;
+ this.method = method.toUpperCase();
+ this.query_params = query_params;
+ this.data = ("object" === typeof data) ? JSON.stringify(data) : data;
- global[name] = exports;
- global[name].noConflict = function() {
- if(overwrittenName){
- global[name] = overwrittenName;
- }
- return exports;
- };
- return global[name];
-}());
-//Ajax
-(function() {
- var name = 'Ajax', global = this, overwrittenName = global[name], exports;
-
- Function.prototype.partial = function() {
- var fn = this,
- b = [].slice.call(arguments);
- return function() {
- return fn.apply(this, b.concat([].slice.call(arguments)))
- }
- }
-
- exports = (function() {
- function Ajax() {
- this.logger=new global.Logger(name);
- var self=this;
- function encode(data) {
- var result = "";
- if (typeof data === "string") {
- result = data;
- } else {
- var e = encodeURIComponent;
- for (var i in data) {
- if (data.hasOwnProperty(i)) {
- result += '&' + e(i) + '=' + e(data[i]);
- }
- }
- }
- return result;
- }
- var request = function(m, u, d) {
- var p = new Promise();
- (function(xhr) {
- xhr.onreadystatechange = function() {
- this.readyState ^ 4 || (self.logger.timeEnd(m + ' ' + u), p.done(null, this));
- };
- xhr.onerror=function(response){
- p.done(response, null);
- }
- xhr.onecomplete=function(response){
- self.info("%s request to %s returned %s", m, u, this.status );
- }
- xhr.open(m, u);
- self.logger.time(m + ' ' + u);
- xhr.send(encode(d));
- }(new XMLHttpRequest()));
- return p;
- };
- this.request=request;
- this.get = request.partial('GET');
- this.post = request.partial('POST');
- this.put = request.partial('PUT');
- this.delete = request.partial('DELETE');
- }
- return new Ajax();
- }());
+ if (VALID_REQUEST_METHODS.indexOf(this.method) === -1) {
+ throw new UsergridInvalidHTTPMethodError("invalid request method '" + this.method + "'");
+ }
- global[name] = exports;
- global[name].noConflict = function() {
- if(overwrittenName){
- global[name] = overwrittenName;
- }
- return exports;
- };
- return global[name];
-}());
-//KeyStore
-(function() {
- var name = 'KeyStore', global = this, overwrittenName = global[name], exports;
-
- exports = (function() {
- global.indexedDB = global.indexedDB || global.mozIndexedDB || global.webkitIndexedDB || global.msIndexedDB;
- // (Mozilla has never prefixed these objects, so we don't need global.mozIDB*)
- global.IDBTransaction = global.IDBTransaction || global.webkitIDBTransaction || global.msIDBTransaction;
- global.IDBKeyRange = global.IDBKeyRange || global.webkitIDBKeyRange || global.msIDBKeyRange;
- function KeyStore(database, version, storeName, keyPath, callback) {
- this.logger=new global.Logger(name);
- this.db = null;
- this.error = null;
- this.ready = false;
- this.database=database;
- this.version=version;
- this.storeName = storeName;
- this.keyPath = keyPath;
- this.init(callback)
-
- }
- KeyStore.prototype.init=function(callback) {
- var self=this;
- Promise.chain([
- function(){return self.openDatabase(null,self)},
- function(err,self){return self.getStore(err,self)}
- ]).then(callback);
- };
- KeyStore.prototype.openDatabase=function(err, self) {
- var p = new Promise();
- var req = global.indexedDB.open(this.database, this.version);
- req.onerror=function(){done(this, self)};
- req.onsuccess = function (evt) {
- self.db = this.result;
- //self.objectStore=self.db.transaction([self.storeName], "readwrite").objectStore(self.storeName);
- p.done(null, self);
- };
- req.onupgradeneeded = function (evt) {
- try {
- self.objectStore = event.currentTarget.transaction.objectStore(self.storeName);
- } catch (e) {
- self.objectStore = self.db.createObjectStore(self.storeName, {keyPath: self.keyPath});
- self.objectStore.createIndex(self.keyPath, self.keyPath, {unique: true});
- }
- };
- return p;
- }
- KeyStore.prototype.getStore=function(err, self){
- var p = new Promise();
- self.objectStore = self.db.transaction([self.storeName], "readwrite").objectStore(self.storeName);
- p.done(null, self);
- return p;
- };
- KeyStore.prototype.delete = function(key, callback) {
- var self=this;
- var p = new Promise();
- self.get(key).then(function(err, value){
- var item = self.objectStore.get(key);
- item.onsuccess = function(event) {
- self.objectStore.delete(key);
- p.done(null, self);
- };
- item.onerror = function(event) {
- p.done(this, self);
- };
- isFunction(callback) && callback(err, self);
- });
- return p;
- };
- KeyStore.prototype.get = function(key, callback) {
- var self=this;
- var p = new Promise();
- Promise.chain([
- function(){return self.openDatabase(null,self)},
- function(err,self){return self.getStore(err,self)},
- function(err, self){
- var p = new Promise();
- var item = self.objectStore.get(key);
- item.onsuccess = function(event) {
- p.done(null, this.result ? this.result.value : null);
- };
- item.onerror = function(event) {
- p.done(this, null);
- };
- return p;
- }
- ]).then(function(err, value){
- isFunction(callback) && callback(err, value);
- p.done(null, self);
- })
- return p;
- };
- KeyStore.prototype.set = function(key, value, callback) {
- var self=this;
- var data = {
- 'key': key,
- 'value': value
- };
- var p = new Promise();
- self.delete(key)
- .then(function(err, self){
- var item= self.objectStore.add(data);
- item.onsuccess = function(event) {
- p.done(null, data.value);
- };
- item.onerror=function(event){
- p.done(this, null);
- }
- isFunction(callback) && callback(err, self);
- })
- return p;
- };
- KeyStore.prototype.clear = function(callback) {
- var self=this;
- self.getStore(function(err, store){
- var req=store.clear();
- req.onsuccess = function(evt) {
- isFunction(callback) && callback(null, null);
- };
- req.onerror = function (evt) {
- isFunction(callback) && callback(new Usergrid.Error(this), null);
- };
- });
- };
- return KeyStore;
- }());
-
- global[name] = exports;
- global[name].noConflict = function() {
- if(overwrittenName){
- global[name] = overwrittenName;
- }
- return exports;
- };
- return global[name];
-}());
-(function() {
- var name = 'Usergrid', global = this, overwrittenName = global[name], exports;
-
- exports = (function() {
- function Usergrid(){
- this.logger=new global.Logger(name);
- var self=this;
- }
- Usergrid.isValidEndpoint = function(endpoint) {
- //TODO actually implement this
- return true;
- };
- var VALID_REQUEST_METHODS=['GET','POST','PUT','DELETE'];
- Usergrid.Request=function(method, endpoint, query_params, data, callback){
- var p = new Promise();
- this.method=method.toUpperCase();
- this.endpoint=endpoint;
- this.query_params=query_params;
- this.data=data;
- this.logger=new global.Logger("Usergrid.Request");
- var self=this;
- if(VALID_REQUEST_METHODS.indexOf(this.method)===-1){
- throw "invalid request method '"+this.method+"'";
- }
- if(!Usergrid.isValidEndpoint(this.endpoint)){
- throw "The provided endpoint is not valid: "+this.endpoint;
- }
- var encoded_params = encodeParams(this.query_params);
- if (encoded_params) {
- this.endpoint += "?" + encoded_params;
- }
- Ajax.request(this.method, this.endpoint, this.data).then(function(err, request){
- return new Usergrid.Response(err, request, callback);
- });
- };
-
-
- //TODO more granular handling of statusCodes
- Usergrid.Response=function(err, response, callback){
- this.logger=new global.Logger(name);
- this.success=true;
- this.err=err;
- this.response=response;
- this.text=this.response.responseText;
- try{
- this.data=JSON.parse(this.text);
- }catch(e){
- this.logger.error("Error parsing response text: ",this.text);
- this.data=null;
- }
- this.status=parseInt(response.status);
- this.statusGroup=(this.status - this.status%100);
- switch(this.statusGroup){
- case 200:
- this.success=true;
- break;
- case 400:
- case 500:
- case 300:
- case 100:
- default:
- //server error
- this.success=false;
- break;
- }
- var self=this;
- if(this.success){
- callback(null, self);
- }else{
- callback(new Usergrid.Error(this.data), self);
- }
- };
-
- Usergrid.Error=function(options){
- this.name="UsergridError";
- this.timestamp=Date.now();
- if(options instanceof Error){
- this.exception=options.name||"";
- this.message=options.message||"An error has occurred";
- }else if("object"===typeof options){
- this.exception=options.error||"unknown_error";
- this.message=options.error_description||"An error has occurred";
- }else if("string"===typeof options){
- this.exception="unknown_error";
- this.message=options||"An error has occurred";
- }
- }
- Usergrid.Error.prototype=new Error();
-
- Usergrid.Client=function(callback){
- this.logger=new global.Logger(name);
- var self=this;
- var keyStore=new KeyStore('usergrid-javascript-sdk', 2, "data", "key", function(err, ks){
- self.keyStore=ks;
- callback(err, self);
- });
- };
- Usergrid.Client.prototype.set = function(key, value, callback) {
- value = JSON.stringify(value);
- if (value) {
- this.keyStore.set(key, value, callback);
- } else {
- this.keyStore.delete(key, callback);
- }
- };
- Usergrid.Client.prototype.get = function(key, callback) {
- if ("undefined" !== typeof this.keyStore) {
- this.keyStore.get(key, callback);
- }
- };
- Usergrid.Entity=function(){};
- Usergrid.Collection=function(){};
- return Usergrid;
- }());
- global[name] = exports;
- global[name].noConflict = function() {
- if(overwrittenName){
- global[name] = overwrittenName;
- }
- return exports;
- };
- return global[name];
-}());
-/*(function(global, storage) {
- var name = 'Usergrid', overwrittenName = global[name];
- var Usergrid=Usergrid||global.Usergrid;
-
- global[name] = {
- Request : Usergrid.Request,
- Response : Usergrid.Response,
- Error : Usergrid.Error,
- Client : Usergrid.Client,
- Entity : Usergrid.Entity,
- Collection : Usergrid.Collection,
- version : '0.10.07'
- };
+ /*
+ Prepare our request
+ */
+ if (!isValidUrl(this.endpoint)) {
+ this.logger.error(endpoint, this.endpoint, /^https:\/\//.test(endpoint), api_uri, orgName, appName);
+ throw new UsergridError("The provided endpoint is not valid: " + this.endpoint);
+ }
+ /* a callback to make the request */
+ var request=function () {return Ajax.request(this.method, this.endpoint, this.data)}.bind(this);
+ /* a callback to process the response */
+ var response=function (err, request) {return new Usergrid.Response(err, request)}.bind(this);
+ /* a callback to clean up and return data to the client */
+ var oncomplete=function (err, response) {
+ p.done(err, response);
+ this.logger.info("REQUEST", err, response);
+ doCallback(callback, [err, response]);
+ this.logger.timeEnd("process request " + method + " " + endpoint);
+ }.bind(this);
+ /* and a promise to chain them all together */
+ Promise.chain([request,response]).then(oncomplete);
+
+ return p;
+ };
+ Usergrid.Request.prototype= new UsergridStorable();
+ Usergrid.Request.prototype.validate=function(){
+ var p = new Promise();
+ p.done(null, this);
+ return p;
+ }
+ Usergrid.Request.prototype.prepare=function(){
+ var p = new Promise();
+ p.done(null, this);
+ return p;
+ }
+ Usergrid.Request.prototype.fire=function(){
+ var p = new Promise();
+ p.done(null, this);
+ return p;
+ }
+
+ //TODO more granular handling of statusCodes
+ Usergrid.Response = function (err, response) {
+ var p = new Promise();
+ this.logger = new global.Logger(name);
+ this.success = true;
+ this.err = err;
+ this.data = {};
+ var data;
+ try {
+ data = JSON.parse(response.responseText);
+ } catch (e) {
+ //this.logger.error("Error parsing response text: ",this.text);
+ this.logger.error("Caught error ", e.message);
+ data = {}
+ } finally {
+ this.data = data;
+ }
+ this.status = parseInt(response.status);
+ this.statusGroup = (this.status - this.status % 100);
+ switch (this.statusGroup) {
+ case 200:
+ this.success = true;
+ break;
+ case 400:
+ case 500:
+ case 300:
+ case 100:
+ default:
+ //server error
+ this.success = false;
+ break;
+ }
+ var self = this;
+ if (this.success) {
+ p.done(null, this);
+ } else {
+ p.done(UsergridError.fromResponse(this.data), this);
+ }
+ return p;
+ };
+ Usergrid.Response.prototype.getEntities = function () {
+ var entities=[]
+ if (this.success && this.data.entities) {
+ entities=this.data.entities;
+ }
+ return entities;
+ }
+ Usergrid.Response.prototype.getEntity = function () {
+ var entities=this.getEntities();
+ return entities[0];
+ }
+ Usergrid.Client = function (options) {
+ this.logger = new global.Logger('Usergrid.Client');
+ var self = this;
+ this.getStorage();
+ this.set('api_uri', options.URI || 'https://api.usergrid.com');
+ this.set('orgName', options.orgName);
+ this.set('appName', options.appName);
+ //other options
+ this.set('buildCurl', options.buildCurl || false);
+ this.set('logging', options.logging || false);
+
+ //Moved to Ajax transport layer
+ /*this.set('api_call_timeout', options.callTimeout || 30000);
+ this.set('api_call_timeout_callback', options.callTimeoutCallback || global.NOOP);
+ this.set('api_logout_callback', options.logoutCallback || global.NOOP);*/
+
+
+ };
+ /*
+ Add browser storage capability (defaults to sessionStorage,
+ but you can inject anything that implements window.Storage
+ eg. client._storage=localStorage;
+ */
+ UsergridStorable.mixin(Usergrid.Client);
+ /*
+ Add rudimentary eventing
+ */
+ UsergridEventable.mixin(Usergrid.Client);
+
+ /*
+ * function for building asset urls
+ *
+ * @method buildAssetURL
+ * @public
+ * @params {string} uuid
+ * @return {string} assetURL
+ */
+ Usergrid.Client.prototype.buildAssetURL = function(uuid) {
+ var qs = {};
+ var uri_elements=this.get('api_uri','orgName','appName');
+ uri_elements=uri_elements.concat(['assets', uuid, 'data']);
+ var assetURL = uri_elements.join('/');
+ var token = this.getToken();
+ if (token) {
+ qs.access_token = token;
+ }
+ //append params to the path
+ var encoded_params = encodeParams(qs);
+ if (encoded_params) {
+ assetURL += "?" + encoded_params;
+ }
+
+ return assetURL;
+ };
+
+ /*
+ * function for building asset urls
+ *
+ * @method buildAssetURL
+ * @public
+ * @params {string} uuid
+ * @return {string} assetURL
+ */
+ Usergrid.Client.prototype.buildEndpointURL = function(endpoint, qs) {
+ qs =qs|| {};
+ var endSlashes=/(^\/|\/$)/g;
+ var assetURL = [endpoint.replace(endSlashes,'')].concat(this.get('api_uri','orgName','appName'));
+ var token = this.getToken();
+ if (token) {qs.access_token = token;}
+ var encoded_params = encodeParams(qs);
+ if (encoded_params) {
+ assetURL += "?" + encoded_params;
+ }
+
+ return assetURL;
+ };
+
+
+ /*
+ * Main function for making requests to the API. Can be called directly.
+ *
+ * options object:
+ * `method` - http method (GET, POST, PUT, or DELETE), defaults to GET
+ * `qs` - object containing querystring values to be appended to the uri
+ * `body` - object containing entity body for POST and PUT requests
+ * `endpoint` - API endpoint, for example 'users/fred'
+ * `mQuery` - boolean, set to true if running management query, defaults to false
+ *
+ * @method request
+ * @public
+ * @params {object} options
+ * @param {function} callback
+ * @return {callback} callback(err, data)
+ */
+ Usergrid.Client.prototype.request = function (options, callback) {
+ var p = new Promise();
+ var _callback = function (err, data) {
+ p.done(err, data);
+ doCallback(callback, [err, data]);
+ };
+ this.logger = new Logger("Request");
+ var self = this;
+ var method = options.method || 'GET';
+ var endpoint = options.endpoint;
+ var body = options.body || {};
+ var qs = options.qs || {};
+ var mQuery = options.mQuery || false; //is this a query to the management endpoint?
+ /*
+ could also use headers for the token
+ xhr.setRequestHeader("Authorization", "Bearer " + self.getToken());
+ xhr.withCredentials = true;
+ */
+ var api_uri = this.get('api_uri');
+ var orgName = this.get('orgName');
+ var appName = this.get('appName');
+ if (this.getToken())qs.access_token = this.getToken();
+
+ //if(isValidUrl(endpoint)){
+ if (api_uri && orgName && appName) {
+ endpoint = [api_uri, orgName, appName, endpoint].join('/');
+ } else {
+ endpoint = [api_uri, endpoint].join('/');
+ //throw new UsergridInvalidURIError('No Org name or App name specified.', 'no_org_or_app_name_specified');
+ }
+
+ var req = new Usergrid.Request(method, endpoint, qs, body, function (err, response) {
+ if ([
+ "auth_expired_session_token",
+ "auth_missing_credentials",
+ "auth_unverified_oath",
+ "expired_token",
+ "unauthorized",
+ "auth_invalid"
+ ].indexOf(response.error) !== -1) {
+ //throw err;
+ }
+ doCallback(callback, [err, response]);
+ p.done(err, response);
+ });
+
+
+ return p;
+ /*}catch(e){
+ if (typeof(this.logoutCallback) === 'function') {
+ this.logoutCallback(true, 'no_org_or_app_name_specified');
+ }
+ _callback(true, e);
+
+ }*/
+ };
+
+ /*
+ * Main function for creating new entities - should be called directly.
+ *
+ * options object: options {data:{'type':'collection_type', 'key':'value'}, uuid:uuid}}
+ *
+ * @method createEntity
+ * @public
+ * @params {object} options
+ * @param {function} callback
+ * @return {callback} callback(err, data)
+ */
+ Usergrid.Client.prototype.createEntity = function (options, callback) {
+ // todo: replace the check for new / save on not found code with simple save
+ // when users PUT on no user fix is in place.
+ var getOnExist = options['getOnExist'] || false; //if true, will return entity if one already exists
+ delete options['getOnExist']; //so it doesn't become part of our data model
+ var entity_data = {
+ client: this,
+ data: options
+ };
+ var entity = new Usergrid.Entity(entity_data);
+ var self = this;
+ entity.fetch(function (err, data) {
+ console.log(err, data);
+ //if the fetch doesn't find what we are looking for, or there is no error, do a save
+ var common_errors = ['service_resource_not_found', 'no_name_specified', 'null_pointer'];
+ var okToSave = (err.name && common_errors.indexOf(err.name) !== -1) || (!err && getOnExist);
+
+ if (okToSave) {
+ entity.set(entity_data.data); //add the data again just in case
+ entity.save(function (err, data) {
+ doCallback(callback, [err, entity, data]);
+ });
+ } else {
+ doCallback(callback, [err, entity, data]);
+ }
+ });
+
+ };
+
+ /*
+ * Main function for getting existing entities - should be called directly.
+ *
+ * You must supply a uuid or (username or name). Username only applies to users.
+ * Name applies to all custom entities
+ *
+ * options object: options {data:{'type':'collection_type', 'name':'value', 'username':'value'}, uuid:uuid}}
+ *
+ * @method createEntity
+ * @public
+ * @params {object} options
+ * @param {function} callback
+ * @return {callback} doCallback(callback, [err, data])
+ */
+ Usergrid.Client.prototype.getEntity = function (options, callback) {
+ var entity_data = {
+ client: this,
+ data: options
+ };
+ var entity = new Usergrid.Entity(entity_data);
+ entity.fetch(function (err, data) {
+ doCallback(callback, [err, entity, data]);
+ });
+ };
+
+ /*
+ * Main function for restoring an entity from serialized data.
+ *
+ * serializedObject should have come from entityObject.serialize();
+ *
+ * @method restoreEntity
+ * @public
+ * @param {string} serializedObject
+ * @return {object} Entity Object
+ */
+ Usergrid.Client.prototype.restoreEntity = function (serializedObject) {
+ return new Usergrid.Entity({ client: this, data: JSON.parse(serializedObject)});
+ };
+ /*
+ * Main function for creating new collections - should be called directly.
+ *
+ * options object: options {client:client, type: type, qs:qs}
+ *
+ * @method createCollection
+ * @public
+ * @params {object} options
+ * @param {function} callback
+ * @return {callback} callback(err, data)
+ */
+ Usergrid.Client.prototype.createCollection = function (options, callback) {
+ options.client = this;
+ var collection = new Usergrid.Collection(options, function (err, data) {
+ if (typeof(callback) === 'function') {
+ callback(err, collection, data);
+ }
+ });
+ };
+
+ //Usergrid.Entity=function(){};
+ //Usergrid.Collection=function(){};
+ global[name] = Usergrid;
global[name].noConflict = function() {
if(overwrittenName){
global[name] = overwrittenName;
@@ -613,6 +531,7 @@ Function.prototype.extend = function(superClass) {
return Usergrid;
};
return global[name];
-}(this, localStorage));*/
+}(this));
+
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/9dfc5628/sdks/html5-javascript/lib/modules/Asset.js
----------------------------------------------------------------------
diff --git a/sdks/html5-javascript/lib/modules/Asset.js b/sdks/html5-javascript/lib/modules/Asset.js
new file mode 100644
index 0000000..0eed742
--- /dev/null
+++ b/sdks/html5-javascript/lib/modules/Asset.js
@@ -0,0 +1,149 @@
+/*
+ * XMLHttpRequest.prototype.sendAsBinary polyfill
+ * from: https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest#sendAsBinary()
+ *
+ * @method sendAsBinary
+ * @param {string} sData
+ */
+if (!XMLHttpRequest.prototype.sendAsBinary) {
+ XMLHttpRequest.prototype.sendAsBinary = function(sData) {
+ var nBytes = sData.length,
+ ui8Data = new Uint8Array(nBytes);
+ for (var nIdx = 0; nIdx < nBytes; nIdx++) {
+ ui8Data[nIdx] = sData.charCodeAt(nIdx) & 0xff;
+ }
+ this.send(ui8Data);
+ };
+}
+
+
+/*
+ * A class to model a Usergrid asset.
+ *
+ * @constructor
+ * @param {object} options {name:"photo.jpg", path:"/user/uploads", "content-type":"image/jpeg", owner:"F01DE600-0000-0000-0000-000000000000" }
+ * @returns {callback} callback(err, asset)
+ */
+Usergrid.Asset = function(options, callback) {
+ var self = this,
+ messages = [];
+ self._client = options.client;
+ self._data = options.data || {};
+ self._data.type = "assets";
+ var missingData = ["name", "owner", "path"].some(function(required) { return !(required in self._data)});
+ if(missingData){
+ return doCallback(callback, [true, new Usergrid.Error("Invalid asset data: 'name', 'owner', and 'path' are required properties.")], self);
+ }
+ self.save(function(err, data) {
+ if (err) {
+ doCallback(callback, [true, new Usergrid.Error(data)], self);
+ } else {
+ if (data.entities.length){
+ self.set(data.entities[0]);
+ }
+ doCallback(callback, [false, self], self);
+ }
+ });
+};
+
+/*
+ * Inherit from Usergrid.Entity.
+ */
+Usergrid.Asset.prototype = new Usergrid.Entity();
+
+/*
+ * Add an asset to a folder.
+ *
+ * @method connect
+ * @public
+ * @param {object} options {folder:"F01DE600-0000-0000-0000-000000000000"}
+ * @returns {callback} callback(err, asset)
+ */
+
+Usergrid.Asset.prototype.addToFolder = function(options, callback) {
+ var self = this,
+ error = null;
+ if (('folder' in options) && isUUID(options.folder)) {
+ //we got a valid UUID
+ var folder = Usergrid.Folder({
+ uuid: options.folder
+ }, function(err, folder) {
+ if (err) {
+ return callback.call(self, err, folder);
+ }
+ var endpoint = ["folders", folder.get("uuid"), "assets", self.get("uuid")].join('/');
+ var options = {
+ method: 'POST',
+ endpoint: endpoint
+ };
+ this._client.request(options, callback);
+ });
+ } else {
+ doCallback(callback, [true, new Usergrid.Error('folder not specified')], self);
+ }
+};
+
+/*
+ * Upload Asset data
+ *
+ * @method upload
+ * @public
+ * @param {object} data Can be a javascript Blob or File object
+ * @returns {callback} callback(err, asset)
+ */
+Usergrid.Asset.prototype.upload = function(data, callback) {
+ if (!(window.File && window.FileReader && window.FileList && window.Blob)) {
+ return doCallback(callback, [true, new Usergrid.Error('The File APIs are not fully supported by your browser.')], self);
+ }
+ var self = this;
+ var endpoint = [this._client.URI, this._client.orgName, this._client.appName, "assets", self.get("uuid"), 'data'].join('/'); //self._client.buildAssetURL(self.get("uuid"));
+
+ var xhr = new XMLHttpRequest();
+ xhr.open("POST", endpoint, true);
+ xhr.onerror = function(err) {
+ //callback(true, err);
+ doCallback(callback, [true, new Usergrid.Error('The File APIs are not fully supported by your browser.')], self)
+ };
+ xhr.onload = function(ev) {
+ if (xhr.status >= 300) {
+ doCallback(callback, [true, new Usergrid.Error(JSON.parse(xhr.responseText))], self)
+ } else {
+ doCallback(callback, [null, self], self)
+ }
+ };
+ var fr = new FileReader();
+ fr.onload = function() {
+ var binary = fr.result;
+ xhr.overrideMimeType('application/octet-stream');
+ setTimeout(function() {
+ xhr.sendAsBinary(binary);
+ }, 1000);
+ };
+ fr.readAsBinaryString(data);
+}
+
+/*
+ * Download Asset data
+ *
+ * @method download
+ * @public
+ * @returns {callback} callback(err, blob) blob is a javascript Blob object.
+ */
+Usergrid.Asset.prototype.download = function(callback) {
+ var self = this;
+ var endpoint = [this._client.URI, this._client.orgName, this._client.appName, "assets", self.get("uuid"), 'data'].join('/');
+ var xhr = new XMLHttpRequest();
+ xhr.open("GET", endpoint, true);
+ xhr.responseType = "blob";
+ xhr.onload = function(ev) {
+ var blob = xhr.response;
+ //callback(null, blob);
+ doCallback(callback, [false, blob], self)
+ };
+ xhr.onerror = function(err) {
+ callback(true, err);
+ doCallback(callback, [true, new Usergrid.Error(err)], self)
+ };
+
+ xhr.send();
+}
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/9dfc5628/sdks/html5-javascript/lib/modules/Client.js
----------------------------------------------------------------------
diff --git a/sdks/html5-javascript/lib/modules/Client.js b/sdks/html5-javascript/lib/modules/Client.js
new file mode 100644
index 0000000..727e257
--- /dev/null
+++ b/sdks/html5-javascript/lib/modules/Client.js
@@ -0,0 +1,860 @@
+(function() {
+ var name = 'Client', global = this, overwrittenName = global[name], exports;
+exports = (function() {
+ Usergrid.Client = function(options) {
+ //usergrid endpoint
+ this.URI = options.URI || 'https://api.usergrid.com';
+
+ //Find your Orgname and Appname in the Admin portal (http://apigee.com/usergrid)
+ if (options.orgName) {
+ this.set('orgName', options.orgName);
+ }
+ if (options.appName) {
+ this.set('appName', options.appName);
+ }
+
+ //other options
+ this.buildCurl = options.buildCurl || false;
+ this.logging = options.logging || false;
+
+ //timeout and callbacks
+ this._callTimeout = options.callTimeout || 30000; //default to 30 seconds
+ this._callTimeoutCallback = options.callTimeoutCallback || null;
+ this.logoutCallback = options.logoutCallback || null;
+ var self=this;
+ this.keyStore=options.keyStore||new KeyStore('usergrid-javascript-sdk', 2, "data", "key", function(err, ks){
+ self.logger.info("'%s' keystore created.", 'usergrid-javascript-sdk');
+ });
+ };
+
+ /*
+ * Main function for making requests to the API. Can be called directly.
+ *
+ * options object:
+ * `method` - http method (GET, POST, PUT, or DELETE), defaults to GET
+ * `qs` - object containing querystring values to be appended to the uri
+ * `body` - object containing entity body for POST and PUT requests
+ * `endpoint` - API endpoint, for example 'users/fred'
+ * `mQuery` - boolean, set to true if running management query, defaults to false
+ *
+ * @method request
+ * @public
+ * @params {object} options
+ * @param {function} callback
+ * @return {callback} callback(err, data)
+ */
+ Usergrid.Client.prototype.request = function (options, callback) {
+ var self = this;
+ var method = options.method || 'GET';
+ var endpoint = options.endpoint;
+ var body = options.body || {};
+ var qs = options.qs || {};
+ var mQuery = options.mQuery || false; //is this a query to the management endpoint?
+ var orgName = this.get('orgName');
+ var appName = this.get('appName');
+ var uri;
+ if(!mQuery && !orgName && !appName){
+ if (typeof(this.logoutCallback) === 'function') {
+ return this.logoutCallback(true, 'no_org_or_app_name_specified');
+ }
+ }
+ if (mQuery) {
+ uri = this.URI + '/' + endpoint;
+ } else {
+ uri = this.URI + '/' + orgName + '/' + appName + '/' + endpoint;
+ }
+
+ if (self.getToken()) {
+ qs.access_token = self.getToken();
+ /* //could also use headers for the token
+ xhr.setRequestHeader("Authorization", "Bearer " + self.getToken());
+ xhr.withCredentials = true;
+ */
+ }
+
+ //append params to the path
+ var encoded_params = encodeParams(qs);
+ if (encoded_params) {
+ uri += "?" + encoded_params;
+ }
+
+ //stringify the body object
+ body = JSON.stringify(body);
+
+ //so far so good, so run the query
+ var xhr = new XMLHttpRequest();
+ xhr.open(method, uri, true);
+ //add content type = json if there is a json payload
+ if (body) {
+ xhr.setRequestHeader("Content-Type", "application/json");
+ xhr.setRequestHeader("Accept", "application/json");
+ }
+
+ // Handle response.
+ xhr.onerror = function(response) {
+ self._end = new Date().getTime();
+ if (self.logging) {
+ console.log('success (time: ' + self.calcTimeDiff() + '): ' + method + ' ' + uri);
+ }
+ if (self.logging) {
+ console.log('Error: API call failed at the network level.');
+ }
+ //network error
+ clearTimeout(timeout);
+ var err = true;
+ if (typeof(callback) === 'function') {
+ callback(err, response);
+ }
+ };
+
+ xhr.onload = function(response) {
+ //call timing, get time, then log the call
+ self._end = new Date().getTime();
+ if (self.logging) {
+ console.log('success (time: ' + self.calcTimeDiff() + '): ' + method + ' ' + uri);
+ }
+ //call completed
+ clearTimeout(timeout);
+ //decode the response
+ try{
+ response = JSON.parse(xhr.responseText);
+ }catch (e){
+ response = {error:'unhandled_error',error_description:xhr.responseText};
+ xhr.status = xhr.status === 200 ? 400 : xhr.status;
+ console.error(e);
+ }
+ if (xhr.status != 200) {
+ //there was an api error
+ var error = response.error;
+ var error_description = response.error_description;
+ if (self.logging) {
+ console.log('Error (' + xhr.status + ')(' + error + '): ' + error_description);
+ }
+ if ( (error == "auth_expired_session_token") ||
+ (error == "auth_missing_credentials") ||
+ (error == "auth_unverified_oath") ||
+ (error == "expired_token") ||
+ (error == "unauthorized") ||
+ (error == "auth_invalid")) {
+ //these errors mean the user is not authorized for whatever reason. If a logout function is defined, call it
+ //if the user has specified a logout callback:
+ if (typeof(self.logoutCallback) === 'function') {
+ return self.logoutCallback(true, response);
+ }
+ }
+ if (typeof(callback) === 'function') {
+ callback(true, response);
+ }
+ } else {
+ if (typeof(callback) === 'function') {
+ callback(false, response);
+ }
+ }
+ };
+
+ var timeout = setTimeout(
+ function() {
+ xhr.abort();
+ if (self._callTimeoutCallback === 'function') {
+ self._callTimeoutCallback('API CALL TIMEOUT');
+ } else {
+ self.callback('API CALL TIMEOUT');
+ }
+ },
+ self._callTimeout); //set for 30 seconds
+
+ if (this.logging) {
+ console.log('calling: ' + method + ' ' + uri);
+ }
+ if (this.buildCurl) {
+ var curlOptions = {
+ uri:uri,
+ body:body,
+ method:method
+ }
+ this.buildCurlCall(curlOptions);
+ }
+ this._start = new Date().getTime();
+ xhr.send(body);
+ }
+
+ /*
+ * function for building asset urls
+ *
+ * @method buildAssetURL
+ * @public
+ * @params {string} uuid
+ * @return {string} assetURL
+ */
+ Usergrid.Client.prototype.buildAssetURL = function(uuid) {
+ var self = this;
+ var qs = {};
+ var assetURL = this.URI + '/' + this.orgName + '/' + this.appName + '/assets/' + uuid + '/data';
+
+ if (self.getToken()) {
+ qs.access_token = self.getToken();
+ }
+
+ //append params to the path
+ var encoded_params = encodeParams(qs);
+ if (encoded_params) {
+ assetURL += "?" + encoded_params;
+ }
+
+ return assetURL;
+ };
+
+ /*
+ * Main function for creating new groups. Call this directly.
+ *
+ * @method createGroup
+ * @public
+ * @params {string} path
+ * @param {function} callback
+ * @return {callback} callback(err, data)
+ */
+ Usergrid.Client.prototype.createGroup = function(options, callback) {
+ var getOnExist = options.getOnExist || false;
+
+ options = {
+ path: options.path,
+ client: this,
+ data: options
+ };
+
+ var group = new Usergrid.Group(options);
+ group.fetch(function(err, data){
+ var okToSave = (err && 'service_resource_not_found' === data.error || 'no_name_specified' === data.error || 'null_pointer' === data.error) || (!err && getOnExist);
+ if (okToSave) {
+ group.save(function(err, data){
+ if (typeof(callback) === 'function') {
+ callback(err, group);
+ }
+ });
+ } else {
+ if(typeof(callback) === 'function') {
+ callback(err, group);
+ }
+ }
+ });
+ };
+
+ /*
+ * Main function for creating new entities - should be called directly.
+ *
+ * options object: options {data:{'type':'collection_type', 'key':'value'}, uuid:uuid}}
+ *
+ * @method createEntity
+ * @public
+ * @params {object} options
+ * @param {function} callback
+ * @return {callback} callback(err, data)
+ */
+ Usergrid.Client.prototype.createEntity = function (options, callback) {
+ // todo: replace the check for new / save on not found code with simple save
+ // when users PUT on no user fix is in place.
+ var getOnExist = options.getOnExist || false; //if true, will return entity if one already exists
+ delete options.getOnExist;//so it doesn't become part of our data model
+ var options = {
+ client:this,
+ data:options
+ };
+ var entity = new Usergrid.Entity(options);
+ entity.fetch(function(err, data) {
+ //if the fetch doesn't find what we are looking for, or there is no error, do a save
+ var okToSave = (err && 'service_resource_not_found' === data.error || 'no_name_specified' === data.error || 'null_pointer' === data.error) || (!err && getOnExist);
+ if(okToSave) {
+ entity.set(options.data); //add the data again just in case
+ entity.save(function(err, data) {
+ if (typeof(callback) === 'function') {
+ callback(err, entity, data);
+ }
+ });
+ } else {
+ if (typeof(callback) === 'function') {
+ callback(err, entity, data);
+ }
+ }
+ });
+
+ };
+
+ /*
+ * Main function for getting existing entities - should be called directly.
+ *
+ * You must supply a uuid or (username or name). Username only applies to users.
+ * Name applies to all custom entities
+ *
+ * options object: options {data:{'type':'collection_type', 'name':'value', 'username':'value'}, uuid:uuid}}
+ *
+ * @method createEntity
+ * @public
+ * @params {object} options
+ * @param {function} callback
+ * @return {callback} callback(err, data)
+ */
+ Usergrid.Client.prototype.getEntity = function (options, callback) {
+ var options = {
+ client:this,
+ data:options
+ }
+ var entity = new Usergrid.Entity(options);
+ entity.fetch(function(err, data) {
+ if (typeof(callback) === 'function') {
+ callback(err, entity, data);
+ }
+ });
+ };
+
+ /*
+ * Main function for restoring an entity from serialized data.
+ *
+ * serializedObject should have come from entityObject.serialize();
+ *
+ * @method restoreEntity
+ * @public
+ * @param {string} serializedObject
+ * @return {object} Entity Object
+ */
+ Usergrid.Client.prototype.restoreEntity = function (serializedObject) {
+ var data = JSON.parse(serializedObject);
+ var options = {
+ client:this,
+ data:data
+ }
+ var entity = new Usergrid.Entity(options);
+ return entity;
+ };
+
+ /*
+ * Main function for creating new collections - should be called directly.
+ *
+ * options object: options {client:client, type: type, qs:qs}
+ *
+ * @method createCollection
+ * @public
+ * @params {object} options
+ * @param {function} callback
+ * @return {callback} callback(err, data)
+ */
+ Usergrid.Client.prototype.createCollection = function (options, callback) {
+ options.client = this;
+ var collection = new Usergrid.Collection(options, function(err, data) {
+ if (typeof(callback) === 'function') {
+ callback(err, collection, data);
+ }
+ });
+ };
+
+ /*
+ * Main function for restoring a collection from serialized data.
+ *
+ * serializedObject should have come from collectionObject.serialize();
+ *
+ * @method restoreCollection
+ * @public
+ * @param {string} serializedObject
+ * @return {object} Collection Object
+ */
+ Usergrid.Client.prototype.restoreCollection = function (serializedObject) {
+ var data = JSON.parse(serializedObject);
+ data.client = this;
+ var collection = new Usergrid.Collection(data);
+ return collection;
+ };
+
+ /*
+ * Main function for retrieving a user's activity feed.
+ *
+ * @method getFeedForUser
+ * @public
+ * @params {string} username
+ * @param {function} callback
+ * @return {callback} callback(err, data, activities)
+ */
+ Usergrid.Client.prototype.getFeedForUser = function(username, callback) {
+ var options = {
+ method: "GET",
+ endpoint: "users/"+username+"/feed"
+ };
+
+ this.request(options, function(err, data){
+ if(typeof(callback) === "function") {
+ if(err) {
+ callback(err);
+ } else {
+ callback(err, data, data.entities);
+ }
+ }
+ });
+ };
+
+ /*
+ * Function for creating new activities for the current user - should be called directly.
+ *
+ * //user can be any of the following: "me", a uuid, a username
+ * Note: the "me" alias will reference the currently logged in user (e.g. 'users/me/activties')
+ *
+ * //build a json object that looks like this:
+ * var options =
+ * {
+ * "actor" : {
+ * "displayName" :"myusername",
+ * "uuid" : "myuserid",
+ * "username" : "myusername",
+ * "email" : "myemail",
+ * "picture": "http://path/to/picture",
+ * "image" : {
+ * "duration" : 0,
+ * "height" : 80,
+ * "url" : "http://www.gravatar.com/avatar/",
+ * "width" : 80
+ * },
+ * },
+ * "verb" : "post",
+ * "content" : "My cool message",
+ * "lat" : 48.856614,
+ * "lon" : 2.352222
+ * }
+ *
+ * @method createEntity
+ * @public
+ * @params {string} user // "me", a uuid, or a username
+ * @params {object} options
+ * @param {function} callback
+ * @return {callback} callback(err, data)
+ */
+ Usergrid.Client.prototype.createUserActivity = function (user, options, callback) {
+ options.type = 'users/'+user+'/activities';
+ var options = {
+ client:this,
+ data:options
+ }
+ var entity = new Usergrid.Entity(options);
+ entity.save(function(err, data) {
+ if (typeof(callback) === 'function') {
+ callback(err, entity);
+ }
+ });
+ };
+
+ /*
+ * Function for creating user activities with an associated user entity.
+ *
+ * user object:
+ * The user object passed into this function is an instance of Usergrid.Entity.
+ *
+ * @method createUserActivityWithEntity
+ * @public
+ * @params {object} user
+ * @params {string} content
+ * @param {function} callback
+ * @return {callback} callback(err, data)
+ */
+ Usergrid.Client.prototype.createUserActivityWithEntity = function(user, content, callback) {
+ var username = user.get("username");
+ var options = {
+ actor: {
+ "displayName":username,
+ "uuid":user.get("uuid"),
+ "username":username,
+ "email":user.get("email"),
+ "picture":user.get("picture"),
+ "image": {
+ "duration":0,
+ "height":80,
+ "url":user.get("picture"),
+ "width":80
+ },
+ },
+ "verb":"post",
+ "content":content
+ };
+
+ this.createUserActivity(username, options, callback);
+
+ };
+
+ /*
+ * A private method to get call timing of last call
+ */
+ Usergrid.Client.prototype.calcTimeDiff = function () {
+ var seconds = 0;
+ var time = this._end - this._start;
+ try {
+ seconds = ((time/10) / 60).toFixed(2);
+ } catch(e) {
+ return 0;
+ }
+ return seconds;
+ };
+
+ /*
+ * A public method to store the OAuth token for later use - uses localstorage if available
+ *
+ * @method setToken
+ * @public
+ * @params {string} token
+ * @return none
+ */
+ Usergrid.Client.prototype.setToken = function (token) {
+ this.set('token', token);
+ };
+
+ /*
+ * A public method to get the OAuth token
+ *
+ * @method getToken
+ * @public
+ * @return {string} token
+ */
+ Usergrid.Client.prototype.getToken = function () {
+ return this.get('token');
+ };
+
+ Usergrid.Client.prototype.setObject = function(key, value) {
+ if (value) {
+ value = JSON.stringify(value);
+ }
+ this.set(key, value);
+ };
+
+ Usergrid.Client.prototype.set = function (key, value) {
+ var keyStore = 'apigee_' + key;
+ this[key] = value;
+ if(typeof(Storage)!=="undefined"){
+ if (value) {
+ localStorage.setItem(keyStore, value);
+ } else {
+ localStorage.removeItem(keyStore);
+ }
+ }
+ };
+
+ Usergrid.Client.prototype.getObject = function(key) {
+ return JSON.parse(this.get(key));
+ };
+
+ Usergrid.Client.prototype.get = function (key) {
+ var keyStore = 'apigee_' + key;
+ var value=null;
+ if (this[key]) {
+ value= this[key];
+ } else if(typeof(Storage)!=="undefined") {
+ value= localStorage.getItem(keyStore);
+ }
+ return value ;
+ };
+
+ /*
+ * A public facing helper method for signing up users
+ *
+ * @method signup
+ * @public
+ * @params {string} username
+ * @params {string} password
+ * @params {string} email
+ * @params {string} name
+ * @param {function} callback
+ * @return {callback} callback(err, data)
+ */
+ Usergrid.Client.prototype.signup = function(username, password, email, name, callback) {
+ var self = this;
+ var options = {
+ type:"users",
+ username:username,
+ password:password,
+ email:email,
+ name:name
+ };
+
+ this.createEntity(options, callback);
+ };
+
+ /*
+ *
+ * A public method to log in an app user - stores the token for later use
+ *
+ * @method login
+ * @public
+ * @params {string} username
+ * @params {string} password
+ * @param {function} callback
+ * @return {callback} callback(err, data)
+ */
+ Usergrid.Client.prototype.login = function (username, password, callback) {
+ var self = this;
+ var options = {
+ method:'POST',
+ endpoint:'token',
+ body:{
+ username: username,
+ password: password,
+ grant_type: 'password'
+ }
+ };
+ this.request(options, function(err, data) {
+ var user = {};
+ if (err && self.logging) {
+ console.log('error trying to log user in');
+ } else {
+ var options = {
+ client:self,
+ data:data.user
+ };
+ user = new Usergrid.Entity(options);
+ self.setToken(data.access_token);
+ }
+ if (typeof(callback) === 'function') {
+ callback(err, data, user);
+ }
+ });
+ };
+
+
+ Usergrid.Client.prototype.reAuthenticateLite = function (callback) {
+ var self = this;
+ var options = {
+ method:'GET',
+ endpoint:'management/me',
+ mQuery:true
+ };
+ this.request(options, function(err, response) {
+ if (err && self.logging) {
+ console.log('error trying to re-authenticate user');
+ } else {
+
+ //save the re-authed token and current email/username
+ self.setToken(response.access_token);
+
+ }
+ if (typeof(callback) === 'function') {
+ callback(err);
+ }
+ });
+ };
+
+
+ Usergrid.Client.prototype.reAuthenticate = function (email, callback) {
+ var self = this;
+ var options = {
+ method:'GET',
+ endpoint:'management/users/'+email,
+ mQuery:true
+ };
+ this.request(options, function(err, response) {
+ var organizations = {};
+ var applications = {};
+ var user = {};
+ var data;
+ if (err && self.logging) {
+ console.log('error trying to full authenticate user');
+ } else {
+ data = response.data;
+ self.setToken(data.token);
+ self.set('email', data.email);
+
+ //delete next block and corresponding function when iframes are refactored
+ localStorage.setItem('accessToken', data.token);
+ localStorage.setItem('userUUID', data.uuid);
+ localStorage.setItem('userEmail', data.email);
+ //end delete block
+
+
+ var userData = {
+ "username" : data.username,
+ "email" : data.email,
+ "name" : data.name,
+ "uuid" : data.uuid
+ };
+ var options = {
+ client:self,
+ data:userData
+ };
+ user = new Usergrid.Entity(options);
+
+ organizations = data.organizations;
+ var org = '';
+ try {
+ //if we have an org stored, then use that one. Otherwise, use the first one.
+ var existingOrg = self.get('orgName');
+ org = (organizations[existingOrg])?organizations[existingOrg]:organizations[Object.keys(organizations)[0]];
+ self.set('orgName', org.name);
+ } catch(e) {
+ err = true;
+ if (self.logging) {
+ console.log('error selecting org');
+ }
+ } //should always be an org
+
+ applications = self.parseApplicationsArray(org);
+ self.selectFirstApp(applications);
+
+ self.setObject('organizations', organizations);
+ self.setObject('applications', applications);
+
+ }
+ if (typeof(callback) === 'function') {
+ callback(err, data, user, organizations, applications);
+ }
+ });
+ };
+
+ /*
+ * A public method to log in an app user with facebook - stores the token for later use
+ *
+ * @method loginFacebook
+ * @public
+ * @params {string} username
+ * @params {string} password
+ * @param {function} callback
+ * @return {callback} callback(err, data)
+ */
+ Usergrid.Client.prototype.loginFacebook = function (facebookToken, callback) {
+ var self = this;
+ var options = {
+ method:'GET',
+ endpoint:'auth/facebook',
+ qs:{
+ fb_access_token: facebookToken
+ }
+ };
+ this.request(options, function(err, data) {
+ var user = {};
+ if (err && self.logging) {
+ console.log('error trying to log user in');
+ } else {
+ var options = {
+ client: self,
+ data: data.user
+ }
+ user = new Usergrid.Entity(options);
+ self.setToken(data.access_token);
+ }
+ if (typeof(callback) === 'function') {
+ callback(err, data, user);
+ }
+ });
+ };
+
+ /*
+ * A public method to get the currently logged in user entity
+ *
+ * @method getLoggedInUser
+ * @public
+ * @param {function} callback
+ * @return {callback} callback(err, data)
+ */
+ Usergrid.Client.prototype.getLoggedInUser = function (callback) {
+ if (!this.getToken()) {
+ callback(true, null, null);
+ } else {
+ var self = this;
+ var options = {
+ method:'GET',
+ endpoint:'users/me'
+ };
+ this.request(options, function(err, data) {
+ if (err) {
+ if (self.logging) {
+ console.log('error trying to log user in');
+ }
+ if (typeof(callback) === 'function') {
+ callback(err, data, null);
+ }
+ } else {
+ var options = {
+ client:self,
+ data:data.entities[0]
+ };
+ var user = new Usergrid.Entity(options);
+ if (typeof(callback) === 'function') {
+ callback(err, data, user);
+ }
+ }
+ });
+ }
+ };
+
+ /*
+ * A public method to test if a user is logged in - does not guarantee that the token is still valid,
+ * but rather that one exists
+ *
+ * @method isLoggedIn
+ * @public
+ * @return {boolean} Returns true the user is logged in (has token and uuid), false if not
+ */
+ Usergrid.Client.prototype.isLoggedIn = function () {
+ return "undefined" !== typeof this.getToken();
+ };
+
+ /*
+ * A public method to log out an app user - clears all user fields from client
+ *
+ * @method logout
+ * @public
+ * @return none
+ */
+ Usergrid.Client.prototype.logout = function () {
+ this.setToken(null);
+ };
+
+ /*
+ * A private method to build the curl call to display on the command line
+ *
+ * @method buildCurlCall
+ * @private
+ * @param {object} options
+ * @return {string} curl
+ */
+ Usergrid.Client.prototype.buildCurlCall = function (options) {
+ var curl = ['curl'];
+ var method = (options.method || 'GET').toUpperCase();
+ var body = options.body;
+ var uri = options.uri;
+
+ //curl - add the method to the command (no need to add anything for GET)
+ curl.push('-X');
+ curl.push((['POST','PUT','DELETE'].indexOf(method)>=0)?method:'GET');
+
+ //curl - append the path
+ curl.push(uri);
+
+ if("object"===typeof body && Object.keys(body).length>0 && ['POST','PUT'].indexOf(method)!==-1){
+ curl.push('-d');
+ curl.push("'"+JSON.stringify(body)+"'");
+ }
+ curl=curl.join(' ');
+ //log the curl command to the console
+ console.log(curl);
+
+ return curl;
+ }
+
+ Usergrid.Client.prototype.getDisplayImage = function (email, picture, size) {
+ size = size || 50;
+ var image='https://apigee.com/usergrid/images/user_profile.png';
+ try {
+ if (picture) {
+ image= picture;
+ }else if (email.length) {
+ image= 'https://secure.gravatar.com/avatar/' + MD5(email) + '?s=' + size + encodeURI("&d=https://apigee.com/usergrid/images/user_profile.png");
+ }
+ } catch(e) {
+ //TODO do something with this error?
+ }finally{
+ return image;
+ }
+ }
+ return Usergrid.Client;
+}());
+ global[name] = exports;
+ global[name].noConflict = function() {
+ if(overwrittenName){
+ global[name] = overwrittenName;
+ }
+ return exports;
+ };
+ return global[name];
+}());
+
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/9dfc5628/sdks/html5-javascript/lib/modules/Collection.js
----------------------------------------------------------------------
diff --git a/sdks/html5-javascript/lib/modules/Collection.js b/sdks/html5-javascript/lib/modules/Collection.js
new file mode 100644
index 0000000..5173fc9
--- /dev/null
+++ b/sdks/html5-javascript/lib/modules/Collection.js
@@ -0,0 +1,459 @@
+
+/*
+ * The Collection class models Usergrid Collections. It essentially
+ * acts as a container for holding Entity objects, while providing
+ * additional funcitonality such as paging, and saving
+ *
+ * @constructor
+ * @param {string} options - configuration object
+ * @param {function} callback
+ * @return {callback} callback(err, data)
+ */
+Usergrid.Collection = function(options, callback) {
+
+ if (options) {
+ this._client = options.client;
+ this._type = options.type;
+ this.qs = options.qs || {};
+
+ //iteration
+ this._list = options.list || [];
+ this._iterator = options.iterator || -1; //first thing we do is increment, so set to -1
+
+ //paging
+ this._previous = options.previous || [];
+ this._next = options.next || null;
+ this._cursor = options.cursor || null;
+
+ //restore entities if available
+ if (options.list) {
+ var count = options.list.length;
+ for(var i=0;i<count;i++){
+ //make new entity with
+ var entity = this._client.restoreEntity(options.list[i]);
+ this._list[i] = entity;
+ }
+ }
+ }
+ if (callback) {
+ //populate the collection
+ this.fetch(callback);
+ }
+
+};
+
+
+/*
+ * method to determine whether or not the passed variable is a Usergrid Collection
+ *
+ * @method isCollection
+ * @public
+ * @params {any} obj - any variable
+ * @return {boolean} Returns true or false
+ */
+Usergrid.isCollection = function(obj){
+ return (obj && obj instanceof Usergrid.Collection);
+}
+
+
+/*
+ * gets the data from the collection object for serialization
+ *
+ * @method serialize
+ * @return {object} data
+ */
+Usergrid.Collection.prototype.serialize = function () {
+
+ //pull out the state from this object and return it
+ var data = {}
+ data.type = this._type;
+ data.qs = this.qs;
+ data.iterator = this._iterator;
+ data.previous = this._previous;
+ data.next = this._next;
+ data.cursor = this._cursor;
+
+ this.resetEntityPointer();
+ var i=0;
+ data.list = [];
+ while(this.hasNextEntity()) {
+ var entity = this.getNextEntity();
+ data.list[i] = entity.serialize();
+ i++;
+ }
+
+ data = JSON.stringify(data);
+ return data;
+};
+
+Usergrid.Collection.prototype.addCollection = function (collectionName, options, callback) {
+ self = this;
+ options.client = this._client;
+ var collection = new Usergrid.Collection(options, function(err, data) {
+ if (typeof(callback) === 'function') {
+
+ collection.resetEntityPointer();
+ while(collection.hasNextEntity()) {
+ var user = collection.getNextEntity();
+ var email = user.get('email');
+ var image = self._client.getDisplayImage(user.get('email'), user.get('picture'));
+ user._portal_image_icon = image;
+ }
+
+ self[collectionName] = collection;
+ callback(err, collection);
+ }
+ });
+};
+
+/*
+ * Populates the collection from the server
+ *
+ * @method fetch
+ * @param {function} callback
+ * @return {callback} callback(err, data)
+ */
+Usergrid.Collection.prototype.fetch = function (callback) {
+ var self = this;
+ var qs = this.qs;
+
+ //add in the cursor if one is available
+ if (this._cursor) {
+ qs.cursor = this._cursor;
+ } else {
+ delete qs.cursor;
+ }
+ var options = {
+ method:'GET',
+ endpoint:this._type,
+ qs:this.qs
+ };
+ this._client.request(options, function (err, data) {
+ if(err && self._client.logging) {
+ console.log('error getting collection');
+ } else {
+ //save the cursor if there is one
+ var cursor = data.cursor || null;
+ self.saveCursor(cursor);
+ if (data.entities) {
+ self.resetEntityPointer();
+ var count = data.entities.length;
+ //save entities locally
+ self._list = []; //clear the local list first
+ for (var i=0;i<count;i++) {
+ var uuid = data.entities[i].uuid;
+ if (uuid) {
+ var entityData = data.entities[i] || {};
+ self._baseType = data.entities[i].type; //store the base type in the collection
+ entityData.type = self._type;//make sure entities are same type (have same path) as parent collection.
+ var entityOptions = {
+ type:self._type,
+ client:self._client,
+ uuid:uuid,
+ data:entityData
+ };
+
+ var ent = new Usergrid.Entity(entityOptions);
+ ent._json = JSON.stringify(entityData, null, 2);
+ var ct = self._list.length;
+ self._list[ct] = ent;
+ }
+ }
+ }
+ }
+ if (typeof(callback) === 'function') {
+ callback(err, data);
+ }
+ });
+};
+
+/*
+ * Adds a new Entity to the collection (saves, then adds to the local object)
+ *
+ * @method addNewEntity
+ * @param {object} entity
+ * @param {function} callback
+ * @return {callback} callback(err, data, entity)
+ */
+Usergrid.Collection.prototype.addEntity = function (options, callback) {
+ var self = this;
+ options.type = this._type;
+
+ //create the new entity
+ this._client.createEntity(options, function (err, entity) {
+ if (!err) {
+ //then add the entity to the list
+ var count = self._list.length;
+ self._list[count] = entity;
+ }
+ if (typeof(callback) === 'function') {
+ callback(err, entity);
+ }
+ });
+};
+
+Usergrid.Collection.prototype.addExistingEntity = function (entity) {
+ //entity should already exist in the db, so just add it to the list
+ var count = this._list.length;
+ this._list[count] = entity;
+};
+
+/*
+ * Removes the Entity from the collection, then destroys the object on the server
+ *
+ * @method destroyEntity
+ * @param {object} entity
+ * @param {function} callback
+ * @return {callback} callback(err, data)
+ */
+Usergrid.Collection.prototype.destroyEntity = function (entity, callback) {
+ var self = this;
+ entity.destroy(function(err, data) {
+ if (err) {
+ if (self._client.logging) {
+ console.log('could not destroy entity');
+ }
+ if (typeof(callback) === 'function') {
+ callback(err, data);
+ }
+ } else {
+ //destroy was good, so repopulate the collection
+ self.fetch(callback);
+ }
+ });
+ //remove entity from the local store
+ this.removeEntity(entity);
+};
+
+
+Usergrid.Collection.prototype.removeEntity = function (entity) {
+ var uuid = entity.get('uuid');
+ for (var key in this._list) {
+ var listItem = this._list[key];
+ if (listItem.get('uuid') === uuid) {
+ return this._list.splice(key, 1);
+ }
+ }
+ return false;
+};
+
+/*
+ * Looks up an Entity by UUID
+ *
+ * @method getEntityByUUID
+ * @param {string} UUID
+ * @param {function} callback
+ * @return {callback} callback(err, data, entity)
+ */
+Usergrid.Collection.prototype.getEntityByUUID = function (uuid, callback) {
+
+ for (var key in this._list) {
+ var listItem = this._list[key];
+ if (listItem.get('uuid') === uuid) {
+ return listItem;
+ }
+ }
+
+ //get the entity from the database
+ var options = {
+ data: {
+ type: this._type,
+ uuid:uuid
+ },
+ client: this._client
+ }
+ var entity = new Usergrid.Entity(options);
+ entity.fetch(callback);
+};
+
+/*
+ * Returns the first Entity of the Entity list - does not affect the iterator
+ *
+ * @method getFirstEntity
+ * @return {object} returns an entity object
+ */
+Usergrid.Collection.prototype.getFirstEntity = function () {
+ var count = this._list.length;
+ if (count > 0) {
+ return this._list[0];
+ }
+ return null;
+};
+
+/*
+ * Returns the last Entity of the Entity list - does not affect the iterator
+ *
+ * @method getLastEntity
+ * @return {object} returns an entity object
+ */
+Usergrid.Collection.prototype.getLastEntity = function () {
+ var count = this._list.length;
+ if (count > 0) {
+ return this._list[count-1];
+ }
+ return null;
+};
+
+/*
+ * Entity iteration -Checks to see if there is a "next" entity
+ * in the list. The first time this method is called on an entity
+ * list, or after the resetEntityPointer method is called, it will
+ * return true referencing the first entity in the list
+ *
+ * @method hasNextEntity
+ * @return {boolean} true if there is a next entity, false if not
+ */
+Usergrid.Collection.prototype.hasNextEntity = function () {
+ var next = this._iterator + 1;
+ var hasNextElement = (next >=0 && next < this._list.length);
+ if(hasNextElement) {
+ return true;
+ }
+ return false;
+};
+
+/*
+ * Entity iteration - Gets the "next" entity in the list. The first
+ * time this method is called on an entity list, or after the method
+ * resetEntityPointer is called, it will return the,
+ * first entity in the list
+ *
+ * @method hasNextEntity
+ * @return {object} entity
+ */
+Usergrid.Collection.prototype.getNextEntity = function () {
+ this._iterator++;
+ var hasNextElement = (this._iterator >= 0 && this._iterator <= this._list.length);
+ if(hasNextElement) {
+ return this._list[this._iterator];
+ }
+ return false;
+};
+
+/*
+ * Entity iteration - Checks to see if there is a "previous"
+ * entity in the list.
+ *
+ * @method hasPrevEntity
+ * @return {boolean} true if there is a previous entity, false if not
+ */
+Usergrid.Collection.prototype.hasPrevEntity = function () {
+ var previous = this._iterator - 1;
+ var hasPreviousElement = (previous >=0 && previous < this._list.length);
+ if(hasPreviousElement) {
+ return true;
+ }
+ return false;
+};
+
+/*
+ * Entity iteration - Gets the "previous" entity in the list.
+ *
+ * @method getPrevEntity
+ * @return {object} entity
+ */
+Usergrid.Collection.prototype.getPrevEntity = function () {
+ this._iterator--;
+ var hasPreviousElement = (this._iterator >= 0 && this._iterator <= this._list.length);
+ if(hasPreviousElement) {
+ return this._list[this._iterator];
+ }
+ return false;
+};
+
+/*
+ * Entity iteration - Resets the iterator back to the beginning
+ * of the list
+ *
+ * @method resetEntityPointer
+ * @return none
+ */
+Usergrid.Collection.prototype.resetEntityPointer = function () {
+ this._iterator = -1;
+};
+
+/*
+ * Method to save off the cursor just returned by the last API call
+ *
+ * @public
+ * @method saveCursor
+ * @return none
+ */
+Usergrid.Collection.prototype.saveCursor = function(cursor) {
+ //if current cursor is different, grab it for next cursor
+ if (this._next !== cursor) {
+ this._next = cursor;
+ }
+};
+
+/*
+ * Resets the paging pointer (back to original page)
+ *
+ * @public
+ * @method resetPaging
+ * @return none
+ */
+Usergrid.Collection.prototype.resetPaging = function() {
+ this._previous = [];
+ this._next = null;
+ this._cursor = null;
+};
+
+/*
+ * Paging - checks to see if there is a next page od data
+ *
+ * @method hasNextPage
+ * @return {boolean} returns true if there is a next page of data, false otherwise
+ */
+Usergrid.Collection.prototype.hasNextPage = function () {
+ return (this._next);
+};
+
+/*
+ * Paging - advances the cursor and gets the next
+ * page of data from the API. Stores returned entities
+ * in the Entity list.
+ *
+ * @method getNextPage
+ * @param {function} callback
+ * @return {callback} callback(err, data)
+ */
+Usergrid.Collection.prototype.getNextPage = function (callback) {
+ if (this.hasNextPage()) {
+ //set the cursor to the next page of data
+ this._previous.push(this._cursor);
+ this._cursor = this._next;
+ //empty the list
+ this._list = [];
+ this.fetch(callback);
+ }
+}
+
+/*
+ * Paging - checks to see if there is a previous page od data
+ *
+ * @method hasPreviousPage
+ * @return {boolean} returns true if there is a previous page of data, false otherwise
+ */
+Usergrid.Collection.prototype.hasPreviousPage = function () {
+ return (this._previous.length > 0);
+};
+
+/*
+ * Paging - reverts the cursor and gets the previous
+ * page of data from the API. Stores returned entities
+ * in the Entity list.
+ *
+ * @method getPreviousPage
+ * @param {function} callback
+ * @return {callback} callback(err, data)
+ */
+Usergrid.Collection.prototype.getPreviousPage = function (callback) {
+ if (this.hasPreviousPage()) {
+ this._next=null; //clear out next so the comparison will find the next item
+ this._cursor = this._previous.pop();
+ //empty the list
+ this._list = [];
+ this.fetch(callback);
+ }
+};
http://git-wip-us.apache.org/repos/asf/incubator-usergrid/blob/9dfc5628/sdks/html5-javascript/lib/modules/Counter.js
----------------------------------------------------------------------
diff --git a/sdks/html5-javascript/lib/modules/Counter.js b/sdks/html5-javascript/lib/modules/Counter.js
new file mode 100644
index 0000000..cb9c568
--- /dev/null
+++ b/sdks/html5-javascript/lib/modules/Counter.js
@@ -0,0 +1,186 @@
+/*
+ * A class to model a Usergrid event.
+ *
+ * @constructor
+ * @param {object} options {timestamp:0, category:'value', counters:{name : value}}
+ * @returns {callback} callback(err, event)
+ */
+Usergrid.Counter = function(options, callback) {
+ var self=this;
+ this._client = options.client;
+ this._data = options.data || {};
+ this._data.category = options.category||"UNKNOWN";
+ this._data.timestamp = options.timestamp||0;
+ this._data.type = "events";
+ this._data.counters=options.counters||{};
+ if(typeof(callback) === 'function') {
+ callback.call(self, false, self);
+ }
+ //this.save(callback);
+};
+var COUNTER_RESOLUTIONS=[
+ 'all', 'minute', 'five_minutes', 'half_hour',
+ 'hour', 'six_day', 'day', 'week', 'month'
+];
+/*
+ * Inherit from Usergrid.Entity.
+ * Note: This only accounts for data on the group object itself.
+ * You need to use add and remove to manipulate group membership.
+ */
+Usergrid.Counter.prototype = new Usergrid.Entity();
+
+/*
+ * overrides Entity.prototype.fetch. Returns all data for counters
+ * associated with the object as specified in the constructor
+ *
+ * @public
+ * @method increment
+ * @param {function} callback
+ * @returns {callback} callback(err, event)
+ */
+Usergrid.Counter.prototype.fetch=function(callback){
+ this.getData({}, callback);
+}
+/*
+ * increments the counter for a specific event
+ *
+ * options object: {name: counter_name}
+ *
+ * @public
+ * @method increment
+ * @params {object} options
+ * @param {function} callback
+ * @returns {callback} callback(err, event)
+ */
+Usergrid.Counter.prototype.increment=function(options, callback){
+ var self=this,
+ name=options.name,
+ value=options.value;
+ if(!name){
+ if(typeof(callback) === 'function') {
+ return callback.call(self, true, "'value' for increment, decrement must be a number");
+ }
+ }else if(isNaN(value)){
+ if(typeof(callback) === 'function') {
+ return callback.call(self, true, "'value' for increment, decrement must be a number");
+ }
+ }else{
+ self._data.counters[name]=(parseInt(value))||1;
+ return self.save(callback);
+ }
+};
+/*
+ * decrements the counter for a specific event
+ *
+ * options object: {name: counter_name}
+ *
+ * @public
+ * @method decrement
+ * @params {object} options
+ * @param {function} callback
+ * @returns {callback} callback(err, event)
+ */
+
+Usergrid.Counter.prototype.decrement=function(options, callback){
+ var self=this,
+ name=options.name,
+ value=options.value;
+ self.increment({name:name, value:-((parseInt(value))||1)}, callback);
+};
+/*
+ * resets the counter for a specific event
+ *
+ * options object: {name: counter_name}
+ *
+ * @public
+ * @method reset
+ * @params {object} options
+ * @param {function} callback
+ * @returns {callback} callback(err, event)
+ */
+
+Usergrid.Counter.prototype.reset=function(options, callback){
+ var self=this,
+ name=options.name;
+ self.increment({name:name, value:0}, callback);
+};
+
+/*
+ * gets data for one or more counters over a given
+ * time period at a specified resolution
+ *
+ * options object: {
+ * counters: ['counter1', 'counter2', ...],
+ * start: epoch timestamp or ISO date string,
+ * end: epoch timestamp or ISO date string,
+ * resolution: one of ('all', 'minute', 'five_minutes', 'half_hour', 'hour', 'six_day', 'day', 'week', or 'month')
+ * }
+ *
+ * @public
+ * @method getData
+ * @params {object} options
+ * @param {function} callback
+ * @returns {callback} callback(err, event)
+ */
+Usergrid.Counter.prototype.getData=function(options, callback){
+ var start_time,
+ end_time,
+ start=options.start||0,
+ end=options.end||Date.now(),
+ resolution=(options.resolution||'all').toLowerCase(),
+ counters=options.counters||Object.keys(this._data.counters),
+ res=(resolution||'all').toLowerCase();
+ if(COUNTER_RESOLUTIONS.indexOf(res)===-1){
+ res='all';
+ }
+ if(start){
+ switch(typeof start){
+ case "undefined":
+ start_time=0;
+ break;
+ case "number":
+ start_time=start;
+ break;
+ case "string":
+ start_time=(isNaN(start))?Date.parse(start):parseInt(start);
+ break;
+ default:
+ start_time=Date.parse(start.toString());
+ }
+ }
+ if(end){
+ switch(typeof end){
+ case "undefined":
+ end_time=Date.now();
+ break;
+ case "number":
+ end_time=end;
+ break;
+ case "string":
+ end_time=(isNaN(end))?Date.parse(end):parseInt(end);
+ break;
+ default:
+ end_time=Date.parse(end.toString());
+ }
+ }
+ var self=this;
+ //https://api.usergrid.com/yourorgname/sandbox/counters?counter=test_counter
+ var params=Object.keys(counters).map(function(counter){
+ return ["counter", encodeURIComponent(counters[counter])].join('=');
+ });
+ params.push('resolution='+res)
+ params.push('start_time='+String(start_time))
+ params.push('end_time='+String(end_time))
+
+ var endpoint="counters?"+params.join('&');
+ this._client.request({endpoint:endpoint}, function(err, data){
+ if(data.counters && data.counters.length){
+ data.counters.forEach(function(counter){
+ self._data.counters[counter.name]=counter.value||counter.values;
+ })
+ }
+ if(typeof(callback) === 'function') {
+ callback.call(self, err, data);
+ }
+ })
+};